Flash of previous page while navigating between pages in react js application - ios

I am developing a react js application for ios and android. In my application while navigating from one page to another,a flash of previous page is displaying for 1 second and then my next page is loading.This issue is prevalent only in ios app.
Issue does not appear while checking in browser safari,chrome.Only in app
Please provide solution.

We are not using react native and react router.
Few pages are developed in reactjs and integrated in to an existing mobile app.
In the above code:
else {
console.log('clicked');
window.location.href = path + '?id=' + id + '&time=' `window.sessionStorage.getItem('time') + '&prodId=' + productId + '&qty=' + `qty + '&storeCall=true';
}
here we are navigating to another jsx page with window.location.href
While navigating a getting issues in ios app.Flash of previous page showing up for a second

import React from 'react';
import Copyright from './Copyright.jsx';
import { browserHistory } from 'react-router';
import axios from 'axios';
import envConstant from '../../../../../config/labelConstants.js';
import { ClipLoader } from 'react-spinners';
var x=0;
let submitOrder, flag = "false", footerBtn = '', vendor;
let closeFunc;
class Footer extends React.Component {
constructor(props) {
super(props);
this.orderSubmit = this.orderSubmit.bind(this);
this.validateSubmit = this.validateSubmit.bind(this);
this.validateNetwork = this.validateNetwork.bind(this);
this.disableBtn = this.disableBtn.bind(this);
this.state = {
data: 'Initial data....',
price: 'total',
loading:false
}
this.propTypes = {
alertFunc: React.PropTypes.func,
couponAvail: React.PropTypes.func,
alertClose:React.PropTypes.func
};
};
validateSubmit() {
const react = this;
var submit = false;
var phoneNum;
var fname = this.props.UserDetails.refs.fname.value;
var lname = this.props.UserDetails.refs.lname.value;
var phone = this.props.UserDetails.refs.phone.value.replace(/[-.]/gi, '');
if (phone != null) {
phoneNum = phone.toString();
}
var email = this.props.UserDetails.refs.email.value;
var agree = window.sessionStorage.getItem('agree');
submitOrder = {};
let prodId, qty;
if (null == window.sessionStorage.getItem('prodID') && null == window.sessionStorage.getItem('qty')) {
prodId = window.sessionStorage.getItem('initprodID');
qty = 1;
} else {
prodId = window.sessionStorage.getItem('prodID');
qty = window.sessionStorage.getItem('qty');
}
submitOrder = {
fname: this.props.UserDetails.refs.fname.value,
lname: this.props.UserDetails.refs.lname.value,
coupon: window.sessionStorage.getItem('successCoupon'),
email: this.props.UserDetails.refs.email.value,
phoneNum: this.props.UserDetails.refs.phone.value.replace(/[-.]/gi, ''),
id: window.sessionStorage.getItem('id'),
qty: qty,
prodID: prodId,
emailOptIn: window.sessionStorage.getItem('emailOptIn'),
smsOptIn: window.sessionStorage.getItem('smsOptIn'),
time: window.sessionStorage.getItem('time')
};
if (fname == null || fname == '') {
this.props.alertFunc(envConstant.enterDetails,react.props.UserDetails.refs.fname);
submit = false;
return false;
}
if (lname == null || lname == '') {
this.props.alertFunc(envConstant.enterDetails,react.props.UserDetails.refs.lname);
submit = false;
return false;
}
if (phoneNum == null || phoneNum == '') {
this.props.alertFunc(envConstant.enterDetails,react.props.UserDetails.refs.phone);
submit = false;
return false;
}
if (email == null || email == '') {
this.props.alertFunc(envConstant.enterDetails,react.props.UserDetails.refs.email);
submit = false;
return false;
}
if ('' != fname || null != fname || '' == lname || null != lname) {
submit = true;
}
if (null != fname || '' != fname) {
const re = /^[a-zA-Z\ ]*$/;
if (!re.test(fname)) {
this.props.alertFunc(envConstant.invalidName,react.props.UserDetails.refs.fname);
submit = false;
return false;
} else {
submit = true;
}
}
if (null != lname || '' != lname) {
const re = /^[a-zA-Z\'\-\. ]*$/;
if (!re.test(lname)) {
this.props.alertFunc(envConstant.invalidName,react.props.UserDetails.refs.lname);
submit = false;
return false;
} else {
submit = true;
}
}
if (null != phoneNum || '' != phoneNum) {
if (vendor == "boots") {
if (phoneNum.length != "11") {
this.props.alertFunc(envConstant.invalidPhnum,react.props.UserDetails.refs.phone);
submit = false;
return false;
} else {
submit = true;
}
} else if (vendor == "roi") {
const re = /^[0]+[0-9]*$/;
if (phoneNum.length != "11" || !re.test(phoneNum)) {
this.props.alertFunc(envConstant.invalidPhnum,react.props.UserDetails.refs.phone);
submit = false;
return false;
} else {
submit = true;
}
} else {
if (phoneNum.length != "10") {
this.props.alertFunc(envConstant.invalidPhnum,react.props.UserDetails.refs.phone);
submit = false;
return false;
} else {
submit = true;
}
}
}
if (null != email || '' != email) {
const re = /^([a-zA-Z0-9_\.\-])+\#(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
if (!re.test(email)) {
this.props.alertFunc(envConstant.invalidEmail,react.props.UserDetails.refs.email);
submit = false;
return false;
} else {
submit = true;
}
}
if (agree == "false" || null == agree) {
this.props.alertFunc(envConstant.agreeTerms);
submit = false;
return false;
}
if (submit == true) {
return true;
}
}
validateNetwork() {
var hasConn = window.navigator.onLine;
if (hasConn) {
return hasConn;
}
else {
this.props.alertFunc(envConstant.networkFailure);
}
}
orderSubmit(e) {
const react = this;
if (this.props.footer == envConstant.submitFoot) {
window.sessionStorage.setItem('id', this.props.id);
if (this.validateNetwork()) {
if (this.validateSubmit()) {
axios({
method: 'post',
url: react.props.urlValue + '/inputFields',
data: submitOrder
}).then((response) => {
this.setState({loading:true});
window.location.href = react.props.path;
});
}
}
}
if (this.props.footer == envConstant.orderInfoFoot) {
if (this.validateNetwork()) {
let qty, productId;
this.setState({loading:true});
if (null == window.sessionStorage.getItem('qty') || 'null' == `window.sessionStorage.getItem('qty')) {`
qty = 1;
productId = window.sessionStorage.getItem('initprodID');
} else {
qty = window.sessionStorage.getItem('qty');
productId = window.sessionStorage.getItem('prodID');
}
let path = this.props.path;
let id = this.props.id;
if (null != window.sessionStorage.getItem('coupon') && "null" != `window.sessionStorage.getItem('coupon')) {`
if (window.sessionStorage.getItem('errorcode') == '' && null != `window.sessionStorage.getItem('coupon') &&` `window.sessionStorage.getItem('couponApplied') == "true") {`
setTimeout(function () {
if (window.sessionStorage.getItem('status1') != 'failure') {
window.location.href = path + '?id=' + id + '&time=' + `window.sessionStorage.getItem('time') + '&prodId=' + productId + '&qty=' +` `qty + '&storeCall=true';`
}
},1500);
}
}
else {
console.log('clicked');
window.location.href = path + '?id=' + id + '&time=' + `window.sessionStorage.getItem('time') + '&prodId=' + productId + '&qty=' +` `qty + '&storeCall=true';`
}
}
}
if (this.props.footer == envConstant.ThankyouFoot) {
let callBackUrl = this.props.callBackUrl;
if (window.navigator.userAgent.includes("iPhone")) {
window.location = "QP_DONE:DONE";
} else {
try {
window.quickprint.onCheckoutComplete();
} catch (e) {
if (undefined != callBackUrl && '' != callBackUrl && null != callBackUrl) {
if (callBackUrl.includes('?')) {
window.location = callBackUrl + '?action=done';
} else {
window.location = callBackUrl + '&action=done';
}
}
}
}
}
}
componentDidMount() {
let footerHeight = this.refs.footerHeight.clientHeight;
window.sessionStorage.setItem('footerHeight', footerHeight);
}
disableBtn(id) {
window.sessionStorage.setItem('disable', "true");
if(window.sessionStorage.getItem('alert1'+id)=="0" || `window.sessionStorage.getItem('alert1'+id)=="1" || `window.sessionStorage.getItem('alert1'+id)==1){
alert(envConstant.priceInvalid);
}else{
x=0;
window.sessionStorage.setItem('alert1'+id,x++);
}
//this.props.alertFunc(envConstant.priceInvalid)
}
render() {
vendor = this.props.vendor;
let copyrightsWrapper;
if (vendor != "ts" && vendor != "roi") {
copyrightsWrapper = (
<Copyright copyRightMessage={this.props.copyRightMessage} />
);
}
if (typeof window !== 'undefined') {
window.sessionStorage.setItem('callBackUrl',this.props.callBackUrl);
if (window.sessionStorage.getItem('status') == "success" || `window.sessionStorage.getItem('status') == "") {`
if ((window.sessionStorage.getItem('status1') != "failure" || `window.sessionStorage.getItem('couponApplied') == "false") && `window.sessionStorage.getItem('flagDrop') != "true" &&` `window.sessionStorage.getItem('couponFocus') != "true") {
var discTotal = `window.sessionStorage.getItem('discount').split(this.props.currency);`
if (parseInt(discTotal[1]) > 998) {
window.sessionStorage.setItem('alert1'+this.props.id,x++);
this.disableBtn(this.props.id);
} else {
window.sessionStorage.setItem('disable', "false");
}
}
}
if (window.sessionStorage.getItem('status') == null) {
if (window.sessionStorage.getItem('invalid') != 'true') {
if (null == window.sessionStorage.getItem('total')) {
var initTotal = `window.sessionStorage.getItem('inittotal').split(this.props.currency);`
if (parseInt(initTotal[1]) > 998) {
window.sessionStorage.setItem('alert1'+this.props.id,1);
this.disableBtn(this.props.id);
} else {
window.sessionStorage.setItem('disable', "false");
}
} else {
var prodTotal = `window.sessionStorage.getItem('total').split(this.props.currency);`
if (parseInt(prodTotal[1]) > 998) {
window.sessionStorage.setItem('alert1'+this.props.id,1);
this.disableBtn(this.props.id);
} else {
window.sessionStorage.setItem('disable', "false");
}
}
}
}
if (window.sessionStorage.getItem('disable') == "true") {
footerBtn = (
<button type="button"
className="btn-off supp-color btn-w1" `disabled="disabled"> {this.props.footer}</button>`
);
} else {
footerBtn = (
<button ref="footerBtn" type="button" className="btn-on supp-color btn-`w1" onClick={this.orderSubmit}>{this.props.footer}</button>`
);
}
}else{
footerBtn = (
<button ref="footerBtn" type="button" className="btn-on supp-color btn-w1" >{this.props.footer}</button>
);
}
return (
<div className="op-footer footer_height" ref="footerHeight" id="footerValue">
{copyrightsWrapper}
<div className="background-white">
<div className={'sweet-loading '+ this.state.loading}>
<ClipLoader color={'#a0a0a0'} loading={this.state.loading}/>
</div>
{footerBtn}
</div>
</div>
);
}
}
export default Footer;

Related

Value cannot be null. Parameter name DropdownList in ASP. NET CORE

I have a problem in mi code, when show the error message appears the message of the title
This is the code of my form Register
<div class="form-group col-md-6">
#if (!Model.MODEL_PACIENTE.PAC_ID.Equals(0))
{
<label>Comuna:</label>
#Html.DropDownList("MODEL_PACIENTE.PAC_COMUNA", new SelectList(Model.MODEL_PACIENTE.Comuna_Lista, "Text", "Text"),
new { #class = "form-control" })
}
else
{
<label>Comuna:</label>
#Html.DropDownList("MODEL_PACIENTE.PAC_COMUNA", new SelectList(Model.MODEL_PACIENTE.Comuna_Lista, "Text", "Text"),
"ESCOGA UNA COMUNA", new { #class = "form-control" }) // HERE IS THE ERROR WHEN MY DNI IS REGISTER IN THE BD }
<span asp-validation-for="MODEL_PACIENTE.PAC_COMUNA" class="text-danger"></span>
</div>
Code of my class GetOdontologo
public List<SelectListItem> GetOdontologo(ApplicationDbContext context)
{
List<SelectListItem> selectListItems = null;
try
{
selectListItems = new List<SelectListItem>();
context.TBL_ODONTOLOGO.ToList().ForEach(item =>
{
selectListItems.Add(new SelectListItem
{
Value = item.ODONT_ID.ToString(),
// Text = item.ODONT_CODIGO
Text = item.ODONT_CODIGO + '-' + item.ODONT_APELLIDO + ' ' + item.ODONT_NOMBRE
});
});
}
catch (Exception ex)
{
Console.WriteLine($"Error: '{ex}'");
}
return selectListItems;
}
This is the class GetComuna
public List<SelectListItem> GetComuna(ApplicationDbContext context)
{
List<SelectListItem> selectListItems = null;
try
{
selectListItems = new List<SelectListItem>();
context.TBL_PROVINCIA.ToList().ForEach(item =>
{
selectListItems.Add(new SelectListItem
{
Value = item.PROV_ID.ToString(),
Text = item.PROV_NOMBRE
});
});
}
catch (Exception ex)
{
Console.WriteLine($"Error: '{ex}'");
}
return selectListItems;
}
And this the code of my method "onget"
public void OnGet(int idActPac)
{
_DataPac2 = null;
if(idActPac.Equals(0))
{
_DataPac2 = null;
}
if (_dataInput != null || _DataPac1 != null || _DataPac2 != null)
{
if (_dataInput != null)
{
MODEL_PACIENTE = _dataInput;
MODEL_PACIENTE.AvatarImage = null;
}
else
{
if (_DataPac1 != null || _DataPac2 != null)
{
if (_DataPac2 != null)
_DataPac1 = _DataPac2;
MODEL_PACIENTE = new PACIENTE
{
PAC_ID = _DataPac1.PAC_ID,
PAC_NOMBRE = _DataPac1.PAC_NOMBRE,
PAC_APELLIDO = _DataPac1.PAC_APELLIDO,
PAC_CODIGO = _DataPac1.PAC_CODIGO,
PAC_EDAD = _DataPac1.PAC_EDAD,
PAC_COD_ODONT = _DataPac1.PAC_COD_ODONT,
PAC_COMUNA = _DataPac1.PAC_COMUNA,
PAC_CORREO = _DataPac1.PAC_CORREO,
PAC_DIRECCION = _DataPac1.PAC_DIRECCION,
PAC_OBSERVACIONES = _DataPac1.PAC_OBSERVACIONES,
PAC_OTRAS_COMUNAS = _DataPac1.PAC_OTRAS_COMUNAS,
PAC_CONVENIO = _DataPac1.PAC_CONVENIO,
PAC_PREVISIONES = _DataPac1.PAC_PREVISIONES,
PAC_REPRESENTANTE = _DataPac1.PAC_REPRESENTANTE,
PAC_RUT = _DataPac1.PAC_RUT,
PAC_SEXO = _DataPac1.PAC_SEXO,
PAC_TELEFONO = _DataPac1.PAC_TELEFONO,
PAC_FECHA_NAC = _DataPac1.PAC_FECHA_NAC,
PAC_FEC_ACT = _DataPac1.PAC_FEC_ACT,
PAC_FEC_REG = _DataPac1.PAC_FEC_REG,
PAC_IMAGEN = _DataPac1.PAC_IMAGEN,
//AL USAR EL METODO ACTUALIZAR AL CARGAR LOS DATOS EN LOS INPUT NO OLVIDAR QUE SE DEBE CARGAR
//NUEVAMENTE LOS DropDownList LLAMANDOLO NUEVAMENTE AL FINAL COMO SE VE EN EL CODIGO A CONTINUACION
Genero_Lista = _lPacienteGen.GetGenero(_context),
Comuna_Lista = _lComuna.GetComuna(_context),
Odontologo_Lista = _lOdontologo.GetOdontologo(_context)
};
if (_dataInput != null)
{
MODEL_PACIENTE.ErrorMessage = _dataInput.ErrorMessage;
}
}
}
}
else
{
var Cod_Pac = 0;
String TempCodPac = null;
var Ultimo_Paciente = (from t in _context.TBL_PACIENTE
orderby t.PAC_CODIGO
select t).LastOrDefault();
if (Ultimo_Paciente != null)
{
Cod_Pac = (Ultimo_Paciente.PAC_CODIGO != null) ?
Convert.ToInt32(Ultimo_Paciente.PAC_CODIGO) + 1 :
1;
if (Cod_Pac < 10)
{
TempCodPac = String.Concat("0000", Convert.ToString(Cod_Pac));
}
else if (Cod_Pac >= 10 && Cod_Pac <= 11)
{
TempCodPac = String.Concat("000", Convert.ToString(Cod_Pac));
}
else if (Cod_Pac > 10 && Cod_Pac < 100)
{
TempCodPac = String.Concat("000", Convert.ToString(Cod_Pac));
}
else if (Cod_Pac >= 100 && Cod_Pac <=101)
{
TempCodPac = String.Concat("00", Convert.ToString(Cod_Pac));
}
else if (Cod_Pac > 100 && Cod_Pac < 1000)
{
TempCodPac = String.Concat("00", Convert.ToString(Cod_Pac));
}
else if (Cod_Pac >= 1000 && Cod_Pac <= 1001)
{
TempCodPac = String.Concat("0", Convert.ToString(Cod_Pac));
}
else if (Cod_Pac > 1000 && Cod_Pac <= 9999)
{
TempCodPac = String.Concat("0", Convert.ToString(Cod_Pac));
}
else if (Cod_Pac > 9999 && Cod_Pac < 99999)
{
TempCodPac = String.Concat("", Convert.ToString(Cod_Pac));
}
}
MODEL_PACIENTE = new PACIENTE
{
PAC_CODIGO = TempCodPac,
Genero_Lista = _lPacienteGen.GetGenero(_context),
Comuna_Lista = _lComuna.GetComuna(_context),
Odontologo_Lista = _lOdontologo.GetOdontologo(_context),
PAC_COD_ODONT = "00000"
};
}
_DataPac2 = _DataPac1;
_DataPac1 = null;
}
The code of my method Save_Patient
private async Task<bool> Guardar_Paciente_Async()
{
_dataInput = MODEL_PACIENTE;
var valor = false;
if (ModelState.IsValid)
{
var PacLista = _context.TBL_PACIENTE.Where(u => u.PAC_RUT.Equals(MODEL_PACIENTE.PAC_RUT)).ToList();
if (PacLista.Count.Equals(0))
{
var strategy = _context.Database.CreateExecutionStrategy();
await strategy.ExecuteAsync(async () =>
{
using (var transaction = _context.Database.BeginTransaction())
{
try
{
var imagenByte = await _lCargarImagen.ByteAvatarImageAsync(MODEL_PACIENTE.AvatarImage, _environment, "images/user_icon.png");
string TmpCodPac = _dataInput.PAC_COD_ODONT;
String vfCodPac = TmpCodPac.Substring(0, 4);
var Nuevo_Paciente = new MODELO_PACIENTE
{
PAC_CODIGO = _dataInput.PAC_CODIGO,
PAC_NOMBRE = _dataInput.PAC_NOMBRE.ToUpper(),
PAC_APELLIDO = _dataInput.PAC_APELLIDO.ToUpper(),
PAC_SEXO = _dataInput.PAC_SEXO,
PAC_RUT = _dataInput.PAC_RUT,
PAC_FECHA_NAC = _dataInput.PAC_FECHA_NAC,
PAC_EDAD = _dataInput.PAC_EDAD,
PAC_REPRESENTANTE = _dataInput.PAC_REPRESENTANTE?.ToUpper(),
PAC_DIRECCION = _dataInput.PAC_DIRECCION?.ToUpper(),
PAC_COMUNA = _dataInput.PAC_COMUNA?.ToUpper(),
PAC_OTRAS_COMUNAS = _dataInput.PAC_OTRAS_COMUNAS?.ToUpper(),
PAC_TELEFONO = _dataInput.PAC_TELEFONO,
PAC_CORREO = _dataInput.PAC_CORREO,
PAC_CONVENIO = _dataInput.PAC_CONVENIO?.ToUpper(),
PAC_PREVISIONES = _dataInput.PAC_PREVISIONES?.ToUpper(),
PAC_OBSERVACIONES = _dataInput.PAC_OBSERVACIONES?.ToUpper(),
PAC_COD_ODONT = vfCodPac,
PAC_IMAGEN = imagenByte,
PAC_FEC_REG = DateTime.Now,
PAC_FEC_ACT = DateTime.Now
};
await _context.AddAsync(Nuevo_Paciente);
_context.SaveChanges();
transaction.Commit();
_dataInput = null;
valor = true;
}
catch (Exception ex)
{
_dataInput.ErrorMessage = ex.Message;
transaction.Rollback();
valor = false;
}
}
});
}
else
{
_dataInput.ErrorMessage = $"El RUT {MODEL_PACIENTE.PAC_RUT} ya se encuentra Registrado";
// It should show this error in the respective "input", but the error message you see below in the image appears
}
}
else
{
foreach (var modelState in ModelState.Values)
{
foreach (var error in modelState.Errors)
{
_dataInput.ErrorMessage += error.ErrorMessage;
}
}
valor = false;
}
return valor;
}
If I debug, when I start it loads the 2 records from the dentist table, but when I put the existing ID at the time of appearing the error message appears what is seen in the image and when trying to load the list again it comes out null
After checking the ID error, the "Odontologia Lista" method returns null and the title error appears
where is the problem ?, I appreciate your help or guide to solve this problem.
You can try to check the following code:
MODEL_PACIENTE = new PACIENTE
{
PAC_CODIGO = TempCodPac,
//Genero_Lista = _lPacienteGen.GetGenero(_context),
Comuna_Lista = _lComuna.GetComuna(_context),
//Odontologo_Lista = _lOdontologo.GetOdontologo(_context),
PAC_COD_ODONT = "00000"
};
Odontologo_Lista = _lOdontologo.GetOdontologo(_context), is commented.If _dataInput == null && _DataPac1 == null && _DataPac2 == null,the Odontologo_Lista will not be set,and you will get the error Value cannot be null.

Xamarin Android Take picture intent save 0b file

i'm trying to take a pitcure with camera startin from fileupload of webview.
All code works for file chooser, but when i take a pitcure with camera, i found a 0b file in the directory where i create the temp file.
Someone can help me?
Here my code for customchromeclient filechooser event:
public override bool OnShowFileChooser(Android.Webkit.WebView webView, Android.Webkit.IValueCallback filePathCallback, FileChooserParams fileChooserParams)
{
string[] type = fileChooserParams.GetAcceptTypes();
this.mFilePathCallback = filePathCallback;
px_MyActivity.mFilePathCallback = filePathCallback;
if (string.Join("/", type).Contains("jpg") || string.Join("/", type).Contains("image"))
{
try
{
Intent takePictureIntent = new Intent(Android.Provider.MediaStore.ActionImageCapture);
if (takePictureIntent.ResolveActivity(px_MyActivity.PackageManager) != null) {
Java.IO.File photoFile = null;
try
{
photoFile = createImageFile();
}
catch(Exception e)
{
}
if (photoFile != null) {
mCameraPhotoPath = "file:" + photoFile.AbsolutePath;
//takePictureIntent.PutExtra(Android.Provider.MediaStore.ExtraOutput, photoFile);
px_MyActivity.mCameraPhotoPath = Android.Net.Uri.FromFile(photoFile); ;
} else {
takePictureIntent = null;
}
}
Intent contentSelectionIntent = new Intent(Intent.ActionGetContent);
contentSelectionIntent.AddCategory(Intent.CategoryOpenable);
contentSelectionIntent.SetType("image/*");
Intent[] intentArray;
if(takePictureIntent != null) {
intentArray = new Intent[]{takePictureIntent};
} else {
intentArray = new Intent[0];
}
//Intent chooserIntent = new Intent(Intent.ActionChooser);
Intent chooserIntent = Intent.CreateChooser(contentSelectionIntent, "Carica Foto");
chooserIntent.PutExtra(Intent.ExtraIntent, contentSelectionIntent);
chooserIntent.PutExtra(Intent.ExtraTitle, "Carica Foto");
chooserIntent.PutExtra(Intent.ExtraInitialIntents, intentArray);
px_MyActivity.StartActivityForResult(chooserIntent, PHOTO_REQUEST);
}catch(Exception ex){
}
}
else if (string.Join("/", type).Contains("mpg"))
{
Intent takePictureIntent = new Intent(Android.Provider.MediaStore.ActionVideoCapture);
}
else
{
Intent chooserIntent = fileChooserParams.CreateIntent();
chooserIntent.SetType("file/*");
chooserIntent.AddCategory(Intent.CategoryOpenable);
px_MyActivity.StartActivity(Intent.CreateChooser(chooserIntent, "File Chooser"), FILECHOOSER_RESULTCODE, this.OnFileChooserEnd);
}
return true;
}
private Java.IO.File createImageFile(){
// Create an image file name
string timeStamp = Android.OS.SystemClock.CurrentThreadTimeMillis().ToString();
string imageFileName = "JPEG_" + timeStamp + "_";
Java.IO.File storageDir = new Java.IO.File(Android.OS.Environment.ExternalStorageDirectory.Path);
Java.IO.File imageFile = Java.IO.File.CreateTempFile(
imageFileName, /* prefix */
".jpg", /* suffix */
storageDir /* directory */
);
return imageFile;
}
and here the code for avtivityresult:
protected override void OnActivityResult(int requestCode, Result resultVal, Android.Content.Intent data)
{
if (resultVal == Result.Ok)
{
if (requestCode == SPEECH)
{
var matches = data.GetStringArrayListExtra(RecognizerIntent.ExtraResults);
if (matches.Count != 0)
{
string xResult = matches[0];
if (xResult.Length > 500)
{
xResult = xResult.Substring(0, 500);
}
Xamarin.Forms.MessagingCenter.Send(this, "SpeechEnd", xResult);
}
}else if (requestCode == FILECHOOSER_RESULTCODE)
{
}else if (requestCode == PHOTO_REQUEST)
{
if (mFilePathCallback == null)
{
base.OnActivityResult(requestCode, resultVal, data);
return;
}
Android.Net.Uri[] result = null;
if (data == null)
{
if (mCameraPhotoPath != null)
{
result = new Android.Net.Uri[] { mCameraPhotoPath };
}
}
else
{
string xDataString = data.DataString;
if (xDataString != null)
{
result = new Android.Net.Uri[] { Android.Net.Uri.Parse(xDataString) };
}
else
{
Android.Graphics.Bitmap xImage = (Android.Graphics.Bitmap)data.Extras.Get("data");
try
{
//if(Android.Support.V4.Content.ContextCompat.CheckSelfPermission(this, Android.Manifest.Permission.ReadExternalStorage) == Permission.Granted)
//{
// var xStream = new System.IO.FileStream(mCameraPhotoPath.Path, System.IO.FileMode.OpenOrCreate);
// xImage.Compress(Bitmap.CompressFormat.Jpeg, 100, xStream);
// xStream.Flush();
// xStream.Close();
// //string path = Android.Provider.MediaStore.Images.Media.InsertImage(ContentResolver, xImage, "Title", "prova 1");
// // string path = Android.Provider.MediaStore.Images.Media.InsertImage(ContentResolver, mCameraPhotoPath.Path, "Title.jpg", "prova 1");
//}
if (mCameraPhotoPath != null)
{
result = new Android.Net.Uri[] { mCameraPhotoPath };
}
}
catch (Java.IO.IOException e)
{
e.PrintStackTrace();
}
}
}
//mFilePathCallback.OnReceiveValue(Android.Webkit.WebChromeClient.FileChooserParams.ParseResult((int)resultVal, data));
mFilePathCallback.OnReceiveValue(result);
mFilePathCallback = null;
}
}else{
if (requestCode == PHOTO_REQUEST)
{
mFilePathCallback.OnReceiveValue(Android.Webkit.WebChromeClient.FileChooserParams.ParseResult((int)resultVal, null));
}
}

How to increase the performance for login response

I am working on one MVC application. After clicking on login button it is taking me almost 7 second to redirect on home page which is not a good response time as per performance. Please help me how to make response time better.
Below is my controller code.
public ActionResult UserLogIn(Models.LogIn user)
{
if (ModelState.IsValid)
{
if (IsValid(user.User_Id, user.User_Password))
{
using (var db = new CopaRuleContext())
{
var ApproveUsers = db.tbl_User.Where(u => u.User_Approved == "Yes" && u.User_Id == user.User_Id).ToList();
var UserDetails = db.tbl_User.FirstOrDefault(u => u.User_Id == user.User_Id);
string UserRole = UserDetails.User_Role;
if (UserRole != null)
{
Session["UserRole"] = UserDetails.User_Role;
}
var rolename = db.tbl_Roles.FirstOrDefault(u => u.Role_Name == UserRole);
if (rolename != null)
{
Session["RoleName"] = rolename.Role_Description;
}
var firstname = UserDetails.User_First_Name;
var lastname = UserDetails.User_Last_Name;
firstname = firstname.Substring(0, 1).ToUpper() + firstname.Substring(1).ToLower();
lastname = lastname.Substring(0, 1).ToUpper() + lastname.Substring(1).ToLower();
Session["UserName"] = firstname + ' ' + lastname;
Session["UserId"] = UserDetails.User_Id;
if (ApproveUsers != null && ApproveUsers.Count() > 0)
{
if (UserDetails.User_Is_Deleted != 1)
{
Session["Process"] = "PP";
if (UserRole == "Role-1")
{
FormsAuthentication.SetAuthCookie(user.User_Id, false);
return RedirectToAction("Notification", "Inbox");
}
else if (UserRole == "Role-2")
{
FormsAuthentication.SetAuthCookie(user.User_Id, false);
return RedirectToAction("Clear", "Clear");
}
if (UserRole == "Role-3")
{
FormsAuthentication.SetAuthCookie(user.User_Id, false);
return RedirectToAction("Notification", "Inbox");
}
if (UserRole == "Role-4")
{
FormsAuthentication.SetAuthCookie(user.User_Id, false);
return RedirectToAction("Notification", "Inbox");
}
}
}
}
}
}
return View(user);
}
I was having problem with password encryption. I was using salt hash technique to encrypt the password which was affecting the performance of login. I have changed it with SHA1 encryption and performance has became incredibly fast.

asp.net-MVC Unexplained Production Exception

After moving my application to production, I get the regular Object reference not set to an instance of an object. exception logged in my event viewer.
This exception occurs intermittently few times a day, the problem is that I cannot put my hand on the problem, the logged exception details are not helpful, as there are no code line numbers included in the stack trace.
The Exception occurs on an action in my home controller which is the entry point action for each user arriving at the web site.
Can anyone help me reason with the below trace:
ERROR => Object reference not set to an instance of an object.
(XXX.XXX.Web.Controllers.HomeController.Index)
(
<>c__DisplayClass2b.<BeginInvokeAction>b__1c =>
<>c__DisplayClass33.<BeginInvokeActionMethodWithFilters>b__32 =>
<>c__DisplayClass46.<InvokeActionMethodFilterAsynchronouslyRecursive>b__3f =>
AsyncInvocationWithFilters.<InvokeActionMethodFilterAsynchronouslyRecursive>b__3d =>
WrappedAsyncResult`2.CallEndDelegate =>
AsyncControllerActionInvoker.<BeginInvokeSynchronousActionMethod>b__39 =>
ControllerActionInvoker.InvokeActionMethod =>
ReflectedActionDescriptor.Execute =>
<no type>.lambda_method => HomeController.Index )
System.NullReferenceException: Object reference not set to an instance of an object.
at XXXX.XXXX.Web.Controllers.HomeController.Index()
Code:
[SSOAuthorize]
public ActionResult Index()
{
try
{
ViewBag.ShowXXXAccountPrompt = false;
ViewBag.IsErrored = "false";
#region "Session Check"
if (_webHttpContext == null)
{
return RedirectToAction("signout", "Federation");
}
if (_webHttpContext.Session == null)
{
return RedirectToAction("signout", "Federation");
}
if (_webHttpContext.Session.PortalUser == null)
{
return RedirectToAction("signout", "Federation");
}
#endregion
if (_webHttpContext.Session.PortalUser != null)
{
if (!string.IsNullOrEmpty(_webHttpContext.Session.PortalUser.UserName))
{
var user = _usersManagementService.GetUserByUsername(_webHttpContext.Session.PortalUser.UserName);
var latestsubline = _subscriptionLineService.GetLatestLineByUserName(_webHttpContext.Session.PortalUser.UserName);
var isDualAccount = latestsubline == null ? false : latestsubline.Action == (int)Entities.SubscriptionLineAction.Activate? latestsubline.IsDualAccount : false;
isDualAccount = isDualAccount == null ? false : isDualAccount;
if(user == null)
{
//whenever there is no account Just Create it, the subscriptionLines table is irrelevant
_usersManagementService.CreateUser(_webHttpContext.Session.PortalUser.UserName, isDualAccount);
}
if (user.Status == AccountStatus.Inactive)
{
//Account Re-Activation Logic
if (_usersManagementService.CreateAccountHistory(user))
{
user.FirstLogonOn = DateTime.Now;
user.DeactivatedOn = null;
user.Status = AccountStatus.Active;
user.IsDualAccount = isDualAccount;
_usersManagementService.UpdateAccount(user);
#region "Check XXX Dual Account"
try
{
if (_webHttpContext.Session.MultipleAccountDialogueInformed == false)
{
_webHttpContext.Session.MultipleAccountDialogueInformed = true;
if (user.IsDualAccount == true)
{
ViewBag.ShowXXXAccountPrompt = true;
}
else
{
ViewBag.ShowXXXAccountPrompt = false;
}
}
}
catch (Exception ex)
{
_logger.Log(LogLevel.Error, "XXX Account Service _ " + ex.Message, ex);
}
#endregion
}
else
{
ViewBag.IsErrored = "true";
return View(_webHttpContext.Account);
}
}
else
{
#region "Check XXX Dual Account"
try
{
if (_webHttpContext.Session.MultipleAccountDialogueInformed == false)
{
_webHttpContext.Session.MultipleAccountDialogueInformed = true;
if (user.IsDualAccount == true)
{
ViewBag.ShowXXXAccountPrompt = true;
}
else
{
ViewBag.ShowXXXAccountPrompt = false;
}
}
}
catch (Exception ex)
{
_logger.Log(LogLevel.Error, "XXX Account Service _ " + ex.Message, ex);
}
#endregion
}
_webHttpContext.BrowserDetails.OperatingSystem = Entities.OperatingSystem.MacinXXXh;
_webHttpContext.Session.PortalUser.Id = user.Id;
if (_webHttpContext.BrowserDetails.OperatingSystem == Entities.OperatingSystem.Windows)
{
ViewBag.ProductType = "ZZZ";
var YYYInstallsDetails = GetYYYInstallsDetails(0);
ViewBag.RemainingInstallCount = YYYInstallsDetails.NumberOfSeatsAvailable;
ViewBag.YYYInstallsDetails = YYYInstallsDetails.YYYCustomersLicenseDetailsList;
ViewBag.YYYInstallsDetailsCount = YYYInstallsDetails.YYYCustomersLicenseDetailsList.Count;
ViewBag.DownloadPageUrl = getDownloadPageUrl(ProductType.ComputerProtectionNT);
ViewBag.ProductId = (int)ProductType.ComputerProtectionNT;
}
else if (_webHttpContext.BrowserDetails.OperatingSystem == Entities.OperatingSystem.MacinXXXh)
{
ViewBag.ProductType = "MacZZZ";
var YYYInstallsDetails = GetYYYInstallsDetails(1);
ViewBag.RemainingInstallCount = YYYInstallsDetails.NumberOfSeatsAvailable;
ViewBag.YYYInstallsDetails = YYYInstallsDetails.YYYCustomersLicenseDetailsList;
ViewBag.YYYInstallsDetailsCount = YYYInstallsDetails.YYYCustomersLicenseDetailsList.Count;
ViewBag.DownloadPageUrl = getDownloadPageUrl(ProductType.ComputerProtectionOSX);
ViewBag.ProductId = (int)ProductType.ComputerProtectionOSX;
}
else if (_webHttpContext.BrowserDetails.OperatingSystem == Entities.OperatingSystem.Other)
{
ViewBag.ProductType = "AndroidZZZ";
var YYYInstallsDetails = GetYYYInstallsDetails(2);
ViewBag.RemainingInstallCount = YYYInstallsDetails.NumberOfSeatsAvailable;
ViewBag.YYYInstallsDetails = YYYInstallsDetails.YYYCustomersLicenseDetailsList;
ViewBag.YYYInstallsDetailsCount = YYYInstallsDetails.YYYCustomersLicenseDetailsList.Count;
ViewBag.DownloadPageUrl = getDownloadPageUrl(ProductType.ComputerProtectionAndroid);
ViewBag.ProductId = (int)ProductType.ComputerProtectionAndroid;
}
ViewBag.ZZZInstallUrl = PortalConfig.ZZZInstallUrl;
ViewBag.ScInstallUrl = PortalConfig.SafeCentralInstallUrl;
ViewBag.MacZZZInstallUrl = PortalConfig.MacZZZInstallUrl;
ViewBag.TTTTEmail = _webHttpContext.Session.PortalUser.UserName;
}
else // if primary username coming back from sso is empty
{
return RedirectToAction("signout", "Federation");
}
}
else // if the portal user is null
{
return RedirectToAction("signout", "Federation");
}
}
catch (Exception ex)
{
ViewBag.IsErrored = "true";
_logger.Log(LogLevel.Error, ex.Message, ex);
}
return View(_webHttpContext.Account);
}

How to read modelstate errors when returned by Json?

How can I display ModelState errors returned by JSON?
I want to do something like this:
if (!ValidateLogOn(Name, currentPassword))
{
ModelState.AddModelError("_FORM", "Username or password is incorrect.");
//Return a json object to the javascript
return Json(new { ModelState });
}
What must be my code in the view to read the ModelState errors and display them?
My actual code in the view to read the JSON values is as follows:
function createCategoryComplete(e) {
var obj = e.get_object();
alert(obj.Values);
}
This is draft code but the same idea works for me in production.
The main idea here is that Json errors have predefined tag names, that no normal objects will have. For errors validation errors HTML is re-created using JavaScript (both top summary and form elements highlighting).
Server side:
public static JsonResult JsonValidation(this ModelStateDictionary state)
{
return new JsonResult
{
Data = new
{
Tag = "ValidationError",
State = from e in state
where e.Value.Errors.Count > 0
select new
{
Name = e.Key,
Errors = e.Value.Errors.Select(x => x.ErrorMessage)
.Concat(e.Value.Errors.Where(x => x.Exception != null).Select(x => x.Exception.Message))
}
}
};
}
in action:
if (!ModelState.IsValid && Request.IsAjaxRequest())
return ModelState.JsonValidation();
Client side:
function getValidationSummary() {
var el = $(".validation-summary-errors");
if (el.length == 0) {
$(".title-separator").after("<div><ul class='validation-summary-errors ui-state-error'></ul></div>");
el = $(".validation-summary-errors");
}
return el;
}
function getResponseValidationObject(response) {
if (response && response.Tag && response.Tag == "ValidationError")
return response;
return null;
}
function CheckValidationErrorResponse(response, form, summaryElement) {
var data = getResponseValidationObject(response);
if (!data) return;
var list = summaryElement || getValidationSummary();
list.html('');
$.each(data.State, function(i, item) {
list.append("<li>" + item.Errors.join("</li><li>") + "</li>");
if (form && item.Name.length > 0)
$(form).find("*[name='" + item.Name + "']").addClass("ui-state-error");
});
}
$.ajax(... function(response) {
CheckValidationErrorResponse(xhr.responseText); } );
Why not return the original ModelState object to the client, and then use jQuery to read the values. To me it looks much simpler, and uses the common data structure (.net's ModelState)
C#:
return Json(ModelState);
js:
var message = "";
if (e.response.length > 0) {
$.each(e.response, function(i, fieldItem) {
$.each(fieldItem.Value.Errors, function(j, errItem) {
message += errItem.ErrorMessage;
});
message += "\n";
});
alert(message);
}
this is a tiny tweak to queen3's client side code which handles specific validation messages, and creates a similar document to that created by MVC3:
function getValidationSummary() {
var $el = $(".validation-summary-errors > ul");
if ($el.length == 0) {
$el = $("<div class='validation-summary-errors'><ul></ul></div>")
.hide()
.insertBefore('fieldset:first')
.find('ul');
}
return $el;
}
function getResponseValidationObject(response) {
if (response && response.Tag && response.Tag == "ValidationError")
return response;
return null;
}
function isValidationErrorResponse(response, form, summaryElement) {
var $list,
data = getResponseValidationObject(response);
if (!data) return false;
$list = summaryElement || getValidationSummary();
$list.html('');
$.each(data.State, function (i, item) {
var $val, lblTxt, errorList ="";
if (item.Name) {
$val = $(".field-validation-valid,.field-validation-error")
.first("[data-valmsg-for=" + item.Name + "]")
.removeClass("field-validation-valid")
.addClass("field-validation-error");
$("input[name=" + item.Name + "]").addClass("input-validation-error")
lblTxt = $("label[for=" + item.Name + "]").text();
if (lblTxt) { lblTxt += ": "; }
}
if ($val.length) {
$val.text(item.Errors.shift());
if (!item.Errors.length) { return; }
}
$.each(item.Errors, function (c,val) {
errorList += "<li>" + lblTxt + val + "</li>";
});
$list.append(errorList);
});
if ($list.find("li:first").length) {$list.closest("div").show(); }
return true;
}
See below for code with a few amendments to Brent's answer. CheckValidationErrorResponse looks for the Validation Summary regardless of whether it's in the valid or invalid state, and inserts it if not found. If validation errors are found in the response, it applies the validation-summary-errors class to the Summary, else it applies validation-summary-valid. It assumes CSS is present to control the visibility of the Summary.
The code clears existing instances of field-validation-error, and reapplies them for errors found in the response.
function getValidationSummary(form) {
var $summ = $(form).find('*[data-valmsg-summary="true"]');
if ($summ.length == 0)
{
$summ = $('<div class="validation-summary-valid" data-valmsg-summary="true"><ul></ul></div>');
$summ.appendTo(form);
}
return $summ;
}
function getValidationList(summary) {
var $list = $(summary).children('ul');
if ($list.length == 0) {
$list = $('<ul></ul>');
$list.appendTo(summary);
}
return $list;
}
function getResponseValidationErrors(data) {
if (data && data.ModelErrors && data.ModelErrors.length > 0)
return data.ModelErrors;
return null;
}
function CheckValidationErrorResponse(data, form, summaryElement) {
var errors = getResponseValidationErrors(data);
var $summ = summaryElement || getValidationSummary(form);
var $list = getValidationList($summ);
$list.html('');
$(form).find(".field-validation-error")
.removeClass("field-validation-error")
.addClass("field-validation-valid");
if (!errors)
{
$summ.removeClass('validation-summary-errors').addClass('validation-summary-valid');
return false;
}
$.each(errors, function (i, item) {
var $val, $input, errorList = "";
if (item.Name) {
$val = $(form).find(".field-validation-valid, .field-validation-error")
.filter("[data-valmsg-for=" + item.Name + "]")
.removeClass("field-validation-valid")
.addClass("field-validation-error");
$input = $(form).find("*[name='" + item.Name + "']");
if (!$input.is(":hidden") && !$val.length)
{
$input.parent().append("<span class='field-validation-error' data-valmsg-for='" + item.Name + "' data-valmsg-replace='false'>*</span>");
}
$input.addClass("input-validation-error");
}
$.each(item.Errors, function (c, err) {
errorList += "<li>" + err + "</li>";
});
$list.append(errorList);
});
$summ.removeClass('validation-summary-valid').addClass('validation-summary-errors');
return true;
}
C#
public class ValidateModelAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(HttpActionContext actionContext)
{
if (actionContext.ModelState.IsValid == false)
{
actionContext.Response = actionContext.Request.CreateErrorResponse(
HttpStatusCode.BadRequest, actionContext.ModelState);
}
}
}
JavaScript
$.ajax({
type: "GET",
url: "/api/xxxxx",
async: 'false',
error: function (xhr, status, err) {
if (xhr.status == 400) {
DisplayModelStateErrors(xhr.responseJSON.ModelState);
}
},
....
function DisplayModelStateErrors(modelState) {
var message = "";
var propStrings = Object.keys(modelState);
$.each(propStrings, function (i, propString) {
var propErrors = modelState[propString];
$.each(propErrors, function (j, propError) {
message += propError;
});
message += "\n";
});
alert(message);
};
If you are returning JSON, you cannot use ModelState. Everything that the view needs should be contained inside the JSON string. So instead of adding the error to the ModelState you could add it to the model you are serializing:
public ActionResult Index()
{
return Json(new
{
errorControl = "_FORM",
errorMessage = "Username or password is incorrect.",
someOtherProperty = "some other value"
});
}

Resources