I'm working with a very weird endpoint,
Now the data I post to my endpoint is the scorecardId and the DashboardConfig and the rest of my data is populated via the backend, which is the UserId and the DateCreated, Now I need to do a get request for the specific user and I did something like this:
#region Public Methods
[HttpGet]
[Route("GetbyUserID")]
[ValidateModel]
public IHttpActionResult GetbyUserID(Guid UserID)
{
UserID = this.GetUserId();
var config = _prefentialDashboardConfigService.GetByUserID(UserID);
return Ok(config);
}
My model:
public Guid ScorecardId { get; set; }
public Guid UserId { get; set; }
public DateTime DateCreated { get; set; }
public string DashboardConfig { get; set; }
My CRUD:
public PrefentialDashboardConfig GetByUserID(System.Guid UserId, params string[] includes)
{
return Repository.SingleOrDefault<PrefentialDashboardConfig>(config => config.UserId == UserId, includes);
}
}
My ICRUD:
T SingleOrDefault<T>(Expression<Func<T, bool>> where, params string[] includes) where T : class;
And in my front end I just called the get request but it gives me a 404 resource not found error. I call my end point like this in knockout:
var test = PreferentialProcurementDashboardApi.GetbyUserID();
//For testing purposes
console.log("You got it right!" + JSON.stringify(test));
What would be the best way to get my data to the frontend console by the UserId which is taken from my backend?
only guessing, you are probably not passing the UserId when you are doing the http get request.
var test = PreferentialProcurementDashboardApi.GetbyUserID();
probably should be
var test = PreferentialProcurementDashboardApi.GetbyUserID(5);
check the network tab in the browser dev tools to make sure that there are parameters are being passed to the backend
Related
I have a webApi and an MVC application.
The webApi has all the logic and the MVC application is just the presentation.
Im using RestSharp to get the data from the WebApi to the MVC application.
Im sharing here one method that retrieves all user information
public IUser getUserInformationLogin(string palsoftID)
{
var request = new RestRequest("FrontDeskLog/GetUserInfo/{PalsoftID}", Method.POST) { RequestFormat = DataFormat.Json };
request.AddParameter("PalsoftID", palsoftID, ParameterType.UrlSegment);
var response = service.Execute<User>(request);
return response.Data
}
everything is good until I add Serialize attribute to the User class, I need to make User serializable in order to use session state StateServer for my MVC application.
But after adding the serialize attr the above method always returns null.
If I debug i can see that in the Response. Content all data is there, but response.data returns a null object.
Any help will be very appreciated.
The Method in the webApi is this one
public IUser GetUserInfo(string PalsoftID)
{
FrontDeskDb data = new FrontDeskDb();
return data.getUsersInfo(PalsoftID);
}
this is the class Roles
public class Roles
{
public int RoleID { get; set; }
public string Role { get; set; }
public bool Main { get; set; }
}
Thank you.
I am trying to implement Oauth 2.0 security integration with Asp.net web api 2 but only with external logins like google.I am pretty new for Oauth thing.
Can any one suggest any good tutorial/ example with only external login.
I do not want local user to register etc.
Google describes all the options pretty well on their website Using OAuth 2.0 to Access Google APIs
The most important steps are:
Register your application at Google Developer Console
Enable all your required scopes
Specify the allowed callback url to your website
Basically it works like this:
You redirect the user to your /api/Account/Login page
This Action method will redirect the user to the Google login page
User logs in and gets redirected to the callback url you specified (and approved in the Developer Console)
This callback url Action method will ask Google for a token based on the authorization code.
Following code snipped should get you started:
[RoutePrefix("api/Account")]
public class AccountController : ApiController
{
private readonly string _clientId = "YourCliendId";
[Route("Login")]
public HttpResponseMessage GetLogin()
{
string scope = HttpUtility.UrlEncode("Space Seperated list of scopes");
string redirectUri = HttpUtility.UrlEncode("http://YourWebsiteURL/api/Account/OAuthCallback");
string accessType = "Either online or offline";
string requestUri = string.Format("https://accounts.google.com/o/oauth2/auth?response_type=code&client_id={0}&redirect_uri={1}&scope={2}&access_type={3}&approval_prompt=auto&include_granted_scopes=true", _clientId, redirectUri, scope, accessType);
HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.MovedPermanently);
response.Headers.Location = new Uri(requestUri);
return response;
}
[Route("Logout")]
public HttpResponseMessage GetLogout()
{
//Optionally if you need to be able to logout...
HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.Moved);
response.Headers.Location = new Uri("https://accounts.google.com/logout");
return response;
}
[Route("OAuthCallback")]
public HttpResponseMessage GetOAuthCallback(string error)
{
//This would be a nice place to include some logging...
HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.Moved);
response.Headers.Location = new Uri("http://YourWebsiteURL");
return response;
}
[Route("OAuthCallback")]
public HttpResponseMessage GetOAuthCallback(string code, string scope)
{
string redirectUri = HttpUtility.UrlEncode("http://YourWebsiteURL/api/Account/OAuthCallback");
string postMessage = string.Format("code={0}&client_id={1}&client_secret={2}&redirect_uri={3}&grant_type=authorization_code", code, _clientId, "YourGoogleSecretCode", redirectUri);
string jsonMessage;
using (WebClient client = new WebClient())
{
//Convert the authorization code to a token
client.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded; charset=utf-8";
jsonMessage = client.UploadString("https://accounts.google.com/o/oauth2/token", "POST", postMessage);
}
Token token = JsonConvert.DeserializeObject<Token>(jsonMessage);
//Do something with the token. E.g. put it in a cookie / header ... and pass it to the client.
}
}
public class Token
{
[JsonProperty("access_token")]
public string AccessToken { get; set; }
[JsonProperty("expires_in")]
public int ExpiresIn { get; set; }
[JsonProperty("token_type")]
public string TokenType { get; set; }
}
public class TokenInfo
{
[JsonProperty("issued_to")]
public string IssuedTo { get; set; }
[JsonProperty("audience")]
public string Audience { get; set; }
[JsonProperty("user_id")]
public string UserId { get; set; }
[JsonProperty("scope")]
public string Scope { get; set; }
[JsonProperty("expires_in")]
public int ExpiresIn { get; set; }
[JsonProperty("email")]
public string Email { get; set; }
[JsonProperty("verified_email")]
public bool VerifiedEmail { get; set; }
[JsonProperty("access_type")]
public string AccessType { get; set; }
}
BTW. If you need to later on validate the token you can use the following code:
string requestUri = string.Format("https://www.googleapis.com/oauth2/v1/tokeninfo?access_token={0}", token.AccessToken);
string tokenInfoMessage;
using (WebClient client = new WebClient())
{
tokenInfoMessage = client.DownloadString(requestUri);
}
TokenInfo tokenInfo = JsonConvert.DeserializeObject<TokenInfo>(tokenInfoMessage);
//Don't forget to validate the Audience and Scope, because the token might be a valid token (but not meant for your website).
if (tokenInfo.Audience == _clientId && tokenInfo.Scope.Contains("All the scopes that you provided") && tokenInfo.UserId == "TheGoogleUserIdYouWantToCheck")
{
//Looks valid, so continue with whatever you want to do...
}
I need to use EntityQuery in BreezeSharp to get Access Token from my Breeze WebAPI
I have a class called TokenResponseModel for deserializing my json from the server as follows:
using Newtonsoft.Json;
namespace CMIS.Integration.Common
{
class TokenResponseModel
{
[JsonProperty("access_token")]
public string AccessToken { get; set; }
[JsonProperty("token_type")]
public string TokenType { get; set; }
[JsonProperty("expires_in")]
public int ExpiresIn { get; set; }
[JsonProperty("userName")]
public string Username { get; set; }
[JsonProperty(".issued")]
public string IssuedAt { get; set; }
[JsonProperty(".expires")]
public string ExpiresAt { get; set; }
}
}
I have the following code to run:
EntityQuery query=EntityQuery.From("Token",new TokenResponseModel()).
WithParameters(new Dictionary<string,object>{{"grant_type","password"},{"username","my_username"},{"password","my_password"}});
EntityManager mng = new EntityManager(baseUrl);
var tokenobject = await query.Execute(mng);
When I run it, I Get an error. It requires metadata which is not there for the "/Token" method on the server.
How Can I call it with BreezeSharp.
With RestSharp I can do it as follows:
RestRequest request = new RestRequest("/Token", Method.POST);
request.AddParameter("grant_type", "password");
request.AddParameter("username", "my_username");
request.AddParameter("password", "my_password");
RestClient client = new RestClient(baseUrl);
var response = client.Execute<AccessToken>(request);
And this works fine.
Thanks
More Explanation:
What I want to say is that sometimes I just need to get the result from the breeze server just i a JSON format. I don't want it mapped to any objects on the client. A good example is my case for authenticating a user using the Token method. I know how to parse the JSON myself. I just want breeze to bring the result from the call below:
string baseUrl = "http://myserver_url/NHIFService/";
EntityQuery query = EntityQuery.From<string>("Token").WithParameters(new new Dictionary<string, object> { { "grant_type", "password" }, { "username", "my_username" }, { "password", "my_password" } });
EntityManager mng = new EntityManager(baseUrl);
var tokenobject = await query.Execute(mng);
I want to be able to do this because sometimes I return anonymous objects from the server that do not have a match on the client or server.
Can breese sharp allow me to do this without caring about the metadata. Or how can I supress metadata fetching.
Thank you.
After going through the BreezeSharp Source Code I came with the solution for doing what I wanted. The guys at IdeaBlade have created this DataService class that enables returning RAW JSON from the server without even caring about the Metadata. Here is how I did it:
string token = await AuthenticationHelper.GetAccessToken();
string baseUrl = "http://my_server_url/appname/breeze/my_controller/";
DataService ds = new DataService(baseUrl);
string resourcePath = string.Format("GetCardDetails?CardNo={0}", cardNoTextEdit.EditValue);
ds.HttpClient.DefaultRequestHeaders.Add("Authorization", "Bearer " + token);
string result=await ds.GetAsync(resourcePath);
Congratulation guys Breeze Sharp is awesome.
I just followed an MVC tutorial on creating an image Gallery, which connects the Controller to the data connection, like this:
ImageController.cs:
...
private CustomMembershipDB db = new CustomMembershipDB();
public ViewResult Index()
{
return View(db.lm_pics.ToList());
}
...
Instead of connecting directly to CustomMembershipDB, I'd like to use my own Model named GalleryModel.cs. I'm thinking this would allow me to create more functionality that just direct data access.
I am not sure how to write this model, or how to reference it in the controller so that it behaves the same way as a direct database connection does now.
Currently, my GalleryModel.cs file looks lke this (edited to correct error):
namespace LMProj_MVC.Models
{
public class GalleryModel
{
public string Picname { get; set; }
public string Decription{ get; set; }
public int Userid { get; set; }
}
public class PicDBContext : CustomMembershipDB
{
public DbSet<GalleryModel> GalleryModel { get; set; }
}
}
I'd like to be able to show the gallery using an iEnumberable list as I am doing now, in addition to creating other methods. Could someone tell me what I'm missing?
You need to create an instance of your model object for each of your database pictures. You could use LINQ to do this, for example:
var picSummaries = db.lm_pics.Select(pic => new GalleryModel{
Picname = pic.Name,
Description = pic.Description,
Userid = pic.User.Id
});
Or you could use a for each loop:
var picSummaries = new List<GalleryModel>();
foreach (var pic in db.lm_pics)
{
picSummaries.Add(new GalleryModel{
Picname = pic.Name,
Description = pic.Description,
Userid = pic.User.Id
});
}
then return the view as before:
return View(picSummaries);
Id like to have my mvc 2 app generating reports in both MS Word and PDF formats....currently working on Word. I found this:
http://www.revium.com.au/articles/sandbox/aspnet-mvc-convert-view-to-word-document/
Which i think basically streams the view output from a controller action to a word document....
public ActionResult DetailedReport()
{
//[...]
return View();
}
public ActionResult DetailedReportWord()
{
string url = "DetailedReport";
return new WordActionResult(url, "detailed-report.doc");
}
And heres the class that extends ActionResult
public class WordActionResult : ActionResult
{ private string Url { get; set;}
private string FileName { get; set;}
public WordActionResult(string url, string fileName)
{
Url = url;
FileName = fileName;
}
public override void ExecuteResult(ControllerContext context)
{
var curContext = HttpContext.Current;
curContext.Response.Clear();
curContext.Response.AddHeader("content-disposition", "attachment;filename=" + FileName);
curContext.Response.Charset = "";
curContext.Response.Cache.SetCacheability(HttpCacheability.NoCache);
curContext.Response.ContentType = "application/ms-word";
var wreq = (HttpWebRequest) WebRequest.Create(Url);
var wres = (HttpWebResponse) wreq.GetResponse();
var s = wres.GetResponseStream();
var sr = new StreamReader(s, Encoding.ASCII);
curContext.Response.Write(sr.ReadToEnd());
curContext.Response.End();
}
}
Which looks pretty good - but my problem is that my view renders from a ViewModel, here is the Action
[HttpPost]
public ActionResult StartSearch(SearchResultsViewModel model)
{
SearchResultsViewModel resultsViewModel = _searchService.Search(model.Search, 1, PAGE_SIZE);
return View("Index", resultsViewModel);
}
and here is my model:
public class SearchResultsViewModel
{
[SearchWordLimit]
public string Search { get; set; }
public IEnumerable<Employee> Employees { get; private set; }
public IEnumerable<Organization> Organizations { get; private set; }
public PageInfo PageInfo { get; private set;}
public SearchResultsViewModel()
{
}
public SearchResultsViewModel(string searchString, IEnumerable<Employee> employees, IEnumerable<Organization> organizations, PageInfo pageInfo)
{
Search = searchString;
Employees = employees;
Organizations = organizations;
PageInfo = pageInfo;
}
}
I'm having trouble kinda connecting the two - to stream the view using my viewmodel to pdf
There's nothing out of the box in ASP.NET MVC that allows you to build a PDF or Word file from a POCO class. You have to build it manually or using a third party library. Once you have done this you could easily write the bytes to the response stream:
public ActionResult SomeAction(SearchResultsViewModel model)
{
byte[] pdf = GeneratePdfForModel(model);
return File(pdf, "application/pdf");
}
The GeneratePdfForModel method will of course be specific on what library/API you are using to generate the document.
The trick is to generate the PDF file from the MS-Word file. You most likely need a 3rd party component for this.
If you don't need perfect conversion fidelity, just something that is 'good enough', then try Aspose.Words. If you need perfect conversion Fidelity then try a product I have worked on, it allows the conversion of all typical MS-Office types to PDF format using a web services interface.
I'm a bit late to this, but from what I can see:
public ActionResult DetailedReportWord()
{
string url = "DetailedReport";
return new WordActionResult(url, "detailed-report.doc");
}
Your url is pointing back to the same Action, it should be pointing at your "StartSearch" action as that is the one that produces the HTML you are wanting to be opened by Word. It needs to be a full URL too I think.
I am trying to use this method too, I found it from your question! I'm having issues passing over the authorised credentials in the WebRequest.Create(Url) for the source View however.