ASP .NET MVC Custom Profile Settings Not Found Issue - asp.net-mvc-3

Currently I am using a custom profile in my ASP .NET MVC application. When creating users and setting the profile properties everything works fine. The issue I am having is that when I edit a user I keep on getting a settings property 'FirstName' was not found error.
Here is the code I am using, and from my understanding it should work fine:
User Profile Class
public class UserProfile : ProfileBase
{
[SettingsAllowAnonymous(false)]
public string FirstName
{
get { return base["FirstName"] as string; }
set { base["FirstName"] = value; }
}
[SettingsAllowAnonymous(false)]
public string LastName
{
get { return base["LastName"] as string; }
set { base["LastName"] = value; }
}
public static UserProfile GetUserProfile()
{
return Create(Membership.GetUser().UserName) as UserProfile;
}
public static UserProfile GetUserProfile(string username)
{
return Create(username) as UserProfile;
}
}
Web.config
<membership>
<providers>
<clear/>
<add name="AspNetSqlMembershipProvider" type="System.Web.Security.SqlMembershipProvider" connectionStringName="ApplicationServices"
enablePasswordRetrieval="false" enablePasswordReset="true" requiresQuestionAndAnswer="false" requiresUniqueEmail="false"
maxInvalidPasswordAttempts="5" minRequiredPasswordLength="6" minRequiredNonalphanumericCharacters="0" passwordAttemptWindow="10"
applicationName="/" />
</providers>
</membership>
<profile inherits="MissionManager.Models.UserProfile">
<providers>
<clear/>
<add name="AspNetSqlProfileProvider" type="System.Web.Profile.SqlProfileProvider" connectionStringName="ApplicationServices" applicationName="/" />
</providers>
</profile>
Calling Code - Note that before I even hit this method, ASP .NET is running into the error mentioned above.
[HttpPost]
public ActionResult Edit(UserModel model)
{
try
{
MembershipService.UpdateUser(User.Identity.Name, model);
return RedirectToAction("Index");
}
catch
{
return View();
}
}

I have something similar that works. The differences are:
public string FirstName
{
get { return this["FirstName"] as string; }
set { this["FirstName"] = value; }
}
public string LastName
{
get { return this["LastName"] as string; }
set { this["LastName"] = value; }
}
I don't have the attributes on the custom properties and I use this instread of base
HTH

Related

Can't find user tables MVC Web API

After successful registration, can't find aspnet user tables and also when I tried to login, it returns invalid grant type
public IdentityResult Register(string username, string password)
{
var userStore = new UserStore<IdentityUser>();
var manager = new UserManager<IdentityUser>(userStore);
var user = new IdentityUser() { UserName = username, Email = username };
manager.PasswordValidator = new PasswordValidator
{
RequiredLength = 3
};
IdentityResult result = manager.Create(user, password);
return result;
}
when I tried to login, it returns invalid grant type
public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
{
var userStore = new UserStore<IdentityUser>(new ApplicationDbContext());
var manager = new UserManager<IdentityUser>(userStore);
var user = await manager.FindAsync(context.UserName, context.Password);
if(user !=null)
{
var identity = new ClaimsIdentity(context.Options.AuthenticationType);
identity.AddClaim(new Claim("Username", user.UserName));
identity.AddClaim(new Claim("Email", user.Email));
identity.AddClaim(new Claim("LoggedOn", DateTime.Now.ToString()));
context.Validated();
}
else
{
return;
}
}
public class ApplicationDbContext : IdentityDbContext
{
public ApplicationDbContext()
: base("MyEntities")
{
}
public DbSet<userlogindetails> userlogindetails{ get; set; }
}
webconfig
<add name="MyEntities" connectionString="metadata=res://*/Models.MyModel.csdl|res://*/Models.MyModel.ssdl|res://*/Models.MyModel.msl;provider=System.Data.SqlClient;provider connection string="data source=MY-PC\SQLEXPRESS;initial catalog=MyDB;user id=user;password=pass;MultipleActiveResultSets=True;App=EntityFramework"" providerName="System.Data.EntityClient" />
It turns out that i need to add Default ConnectionString
<add name="DefaultConnection" connectionString="Data Source=My-PC\SQLEXPRESS;Initial Catalog=MyDB;User ID=username;Password=pass" providerName="System.Data.SqlClient" />

WCF slow first call

I create one WCF service from scratch with the Visual Studio project creation wizard.
Here is the interface of the service:
namespace ServiceTest {
[ServiceContract]
public interface IService1 {
[OperationContract]
string GetData(int value);
[OperationContract]
CompositeType GetDataUsingDataContract(CompositeType composite);
}
[DataContract]
public class CompositeType {
bool boolValue = true;
string stringValue = "Hello ";
[DataMember]
public bool BoolValue {
get { return boolValue; }
set { boolValue = value; }
}
[DataMember]
public string StringValue {
get { return stringValue; }
set { stringValue = value; }
}
}
And the implementation:
namespace ServiceTest {
public class Service1 : IService1 {
public string GetData(int value) {
return string.Format("You entered: {0}", value);
}
public CompositeType GetDataUsingDataContract(CompositeType composite) {
if (composite == null) {
throw new ArgumentNullException("composite");
}
if (composite.BoolValue) {
composite.StringValue += "Suffix";
}
return composite;
}
}
And Web.config:
<configuration>
<appSettings>
<add key="aspnet:UseTaskFriendlySynchronizationContext" value="true"/>
</appSettings>
<system.web>
<compilation debug="true" targetFramework="4.6.1"/>
<httpRuntime targetFramework="4.6.1"/>
<httpModules>
<add name="ApplicationInsightsWebTracking" type="Microsoft.ApplicationInsights.Web.ApplicationInsightsHttpModule, Microsoft.AI.Web"/>
</httpModules>
</system.web>
<system.serviceModel>
<behaviors>
<serviceBehaviors>
<behavior>
<serviceMetadata httpGetEnabled="true" httpsGetEnabled="true"/>
<serviceDebug includeExceptionDetailInFaults="false"/>
</behavior>
</serviceBehaviors>
</behaviors>
<protocolMapping>
<add binding="basicHttpsBinding" scheme="https"/>
</protocolMapping>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true"/>
</system.serviceModel>
<system.webServer>
<modules runAllManagedModulesForAllRequests="true">
<remove name="ApplicationInsightsWebTracking"/>
<add name="ApplicationInsightsWebTracking" type="Microsoft.ApplicationInsights.Web.ApplicationInsightsHttpModule, Microsoft.AI.Web"
preCondition="managedHandler"/>
</modules>
<directoryBrowse enabled="true"/>
<validation validateIntegratedModeConfiguration="false"/>
</system.webServer>
</configuration>
And in the other side, the client (a simple console application) with the code:
namespace ClientServiceTest {
class Program {
static void Main(string[] args) {
Service1Client client = new Service1Client();
DateTime begin = DateTime.Now;
string res = client.GetData(0);
TimeSpan interval = DateTime.Now - begin;
;
}
}
My question is:
On the first call, the interval.TotalMilliseconds is around 250.
If I play again the call with the same client, I get around 10 ms.
How can I reduce this initial cost?
I'm assuming the first call causes the Application Pool to load and then load the service and everything is already loaded for the second call.
In IIS Manager, try setting the Start Mode for the Application Pool that your WCF service is running in to AlwaysRunning and the Idle Time-out Action to Suspend. You might also want to increase the Idle Time-out(minutes).

post to wcf using volley (android)

i am trying to solve this error from a week but any of my workaround is not working unfortunately
i am trying to send json String like this String={"name":"ABC"} to WCF(ASP.NET) using volley library post method but its not working anyhow gives this error
BasicNetwork.performRequest: Unexpected response code 400 for http://192.168.1.11/MyDemoService/Service1.svc/insert
i am not sure what is wrong and where is the mistake is being made
Here is the WCF Code:
[WebInvoke(Method = "POST", UriTemplate = "insert", BodyStyle = WebMessageBodyStyle.Wrapped, RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)]
string insert(string name);
insert Function :
public string insert(string name)
{
//write database related insert logic here.
//string response2="{\"name\":\"mohib\"}";
//info m = JsonConvert.DeserializeObject<info>(name);
//string n = m.name;
// string ds = name;
string conStr = #"Data Source=CRESIDIAN-DELL;Initial Catalog=WCFTest;User Id=sa;Password=1234";
// string msg = "true";
try
{
SqlConnection con = new SqlConnection(conStr);
con.Open();
string query = "insert into DemoTable (name) values ('" + name + "')";
SqlCommand com = new SqlCommand(query, con);
com.ExecuteNonQuery();
msg = "Inserted";
con.Close();
}
catch (Exception e)
{
e.ToString();
}
return msg;
}
WCF Web Config :
<?xml version="1.0"?>
<configuration>
<system.web>
<compilation debug="true" targetFramework="4.0" />
</system.web>
<system.serviceModel>
<services >
<service name="WCFDemo.Service1">
<endpoint address="" binding="webHttpBinding" contract="WCFDemo.IService1" behaviorConfiguration="MyConfig">
</endpoint>
</service>
</services>
<behaviors>
<endpointBehaviors >
<behavior name="MyConfig">
<webHttp/>
</behavior>
</endpointBehaviors>
<serviceBehaviors>
<behavior>
<!-- To avoid disclosing metadata information, set the value below to false before deployment -->
<serviceMetadata httpGetEnabled="true"/>
<!-- To receive exception details in faults for debugging purposes, set the value below to true. Set to false before deployment to avoid disclosing exception information -->
<serviceDebug includeExceptionDetailInFaults="false"/>
</behavior>
</serviceBehaviors>
</behaviors>
<serviceHostingEnvironment multipleSiteBindingsEnabled="true" />
</system.serviceModel>
<system.webServer>
<modules runAllManagedModulesForAllRequests="true"/>
<!--
To browse web app root directory during debugging, set the value below to true.
Set to false before deployment to avoid disclosing web app folder information.
-->
<directoryBrowse enabled="true"/>
</system.webServer>
</configuration>
Volley Code in Android (Client):
String url="http://192.168.1.11/MyDemoService/Service1.svc/insert";
JSONObject params = new JSONObject();
try {
params.put("name", "true");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
JsonObjectRequest jsonObjReq = new JsonObjectRequest(Request.Method.POST,
url, params,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
//Log.d(TAG, response.toString());
Log.d("Tag",response.toString());
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// VolleyLog.d(TAG, "Error: " + error.getMessage());
}
}) {
/**
* Passing some request headers
* */
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<String, String>();
headers.put("Content-Type", "application/json; charset=utf-8");
return headers;
}
};
jsonObjReq.setRetryPolicy(new DefaultRetryPolicy(60000,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
// Adding request to request queue
BaseApplication.getInstance().addToRequestQueue(jsonObjReq,"Post Request");

Session time out error

My application is expiring before 20 minutes and even when we are working on it also it is expiring may I know what I have to change?..
public class CheckSessionOutAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
HttpContext ctx = HttpContext.Current;
if (ctx.Session != null)
{
if (ctx.Session.IsNewSession)
{
string sessionCookie = ctx.Request.Headers["Cookie"];
if ((null != sessionCookie) && (sessionCookie.IndexOf("ASP.NET_SessionId") >= 0))
{
if (ctx.Request.IsAuthenticated)
{
FormsAuthentication.SignOut();
HttpContext.Current.Session.Clear();
RedirectResult redirectingto = new RedirectResult("~/Account/Timeout");
filterContext.Result = redirectingto;
}
else
{
string loginUrl = FormsAuthentication.LoginUrl;
RedirectResult redirectto = new RedirectResult(loginUrl);
filterContext.Result = redirectto;
}
}
}
}
base.OnActionExecuting(filterContext);
}
Web.config file
<authentication mode="Forms">
<forms loginUrl="~/Account/Login" timeout="1000"/>
</authentication>
<sessionState mode="InProc" timeout="20" />

Pretty Error URLs in MVC3 for 404, 500 Etc

My current error handling URLs look rather ugly:
http://localhost:65089/Error/NotFound?aspxerrorpath=/Foo
Would rather have something like this:
http://localhost:65089/Error/NotFound
Web Config Code
<system.web>
<customErrors mode="On" defaultRedirect="~/Error/Unknown">
<error statusCode="404" redirect="~/Error/NotFound" />
</customErrors>
Error Controller
public class ErrorController : Controller
{
//
// GET: /Error/
public ActionResult Unknown()
{
return View();
}
public ActionResult NotFound()
{
return View();
}
}
Thanks in advance!
You can modify Application_Error method in your Global.asax:
protected void Application_Error(object sender, EventArgs e)
{ Exception ex = Server.GetLastError();
if(ex is HttpException && ((HttpException)ex).GetHttpCode()==404)
{
Response.Redirect("/Error/NotFound");
}
}

Resources