I m creating library for my test projects.
Namespace is not working when i create library project.
Please help
#region(GET LOGGED USER ID)
static public Guid GetUserId()
{
Guid guUser = Guid.Empty;
try
{
MembershipUser muUser = Membership.GetUser();
if (muUser != null)
{
guUser = (Guid)muUser.ProviderUserKey;
Membership.GetUser(guUser, true);
}
else
{
//Log out and redirect to login page
FormsAuthentication.SignOut();
FormsAuthentication.RedirectToLoginPage();
}
}
catch (Exception ex)
{
ApplicationError.LogErrors(ex);
}
return guUser;
}
#endregion
This won't work if tested in a unit test solution, because your unit test solution must have the same .config file as the final application project. Otherwise it works perfectly.
Related
So my problem is like that, When I am trying to pass the model in repository method on controller I getting error like this Object reference not set to an instance of an object.
Please help me to solve my issue. Thankyou
Please click on the image right below for your refer.
Please Refer this picture to understand my problem.
public UserController()
{
}
public IUser _userObj;
public UserController(IUser userObj)
{
_userObj = userObj;
}
[HttpPost]
public async Task<ActionResult> AddUser(UserModel model)
{
bool isError = true;
var message = string.Empty;
try
{
if (ModelState.IsValid)
{
var res = await _userObj.AddUser(model);
isError = false;
if (res > 0)
{
message = "Sucess";
isError = false;
}
}
return Json(new
{
IsError = isError,
Message = message
}, JsonRequestBehavior.AllowGet);
}
catch (Exception e)
{
return Json(new
{
IsError = isError
}, JsonRequestBehavior.AllowGet);
}
}
If you are using IoC container like Autofac, register your controller and set your dependency resolver. Check this link https://autofaccn.readthedocs.io/en/latest/integration/mvc.html#quick-start.
You need to add dependency injection for your Interface in Startup.cs file.
In Startup.cs file inside ConfigureService method add
services.AddScoped<IUser, User>();
I am doing an app in which i am calling a web api. I am getting task cancel exception when i call the api in iPad/iPhone.But the response is fine in simulator and android devices.Can anyone please help me in resolving the issue.I am not able to fine where it is going wrong.
Thanks in advance.
Try using Native Http Handler to see it improves.
Declare an interface.
public interface IHttpHandler
{
HttpClient ReturnHandler();
}
Implement it this way.
public class HttpHandler : IHttpHandler
{
public HttpClient ReturnHandler()
{
try
{
var client = new HttpClient(new NSUrlSessionHandler()
{
});
client.Timeout = TimeSpan.FromSeconds(120);
return client;
}
catch (TaskCanceledException ex)
{
Console.WriteLine("TaskCanceledException ReturnHandler-->" + ex.Message);
if (ex.InnerException != null)
{
Console.WriteLine("TaskCanceledException ReturnHandler-->" + ex.InnerException.Message);
}
return null;
}
catch (Exception ex)
{
Console.WriteLine("ReturnHandler Exception-->" + ex.Message);
if (ex.InnerException != null)
{
Console.WriteLine("ReturnHandler Exception-->" + ex.InnerException.Message);
}
return null;
}
}
}
Use Xamarin forms inbuilt Dependency injection to utilise the interface I gave you to have HTTPClient with native handler.
If you don't know how to read Here
Here are my project details
A web-API project containing webapi controllers
I have a separate c# Library project that contains models for my webapi and some method and api for intracting with database.
settings in webconfig
<httpRuntime targetFramework="4.5"/>
<add key="aspnet:UseTaskFriendlySynchronizationContext" value="true"/>
Issue: HttpContext.Current.user is null.I want to access Httpcontext.Current.user in my c# library project.
1.In the code snippet below HttpContext.Current.user is available.This method exist in webapi project.
[HttpPost]
public async Task<IHttpActionResult> Post([FromBody]TEntity entity)
{
System.Security.Principal.IPrincipal p = System.Threading.Thread.CurrentPrincipal;
// context is available till here
var context =HttpContext.Current.User;
return await Task<IHttpActionResult>.Run(() =>
{
if (!ModelState.IsValid)
{
return (IHttpActionResult)Content(HttpStatusCode.BadRequest, ModelState.ToUnexpectedResultWrapper());
}
try
{
TOrchestrator orchestrator = new TOrchestrator();
orchestrator.Insert(entity);
}
catch (ValidationException ex)
{
return Content(HttpStatusCode.BadRequest, ex.ToUnexpectedResultWrapper());
}
catch (DbEntityValidationException ex)
{
return Content(HttpStatusCode.BadRequest, ex.ToUnexpectedResultWrapper());
}
return CreatedAtRoute("REST", new { id = entity.Id }, entity);
});
}
2.In code snippet below that exist in C# library. HttContext.Current.user is null. this method is called from the above method "Post".
public void Insert(Market market)
{
// Context is
System.Security.Principal.IPrincipal p = System.Threading.Thread.CurrentPrincipal;
//IOATIApplicationUser user = UserContextHelper.GetOATIContext().OATIUser;
var http = HttpContext.Current.User;
RunAction<InsertAction, Market>(market);
}
More over I could access user object from System.Threading.Thread.CurrentPrincipal.
If I cant access user object from HttpContext. Can i user System> System.Threading.Thread.CurrentPrincipal. I have heard it is not safe to user "System.Threading.Thread.CurrentPrincipal" and it is ment for window forms only.
HttpContext.Current returns the current HttpContext being serviced by the calling thread. When you start a background task by using Task.Run, it is not associated with an HTTP context by design.
Since you should not be using Task.Run on ASP.NET anyway, removing it is the easiest solution:
[HttpPost]
public IHttpActionResult Post([FromBody]TEntity entity)
{
if (!ModelState.IsValid)
{
return (IHttpActionResult)Content(HttpStatusCode.BadRequest, ModelState.ToUnexpectedResultWrapper());
}
try
{
TOrchestrator orchestrator = new TOrchestrator();
orchestrator.Insert(entity);
}
catch (ValidationException ex)
{
return Content(HttpStatusCode.BadRequest, ex.ToUnexpectedResultWrapper());
}
catch (DbEntityValidationException ex)
{
return Content(HttpStatusCode.BadRequest, ex.ToUnexpectedResultWrapper());
}
return CreatedAtRoute("REST", new { id = entity.Id }, entity);
}
I built a module into my MVC site that allows administrators to create, modify and delete website users. However, I can not seem to update user information via the following code:
[HttpPost]
public ActionResult Edit(User user)
{
if (ModelState.IsValid)
{
try
{
//CHANGE EXISTING USER
MembershipUser siteUser = Membership.GetUser(user.Username);
siteUser.Email = user.Email;
siteUser.IsApproved = true;
siteUser.Comment = "User Update on " + DateTime.UtcNow;
siteUser.UnlockUser();
Membership.UpdateUser(siteUser);
if (!String.IsNullOrEmpty(user.Password))
{
siteUser.ChangePassword(siteUser.GetPassword(), user.Password);
}
unitOfWork.UsersRepository.Update(user);
unitOfWork.Save();
return RedirectToAction("Index");
}
catch (Exception err)
{
// CODE REMOVED FOR BREVITY
}
}
return View(user);
}
Any suggestions?
After further testing, it would appear that one line was causing the user information to reset.
siteUser.UnlockUser();
This line can not be called prior to saving user alterations via Membership.UpdateUser() or the changes will be lost. Hopefully this saves somebody some head scratching.
I have a code base web application that is connected to 2 databases. Depending on which login control a user uses to login, a different database is connected to the code. I am doing all of this by a cookie. This cookie is in a public class called AuthenticatedUser. The class looks like this:
public class AuthenticatedUser : System.Web.UI.Page
{
public static string ConnectionString
{
get
{
HttpCookie myCookie = HttpContext.Current.Request.Cookies["connectionString"];
return GetConnectionStringFromName(myCookie);
}
set
{
if (HttpContext.Current.Request.Cookies["connectionString"] != null)
{
ExpireCookies(HttpContext.Current);
}
var allCookies = HttpContext.Current.Request.Cookies.AllKeys;
HttpCookie cookie = new HttpCookie("connectionString");
cookie.Value = value;
cookie.Expires = DateTime.Now.AddYears(100);
HttpContext.Current.Response.Cookies.Add(cookie);
}
}
private static string GetConnectionStringFromName(HttpCookie myCookie)
{
try
{
string connectionStringName = myCookie.Value;
return ConfigurationManager.ConnectionStrings[connectionStringName].ConnectionString;
}
catch
{
FormsAuthentication.SignOut();
}
finally
{
HttpContext.Current.Response.Redirect("/default.aspx");
}
return "";
} private static void ExpireCookies(HttpContext current)
{
var allCookies = current.Request.Cookies.AllKeys;
foreach (var cook in allCookies.Select(c => current.Response.Cookies[c]).Where(cook => cook != null))
{
cook.Value = "";
cook.Expires = DateTime.Now.AddDays(-1);
current.Request.Cookies.Remove(cook.Name);
cook.Name = "";
}
}
}
This seems to be working on my development machine, but when I tried to deploy it, any user that was using the "remember me" option on the site was getting a null reference error because they did not use the login control to obtain the cookie.
What is the best method to get around this? I was thinking if a user was logged in but the AuthenticatedUser class could not get a Connectionstring to log out the user to force them to use the login control again. What should I do?
Try use:
try
{
FormsAuthentication.SignOut();
}
finally
{
Response.Redirect("~/Home.aspx");
}
This way is preferable, for example if in some time you will decide not- cookie auth, but URL based - the FormsAuthentication will manage it gracefully.