Category Archives: Api

Api

How can I use async in Application_Error() in Global.asax.cs?

I’m not sure if I’m doing everything correctly, but what I want to do is basically log my errors to an external service. The problem is that I’d like to use async/await, but if I add async to the Application_Error, it doesn’t seem to get called.

Maybe that is not modified . Use .Result for task – or, if you want  all to finish, Task.WaitAll

jakubarnold

I’m not sure if I’m doing everything correctly, but what I want to do is basically log my errors to an external service. The problem is that I’d like to use async/await, but if I add async to the Application_Error, it doesn’t seem to get called.

Hi jakubarnold,

Thanks for your post.

What I understand from you is that you want to write mvc application exception message to remote server asynchronously.

For this issue, you should mark the Application_Error as async like below:

protected async void Application_Error(object sender, EventArgs e) 
        {
            Exception ex = Server.GetLastError();
            var isSuccess=await MethodAsync(ex);
        
        }
async Task<bool> MethodAsync(Exception ex)
        {
            //your code write exception to remote server.
            //...............

            return true;
        }

Thanks.

Best Regards!

The HTTP pipeline has APIs to register for async versions of all the methods you see in global.asax. You can then incorporate that with Tasks. This might help:

http://brockallen.com/2013/07/27/implementing-async-http-modules-in-asp-net-using-tpls-task-api/

Is your intention is to return the page back to the user while logging the error? Typically this makes sense as you don’t want to block user while logging errors. Async does not support this behavior. It will still be a synchronous call to your user. Please
check the below blog for more details

Async Doesn’t Change the HTTP Protocol

If your intension is not to hold up the web server thread while doing the error logging, I recommend using async HttpModules for this.

Implementing async HTTP modules in ASP.NET using TPL’s Task API

[RESOLVED]AngularJS in ASP.NET MVC Partial View

I am currently loading Partial View returned by MVC controller to a model dialog via AngularJS $http.get call. My View in rendered properly in modal dialog, but the only problem is that my partial view which is rendered also uses angular expressions etc.
and for some reason angular is not working in my partial view, but if i load this partial view in some other view without ajax call then it angular works properly.

Partial View Code: ~/Views/ArticleType/_Add
MVC Controller: ArticleTypeController

//other scripts files e.g app.js and angular.js are included in main layout file.
<script src="~/Scripts/Angular/ArticleTypeController.js"></script>
<div class="modal-content" ng-controller="ArticleTypeController">
    <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
        Add New Article Type
    </div>
    <form novalidate role="form" name="ArticleTypeForm" ng-submit="ArticleTypeForm.$valid && Add(model)">
        <div class="modal-body">
            <div class="form-group">
                <label for="ArticleType" class="control-label">Article Type</label>
                <input type="text" required ng-model="model.ArticleTypeName" class="form-control" id="ArticleType" />
            </div>
        </div>
 
    </form>
    <div class="modal-footer">
        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
        <button type="submit" class="btn btn-primary" value="Add" >Add</button>
        {{ArticleTypeForm.$valid}}
    </div>
</div>

Angular Controller to load modal with the partial view.
MenuController.js

angular.module('myApp').controller('MenuController', [
        '$scope', '$http', 'httpPreConfig', function ($scope, $http, httpPreConfig) {
 
            $scope.AddArticleType = function () {
                $.get("/ArticleType/Add")//returns the partial view.
                    .success(function (response) {
                        ShowModal(response);//it properly shows the modal. but angular doesn't work
                    });
            }
        }]);

common.js 

$(document).ready(function (e) {
    
    $(document).ajaxStart(function (e) {
        $("#loadingBar").modal('show');
    });
    $(document).ajaxStop(function(e) {
        $("#loadingBar").modal('hide');
    });
    $(document).ajaxComplete(function (e) {
        $("#loadingBar").modal('hide');
    });
    $(document).ajaxError(function (e) {
        $("#loadingBar").modal('hide');
    });
});
 
function ShowModal(content) {
 
    //var html = $complie(content)(scope);
    $("#modal .modal-dialog").html(content);
    $("#modal").modal("show");
}
function HideModal() {
    $("#modal .modal-dialog").html("");
    $("#modal").modal("hide");
}

AS you can see from the image below that Angular expressions are not working in Modal Dialog. The html of this dialog is returned from MVC Controller whcih returns a partial view. 

Any help would be really appreciated. Just so that you know, angular expressions etc. are working in normal views.

Here is the download link to the solution files. : https://app.box.com/s/rxvrhwcdp75zo736k7u5

Hi asad,

According to your description, it works fine if you load that partial view directly, however it doesn’t work if using the AJAX to load the partial view.

I think you may need to compile HTML string or DOM into a template.

More information, please refer to:

# $compile

https://docs.angularjs.org/api/ng/service/$compile  

There are some threads that may help you:

# AngularJS – Dynamically creating elements that specify directives

http://stackoverflow.com/questions/20025526/angularjs-dynamically-creating-elements-that-specify-directives

# Bind Angularjs to newly created html element dynamically

http://stackoverflow.com/questions/19867554/bind-angularjs-to-newly-created-html-element-dynamically

Best Regards

Starain Chen

[RESOLVED]date formt isue c# and jquery

hello, I have a db with the  data attribute

and i’m using jquery date picker to insert date

in my computer I have no problem choosing and inserting but all users has report error: must be a date format

How can I fix it and what  wrong here ? 

code

in my class :

[DisplayFormat(DataFormatString = "{0:dd MMM }")]
           
public DateTime WeekFrom { get; set; }
        
[DisplayFormat(DataFormatString = "{0:dd MMM }")]

public DateTime? Until { get; set; }
 in my script 

$(function () {
    $(".date-picker").datepicker({ dateFormat: 'dd-mm-yy' });
})

my Sql look like this 
WeekForm (datetime not null)
Until(datetimee,null)

how  can I fix it and what is wrong  here?

Based on the current format you are using, you’ll likely need to change the format of your DatePicker to match :

$(".date-picker").datepicker({ dateFormat: 'dd MM' });

Additionally, another problem is that the ‘mm’ value you are using in your DateFormat actually denotes minutes instead of months. If you wanted to use months (which is likely), you’ll instead want to use the capitalized ‘MM’ instead :

$(".date-picker").datepicker({ dateFormat: 'dd-MM-yy' });

This should help to ensure that the formats coincide between your actual DisplayFormat attributes and the value contained in your DatePicker. Additionally, if you are using Chrome or the jQuery.validate library, you might want to look into
this known issue regarding DateTime objects being parsed or validated improperly.

Rion Williams

Based on the current format you are using, you’ll likely need to change the format of your DatePicker to match :

$(".date-picker").datepicker({ dateFormat: 'dd MM' });

Additionally, another problem is that the ‘mm’ value you are using in your DateFormat actually denotes minutes instead of months. If you wanted to use months (which is likely), you’ll instead want to use the capitalized ‘MM’ instead :

$(".date-picker").datepicker({ dateFormat: 'dd-MM-yy' });

This should help to ensure that the formats coincide between your actual DisplayFormat attributes and the value contained in your DatePicker. Additionally, if you are using Chrome or the jQuery.validate library, you might want to look into
this known issue regarding DateTime objects being parsed or validated improperly.

hello Rion, thanks,

using :

$(function () {
    $(".date-picker").datepicker({ dateFormat: 'dd-MM-yy' });
})
i'm getting in my page a date that look like this :"30-September-2014" and error MSG :" The field must be a date"

Oops. 

I appeared to get my ASP.NET and jQuery code mixed up. The lowercase format should be fine : 

$(function () {
    $(".date-picker").datepicker({ dateFormat: 'dd-mm-yy' });
})

Is there any chance that you are using any kind of validation-based scripts (like jQuery.validate)? Or is the error message you are receiving coming from the actual server-side code?

A

Rion Williams

Oops. 

I appeared to get my ASP.NET and jQuery code mixed up. The lowercase format should be fine : 

$(function () {
    $(".date-picker").datepicker({ dateFormat: 'dd-mm-yy' });
})

Is there any chance that you are using any kind of validation-based scripts (like jQuery.validate)? Or is the error message you are receiving coming from the actual server-side code?

thanks Rion for your time and help.  ,

it look fine on my side . i’ll check with users  to find out.

Problem fix . thanks Rion.

and yes this is Jquery validator.

[RESOLVED]How to Post with foreign keys

public List<Job> PostNewJob(Job newJob)
        {
            Job job = new Job();

            job.JobId = newJob.JobId;
            job.JobNumber = newJob.JobNumber;
            job.JobName = newJob.JobName;
            job.JobDescription = newJob.JobDescription;
           
            db.Jobs.Add(newJob);
            db.SaveChanges();

            return db.Jobs.ToList();
        }

 public class Job
    {
        public Job()
        {
            this.Customers = new HashSet<Customer>();
            this.ChangeOrders = new HashSet<ChangeOrder>();
        }
        public int JobId { get; set; }
        public int JobNumber { get; set; }
        public string JobName { get; set; }
        public string JobDescription { get; set; }

        public virtual ICollection<Customer> Customers { get; set; }
        public virtual ICollection<ChangeOrder> ChangeOrders { get; set; }
    }


public List<Customer> PostNewCustomer(Customer newCustomer)
        {
            Customer customer = new Customer();

            customer.CustomerId = newCustomer.CustomerId;
            customer.CustomerName = newCustomer.CustomerName;
            customer.CustomerPhoneNumber = newCustomer.CustomerPhoneNumber;
            customer.CustomerFaxNumber = newCustomer.CustomerFaxNumber;
            customer.JobId = newCustomer.JobId;

            db.Customers.Add(newCustomer);
            db.SaveChanges();

            return db.Customers.ToList();
        }

 public class Customer
    {

        public int CustomerId { get; set; }
        public string CustomerName { get; set; }
        public Int64 CustomerPhoneNumber { get; set; }
        public Int64 CustomerFaxNumber { get; set; }

        public int? JobId { get; set; }
    }


 $scope.submitJob = function () {
        var id = $scope.currentItem.JobName
        var data = {
            JobId: $scope.currentItem.JobId,
            JobNumber: $scope.currentItem.JobNumber,
            JobName: $scope.currentItem.JobName,
            JobDescription: $scope.currentItem.JobDescription
            
            
        }
        $http.post('/api/apiJob/PostNewJob', data).success(function (data, status, headers) {
            console.log(data);
               $scope.PrintPreviewModal();
               window.top.location.reload();
            
        });
 };

  <form ng-submit="submitJob()" enctype="multipart/form-data">
                            <fieldset>
                                <div>
                                    <div class="inline-fields">
                                        <label>Number:</label>
                                        <input ng-model="currentItem.JobNumber" type="text">

                                        <label>Job Name:</label>
                                        <input ng-model="currentItem.JobName" type="text">
                                        <label>Customer:</label>
                                        <input type="text" ng-model="currentItem.CustomerName">
                                    </div>
                                    <div class="inline-fields">
                                        <label>Address:</label>
                                        <input ng-model="currentItem.CustomerAddress" type="text">
                                    </div>
                                    <div class="inline-fields">
                                        <label>City:</label>
                                        <input ng-model="currentItem.CustomerCity" type="text">

                                        <label>St:</label>
                                        <input ng-model="currentItem.CustomerState" type="text">

                                        <label>Zip:</label>
                                        <input ng-model="currentItem.CustomerZipcode" type="text">

                                <input type="submit" value="Save" />

                            </fieldset>
                        </form>

I am trying to change how I post and update my primary class JOB. Previously I was using the Customer Class as a List and I was storing the JOB Customer information in the Job class itself. The problem with this was If I went to go update a Customers information
in the Customer List I would have to go to every Job that has that Customer and Manually update everyone separately. So I am unsure how to do this. When I am creating a New Job how do I  Connect the appropriate Customer with that Job? I am already doing this
with another class called ChangeOrder but the difference is the Job has to be already been created before I can make that Post.. And also, the Customer can be assigned to multiple Jobs. So How does the foreign key work with this? How can you have a Customer
with multiple foreign keys "JobIds" attached to it?

What you are looking is a many to many relationship. Please take a look at this article in MSDN magazine

Handle Many-to-Many Relationships in Entity Framework and ASP.NET MVC

ok, so I created a linking table. What am I doing wrong? Here is what is coming back from the database

 {$id:1, JobCustomerId:1, JobId:1, Job:null, CustomerId:2, Customer:null}
$id: "1"
Customer: null
CustomerId: 2
Job: null
JobCustomerId: 1
JobId: 1

public class JobCustomer
    {
        public int JobCustomerId { get; set; }
        public int JobId { get; set; }
        public virtual Job Job { get; set; }
        public int CustomerId { get; set; }
        public virtual Customer Customer { get; set; }
    }
public class Job
    {
       
        public int JobId { get; set; }
        public int JobNumber { get; set; }
        public string JobName { get; set; }
        public string JobDescription { get; set; }

        public ICollection<JobCustomer> JobCustomers { get; set; }
       
    }
public class Customer
    {

        public int CustomerId { get; set; }
        public string CustomerName { get; set; }
        public Int64 CustomerPhoneNumber { get; set; }
        public Int64 CustomerFaxNumber { get; set; }

        public ICollection<JobCustomer> JobCustomers { get; set; }
      }
public List<JobCustomer> GetJobs()
        {
            List<JobCustomer> jobs = new List<JobCustomer>();
             jobs = db.JobCustomers
                .ToList();
            return jobs;
        }

Hi texas697,

You don’t need to create a link table manually, the EF will create it. For the link table, it doesn’t have the entity field, just the keys of these entities.

For your code, the fluent API would be like this:

modelBuilder.Entity<Job>() 
    .HasMany(j => j.Customers) 
    .WithMany(c => c.Jobs) 
    .Map(m => 
    { 
        m.ToTable("JobCustomer"); 
        m.MapLeftKey("JobId"); 
        m.MapRightKey("CustomerId"); 
    });
public class Job
    {
       
        public int JobId { get; set; }
        public int JobNumber { get; set; }
        public string JobName { get; set; }
        public string JobDescription { get; set; }

        public ICollection<Customer> Customers { get; set; }
       
    }
public class Customer
    {

        public int CustomerId { get; set; }
        public string CustomerName { get; set; }
        public Int64 CustomerPhoneNumber { get; set; }
        public Int64 CustomerFaxNumber { get; set; }

        public ICollection<Job> Jobs { get; set; }
      }

More information, please refer to:

# Configuring a Many-to-Many Relationship

http://msdn.microsoft.com/en-in/data/jj591620.aspx#ManyToMany

Best Regards

Starain Chen

that sure does make things easier. Now what if I have additional classes that need to be linked to Job? How would the modelBuilder look? Do i put this in my IdentityModels? If this is the correct way of doing it, I did do a migration without errors. The
tables in the sql where created. But How Do I query the information from my project? I went through the JobApi but the data for Customers, ChangeOrders, etc… came back null. 

 public class ApplicationUser : IdentityUser
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public bool? Hidden { get; set; }
        public string UserEmail { get; set; }
    }

    public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
    {
        public ApplicationDbContext()

            : base("DefaultConnection", throwIfV1Schema: false)
        {
            this.Configuration.LazyLoadingEnabled = false;
            this.Configuration.ProxyCreationEnabled = false;

        }
        public DbSet<Job> Jobs { get; set; }

        public DbSet<Employee> Employees { get; set; }
        public DbSet<Customer> Customers { get; set; }
        public DbSet<ChangeOrder> ChangeOrders { get; set; }
        public DbSet<JobType> JobTypes { get; set; }
        public DbSet<GeoArea> GeoAreas { get; set; }
        public DbSet<JobClass> JobClasses { get; set; }

        protected override void OnModelCreating
       (DbModelBuilder modelBuilder)
        {
base.OnModelCreating(modelBuilder); modelBuilder.Entity<Job>() .HasMany(j => j.Customers) .WithMany(c => c.Jobs) .Map(m => { m.ToTable("JobCustomer"); m.MapLeftKey("JobId"); m.MapRightKey("CustomerId"); }); modelBuilder.Entity<Job>() .HasMany(j => j.ChangeOrders) .WithMany(c => c.Jobs) .Map(m => { m.ToTable("JobChangeOrder"); m.MapLeftKey("JobId"); m.MapRightKey("ChangeOrderId"); }); modelBuilder.Entity<Job>() .HasMany(j => j.GeoAreas) .WithMany(c => c.Jobs) .Map(m => { m.ToTable("JobGeoArea"); m.MapLeftKey("JobId"); m.MapRightKey("GeoAreaId"); }); modelBuilder.Entity<Job>() .HasMany(j => j.JobTypes) .WithMany(c => c.Jobs) .Map(m => { m.ToTable("JobJobType"); m.MapLeftKey("JobId"); m.MapRightKey("JobTypeId"); }); modelBuilder.Entity<Job>() .HasMany(j => j.JobClasses) .WithMany(c => c.Jobs) .Map(m => { m.ToTable("JobJobClass"); m.MapLeftKey("JobId"); m.MapRightKey("JobClassId"); }); } }

 public class Job
    {
       
        public int JobId { get; set; }
        public int JobNumber { get; set; }
        public string JobName { get; set; }
        public string JobDescription { get; set; }

        
        public ICollection<Customer> Customers { get; set; }
        public ICollection<ChangeOrder> ChangeOrders { get; set; }
        public ICollection<GeoArea> GeoAreas { get; set; }
        public ICollection<JobClass> JobClasses { get; set; }
        public ICollection<JobType> JobTypes { get; set; }
    }

Hi texas697,

Your code is right.

To load the related entities, we could use Include method.

For example:

var data =db.Jobs.Include("Customers");

Best Regards

Starain Chen

[RESOLVED]Where to write repository Pattern in MVC+WCF project?

Hi Folks,

Wanted to learn Repository Pattern implemenation in my project whic has following structure.

Web – MVC4

Services – WCF + EF5

So in all my controller actions will make a call to WCF service to get the Models

Models are shared across WCF & MVC projects. (WCF & MVC are in diff solutions all together).

So, nmow I wanted my project to have Repository Pattern for Data Access which is in WCF.

 

Currently my Service is defined like below with methods.

 public bool SubmitManfLocationrequest(Request req)
        {
            using (LASORContext dbcontext = new LASORContext("xx"))
            {
                dbcontext.Requests.Add(req);
                dbcontext.SaveChanges();
            }
            return true;

        }


        public List<Request> GetAllMFLRequests()
        {
            List<Request> AllMFLRequests = new List<Request>();
            using (LASORContext dbcontext = new LASORContext("xx"))
            {
                AllMFLRequests  = dbcontext.Requests.ToList();
                return AllMFLRequests;
            }
        }

any suggestions on converting this to Repostiory in WCF Service side?

WCF service serving the data, so it is feasible to have a DAL in the service with Repository implementation.

MVC app acts as the client, sends request to WCF service to perform CRUD.

Refer:

http://weblogs.asp.net/sukumarraju/creating-n-tier-web-api-application

At the above blog article I walked through the repository pattern implementation.

* Note that regardless of the technology (WCF or Web API) the pattern implementation is same.

Let me know any further queries.

Hi Ram,

About repository and unit of work patterns, you also could refer to:

# Implementing the Repository and Unit of Work Patterns in an ASP.NET MVC Application

http://www.asp.net/mvc/tutorials/getting-started-with-ef-5-using-mvc-4/implementing-the-repository-and-unit-of-work-patterns-in-an-asp-net-mvc-application

Best Regards

Starain Chen

Ajax call to MVC project

Hello,

I have a webforms project and I am attempting to add a separate MVC WebApi project to my solution to handle ajax calls.  

I would like to be able to make an ajax call from a javascript file that is loaded into the main .aspx page of the webforms project to
some Api Controller in the MVC project

And have data returned back to the client side

Is this possible?

Here is my current code:

$.ajax({
type: "GET",
url: "/RestService/Controllers/CustomerController2",
data: JSON.stringify(jsonArgs),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
//code here doesn’t get called
});

public string GetCustomersByQuery(string searchFor, string searchQuery, string orderBy, string direction, int limit, int offset)
{
//code here doesn’t get called
}

I’m not particularly familiar with webAPI, but shouldn’t your action be part of the url option in your ajax request?

url: "/RestService/Controllers/CustomerController2/GetCustomersByQuery",

You appear to be targeting the URL of the Controller itself and not a particular method within the Controller. You’ll likely want to include the name of your method within the URL that you are targeting :

url: "/RestService/Controllers/CustomerController2/GetCustomersByQuery",

If you continue to have issues targeting this method, I would recommend using the Developer Tools (F12) within your browser and checking the Console, which you display any errors that might be related to your service not being properly called.

Thanks for the replies, but I tried that too, along with a bunch of other variations of url’s and no luck. I think its because the controller was in a separate project, so maybe I have to change something in the web.config or references so the ajax call
can see where it has to go? But I think I’m giving up on this method and going to try something a little simpler that doesn’t include another project in the solution, maybe an HTTP handler

It may be an issue of it being a relative URL as well. You might try to specify the name of the project as well prior to your existing URL and ensure that your service project is actually running alongside of your MVC existing project : 

url: "YourServiceProject/RestService/Controllers/CustomerController2/GetCustomersByQuery",

Hi,

Try after making following changes

1) Please add following entry in WebApiConfig.cs
     config.Routes.MapHttpRoute("DefaultApiWithAction", "api/{controller}/{action}/{id}",
                defaults: new { id = RouteParameter.Optional }
2) Change url to
 url: "/RestService/api/Customer/GetCustomersByQuery"

[RESOLVED]Regarding IOC & DI relation ship and the concept like inject dependencies to invert control

i admit that i really confuse between IOC & DI ? what is relation between IOC & DI ? what is container in DI ? what container does ?

How MS Meaf is similar & different than DI concept & usage ?

please discuss about IOC & DI for beginner.

what is the meaning of this line You need to inject dependencies to invert control ?

Anyone can u plzz discuss with small example to explain what you said like
inject dependencies to invert control

thanks

Hi,

IoC is a generic term meaning rather than having the application call the methods in a framework, the framework calls implementations provided by the application.

DI is a form of IoC, where implementations are passed into an object through constructors/setters/service look-ups, which the object will ‘depend’ on in order to behave correctly.

IoC without using DI, for example would be the Template pattern because the implementation can only be changed through sub-classing.

DI Frameworks are designed to make use of DI and can define interfaces (or Annotations in Java) to make it easy to pass in implementations.

IoC Containers are DI frameworks that can work outside of the programming language.  In some you can configure which implementations to use in metadata files (e.g. XML) which are less invasive.  With some you can do IoC that would normally
be impossible like inject implementation at
pointcuts
.

See also

http://martinfowler.com/articles/injection.html#InversionOfControl

Taken from

http://stackoverflow.com/questions/6550700/inversion-of-control-vs-dependency-injection

mou_inn

How MS Meaf is similar & different than DI concept & usage ?

The Managed Extensibility Framework (MEF) is a composition layer for .NET that improves the flexibility, maintainability and testability of large applications. MEF can be used for third-party plugin extensibility, or it can bring the benefits of a
loosely-coupled plugin-like architecture to regular applications. (taken from

http://mef.codeplex.com/).

Grz, Kris.

thanks for answer but it would be great if u discuss all the points with bit of example that may help me like beginner developer lots. thanks

Hi,

the best thing is to simply take a look at a DI container and its documentation and start using it. There are tutorials available on this site that show it:

Grz, Kris.

[RESOLVED]Get Custom Identity Field and store it into Session as soon as the website loads.

Hello! I do not know how to write this. I have added a custom field/column to the AspNetUsers table, which I use to load a custom ID after the user comes back to the site and is authenticated.

So, what I’m trying to do right now is to load it and store it into a session as soon as the website loads, independently from the controller which is called.

The problem that I’m facing right now is that I do not see an Identity method that actually grabs the data I want.

So, what I’m trying to do is to launch this code as soon as I can.

   var manager = new UserManager<AppUserModels>(new UserStore<AppUserModels>(new AppIdentityDbContext()));
   var currentUser = manager.FindById(User.Identity.GetUserId());
   Session["ID"] = currentUser.BoId.BoId;

But I don’t know where and how. I’m doing this because I do not want to call it from each controller.

Thanks!

Why don’t you issue it as a claim so it’s in the cookie? Look at the API that converts the User object into claims in the sample code. This is a much better approach and you don’t have to use session state (which you should avoid).

Thanks! I haven’t had the chance to use claims yet!

So should I avoid using Session[] at all?

superjose

So should I avoid using Session[] at all?

http://brockallen.com/2012/04/07/think-twice-about-using-session-state/

"Session state is stored in-memory by default. This is a horrible option if you want to remember data for your users. In ASP.NET the hosting application pool

frequently recycles
and this is typically out of your control. This means that all that in-memory state is lost, which is why using session state in-proc is a bad choice."

Amazing!

Thanks a lot!

=====================================

I’d like to thank you for the amazing page you’ve linked! I’m also working with something related to a shopping cart, and it was great to know these practices. It makes lots of sense what is written in the article. I shall use cookies instead of session
from now on.

Now, I’d like to also take this chance to learn how do I read the claim. I don’t know how. Just learned how to set the default like this:

  public class DefaultIdentityFactory : ClaimsIdentityFactory<AppUserModels, string>
        {
            public override async Task<ClaimsIdentity> CreateAsync(UserManager<AppUserModels, string> userManager,
                                        AppUserModels user, string authType)
            {
                var claimsIdentity = await base.CreateAsync(userManager, user, authType);
                claimsIdentity.AddClaim(new Claim("ID", user.IboID.IboID.ToString()));
                return claimsIdentity; ;
            }
        }

And then, I would call it in here:

   public AppUserManager(IUserStore<AppUserModels> store)
            : base(store)
        {
            this.ClaimsIdentityFactory = new DefaultIdentityFactory();
        }

Everything, so far, so good.

But I do not know which method is the one which takes care of calling the Claim’s value. 

Thanks a million!

var cp = (ClaimsPrincipal)User;

var someClaim = cp.FindFirst("someCLaimType");

var someValue = someClaim.Value;

Oooofffffff. Freaking sweeeeeeeettttt! This makes me super excited!!! :D :D :D

You’re the man! Cool Works flawlessly!!!! And that has solved a problem I’ve been fighting with for over a week!!!!! !YESSSSSS!!!!!!

That did the job! A  million thank you!!!

Woohoo – wohooooo hahahaha!!!!

Edit: Hahaha. I didn’t realize that it was your website ;).

[RESOLVED]MVC & External Controllers

I am new to MVC so this is a basic question. I have the following two projects:

1) A Web API that was generated with the PLINQO-EF (LINQ to SQL for Entity Framework) template for CodeSmith.

2) An MVC application using Kendo.

Project 2) needs to use the controllers which reside in project 1). My question is how to use the controllers from project 1) without moving the controllers to project 2), i.e. combining the projects.

Note that I can call the Web API from project 2) via PostAsJsonAsync. However, I want to be able to use constructs like

<siteMapNode controller="grid" action="index" title="my title" area="myarea"/>

hufaun

However, I want to be able to use constructs like

<siteMapNode controller="grid" action="index" title="my title" area="myarea"/>

And why you can put this construct?

You should use your other project as an external url in your sitemap

<siteMapNode
title="my
title
"
url="/virtualdirectory/myaread/grid/index"
/>

Hi hufaun,

Since these projects are independent of each other, in my opinion, you can’t able to access the Web API directly, you need to call it through
HttpClient class.

For the siteMapNote, you need to specify the absolute URL. If these projects are under a website, you could refer to
pprasannak’s solution.

Best Regards

Starain Chen