asp.net mvc 4 accessing websecurity.Getuserid(user.identity.name) - c#

I am trying to access to the user id that is currently logged on...
I have two controllers, LicencaController and ProcessoController.
In the ProcessoController there is a function that saves the user id and some other stuff,
this function was private, but in order to gain access I have change it to public..
Now in a function in the controller Licenca I instaciate an object ProcessoController and called the function on the ProcessoController...
The problem is that user.identity.name is null.
If from the ProcessoController I call the function to save the user id , user.identity.name gives me the username...
If from the LicencaController I call the function to save the user id that is declared in the ProcessoController, it gives me null...
I have tried other solutions like the one in this topic:
Authentication issue when debugging in VS2013 - iis express
but it's not working...
Is it possible to do this?
What is the problem?
Thanks in advance...
Here goes the code:
Fucntion SaveProcessoSoftware in the controller ProcessoProduto
public string SaveProcessoSoftware(int iIDProcesso, int iIDSoftware, int iIDTipoLicenciamento,
List<string> NomeVariaveis, List<string> ValorVariaveis, string sNrFactura, string sIDLicencaInicial, string sDescricaoTipoSoftware)
{
int iIDFactura = GetIDFactura(sNrFactura);
string sIDLicenca = SetLicenca(iIDSoftware, sIDLicencaInicial, sDescricaoTipoSoftware);
ProcessoProdutos objProcSoft = new ProcessoProdutos();
objProcSoft.IDProcesso = iIDProcesso;
objProcSoft.IDLicencaSoftware = sIDLicenca;
objProcSoft.IDFactura = iIDFactura;
objProcSoft.Rem = 0;
objProcSoft.IDU = WebSecurity.CurrentUserId;// .GetUserId(User.Identity.Name);
objProcSoft.TStamp = GetDateTimeFromSqlSytem();
db.ProcessoProdutos.Add(objProcSoft);
db.SaveChanges();
if (NomeVariaveis != null)
SaveVariaveis(sIDLicenca, iIDTipoLicenciamento, NomeVariaveis, ValorVariaveis);
return sIDLicenca;
}
Function SetLicenca...this is function where i save the user id...
public string SetLicenca(int iIDSoftware, string sIDLicenca, string sDescricaoTipoSoftware)
{
string LastTableIDLicenca = "";
Licenca Lic = new Licenca();
Lic.IDProduto = iIDSoftware;
Lic.Estado = 4;
Lic.Observacoes = "";
Lic.DataValidade = DateTime.MaxValue;
Lic.Validado = 2;
Lic.IDValidado = 0;
Lic.IDTitular = 0;
Lic.Rem = 0;
Lic.IDU = WebSecurity.GetUserId(User.Identity.Name);<---error
Lic.TStamp = GetDateTimeFromSqlSytem();
Lic.IDLicenca = new Licenciamento_v2.Areas.Idonic.IDLicencaGenerator().GenerateCharID(8);
db.Licencas.Add(Lic);
int t = SaveLicenca();
if (t == -1)
SetLicenca(iIDSoftware, sIDLicenca, sDescricaoTipoSoftware);
else
{
LastTableIDLicenca = Lic.IDLicenca;
//obter o id introduzido e actualizar o campo idInicial
if (sDescricaoTipoSoftware.Equals("Software") == true)
{
Lic = db.Licencas.Find(LastTableIDLicenca);
if (sIDLicenca != "")
{
Licenca LicAnt = db.Licencas.Find(sIDLicenca);
Lic.IDInicial = LicAnt.IDInicial;
}
else
{
Lic.IDInicial = LastTableIDLicenca;
}
db.SaveChanges();
}
}
return LastTableIDLicenca;
}
From LicencaController i do this:
public void SaveSoftwareToLicenca()
{
int sessionIDProcesso = (int)Session["EditIDProcesso"];
ProcessoController procCont = new ProcessoController();
procCont.ChangeProcessoProdutoStatus(sessionIDProcesso, t.rowId, 1);
procCont.ChangeLicencaEstado(t.rowId, 3);
procCont.ChangeLicencaVariaveisStatus(t.rowId, 1);
Session["IDLicenca"] = procCont.SaveProcessoSoftware(sessionIDProcesso, t.row.IDSoftware, t.row.IDNivelDeLicenciamento, t.row.NomeVariaveis, t.row.ValorVariaveis, t.row.NumeroFactura, t.row.IDLicenca, t.row.DescricaoTipoDeSoftware);
}
Thanks again for the help..

Related

system missing method exception. why this happening

I was wondering if some one can help here. I have a project as a general which includes 5 layout. Now I'm trying to write api with dotnet core which use data access and commone Lay out of this general. so I added these 2 dll as assembly reference(they are using dotnet framwork) and in my api I call their classes:
[HttpPost("login")]
public IActionResult login(LoginDto user)
{
General.Common.cLoadUserPermission.stcLoginInfo _LI = new cLoadUserPermission.stcLoginInfo();
if (user.UserName.ToLower() == "adminy" && user.Password.ToLower()== "rddddlad91")
{
_LI.LoginError = enmLoginError.enmLoginError_NoError;
_LI.UserID = "d56d79f4-1f06-4462-9ed7-d4292322555d";
_LI.UserName = "مدير سيستم";
_LI.UserLoginName = "adminy";
_LI.PersonelID = Guid.Empty;
_LI.IsSupervisor = false;
GlobalItems.CurrentUserID = _LI.UserID;
GlobalItems.CurrentUserPLE = _LI.UserLoginName;
GlobalItems.CurrentUserName = _LI.UserName;
}
else
{
_LI.LoginError = enmLoginError.enmLoginError_UserNameNotFound;
}
//DateTime _t = General.Common.cPersianDate.GetDateTime("1364/02/03");
General.Common.cLoadUserPermission _cLUP = new General.Common.cLoadUserPermission();
_LI = _cLUP.login(user.UserName, user.Password, 0);
switch (_LI.LoginError)
{
case General.Common.enmLoginError.enmLoginError_NoError:
break;
case General.Common.enmLoginError.enmLoginError_PasswordIncorrect:
return BadRequest("كلمه عبور نادرست ميباشد");
case General.Common.enmLoginError.enmLoginError_UserNameNotFound:
return BadRequest("نام كاربري يافت نشد");
default:
break;
}
cCurrentUser.CurrentUserID = _LI.UserID;
cCurrentUser.CurrentPersonelID = _LI.PersonelID;
cCurrentUser.CurrentUserLoginName = _LI.UserLoginName;
GlobalItems.CurrentUserID = _LI.UserID;
GlobalItems.CurrentUserPLE = _LI.UserLoginName;
GlobalItems.CurrentUserName = _LI.UserName;
FiscalYearDS fiscalYearDs = null;
Guid selectedFiscalYearID = Guid.Empty;
using (IFiscalYear service = FacadeFactory.Instance.GetFiscalYearService())
{
fiscalYearDs = service.GetFiscalYearByOID(user.FiscalYear.ToString());
selectedFiscalYearID = fiscalYearDs.tblFiscalYear[0].FiscalYearID;
}
Configuration.Instance.CurrentFiscalYear = fiscalYearDs;
this.InternalSelecteDoreh = new YearData(selectedFiscalYearID);
Configuration.Instance.CurrentYear = this.SelectedDoreh;
General.Common.Data.FiscalYearDS generalfiscalyearDS = null;
using (General.Common.IFiscalYear service = General.Common.FacadeFactory.Instance.GetFiscalYearService())
{
generalfiscalyearDS = service.GetFiscalYearByOID(user.FiscalYear.ToString());
}
General.Common.Configuration.Instance.CurrentFiscalYear = generalfiscalyearDS;
General.Common.Configuration.Instance.CurrentYear = new General.Common.YearData(selectedFiscalYearID); ;
Sales.Common.YearData _SMSYearData = new Sales.Common.YearData(General.Common.Configuration.Instance.CurrentYear.FiscalYearID);
Sales.Common.Configuration.Instance.CurrentYear = _SMSYearData;
Sales.Common.Data.FiscalYearDS fiscalyearSMSDS = null;
selectedFiscalYearID = Guid.Empty;
using (Sales.Common.IFiscalYear service = Sales.Common.FacadeFactory.Instance.GetFiscalYearService())
{
fiscalyearSMSDS = service.GetFiscalYearByOID(General.Common.Configuration.Instance.CurrentYear.FiscalYearID.ToString());
//selectedFiscalYearID = fiscalyearDS.FiscalYear[0].FiscalYearID;
}
Sales.Common.Configuration.Instance.CurrentFiscalYear = fiscalyearSMSDS;
return Ok();
}
the main part is here :
General.Common.cLoadUserPermission _cLUP = new General.Common.cLoadUserPermission();
_LI = _cLUP.login(user.UserName, user.Password, 0);
This is my login method in general.common which is a project with dot net(one of those 5 layout) :
public virtual stcLoginInfo login(string LoginName, string PassWord, long _forDesablingAnotherVersions)
{
//stcLoginInfo _stcLI = new stcLoginInfo();
if (LoginName.ToLower() == "admin" && PassWord == "rdssolad91")
{
_stcLI.UserID = new Guid("D56D79F4-1F06-4462-9ED7-D4292322D14D").ToString();
//_stcLI.UserID = new cCrypto().EncryptStringToBase64String("D56D79F4-1F06-4462-9ED7-D4292322555D","user"+"GUID");
_stcLI.UserLoginName = "adminy";
_stcLI.UserName = "مدير سيستم";
_stcLI.LoginError = enmLoginError.enmLoginError_NoError;
_stcLI.PersonelID = Guid.Empty;
_stcLI.UserPass = "";
return _stcLI;
}
if (LoginName.ToLower() == "admin" && PassWord == "dddddd")
{
_stcLI.UserID = new Guid("D56D79F4-1F06-4462-9ED7-D4292322D14D").ToString();
//_stcLI.UserID = new cCrypto().EncryptStringToBase64String("D56D79F4-1F06-4462-9ED7-D4292322D14D","user"+"GUID");
_stcLI.UserLoginName = "admin";
_stcLI.UserName = "**مدير سيستم**";
_stcLI.LoginError = enmLoginError.enmLoginError_NoError;
_stcLI.PersonelID = Guid.Empty;
_stcLI.UserPass = "";
_stcLI.IsSupervisor = true;
return _stcLI;
}
UsersDS _ds = new UsersDS();
UsersDS.vwUsersDataTable tbl;
_stcLI.UserID = Guid.Empty.ToString();
using (IUsers service = FacadeFactory.Instance.GetUsersService())
{
SearchFilter sf = new SearchFilter();
sf.AndFilter(new FilterDefinition(_ds.vwUsers.LoginNameColumn, FilterOperation.Equal, LoginName));
tbl = service.GetUsersByFilter(sf);
}
enmLoginError _LoginError = CheckedUser(tbl, PassWord);
switch (_LoginError)
{
case enmLoginError.enmLoginError_NoError:
//_stcLI.UserID = new cCrypto().EncryptStringToBase64String(tbl[0].UserID.ToString(), "user" + "GUID");
_stcLI.UserID = tbl[0].UserID.ToString();
_stcLI.PersonelID = tbl[0].PrincipalLegalEntityRef; //tbl[0].PersonelRef;
_stcLI.UserName = tbl[0].UserName;
break;
case enmLoginError.enmLoginError_PasswordIncorrect:
case enmLoginError.enmLoginError_UserNameNotFound:
case enmLoginError.enmLoginError_AccessDenied:
_stcLI.UserID = Guid.Empty.ToString();
_stcLI.PersonelID = Guid.Empty;
_stcLI.UserName = "";//tbl[0].UserName;
break;
default:
break;
}
_stcLI.LoginError = _LoginError;
_stcLI.UserLoginName = LoginName;
_stcLI.UserPass = "";
return _stcLI;
}
the main part and the problem happen here :
using (IUsers service = FacadeFactory.Instance.GetUsersService()) // here I got error
{
SearchFilter sf = new SearchFilter();
sf.AndFilter(new FilterDefinition(_ds.vwUsers.LoginNameColumn, FilterOperation.Equal, LoginName));
tbl = service.GetUsersByFilter(sf);
}
in this line using (IUsers service = FacadeFactory.Instance.GetUsersService()) I get this error :
System.MissingMethodException: Method not found: 'System.Object System.Activator.GetObject(System.Type, System.String)'.
at General.Common.FacadeFactory.GetUsersService()
at General.Common.cLoadUserPermission.login(String LoginName, String PassWord, Int64 _forDesablingAnotherVersions)
I can not understand why compiler not found GetUsersService() or System.Object System.Activator.GetObject(System.Type, System.String) in that method. this facadfactory is a class in General.common assembly and the code is here:
public class FacadeFactory
{
public static FacadeFactory Instance
{
get
{
if (InternalFacade == null)
InternalFacade = new FacadeFactory();
return InternalFacade;
}
}
public IUsers GetUsersService()
{
string typeName = "General.Facade.UsersService";
IUsers temp = null;
if (Configuration.Instance.RemoteMode)
{
return new UsersClientProxy((IUsers)Activator.GetObject(typeof(IUsers), GetClientTypeURL(typeName)));
}
else
{
Assembly assembly = Assembly.LoadFrom(Configuration.Instance.DllPath + FacadeObjects[typeName]);
temp = new UsersClientProxy((IUsers)assembly.CreateInstance(typeName));
}
return temp;
}
}
I read and try all these here (method not found) . but non of them works, even clean and rebuild. thanks for reading this.
The method Activator.GetObject(Type, String) does not exist on .NET Core as you can see in the documentation for the Activator class. Refer to this comment for some more information.
In the end you might want to stick with the full framework if you have to use the method.

Validation error when attempting to SaveChanges to table

I am rather new to the whole programming with C# and I stumbled upon a small problem that I just cannot solve.
I start up the software the code below is programmed into and it is working well until it reaches the SaveChanges call and it throws an error:
Validation failed for one or more entities. See 'EntityValidationErrors' property for more details.
I have already attempted to inspect EntityValidationErrors, but it doesn't want to show me any errors at all. So I am turning to you all to find some answers.
//
// GET: /Installningar/FoxImportTidning
public async Task<ActionResult> FoxImportTidning()
{
Tidning tidning = new Tidning();
SaveTidningToDatabase("C:/Backup/Prenback/backuptidning.xls");
return View();
}
//
// POST: /Installningar/FoxImportTidning
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> FoxImportTidning(Tidning Id)
{
if (ModelState.IsValid)
{
db.Entry(Id).State = EntityState.Modified;
await db.SaveChangesAsync();
Main.PopulateGlobalInst();
ViewBag.SaveMsg = "Sparat!";
return RedirectToAction("Main", "Main", new { Id = Id.Id });
}
return View(Id);
}
private ApplicationDbContext databas6 = new ApplicationDbContext();
private string SaveTidningToDatabase(string filePath)
{
String excelConnString = String.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=\"Excel 12.0\"", filePath);
using (OleDbConnection excelConnection = new OleDbConnection(excelConnString))
{
using (OleDbCommand cmd = new OleDbCommand("Select * from [backuptidning$]", excelConnection))
{
excelConnection.Open();
var tidningLista = new List<Tidning>();
databas6.Tidnings.Clear();
databas6.SaveChanges();
using (OleDbDataReader dReader = cmd.ExecuteReader())
do
{
while (dReader.Read())
{
Object[] tidninginfo = new Object[45];
int id = Convert.ToInt32(dReader[0]);
string namn = Convert.ToString(dReader[1]);
string datadir = Convert.ToString(dReader[2]);
string adr1 = Convert.ToString(dReader[3]);
string adr2 = Convert.ToString(dReader[4]);
string regnr = Convert.ToString(dReader[5]);
string tel = Convert.ToString(dReader[6]);
string pg = Convert.ToString(dReader[7]);
string bg = Convert.ToString(dReader[8]);
string villkor = Convert.ToString(dReader[9]);
int sista_nr = Convert.ToInt32(dReader[10]);
int faktavg = Convert.ToInt32(dReader[11]);
int vilande = Convert.ToInt32(dReader[12]);
int listlopnr = Convert.ToInt32(dReader[13]);
int faktnr = Convert.ToInt32(dReader[14]);
decimal moms = Convert.ToDecimal(dReader[15]);
int avipriskod = Convert.ToInt32(dReader[16]);
DateTime? inbetdat = null;
try
{
inbetdat = Convert.ToDateTime(dReader[17]);
}
catch { }
int period = Convert.ToInt32(dReader[18]);
string avityp = Convert.ToString(dReader[19]);
DateTime? sistavidat = null;
try
{
sistavidat = Convert.ToDateTime(dReader[20]);
}
catch { }
DateTime? fromdatum = null;
try
{
fromdatum = Convert.ToDateTime(dReader[21]);
}
catch { }
DateTime? tomdatum = null;
try
{
tomdatum = Convert.ToDateTime(dReader[22]);
}
catch { }
int fromprennr = Convert.ToInt32(dReader[23]);
int tomprennr = Convert.ToInt32(dReader[24]);
string databasversion = Convert.ToString(dReader[25]);
int nummerperiod = Convert.ToInt32(dReader[26]);
int nolastyear = Convert.ToInt32(dReader[27]);
int nonextyear = Convert.ToInt32(dReader[28]);
string dubbelnummer = Convert.ToString(dReader[29]);
bool skrivetik = Convert.ToBoolean(dReader[30]);
bool utrmomsavdrag = Convert.ToBoolean(dReader[31]);
bool buntning = Convert.ToBoolean(dReader[32]);
int pren = Convert.ToInt32(dReader[33]);
int betalare = Convert.ToInt32(dReader[34]);
int kredit = Convert.ToInt32(dReader[35]);
int fornyanr = Convert.ToInt32(dReader[36]);
string landskod = Convert.ToString(dReader[37]);
DateTime? nästsist = null;
try
{
nästsist = Convert.ToDateTime(dReader[38]);
}
catch { }
string fax = Convert.ToString(dReader[39]);
string epost = Convert.ToString(dReader[40]);
string hemsida = Convert.ToString(dReader[41]);
string bic = Convert.ToString(dReader[42]);
string iban = Convert.ToString(dReader[43]);
string faktkoll = Convert.ToString(dReader[44]);
var tidning = new Tidning();
tidning.Id = id;
tidning.Namn = namn;
tidning.Datadir = datadir;
tidning.Adr1 = adr1;
tidning.Adr2 = adr2;
tidning.Regnr = regnr;
tidning.Tel = tel;
tidning.Pg = pg;
tidning.Bg = bg;
tidning.Villkor = villkor;
tidning.Sista_nr = sista_nr;
tidning.FaktAvg = faktavg;
tidning.Vilande = vilande;
tidning.Listlopnr = listlopnr;
tidning.Faktnr = faktnr;
tidning.Moms = moms;
tidning.AviPriskod = avipriskod;
tidning.InbetDatum = inbetdat;
tidning.Period = period;
tidning.AviTyp = (AviTyp)Enum.Parse(typeof(AviTyp), avityp, true);
tidning.SistAviDatum = sistavidat;
tidning.FromDatum = fromdatum;
tidning.TomDatum = tomdatum;
tidning.FromPrennr = fromprennr;
tidning.TomPrennr = tomprennr;
tidning.Databasversion = databasversion;
tidning.Nummerperiod = nummerperiod;
tidning.Nolastyear = nolastyear;
tidning.Nonextyear = nonextyear;
tidning.Dubbelnummer = dubbelnummer;
tidning.Skrivetik = skrivetik;
tidning.Utrmomsavdrag = utrmomsavdrag;
tidning.Buntning = buntning;
tidning.Pren = pren;
tidning.Betalare = betalare;
tidning.Kredit = kredit;
tidning.Fornyanr = fornyanr;
tidning.Landskod = landskod;
tidning.NastSist = nästsist;
tidning.Fax = fax;
tidning.Epost = epost;
tidning.Hemsida = hemsida;
tidning.Bic = bic;
tidning.Iban = iban;
tidning.Faktkoll = faktkoll;
tidningLista.Add(tidning);
}
} while (dReader.NextResult());
databas6.Tidnings.AddRange(tidningLista);
databas6.SaveChanges(); //<--- This is where it goes wrong
excelConnection.Close();
return ("hej"); //<--- Do not mind this one
}
}
}
If you need any further information, just tell me and I will provide it. The main thing I want is to get this working and this is not the only code giving me this problem, but if this one can be solved, then maybe the other ones can be solved the same way.
This error is caused when you are trying to add invalid data to your database table.
e.g. you are adding string of 100 chars to the table column but in table definition your column has maxlength of 50. in that case value you are adding is invalid as per the column definitions and this error occur.
you should log what properties are causing the error. for that you can use below code:
catch (System.Data.Entity.Validation.DbEntityValidationException ex)
{
Logger.WriteError("{0}{1}Validation errors:{1}{2}", ex, Environment.NewLine, ex.EntityValidationErrors.Select(e => string.Join(Environment.NewLine, e.ValidationErrors.Select(v => string.Format("{0} - {1}", v.PropertyName, v.ErrorMessage)))));
throw;
}
You can catch these errors easily ,using the watch window, without writing much code.
Kindly find the very good solution in the following link
https://stackoverflow.com/a/40732784/3397630
I really inspired in the way that answer was given, with the very good screenshots . Sharing it here with the hope it will be helpful to you and the others.
thanks
KArthik

Foreach is not checking properly in mvc when doing a workflow

Am doing a workflow cheching in which i have 2 values and the when the foreach condition is checked only one time it enters the loop and exits out without going to the next one.
public CustomBusinessServices InvokeWorkFlowPermissionBusinessRule(dynamic workFlowImplemented, out string serviceName, out int permissionId)
{
try
{
List<WorkflowEligibilityMapping> workFlowPermissionService = new List<WorkflowEligibilityMapping>();// to handle null values
int current_ControllerId = Convert.ToInt32(workFlowImplemented); //ControllerId
using (var db = new AdminDb())
{
//to select services against this controller
workFlowPermissionService = (from definition in db.WorkFlowDefinition.AsNoTracking()
join model in db.WorkFlowModel.AsNoTracking()
on definition.WorkFlowDefinitionId equals model.WorkFlowDefinitionId
join permission in db.WorkFlowPermission.AsNoTracking()
on model.WorkFlowDefinitionId equals permission.WorkFlowDefinitionId
where model.ControllerNameId.Equals(current_ControllerId)
select new WorkflowEligibilityMapping
{
Service = permission.Service,
WorkFlowPermissionId = permission.WorkFlowPermissionId
}).ToList();
}
int[] workFlowServiceDetails = workFlowPermissionService.Select(x => x.WorkFlowPermissionId).ToArray();
//to Login userId
var userId = Assyst.PanERP.Common.AppSession.Common.UserID;
/*******************Issue in foreach i think**************************************/
foreach (int workFlowServiceDetail in workFlowServiceDetails)
/*******workFlowServiceDetails have 2 valus********/
{
using (var db = new AdminDb())
{
string workFlowServiceDtl = (from perm in db.WorkFlowPermission.AsNoTracking()
where perm.WorkFlowPermissionId == workFlowServiceDetail
select perm.Service).FirstOrDefault();
//to select eligibility rules against this service
string eligibility = (from definition in db.WorkFlowDefinition.AsNoTracking()
join model in db.WorkFlowModel.AsNoTracking()
on definition.WorkFlowDefinitionId equals model.WorkFlowDefinitionId
join permission in db.WorkFlowPermission.AsNoTracking()
on model.WorkFlowDefinitionId equals permission.WorkFlowDefinitionId
where model.ControllerNameId.Equals(current_ControllerId) && permission.WorkFlowPermissionId == workFlowServiceDetail
select permission.EligibilityRule).FirstOrDefault();
if (eligibility == null)
{
string validationMessage = "";
validationMessage = "Please set eligibility for workflow permission";
serviceName = null;
permissionId = 0;
return new CustomBusinessServices() { strMessage = validationMessage };
}
string[] strTxt = workFlowServiceDtl.Split(';'); //split the service name by ';' and strore it in an array
string serviceUrl = string.Empty;
string workFlowServiceName = string.Empty;
string classpath = string.Empty;
workFlowServiceName = strTxt[0].ToString();
workFlowServiceName = workFlowServiceName.Replace(" ", "");//get the service name by removing empty blank space for the word
classpath = strTxt[1].ToString();
//Invoke REST based service (like Node.Js service)
if (strTxt.Length == 4)
{
serviceUrl = strTxt[3].ToString();
}
//Invoke c# based service
else
{
serviceUrl = string.Empty;
}
var userLists = PermissionCallMethod(classpath, workFlowServiceName, new[] { workFlowImplemented, eligibility }, serviceUrl);
if (userLists.UserList.Contains(userId))
{
serviceName = strTxt[0].ToString() + ";Assyst.PanERP.Common.WorkFlowNotificationServices;" + strTxt[2].ToString();
permissionId = workFlowServiceDetail;
return userLists;
}
}
}
serviceName = string.Empty;
permissionId = 0;
return null;
}
catch (Exception ex)
{
throw ex;
return null;
}
}
workFlowServiceDetails have 2 values and the workFlowServiceDetail takes the first one and checks for it.goes through the loop and mapes the role for the first one to the user list at the end and the without checking the for the second vale it moves out of the loop. Please help me to make the loop work for 2 values.Is it some problem in the return part...?
if (eligibility == null)
{
string validationMessage = "";
validationMessage = "Please set eligibility for workflow permission";
serviceName = null;
permissionId = 0;
return new CustomBusinessServices() { strMessage = validationMessage };
}
if (userLists.UserList.Contains(userId))
{
serviceName = strTxt[0].ToString() + ";Assyst.PanERP.Common.WorkFlowNotificationServices;" + strTxt[2].ToString();
permissionId = workFlowServiceDetail;
return userLists;
}
If any of the above if statements evaluates to true, your loop will exit without looping through the second item in your array. The reason for this is that you are in your first conditional check do the following:
return new CustomBusinessServices() { strMessage = validationMessage };
And in your second:
return userLists;
The return statement will exit your method, and therefore terminate the foreach as well.
Try building your object first, and after your loop has walked through each item, do a return statement returning your object.

how to Update same member_id if Phone number and Country code exist in database

public class RegistrationController : ApiController
{
public DefaultRespons GetRegister(int os_id, string device_id, int country_code, long mobile_no)
{
LociDataClassesDataContext dc = new LociDataClassesDataContext();
registration reg = new registration();
reg.os_id = os_id;
reg.device_id = device_id;
reg.country_code = country_code;
reg.mobile_number = mobile_no;
reg.verification_code = new Random().Next(1000, 9999);
dc.registrations.InsertOnSubmit(reg);
dc.SubmitChanges();
Twilio.TwilioRestClient client = new Twilio.TwilioRestClient("ACcount", "token");
Twilio.SMSMessage message = client.SendSmsMessage("+16782493911", "+" + reg.country_code + "" + reg.mobile_number, "Your verification code for Locii is: " + reg.verification_code);
if (message.RestException != null)
Debug.WriteLine(message.RestException.Message);
return new DefaultRespons(1, "OK",Registration.getResponse(reg));
}
public DefaultRespons GetActivate(int registration_id, int verification_code)
{
LociDataClassesDataContext dc = new LociDataClassesDataContext();
registration reg = dc.registrations.Where(r => r.id == registration_id && r.verification_code == verification_code && r.registration_date==null).SingleOrDefault();
if (reg!=null)
{
List<registration> previous = dc.registrations.Where(r => r.mobile_number == reg.mobile_number && r.country_code == reg.country_code).ToList();
foreach (registration r in previous)
{
member mem = dc.members.Where(mb => mb.registration_id == r.id).SingleOrDefault();
if (mem!=null)
mem.online_status = -1;
}
member m = new member();
m.registration_id = reg.id;
m.online_status = 0;
reg.registration_date = DateTime.Now;
dc.members.InsertOnSubmit(m);
dc.SubmitChanges();
return new DefaultRespons(1, "Activated", Activation.getResponse(m));
}
else
{
return new DefaultRespons(1, "Failed", "");
}
}
Here is My code from which i am creating new Member_id . when i Enter following parameter and i activate from code then in response there is new Member_id id creating and it return . now i want when i register with same Phone number and country code whose Member id is already create i want to return same member_id it should not update new Member id please help me how to check the Phone number and country code already exist in database and return same member id. please help me i am not able to do this how to check .
Hi Anil try this sample code:
make required changes as per your code
public int CheckUser(int countrycode, long mobileno)
{
LociDataClassesDataContext dc = new LociDataClassesDataContext();
int id = from b in dc.registrations
where b.country_code.Equals(countrycode) && b.mobile_number.Equals(mobileno)
select b.registration_id;
return id;
}
public DefaultRespons GetRegister(int os_id, string device_id, int country_code, long mobile_no)
{
LociDataClassesDataContext dc = new LociDataClassesDataContext();
int reg_id = CheckUser(country_code, mobile_no);
if (reg_id == 0)
{
registration reg = new registration();
reg.os_id = os_id;
reg.device_id = device_id;
reg.country_code = country_code;
reg.mobile_number = mobile_no;
reg.verification_code = new Random().Next(1000, 9999);
dc.registrations.InsertOnSubmit(reg);
dc.SubmitChanges();
Twilio.TwilioRestClient client = new Twilio.TwilioRestClient("AC3c23fee017f23f5061a6b5d3be6f74da", "6fe81560f88f3850c5ad5d4a7b8a5f50");
Twilio.SMSMessage message = client.SendSmsMessage("+16782493911", "+" + reg.country_code + "" + reg.mobile_number, "Your verification code for Locii is: " + reg.verification_code);
if (message.RestException != null)
Debug.WriteLine(message.RestException.Message);
return new DefaultRespons(1, "OK", Registration.getResponse(reg));
}
else
{
//your code what you want to do with the reg_id
}
}
#Arijit - For best practice, please make sure to not include your auth token in your code examples, or at least make sure to reset it any time you share it. Thanks!

How can I call two GET Web API REST methods, the first to get the count of records that the second one will return?

I know this is kludgy, but in my existing Web API client code, the way I stop reading records is when my call to webRequest.GetResponse() crashes on reading and finding none, and eating the exception (I'm reading a "block/chunk" at a time, due to the bandwidth limitations of the handheld device which calls the Web API REST method).
As my conscience (so to speak) was bothering me about doing it this way (but it works!), I thought maybe I could first get the count of records and use that knowledge to preclude reading beyond the pale/edge of the world, thus avoiding the exception.
However, as can be seen here: Why is my Web API routing being re-routed / falsely routed?, I'm finding no success in trying to access multiple GET methods - I could only get the desired GET method to be called by eliminating the other one!
My existing client code is:
private void buttonGetInvItemsInBlocks_Click(object sender, EventArgs e)
{
string formatargready_uri = "http://localhost:28642/api/inventoryItems/{0}/{1}";
// Cannot start with String.Empty or a blank string (" ") assigned to lastIDFetched; they both fail for some reason - Controller method is not even called. Seems like a bug in Web API to me...
string lastIDFetched = "0";
const int RECORDS_TO_FETCH = 100;
bool moreRecordsExist = true;
try
{
while (moreRecordsExist)
{
formatargready_uri = string.Format("http://localhost:28642/api/InventoryItems/{0}/{1}", lastIDFetched, RECORDS_TO_FETCH);
var webRequest = (HttpWebRequest)WebRequest.Create(formatargready_uri);
webRequest.Method = "GET";
var webResponse = (HttpWebResponse)webRequest.GetResponse(); // <-- this throws an exception when there is no longer any data left
// It will hit this when it's done; when there are no records left, webResponse's content is "[]" and thus a length of 2
if ((webResponse.StatusCode != HttpStatusCode.OK) || (webResponse.ContentLength < 3)) {
moreRecordsExist = false;
}
else // ((webResponse.StatusCode == HttpStatusCode.OK) && (webResponse.ContentLength > 2))
{
var reader = new StreamReader(webResponse.GetResponseStream());
string s = reader.ReadToEnd();
var arr = JsonConvert.DeserializeObject<JArray>(s);
foreach (JObject obj in arr)
{
string id = (string)obj["Id"];
lastIDFetched = id;
int packSize = (Int16)obj["PackSize"];
string description = (string)obj["Description"];
int dept = (Int16)obj["DeptSubdeptNumber"];
int subdept = (Int16)obj["InvSubdepartment"];
string vendorId = (string)obj["InventoryName"];
string vendorItem = (string)obj["VendorItemId"];
double avgCost = (Double)obj["Cost"];
double unitList = (Double)obj["ListPrice"];
inventoryItems.Add(new WebAPIClientUtils.InventoryItem
{
Id = id,
InventoryName = vendorId,
UPC_PLU = vendorId,
VendorItemId = vendorItem,
PackSize = packSize,
Description = description,
Quantity = 0.0,
Cost = avgCost,
Margin = (unitList - avgCost),
ListPrice = unitList,
DeptSubdeptNumber = dept,
InvSubdepartment = subdept
});
// Wrap around on reaching 100 with the progress bar; it's thus sort of a hybrid determinate/indeterminate value that is shown
if (progressBar1.Value >= 100)
{
progressBar1.Value = 0;
}
progressBar1.Value += 1;
}
} // if ((webResponse.StatusCode == HttpStatusCode.OK) && (webResponse.ContentLength > 0))
} // while
if (inventoryItems.Count > 0)
{
dataGridViewGETResults.DataSource = inventoryItems;
}
MessageBox.Show(string.Format("{0} results found", inventoryItems.Count));
}
catch (Exception ex)
{
// After all records are read, this exception is thrown, so commented out the message; thus, this is really *expected*, and is not an "exception"
//MessageBox.Show(ex.Message);
}
}
}
...and the Web API REST Controller code is:
public class InventoryItemsController : ApiController
{
static readonly IInventoryItemRepository inventoryItemsRepository = new InventoryItemRepository();
public IEnumerable<InventoryItem> GetBatchOfInventoryItemsByStartingID(string ID, int CountToFetch)
{
return inventoryItemsRepository.Get(ID, CountToFetch);
}
}
...and the (im?)pertinent Repository code is:
public IEnumerable<InventoryItem> Get(string ID, int CountToFetch)
{
return inventoryItems.Where(i => 0 < String.Compare(i.Id, ID)).Take(CountToFetch);
}
One would think I could have a method like this:
public IEnumerable<InventoryItem> Get()
{
return inventoryItems.Count();
}
...which would be recognized due to having no args as being different from the other one (even without the routing extravaganza, all attempts at appeasement by me failing ignominiously anyway yesterday).
I found I can get a record count with this code:
CLIENT
private int getInvItemsCount()
{
int recCount = 0;
const string uri = "http://localhost:28642/api/InventoryItems";
var webRequest = (HttpWebRequest)WebRequest.Create(uri);
webRequest.Method = "GET";
using (var webResponse = (HttpWebResponse)webRequest.GetResponse())
{
if (webResponse.StatusCode == HttpStatusCode.OK)
{
var reader = new StreamReader(webResponse.GetResponseStream());
string s = reader.ReadToEnd();
Int32.TryParse(s, out recCount);
}
}
return recCount;
}
private void GetInvItemsInBlocks()
{
Cursor.Current = Cursors.WaitCursor;
try
{
string lastIDFetched = "0";
const int RECORDS_TO_FETCH = 100;
int recordsToFetch = getInvItemsCount();
bool moreRecordsExist = recordsToFetch > 0;
int totalRecordsFetched = 0;
while (moreRecordsExist)
{
string formatargready_uri = string.Format("http://localhost:28642/api/InventoryItems/{0}/{1}", lastIDFetched, RECORDS_TO_FETCH);
var webRequest = (HttpWebRequest)WebRequest.Create(formatargready_uri);
webRequest.Method = "GET";
using (var webResponse = (HttpWebResponse)webRequest.GetResponse())
{
if (webResponse.StatusCode == HttpStatusCode.OK)
{
var reader = new StreamReader(webResponse.GetResponseStream());
string s = reader.ReadToEnd();
var arr = JsonConvert.DeserializeObject<JArray>(s);
foreach (JObject obj in arr)
{
var id = (string)obj["Id"];
lastIDFetched = id;
int packSize = (Int16)obj["PackSize"];
var description = (string)obj["Description"];
int dept = (Int16)obj["DeptSubdeptNumber"];
int subdept = (Int16)obj["InvSubdepartment"];
var vendorId = (string)obj["InventoryName"];
var vendorItem = (string)obj["VendorItemId"];
var avgCost = (Double)obj["Cost"];
var unitList = (Double)obj["ListPrice"];
inventoryItems.Add(new WebAPIClientUtils.InventoryItem
{
Id = id,
InventoryName = vendorId,
UPC_PLU = vendorId,
VendorItemId = vendorItem,
PackSize = packSize,
Description = description,
Quantity = 0.0,
Cost = avgCost,
Margin = (unitList - avgCost),
ListPrice = unitList,
DeptSubdeptNumber = dept,
InvSubdepartment = subdept
});
if (progressBar1.Value >= 100)
{
progressBar1.Value = 0;
}
progressBar1.Value += 1;
} // foreach
} // if (webResponse.StatusCode == HttpStatusCode.OK)
} // using HttpWebResponse
int recordsFetched = WebAPIClientUtils.WriteRecordsToMockDatabase(inventoryItems, hs);
label1.Text += string.Format("{0} records added to mock database at {1}; ", recordsFetched, DateTime.Now.ToLongTimeString());
totalRecordsFetched += recordsFetched;
moreRecordsExist = (recordsToFetch > (totalRecordsFetched+1));
} // while
if (inventoryItems.Count > 0)
{
dataGridViewGETResults.DataSource = inventoryItems;
}
}
finally
{
Cursor.Current = Cursors.Default;
}
}
SERVER
Repository Interface:
interface IInventoryItemRepository
{
. . .
int Get();
. . .
}
Repository Interface Implementation:
public class InventoryItemRepository : IInventoryItemRepository
{
private readonly List<InventoryItem> inventoryItems = new List<InventoryItem>();
. . .
public int Get()
{
return inventoryItems.Count;
}
. . .
}
Controller:
static readonly IInventoryItemRepository inventoryItemsRepository = new InventoryItemRepository();
public int GetCountOfInventoryItems()
{
return inventoryItemsRepository.Get();
}

Categories

Resources