WCF slow first call - performance

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).

Related

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");

Debug Microsoft.AspNet.Identity.Core pdb

I try to implement register base on Microsoft.AspNet.Identity.Core.
package.config :
<?xml version="1.0" encoding="utf-8"?>
<packages>
<package id="EntityFramework" version="6.1.3" targetFramework="net451" />
<package id="Microsoft.AspNet.Identity.Core" version="2.2.1" targetFramework="net451" />
<package id="Microsoft.AspNet.Identity.EntityFramework" version="2.2.1" targetFramework="net451" />
<package id="Microsoft.AspNet.Identity.Owin" version="2.2.1" targetFramework="net451" />
<package id="Microsoft.Owin" version="3.0.1" targetFramework="net451" />
<package id="Microsoft.Owin.Security" version="3.0.1" targetFramework="net451" />
<package id="Microsoft.Owin.Security.Cookies" version="3.0.1" targetFramework="net451" />
<package id="Microsoft.Owin.Security.OAuth" version="3.0.1" targetFramework="net451" />
<package id="Newtonsoft.Json" version="7.0.1" targetFramework="net451" />
<package id="Owin" version="1.0" targetFramework="net451" />
</packages>
My unit test class:
public class register_test
{
Mock<IUserStore<ApplicationUser>> _userStore;
IRegisterService _registerService;
Mock<ApplicationUserManager> _userManagerMock;
IDataProtectionProvider _dataProvider;
public register_test()
{
_dataProvider = new DpapiDataProtectionProvider("paracours");
_userStore = new Mock<IUserStore<ApplicationUser>>();
_userManagerMock = new Mock<ApplicationUserManager>(_userStore.Object, _dataProvider);
_registerService = new RegisterService(_userManagerMock.Object);
}
[Fact]
public async Task register_sucess()
{
ApplicationUser user = new ApplicationUser() { Email = "user1#test.fr", UserName = "user1#test.fr" };
_userManagerMock.Setup(u => u.CreateAsync(It.IsAny<ApplicationUser>(), It.IsAny<string>()))
.ReturnsAsync(IdentityResult.Success)
.Callback(() => user.Id = "0f8fad5b-d9cb-469f-a165-70867728950e");
var result = await _registerService.RegisterAsync(user);
_userManagerMock.Verify(x =>
x.CreateAsync(
It.Is<ApplicationUser>(u => u.Email == "user1#test.fr"),
It.Is<string>(pass => pass == "P#ssword1")));
Assert.NotNull(result);
Assert.Equal(user.Id, "0f8fad5b-d9cb-469f-a165-70867728950e");
}
[Fact]
public void email_token_generation_success()
{
_userManagerMock.Setup(u => u.FindByIdAsync(It.IsAny<string>()))
.ReturnsAsync(new ApplicationUser() { Email = "user1#test.fr", UserName = "user1#test.fr", EmailConfirmed = false });
var result = _registerService.EmailToken("0f8fad5b-d9cb-469f-a165-70867728950e");
Assert.NotNull(result);
}
}
My service :
public class RegisterService : IRegisterService
{
private readonly ApplicationUserManager _userManager;
public RegisterService() { }
public RegisterService(ApplicationUserManager userManager)
{
_userManager = userManager;
}
public virtual async Task<IdentityResult> RegisterAsync(ApplicationUser user)
{
return await _userManager.CreateAsync(user, "P#ssword1");
}
public virtual string EmailToken(string userId)
{
return _userManager.GenerateEmailConfirmationToken(userId);
}
}
My Debug configuration:
uncheck Debug only my code
check activate soupport source server
Debug Symbol
Symbols Microsoft Serveur
with (http:// before)
srv.symbolsource.org/pdb/MyGet
referencesource.microsoft.com/symbols
msdl.microsoft.com/download/symbols
msdl.microsoft.com/download/symbols
I do this :
Put a break point on :
public virtual string EmailToken(string userId){
return _userManager.GenerateEmailConfirmationToken(userId);
}
When I touch F11, it'go to :
using System;
using System.Collections.Generic;
using System.Security.Claims;
namespace Microsoft.AspNet.Identity
{
/// <summary>
/// Extension methods for UserManager
/// </summary>
public static class UserManagerExtensions
{
...
/// <summary>
/// Get the confirmation token for the user
/// </summary>
/// <param name="manager"></param>
/// <param name="userId"></param>
/// <returns></returns>
public static string GenerateEmailConfirmationToken<TUser, TKey>(this UserManager<TUser, TKey> manager,
TKey userId)
where TKey : IEquatable<TKey>
where TUser : class, IUser<TKey>
{
if (manager == null)
{
throw new ArgumentNullException("manager");
}
return AsyncHelper.RunSync(() => manager.GenerateEmailConfirmationTokenAsync(userId));
}
...
}
}
I don't know how to debug :
manager.GenerateEmailConfirmationTokenAsync(userId)
inside
AsyncHelper.RunSync(() =>
Please i need held , it's new for me Task and debug
I solve myself my problem.
When i mock ApplicationUserManager with :
new Mock(_userStore.Object, _dataProvider);
It's create a Castle.Proxie for GenerateEmailConfirmationToken => that couldn't be resolve in the symbol (.pdb)
The solution is to not mock ApplicationUserManager

Obfuscar SkipType configuration element is not working for enums

The Obfuscar SkipType configuration element seems to be not working for enums. This is my fairly minimal configuration file.
<?xml version="1.0"?>
<configuration>
<startup><supportedRuntime version="v4.0"
sku=".NETFramework,Version=v4.0,Profile=Client"/>
</startup>
<Obfuscator>
<Var name="InPath"
value="\users\user\docs\vs2013\projects\wpfapp\wpfapp\bin\debug" />
<Var name="OutPath"
value="\users\user\docs\vs2013\projects\wpfapp\wpfapp\bin\debug" />
<Module file="$(InPath)\wpfapp.exe" />
<Var name="KeepPublicApi" value="true" />
<Var name="HidePrivateApi" value="true" />
<SkipType name="WpfApp.Category" skipFields="true" skipProperties="true" />
</Obfuscator>
</configuration>
The map output file shows that the skipping did not work and the enum type Category was renamed.
Renamed Types:
[WpfApp]WpfApp.Category -> [WpfApp]A.a
{
WpfApp.Category [WpfApp]WpfApp.Category WpfApp.Category::Low -> A
WpfApp.Category [WpfApp]WpfApp.Category WpfApp.Category::High -> a
System.Int32 [WpfApp]System.Int32 WpfApp.Category::value__ skipped: special name
}
Edit: The element <SkipType name="WpfApp.Category" /> causes the same problem.
Edit: The element <SkipType name="WpfApp.Category" skipFields="true" /> causes the same problem.
Edit: The element <SkipField type="WpfApp.Category" name="*" /> causes the same problem.
Edit: This pair
<SkipField type="WpfApp.Category" name="Low" />
<SkipField type="WpfApp.Category" name="High" /> causes the same problem.
The source:
namespace WpfApp
{
public enum Category { Low, High }
//[System.Reflection.Obfuscation]
public partial class MainWindow : Window
{
private ViewModel ViewModel;
public MainWindow()
{
InitializeComponent();
this.DataContext = this.ViewModel = new ViewModel();
}
private void MyButtonClick(object sender, RoutedEventArgs e)
{
this.ViewModel.Process(MyTextBox.Text);
}
}
internal class ViewModel : WpfNotifier
{
private const float DefaultKilograms = 80.0f;
private string _kilograms;
public string Kilograms // WPF binds here
{
get { return this._kilograms; }
set { this._kilograms = value; NotifyPropertyChanged(); }
}
private string _resultText;
public string ResultText // WPF binds here
{
get { return this._resultText; }
set { this._resultText = value; NotifyPropertyChanged(); }
}
internal void Process(string input)
{
float kilograms;
if (Single.TryParse(input, out kilograms))
{
Category c = (kilograms > 100.0f) ? Category.High : Category.Low;
this.ResultText = c.ToString();
}
else
{
this.Kilograms = ViewModel.DefaultKilograms.ToString();
}
}
}
public class WpfNotifier : INotifyPropertyChanged
{
[field: NonSerialized]
public event PropertyChangedEventHandler PropertyChanged; // public for interface
internal void NotifyPropertyChanged([CallerMemberName] string propertyName = "")
{
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
else
; // it is harmless to fail to notify before the window has been loaded and rendered
}
}
}
Is this a bug or is my usage wrong?
Your usage is wrong. If you check the documentation you will see that <SkipType> tags must be put into <Module> tags. Otherwise, Obfuscar has no idea in which module/assembly this skip rule takes effect. So you should try
<Module file="$(InPath)\wpfapp.exe">
<SkipType name="WpfApp.Category" skipFields="true" skipProperties="true" />
</Module>

How do I get return object properties from an AJAX-enabled WCF service (ASP.Net)?

I have created an AJAX-enabled WCF service to return a List<> of a custom class I created. I can get it to return data, but I have no idea how to access the property values of my class.
Here's my class:
[Serializable]
public class Favorite
{
public int Id { get; set; }
public string Title { get; set; }
public string Url { get; set; }
}
Here's my WCF service:
[OperationContract]
public List<Favorite> GetFavorites()
{
MembershipUser thisUser = Membership.GetUser(HttpContext.Current.User.Identity.Name);
int userId = (int)thisUser.ProviderUserKey;
return GetFavorites(userId);
}
Here's the configuration for the service:
<system.serviceModel>
<services>
<service name="MySvc">
<endpoint address="" behaviorConfiguration="MySvcEndpointBehavior"
binding="webHttpBinding"
contract="MySvc" />
</service>
</services>
<behaviors>
<endpointBehaviors>
<behavior name="MySvcEndpointBehavior">
<enableWebScript />
</behavior>
</endpointBehaviors>
</behaviors>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" />
And here is the jQuery script where I actually call the service:
$.ajax({
type: "POST",
url: "MySvc.svc/GetFavorites",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result) {
var favs = result.d;
}
});
In my javascript, I can call "favs.length", and it gives me the right number of results. But if I try, for instance, to access "favs[0].Title", I get a message of "undefined". Can anyone help me?
Just use the console.
success: function (result) {
// log
console.log(result);
// dir
console.dir(result);
// iterating through an object's properties in JS
for(var i = 0; i < favs.length; i++){
for(property in favs[i]){
console.log(property + ": " + favs[i][property]);
}
}
};

ASP .NET MVC Custom Profile Settings Not Found Issue

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

Resources