Post method does not send id - webapi

I have and issue that my post method is getting an id of null when i try and create a new post for my app.
public void Add(Project project)
{
_tRDbContext.Projects.Add(project);
var b = _tRDbContext.Projects.SingleOrDefault(p => p.ProjectId == project.ProjectId);
}
i cant see to find the issue.
my github link for this project is: https://github.com/FLiindberg/TimeRegsAPI

Related

How to add SurfaceController URL to Umbraco Server Variables to access from custom Umbraco DataType in Umbraco 9

I'm porting code for custom DataType from U8 to U9.
This DataType is calling a Surface controller to retrieve some data.
In the Umbraco v version I access the URL from the "Umbraco.Sys.ServerVariables" like:
var apiUrl = Umbraco.Sys.ServerVariables['MainKey']['Controller1URL'];
We set the value to this variable on project startup on the event ServerVariablesParser.Parsing like:
// https://our.umbraco.com/documentation/extending/version7-assets
public class BackofficeControllersURLListRegistrator : IComponent
{
public void Initialize()
{
Umbraco.Web.JavaScript.ServerVariablesParser.Parsing += ServerVariablesParser_Parsing;
}
private void ServerVariablesParser_Parsing(object sender, Dictionary<string, object> e)
{
if (HttpContext.Current == null) throw new InvalidOperationException("HttpContext is null.");
var backofficseUrls = new Dictionary<string, string>();
var url = new System.Web.Mvc.UrlHelper(new RequestContext(new HttpContextWrapper(HttpContext.Current), new RouteData()));
backofficseUrls.Add(
"Controller1URL", url.GetUmbracoApiService<Controllers.ApiControllers.Test1Controller>(controller => controller.TestFunction())
);
e.Add("MainKey", backofficseUrls);
}
public void Terminate()
{
}
}
How would we in Umbraco 9 hook up to ServerVariablesParser Notification if it exists and how to retrieve Controller function URL, so I can retrieve it in DataType JS code like in previous versions?
The question is for umbraco9, but i cant create a new tag...
As you say Umbraco 9 Events has been renamed to Notifications. Looking at the docs I cant see a ServerVariablesParser Notification. Could you not create a custom notification (here), use Dot peek to copy the code from ServerVariablesParser and implement your own event?

Adding newly created header by Asp.Net HeaderPropogation library to telemetry

services.AddHeaderPropogation(o =>
{
o.Headers.Add("Id")
o.Headers.Add("Id", context => {
return new StringValues(Guid.NewGuid().ToString())
});
});
The above code helps me to create a header called id if it doesnt exist with a new guid and if it exists, it would just use the value. This is using Microsoft Header Propogation nuget package. And it works.
But now i have a requirement to add this to Azure Application insights, but the standard way of doiing it only works when the incoming request has headers. If the new GUID is created, it doesnt trigger the ITelemetryInitializer call.
Because for adding Telmetry custom values, we have a class which inherits ITelemtryInitializer and inside that i do call to Request.Headers like below:
var requestTelemetry = telemetry as RequestTelemetry
if(context.Request.Headers.TryGetValue(id, out var value))
requestTelemtry.Properties[id] = value.ToString()
But the above line is never triggered since the Request.Headers never had this id. This id will be created only by the middleware when the api calls the next service.
So my question, is there a way to call the telemetry classes from the Startup> ConfigfureServices and inside the HeaderPropogation code, so that as soon as the new GUID is created, i can add it to telemtry. All the examples of adding to telemetry shows either from controller or DI. How to call it from the Startup itself ?
Or is there a better way to achieve the same ?
Let me post the solution I found. I didnt need to have a telemetryinitializer class to populate the guid in another class. I wanted it to be added as soon as we create it, so this is how i modified th header propogiation code in services in startup.
services.AddHeaderPropagation(options =>
{
var correlationId = "YourId";
options.Headers.Add(correlationId, context => {
var requestTelemetry = context.HttpContext.Features.Get<RequestTelemetry>();
if (context.HttpContext.Request.Headers.TryGetValue(correlationId, out var value))
{
requestTelemetry.Properties[correlationId] = value.ToString();
return value.ToString();
}
else
{
var guidId = Guid.NewGuid().ToString();
requestTelemetry.Properties[correlationId] = guidId;
return new StringValues(guidId);
}
});
});
Key for me has been the realization i can get RequestTelemetry anywhere we want in the code with this properties option.
var requestTelemetry = context.HttpContext.Features.Get<RequestTelemetry>();

Unity: Receive Firebase Short Dynamic Link in DynamicLinkReceived callback event

I would like to use Firebase Dynamic Links for Unity (Android/iOS) so users can invite friends and be rewarded with.
Each user gets a different Short Dynamic Link in the form of https://test.page.link/abcd
The user can share this Short DynamicLink with friends.
When the invited friend comes into the app, this callback is called.
private void OnDynamicLink(object sender, EventArgs args) {
var dynamicLinkEventArgs = args as ReceivedDynamicLinkEventArgs;
Debug.LogFormat("Received dynamic link {0}",
dynamicLinkEventArgs.ReceivedDynamicLink.Url.OriginalString);
}
Unfortunately, I only get back the base link that was necessary to create the short dynamic link.
Received dynamic link https://www.example.com/referral?xxxxxxxxxx
I get an additional native output in my iOS app:
IOSNative::Native->Unity callback data:
{"m_EventName":"continueUserActivity","m_Data":"https://test.page.link/?link=https://www.example.com/referral?xxxxxxxxxx&apn=de.test.testapp&isi=123456789&ibi=de.test.testapp&cid=1579347010984123886&_osl=https://test.page.link/abcd&_fpb=AB6327276CFGHT==&_cpt=cpit&_iumenbl=1&_iumchkactval=1&_plt=2076&_uit=2692&_cpb=1"}
2020-01-14 15:30:20.455009+0100 ambassador[315:8406]
IOSNative::Native->Unity callback data:
{"m_EventName":"applicationDidBecomeActive","m_Data":""}
Now my question is how do I get the generated short dynamic link that I have shared with a friend in OnDynamicLink callback( https://test.page.link/abcd)?
I need the value behind the parameter "&_osl" as seen in additional native output. But I only get the Base Url back in Unity (https://www.example.com/referral?xxxxxxxxxx).
My solution at the end was to shorten the BaseLink with the help of DynamicLinks.GetShortLinkAsync.
//unescape url
baseLink = UnityEngine.Networking.UnityWebRequest.UnEscapeURL(baseLink);
var components = new DynamicLinkComponents(
// The base Link.
new Uri(baseLink),
// The dynamic link URI prefix.
domainUriPrefix) {
IOSParameters = new IOSParameters(PackageName) {
AppStoreId = "XXXXXXXXX"
},
AndroidParameters = new AndroidParameters(PackeName)
};
string inviteLink = string.Empty;
await DynamicLinks.GetShortLinkAsync(components, options).ContinueWith((task) => {
if (task.IsCanceled) {
Debug.LogError("GetShortLinkAsync was canceled.");
return;
}
if (task.IsFaulted) {
Debug.LogError("GetShortLinkAsync encountered an error: " + task.Exception);
return;
}
// Short Link has been created.
inviteLink = task.Result.Url.ToString();
});

LiveAuthClient broken?

It seems very much that the current version of LiveAuthClient is either broken or something in my setup/configuration is. I obtained LiveSDK version 5.4.3499.620 via Package Manager Console.
I'm developing an ASP.NET application and the problem is that the LiveAuthClient-class seems to not have the necessary members/events for authentication so it's basically unusable.
Notice that InitializeAsync is misspelled aswell.
What's wrong?
UPDATE:
I obtained another version of LiveSDK which is for ASP.NET applications but now I get the exception "Could not find key with id 1" everytime I try either InitializeSessionAsync or ExchangeAuthCodeAsync.
https://github.com/liveservices/LiveSDK-for-Windows/issues/3
I don't think this is a proper way to fix the issue but I don't have other options at the moment.
I'm a little late to the party, but since I stumbled across this trying to solve what I assume is the same problem (authenticating users with Live), I'll describe how I got it working.
First, the correct NuGet package for an ASP.NET project is LiveSDKServer.
Next, getting user info is a multi-step process:
Send the user to Live so they can authorize your app to access their data (the extent of which is determined by the "scopes" you specify)
Live redirects back to you with an access code
You then request user information using the access code
This is described fairly well in the Live SDK documentation, but I'll include my very simple working example below to put it all together. Managing tokens, user data, and exceptions is up to you.
public class HomeController : Controller
{
private const string ClientId = "your client id";
private const string ClientSecret = "your client secret";
private const string RedirectUrl = "http://yourdomain.com/home/livecallback";
[HttpGet]
public ActionResult Index()
{
// This is just a page with a link to home/signin
return View();
}
[HttpGet]
public RedirectResult SignIn()
{
// Send the user over to Live so they can authorize your application.
// Specify whatever scopes you need.
var authClient = new LiveAuthClient(ClientId, ClientSecret, RedirectUrl);
var scopes = new [] { "wl.signin", "wl.basic" };
var loginUrl = authClient.GetLoginUrl(scopes);
return Redirect(loginUrl);
}
[HttpGet]
public async Task<ActionResult> LiveCallback(string code)
{
// Get an access token using the authorization code
var authClient = new LiveAuthClient(ClientId, ClientSecret, RedirectUrl);
var exchangeResult = await authClient.ExchangeAuthCodeAsync(HttpContext);
if (exchangeResult.Status == LiveConnectSessionStatus.Connected)
{
var connectClient = new LiveConnectClient(authClient.Session);
var connectResult = await connectClient.GetAsync("me");
if (connectResult != null)
{
dynamic me = connectResult.Result;
ViewBag.Username = me.name; // <-- Access user info
}
}
return View("Index");
}
}

Database not updating model in MVC

So i just started using ASP.NET MVC and i'm really liking it, except i seem to have an odd knack to encounter the most bizarre of errors. I'm making a simple blogging application for myself. I have two simple models: post and comment. I have a partial view for creating a comment that is embedded in the details view for each post. When i submit the form to update the comment, it goes to my CommentsController's create action, which looks like...
[HttpPost]
public ActionResult Create(comment comment)
{
comment.date = DateTime.Now;
if (ModelState.IsValid)
{
post p = db.posts.Find(comment.post); //I've verified that comment.post is coming in
if (p.comments == null) p.comments = new List<comment>();
p.comments.Add(comment);
db.Entry(p).State = EntityState.Modified; //I'm using this line since that's how its done in the edit actionmethod of the BlogController. I was just updating db.posts.Find(... manually, but that wasn't workign either.
db.comments.Add(comment);
db.SaveChanges();
return RedirectToAction("Details", "Blog", new { id = comment.post });
}
return PartialView(comment);
}
The problem is that while the comment gets added to the database just fine, the post doesn't update. When i examine p just before the changes are saved, it's updated, but apparently it never actually commits to database since when i redirect to the Details, those comments aren't there. Is there anything obviously wrong with my code? Am i missing some basic fundamental of .NET or MVC? Let me know if i need to provide more code or context.
Interesting Note: No matter what, post.comments always seems to be null. I set it to an empty list when the post is created, but it still seems to come back null. Not sure if this is just a result of trying to store an empty list or if it has to do with my problem, though. Again, lemme know and i'll stick anything else needed up here.
Thanks!
Perhaps saving the changes is working fine but you don't see the saved comments to a post because you don't load them when you display the post. You can eager load the comments of a post in your action which displays a post like so:
post p = db.posts
.Include(p1 => p1.comments)
.Where(p1 => p1.Id == id)
.SingleOrDefault();
I also think that you can simplify your Create action:
[HttpPost]
public ActionResult Create(comment comment)
{
comment.date = DateTime.Now;
if (ModelState.IsValid)
{
db.comments.Add(comment);
db.SaveChanges();
return RedirectToAction("Details", "Blog", new { id = comment.post });
}
return PartialView(comment);
}
This should work if comment.post is the foreign key of a comment to the related post. (Your code looks like this is the case, because of Find(comment.post))
While #Slauma led me to my solution, I'm just posting my final code i used for future reference (thanks #George Stocker)
public ActionResult Create(comment comment)
{
comment.date = DateTime.Now;
if (ModelState.IsValid)
{
db.comments.Add(comment);
db.SaveChanges();
return RedirectToAction("Details", "Blog", new { id = comment.post });
}
return PartialView(comment);
}
and to retrieve comments...
public ActionResult Details(int id)
{
var post = (from p in db.posts
where p.id == id
select new { p.id, p.title, p.content, p.date, p.tag, comments = (from c in db.comments where c.post == id select c) }).SingleOrDefault();
post p2 = new post(post.id, post.title, post.content, post.date,post.tag, post.comments.ToList());
return View(p2);
}

Resources