session value timeout - asp.net-mvc-3

i am building a site with a login page and want to prevent user from login after 5 try fails for 20 min
maybe one way is this
const int maxTryCount = 5;
const int minutesToSuspend = 20;
[HttpPost]
public ActionResult Index(PeopleAccount account, string returnUrl)
{
if (Session["TimeStamp"] == null || ((DateTime)Session["TimeStamp"]).AddMinutes(minutesToSuspend) <= DateTime.Now)
{
PeopleAccountService service = new PeopleAccountService();
DataSet ds = service.Authentication(account.UserName, account.Password, null, null);
if (ds.Tables[1].Rows.Count > 0)
{
FormsAuthentication.SetAuthCookie(account.UserName, false);
Session.Clear();
Session["UserAccressibility"] = ds.Tables[0];
Session["UserFullName"] = ds.Tables[1].Rows[0][0];
if (returnUrl != null && returnUrl.Length > 1 && returnUrl.StartsWith("/") && !returnUrl.StartsWith("//") && !returnUrl.StartsWith("/\\"))
return Redirect(returnUrl);
return RedirectToAction("Index", "Stuff", null);
}
else
{
Session["TryCount"] = (Session["TryCount"] == null
|| (Session["TimeStamp"] != null && ((DateTime)Session["TimeStamp"]).AddMinutes(minutesToSuspend) <= DateTime.Now)) ?
1 : ((int)Session["TryCount"]) + 1;
if ((int)Session["TryCount"] > maxTryCount)
{
Session["TimeStamp"] = DateTime.Now;
return Redirect("~/UnauthorizedAccess/Index");
}
ModelState.AddModelError("", Paymankaran.Content.Messages.InvalidUsernameAndOrPassword);
ModelState.AddModelError("", string.Format(Paymankaran.Content.Messages.TryCountWarning,
Session["TryCount"], maxTryCount, minutesToSuspend));
return View();
}
}
return Redirect("~/UnauthorizedAccess/Index");
}
}
in fact i am using Session["TimeStamp"] and Session["TryCount"] variables to implement this functionality
is there a better or more secure way?
is this a good way to achieve this functionality?

Using Asp.net membership provider would give you this feature (and much more) for free.

Related

LinqToTwitter: How to return more than 20 followers?

How can I modify this query to return all of a users followers as this only returns 20?
var friendship = await twitterCtx.Friendship.Where(f => f.Type == FriendshipType.FollowersList)
.Where(f => f.ScreenName == "JoeBloggs")
.SingleOrDefaultAsync();
if (friendship != null && friendship.Users != null)
friendship.Users.ForEach(friend =>
Console.WriteLine(
"ID: {0} Name: {1}",
friend.UserIDResponse, friend.ScreenNameResponse));
(I can see there is a Cursor property which is a long for paging results but I haven't been able to work out how to use it.)
From searching around and reading the Twitter API documentation about Rate Limits I have the following which is working fine:
public async Task<IEnumerable<ulong>> GetAllFollowers(string userID)
{
var allFollowerIds = new List<ulong>();
Friendship followers;
long cursor = -1;
do
{
try
{
followers =
await
(from follower in twitterCtx.Friendship
where follower.Type == FriendshipType.FollowerIDs &&
follower.UserID == userID &&
follower.Cursor == cursor &&
follower.Count == 5000
select follower)
.SingleOrDefaultAsync();
}
catch (TwitterQueryException tqe)
{
Console.WriteLine(tqe.ToString());
break;
}
if (followers != null &&
followers.IDInfo != null &&
followers.IDInfo.IDs != null)
{
cursor = followers.CursorMovement.Next;
allFollowerIds.AddRange(followers.IDInfo.IDs);
}
} while (cursor != 0);
return allFollowerIds;
}
This will return a maximum of 75,000 followers for a user authorized application. This is because there's a cap of 15 requests for this particular endpoint. You can make another batch of requests after 15 minutes has passed.
I haven't tried myself but if you need to pull down more followers then that for a particular user you should be able to do so by simply calling this method again with the last cursor value being fed in as the starting value.

Unable to request an A/C through user console in Tivoli identity manager 5.1

I want to understand how ACL's works in Tivoli Identity Manager. I am trying to request for an a/c on a service from a user console but getting an error :
" The request cannot be submitted because the synchronization password does not comply with the password rules that govern the service. Change or reset the synchronization password to comply with the following password rules."
I have set default password to "12345" in provisioning policy and password length from 0 to 8 in password policy and have grant 'ADD' operation in ACL, still dont know what wrong am i doing. pLease suggest
Below is the rule under default Identity policy for ITIM.
function createIdentity() {
var EXISTING_CASE=0;
var UPPER_CASE=1;
var LOWER_CASE=2;
var tf = false;
var identity = "";
var baseidentity = "";
var counter = 0;
var locale = subject.getProperty("erlocale");
var fAttrKey = "uid";
var sAttrKey = "";
var idx1 = 0;
var idx2 = 0;
var fCase = 2;
var sCase = 2;
if ((locale != null) && (locale.length > 0)) {
locale = locale[0];
}
if (locale == null || locale.length == 0)
locale = "";
var firstAttribute = "";
var secondAttribute = "";
if (((fAttrKey != null) && (fAttrKey.length > 0)) || ((sAttrkey != null) && (sAttrkey.length > 0))) {
if ((fAttrKey != null) && (fAttrKey.length > 0)) {
firstAttribute = subject.getProperty(fAttrKey);
if (((firstAttribute != null) && (firstAttribute.length > 0)))
firstAttribute = firstAttribute[0];
if (firstAttribute == null || firstAttribute.length == 0)
firstAttribute = "";
else {
firstAttribute=IdentityPolicy.resolveAttribute(fAttrKey,firstAttribute);
if ((idx1>firstAttribute.length) || (idx1==0))
idx1=firstAttribute.length;
firstAttribute = firstAttribute.substring(0,idx1);
}
if (fCase == UPPER_CASE)
firstAttribute = firstAttribute.toUpperCase(locale);
else if (fCase == LOWER_CASE)
firstAttribute = firstAttribute.toLowerCase(locale);
}
if ((sAttrKey != null) && (sAttrKey.length > 0)) {
secondAttribute = subject.getProperty(sAttrKey);
if (((secondAttribute != null) && (secondAttribute.length > 0)))
secondAttribute = secondAttribute[0];
if (secondAttribute == null || secondAttribute.length == 0)
secondAttribute = "";
else {
secondAttribute=IdentityPolicy.resolveAttribute(sAttrKey,secondAttribute);
if ((idx2>secondAttribute.length) || (idx2==0))
idx2=secondAttribute.length;
secondAttribute = secondAttribute.substring(0,idx2);
}
if (sCase == UPPER_CASE)
secondAttribute = secondAttribute.toUpperCase(locale);
else if (sCase == LOWER_CASE)
secondAttribute = secondAttribute.toLowerCase(locale);
}
baseidentity = firstAttribute + secondAttribute;
}
if ((baseidentity == null) || (baseidentity.length == 0)) {
var givenname = subject.getProperty("givenname");
if (((givenname != null) && (givenname.length > 0)))
givenname = givenname[0];
if(givenname == null || givenname.length == 0)
givenname = "";
else
givenname = givenname.substring(0,1);
baseidentity = givenname + subject.getProperty("sn")[0];
}
tf = IdentityPolicy.userIDExists(baseidentity, false, false);
if (!tf)
return baseidentity;
while (tf) {
counter+=1;
identity = baseidentity + counter;
tf = IdentityPolicy.userIDExists(identity, false, false);
}
return identity;
}
return createIdentity();
I am going to assume when you are requesting access you don't already have an account for the service. Hence, it is trying to create a new account for that service before provisioning the access. When the new account is created, it will use the password from the identity for the service if you have global password synchronization turned on.
The password set on the identity (erSynchPassword) does not meet the password requirements for the individual service. Try changing the password on the identity and make sure that the password meets the service's password requirements. Or, temporarily for testing, disable the password policy that applies to that service and attempt to request access.
If this is a development question, personally I would disable all password policies temporarily to determine if the problem is really a password policy issue. That is the easiest way to troubleshoot the error you are seeing.

ArrayIndex is not supported in LINQ to Entities

// update information from this reponse to database
public bool UpdatePassengerInformation(GetResponse response)
{
try
{
using (MyEntities context = new MyEntities())
{
var masterID = (from Id in context.BookMaster where Id.BookingId == response.BookingId select Id.MasterId).First();
if (masterID != null)
{
for (int i = 0; i < response.Book.Length; i++)
{
var passenger_info = from passenger in context.BookPassenger
where passenger.BookID == masterID &&
assenger.FirstName == response.Book[i].FirstName && passenger.LastName == response.Book[i].LastName select passenger;
// in below loop i got exception "The LINQ expression node type 'ArrayIndex' is not supported in LINQ to Entities."
foreach (BookPassenger book_passenger in passenger_info)
{
book_passenger.TicketId = response.Book[i].TicketId;
book_passenger.TicketNumber = response.Book[i].TicketNumber;
}
}
context.SaveChanges();
}
}
return true;
}
catch (Exception ex)
{
throw ex;
}
}
So don't use it in query, just assign a new variable and use this one.
for (int i = 0; i < response.Book.Length; i++)
{
var responseBook = response.Book[i];
var passenger_info = from passenger in context.BookPassenger
where passenger.BookID == masterID &&
assenger.FirstName == responseBook.FirstName && passenger.LastName == responseBook.LastName select passenger;
foreach (BookPassenger book_passenger in passenger_info)
{
book_passenger.TicketId = responseBook.TicketId;
book_passenger.TicketNumber = responseBook.TicketNumber;
}
}

How to unit test a jpa repository method?

I have coded a JPA repository method and I am now realizing it is impossible to unit test.
Can anyone please advise how to unit test the following method or how to refactor my repository so that it is unit-testable?
Here is the problematic method:
#Override
public List<Pli> findPlisByMultiField(String identifiant, Date dateReceptionFrom, Date dateReceptionTo, PaiementEnum paiement, AREnum ar, String numeroAR, FDVEnum FDV, ConteneurNum conteneurNum, StatutPli statut) {
log.debug("findPlisByMultiField");
CriteriaBuilder criteriaBuilder = em.getCriteriaBuilder();
CriteriaQuery<Pli> c = criteriaBuilder.createQuery(Pli.class);
Root<Pli> pli = c.from(Pli.class);
List<Predicate> criteria = new ArrayList<Predicate>();
if (identifiant != null && !identifiant.trim().equals("")) {
ParameterExpression<String> parameterIdentifiant = criteriaBuilder.parameter(String.class, "identifiant");
Predicate conditionIdentifiant = criteriaBuilder.like(pli.<String> get("identifiant"), parameterIdentifiant);
criteria.add(conditionIdentifiant);
}
if (dateReceptionFrom != null && dateReceptionTo != null) {
ParameterExpression<Date> parameterDateReceptionFrom = criteriaBuilder.parameter(Date.class, "dateReceptionFrom");
ParameterExpression<Date> parameterDateReceptionTo = criteriaBuilder.parameter(Date.class, "dateReceptionTo");
Predicate conditionDateReception = criteriaBuilder.between(pli.<Date> get("dateReception"), parameterDateReceptionFrom, parameterDateReceptionTo);
criteria.add(conditionDateReception);
}
if (paiement != null) {
if (paiement.equals(PaiementEnum.IsPaiement)) {
Predicate conditionPaiementEnum = criteriaBuilder.equal(pli.<PaiementEnum> get("paiement"), true);
criteria.add(conditionPaiementEnum);
} else {
Predicate conditionPaiementEnum = criteriaBuilder.equal(pli.<PaiementEnum> get("paiement"), false);
criteria.add(conditionPaiementEnum);
}
}
if (ar != null) {
if (ar.equals(AREnum.IsAR)) {
Predicate conditionAREnum = criteriaBuilder.equal(pli.<AREnum> get("AR"), true);
criteria.add(conditionAREnum);
} else {
Predicate conditionAREnum = criteriaBuilder.equal(pli.<AREnum> get("AR"), false);
criteria.add(conditionAREnum);
}
}
if (numeroAR != null && !numeroAR.trim().equals("")) {
ParameterExpression<String> parameterNumeroAR = criteriaBuilder.parameter(String.class, "numeroAR");
Predicate conditionNumeroAR = criteriaBuilder.like(pli.<String> get("numeroAR"), parameterNumeroAR);
criteria.add(conditionNumeroAR);
}
if (FDV != null) {
if (FDV.equals(FDVEnum.IsFDV)) {
Predicate conditionFDVEnum = criteriaBuilder.equal(pli.<FDVEnum> get("FDV"), true);
criteria.add(conditionFDVEnum);
} else {
Predicate conditionFDVEnum = criteriaBuilder.equal(pli.<FDVEnum> get("FDV"), false);
criteria.add(conditionFDVEnum);
}
}
if (conteneurNum != null) {
ParameterExpression<ConteneurNum> parameterConteneurNum = criteriaBuilder.parameter(ConteneurNum.class, "conteneurNum");
Predicate conditionConteneurNum = criteriaBuilder.equal(pli.<ConteneurNum> get("conteneurNum"), parameterConteneurNum);
criteria.add(conditionConteneurNum);
}
if (statut != null) {
ParameterExpression<StatutPli> parameterStatut = criteriaBuilder.parameter(StatutPli.class, "statut");
Predicate conditionStatut = criteriaBuilder.equal(pli.<StatutPli> get("statut"), parameterStatut);
criteria.add(conditionStatut);
}
if (criteria.size() == 0) {
return Pli.findAllPlis();
} else if (criteria.size() == 1) {
c.where(criteria.get(0));
} else {
c.where(criteriaBuilder.and(criteria.toArray(new Predicate[0])));
}
TypedQuery<Pli> q = em.createQuery(c);
if (identifiant != null && !identifiant.trim().equals("")) {
q.setParameter("identifiant", "%" + identifiant + "%");
}
if (dateReceptionFrom != null && dateReceptionTo != null) {
q.setParameter("dateReceptionFrom", dateReceptionFrom);
q.setParameter("dateReceptionTo", dateReceptionTo);
}
if (numeroAR != null && !numeroAR.trim().equals("")) {
q.setParameter("numeroAR", "%" + numeroAR + "%");
}
if (conteneurNum != null) {
q.setParameter("conteneurNum", conteneurNum);
}
if (statut != null) {
q.setParameter("statut", statut);
}
return q.getResultList();
}
Well, I don't think you will be able to Unit Test it as it's strictly specified, but you can make a test using an in memory database (look out for HSQL) so that the app don't need to actually go to the real database just for testing.
That way you will be able to create an automated test that could run inside JUnit for example, mocking maybe only some of the methods.

Windows Phone 7 UserExtendedProperties

After being directed here:
http://msdn.microsoft.com/en-us/library/microsoft.phone.info.userextendedproperties.getvalue%28v=VS.92%29.aspx
I tried the following code on my sideloaded application. All that was written out was the 000001 value.
I knew that would be the case in the emulator, but I was hoping to get a real value when it was on my phone. Any ideas?
int ANIDLength = 32;
int ANIDOffset = 2;
string result = string.Empty;
object anid;
if (UserExtendedProperties.TryGetValue("ANID", out anid))
{
if (anid != null && anid.ToString().Length >= (ANIDLength + ANIDOffset))
{
result = anid.ToString().Substring(ANIDOffset, ANIDLength);
}
else
{
result = "000001";
}
}
You need to remove 1 from the calculation of your length check to account for the substring operation working on a zero based index:
if (anid != null && anid.ToString().Length >= (ANIDLength + ANIDOffset - 1))
This works on my machine:
private string GetAnid()
{
object anidValue;
int ANIDLength = 32;
int ANIDOffset = 2;
if (UserExtendedProperties.TryGetValue("ANID", out anidValue))
{
if (anidValue != null && anidValue.ToString().Length >= (ANIDLength + ANIDOffset - 1))
{
return anidValue.ToString().Substring(ANIDOffset, ANIDLength);
}
else
{
return "???";
}
}
else
{
return "???";
}
}

Resources