I need to get some data from service and display it in HTML. I have put API call in service, and I got that data in ts file(checked in console), But When I am trying to get the same data into html, its showing null reference exception. Couldnt figure out what I missed.
export class SsoComponent implements OnInit {
public samlResponseData: SamlResponse;
constructor(
private ssoService: SsoService,
private store: Store<AppState>) { }
ngOnInit() {
this.verifySessionExpiration();
}
public verifySessionExpiration() {
this.store.pipe(select(getAuthData))
.subscribe(authData => {
if (authData) {
this.ssoService.fetchSamlResponse()
.subscribe(samlResponse => {
console.log(samlResponse);
this.samlResponseData = samlResponse;
});
} else {
this.ssoService.goLogin();
}
});
}
I am seeing the correct response in console. This is my code in HTML.
{{samlResponseData.ResponseData}}
I am getting a console error saying, "Unable to set property 'ResponseData' of undefined or null reference"
I have a model SamlResponse with a string property that I want to show it in HTML.
Please help.
The logic you have in verifySessionExpiration() asynchronous. You are getting that error because your template is trying to access samlResponseData before it has a value.
One way to fix it would be to only render the data when you know the value isn't null or undefined.
<ng-container *ngIf="samlResponseData">
{{samlResponseData.ResponseData}}
</ng-container>
Another option would be to initialize samlResponseData to some empty object:
samlResponseData = {};
Related
I was hoping to get some insight on the error that are produced by the system. I am using a already built message system that I got some time ago and it works but sometimes on the forms I will get errors that I do not understand. For instance on a Create I have a try / catch block that produces a message if it has successfully Executed. I have tried to search for these errors in my project and it does not come up with anything. Even if it was in meta data a search should find it.
I use System.Text.StringBuilder sb = new System.Text.StringBuilder(); for the message and the code looks like this:
public ActionResult Create(Vendors model)
{
System.Text.StringBuilder sb = new System.Text.StringBuilder();
try
{
if (ModelState.IsValid)
{
var userId = User.Identity.GetUserId();
//var getdata = ExtendedViewModels.VendorToEntity(model);
model.VendorId = Guid.NewGuid();
model.CreatedDate = System.DateTime.Now;
model.CreatedBy = User.Identity.Name;
model.Status = true;
db.Vendors.Add(model);
db.SaveChanges();
sb.Append("Submitted");
return Content(sb.ToString());
}
else
{
foreach (var key in this.ViewData.ModelState.Keys)
{
foreach (var err in this.ViewData.ModelState[key].Errors)
{
sb.Append(err.ErrorMessage + "<br/>");
}
}
}
}
catch (Exception ex)
{
sb.Append("Error :" + ex.Message);
}
return Content(sb.ToString());
}
When this returns or closes the Modal it produces a message or if there is an error it will produce that so you can fix it like a Required field. If everything is okay it will produce from this:
#Html.StarkAjaxFormSubmiter("frmVendors", "tbVendors", true, "Action Successfully Executed")
This is a green box that shows up as "Action Successfully Executed". If something is wrong a red box shows up and you get a message. In my case I am getting a red box that says Submitted Read Warnings Alerts This is how it is spelled. I doubt this is a error that comes from ASP.Net it looks more like a custom message, I dont know what it means and I cannot find it anywhere. Regardless, it does create the record in the db. The other error I have gotten shows Something is went wrong [object, object] Not only do I want to find out what these mean, I also want to clean them up and give a proper message that makes sense. Does anyone have any ideas as to how to correct this? Could they be encypted in the custom package that was written for this? That is why I cannot find them. I have also viewed the package and did not find anything for this.
This is from Meta data:
//
// Parameters:
// stark:
//
// FormId:
// Enter Here Form ID LIKE So you have to pass = frmCreate
//
// DataTableId:
// Which DataTable You have update after submit provide that ID
//
// IsCloseAfterSubmit:
// Do you want to opened popup close after submit , So pass=true or false any
//
// SuccessMessage:
// Give any Success message
public static MvcHtmlString StarkAjaxFormSubmiter(this HtmlHelper stark, string FormId, string DataTableId, bool IsCloseAfterSubmit, string SuccessMessage);
//
// Parameters:
// stark:
//
// FormId:
// Enter Here Form ID LIKE So you have to pass = frmCreate
//
// DataTableId:
// Which DataTable You have update after submit provide that ID
//
// IsCloseAfterSubmit:
// Do you want to opened popup close after submit , So pass=true or false any
//
// SuccessMessage:
// Give any Success message
//
// AfterSuccessCode:
// Add other JQuery code if you want
public static MvcHtmlString StarkAjaxFormSubmiter(this HtmlHelper stark, string FormId, string DataTableId, bool IsCloseAfterSubmit, string SuccessMessage, string AfterSuccessCode);
Thanks for our help
UPDATE:
I did some searching on the web and found a program called JetBrains dotPeek. I decompiled the dll and sure enough the messages are in there. So I should be able to change them and recompile it and add if I want, to it.
I was not able to edit the decompiled dll. So I decided to just create a class in the main project and copy the the code to that class. Changing what I needed. Where my trouble was, was with misspellings. The dll used Sumitted as the sb.Append("Sumitted") I changed that in the controller to be Submitted. So the dll did not find "Sumitted" in the action, and in the dll class there is an If statement that faults to error if not found - which was listed as Read Warnings Error. I changed that and fixed all the misspellings. I also got rid of the Something is went wrong and changed it to something more meaningful. I will continue to add to this to give more meaningful messages. It helps to know what the error is, instead of [object], [object]. I dont know if this will help others, maybe if they have downloaded the same code I have and have issues.
I'm quite new in programming multi-threading and I could not understand from the xelium example how I could execute a javascript and get the return value.
I have tested:
browser.GetMainFrame().ExecuteJavaScript("SetContent('my Text.')", null, 0);
the javascript is executed, but I this function don’t allow me to get the return value.
I should execute the following function to get all the text the user have written in the box..
browser.GetMainFrame().ExecuteJavaScript("getContent('')", null, 0);
the function TryEval should do this…
browser.GetMainFrame().V8Context.TryEval("GetDirtyFlag", out returninformation , out exx);
But this function can’t be called from the browser, I think it must be called from the renderer? How can I do so?
I couldn’t understand the explanations about CefRenderProcessHandler and OnProcessMessageReceived.. How to register a Scriptable Object and set my javascript & parameters?
Thx for any suggestions how I could solve this!
I have been struggling with this as well. I do not think there is a way to do this synchronously...or easily :)
Perhaps what can be done is this:
From browser do sendProcessMessage with all JS information to renderer
process. You can pass all kinds of parameters to this call in a structured way so encapsulating the JS method name and params in order should not be difficult to do.
In renderer process (RenderProcessHandler onProcessMessageReceived method) do TryEval on the V8Context and get the return value via out parameters and sendProcessMessage back to the
browser process with the JS return value (Note that this supports ordinary return semantics from your JS method).You get the browser instance reference in the onProcessMessageReceived so it is as easy as this (mixed pseudo code)
browser.GetMainFrame().CefV8Context.tryEval(js-code,out retValue, out exception);
process retValue;
browser.sendProcessMessage(...);
Browser will get a callback in the WebClient in onProcessMessageReceived.
There is nothing special here in terms of setting up JS. I have for example a loaded html page with a js function in it. It takes a param as input and returns a string. in js-code parameter to TryEval I simply provide this value:
"myJSFunctionName('here I am - input param')"
It is slightly convoluted but seems like a neat workable approach - better than doing ExecuteJavaScript and posting results via XHR on custom handler in my view.
I tried this and it does work quite well indeed....and is not bad as it is all non-blocking. The wiring in the browser process needs to be done to process the response properly.
This can be extended and built into a set of classes to abstract this out for all kinds of calls..
Take a look at the Xilium demo app. Most of the necessary wiring is already there for onProcessMessage - do a global search. Look for
DemoRendererProcessHandler.cs - renderer side this is where you will invoke tryEval
DemoApp.cs - this is browser side, look for sendProcessMessage - this will initiate your JS invocation process.
WebClient.cs - this is browser side. Here you receive messages from renderer with return value from your JS
Cheers.
I resolved this problem by returning the result value from my JavaScript function back to Xilium host application via an ajax call to a custom scheme handler. According to Xilium's author fddima it is the easiest way to do IPC.
You can find an example of how to implement a scheme handler in the Xilium's demo app.
Check out this post: https://groups.google.com/forum/#!topic/cefglue/CziVAo8Ojg4
using System;
using System.Windows.Forms;
using Xilium.CefGlue;
using Xilium.CefGlue.WindowsForms;
namespace CefGlue3
{
public partial class Form1 : Form
{
private CefWebBrowser browser;
public Form1()
{
InitializeCef();
InitializeComponent();
}
private static void InitializeCef()
{
CefRuntime.Load();
CefMainArgs cefArgs = new CefMainArgs(new[] {"--force-renderer-accessibility"});
CefApplication cefApp = new CefApplication();
CefRuntime.ExecuteProcess(cefArgs, cefApp);
CefSettings cefSettings = new CefSettings
{
SingleProcess = false,
MultiThreadedMessageLoop = true,
LogSeverity = CefLogSeverity.ErrorReport,
LogFile = "CefGlue.log",
};
CefRuntime.Initialize(cefArgs, cefSettings, cefApp);
}
private void Form1_Load(object sender, EventArgs e)
{
browser = new CefWebBrowser
{
Visible = true,
//StartUrl = "http://www.google.com",
Dock = DockStyle.Fill,
Parent = this
};
Controls.Add(browser);
browser.BrowserCreated += BrowserOnBrowserCreated;
}
private void BrowserOnBrowserCreated(object sender, EventArgs eventArgs)
{
browser.Browser.GetMainFrame().LoadUrl("http://www.google.com");
}
}
}
using Xilium.CefGlue;
namespace CefGlue3
{
internal sealed class CefApplication : CefApp
{
protected override CefRenderProcessHandler GetRenderProcessHandler()
{
return new RenderProcessHandler();
}
}
internal sealed class RenderProcessHandler : CefRenderProcessHandler
{
protected override void OnWebKitInitialized()
{
CefRuntime.RegisterExtension("testExtension", "var test;if (!test)test = {};(function() {test.myval = 'My Value!';})();", null);
base.OnWebKitInitialized();
}
}
}
I've got a custom list that contains multi collumns. The validation is made by a custom contenttype. Now I want a combination of two columns to be unique. Until know I did not found a way to solve this problem with on-board functions, so my idea was to use the eventreceiver or a customcontenttype.
What I tried:
ListEventReceiver
public override void ItemAdding(SPItemEventProperties properties)
{
if (properties.AfterProperties["a1"].ToString() == properties.AfterProperties["a2"].ToString())
{
properties.Status = SPEventReceiverStatus.CancelWithError;
properties.Cancel = true;
properties.ErrorMessage = "Failure";
}
base.ItemAdding(properties);
}
It works fine, but the error message is not show as a validation error. It is a new errorpage.
CustomContenttype
If I try to validate in a custom contenttype I can not access the value of an other field from the contenttype. So I can not compare two fields or check they are unique.
if you want to validation using ItemEventReceiver than you should use Sharepoint Error message page.
its will so you better of your Errormessage.I have used it.
Like :
if (properties.AfterProperties["a1"].ToString() == properties.AfterProperties["a2"].ToString())
{
properties.Status = SPEventReceiverStatus.CancelWithRedirectUrl;
properties.RedirectUrl = properties.WebUrl + "/_layouts/error.aspx?ErrorText=Entry is Failure";
}
or another way is Use PreSaveAction with javascript able to do valiation on list's forms.
I'm tryping to use JSON to update records in a database without a postback and I'm having trouble implementing it. This is my first time doing this so I would appreciate being pointed in the right direction.
(Explanation, irrelevant to my question: I am displaying a list of items that are sortable using a jquery plugin. The text of the items can be edited too. When people click submit I want their records to be updated. Functionality will be very similar to this.).
This javascript function creates an array of the objects. I just don't know what to do with them afterwards. It is called by the button's onClick event.
function SaveLinks() {
var list = document.getElementById('sortable1');
var links = [];
for (var i = 0; i < list.childNodes.length; i++) {
var link = {};
link.id = list.childNodes[i].childNodes[0].innerText;
link.title = list.childNodes[i].childNodes[1].innerText;
link.description = list.childNodes[i].childNodes[2].innerText;
link.url = list.childNodes[i].childNodes[3].innerText;
links.push(link);
}
//This is where I don't know what to do with my array.
}
I am trying to get this to call an update method that will persist the information to the database. Here is my codebehind function that will be called from the javascript.
public void SaveList(object o )
{
//cast and process, I assume
}
Any help is appreciated!
I have recently done this. I'm using MVC though it shouldn't be too different.
It's not vital but I find it helpful to create the contracts in JS on the client side and in C# on the server side so you can be sure of your interface.
Here's a bit of sample Javascript (with the jQuery library):
var item = new Item();
item.id = 1;
item.name = 2;
$.post("Item/Save", $.toJSON(item), function(data, testStatus) {
/*User can be notified that the item was saved successfully*/
window.location.reload();
}, "text");
In the above case I am expecting text back from the server but this can be XML, HTML or more JSON.
The server code is something like this:
public ActionResult Save()
{
string json = Request.Form[0];
var serializer = new DataContractJsonSerializer(typeof(JsonItem));
var memoryStream = new MemoryStream(Encoding.Unicode.GetBytes(json));
JsonItem item = (JsonItem)serializer.ReadObject(memoryStream);
memoryStream.Close();
SaveItem(item);
return Content("success");
}
Hope this makes sense.
You don't use CodeBehind for this, you use a new action.
Your action will take an argument which can be materialized from your posted data (which, in your case, is a JavaScript object, not JSON). So you'll need a type like:
public class Link
{
public int? Id { get; set; }
public string Title { get; set; }
public string Description { get; set; }
public string Url { get; set; }
}
Note the nullable int. If you have non-nullable types in your edit models, binding will fail if the user does not submit a value for that property. Using nullable types allows you to detect the null in your controller and give the user an informative message instead of just returning null for the whole model.
Now you add an action:
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult DoStuff(IEnumerable<Link> saveList)
{
Repository.SaveLinks(saveList);
return Json(true);
}
Change your JS object to a form that MVC's DefaultModelBinder will understand:
var links = {};
for (var i = 0; i < list.childNodes.length; i++) {
links["id[" + i + "]"] = list.childNodes[i].childNodes[0].innerText;
links["title[" + i + "]"] = list.childNodes[i].childNodes[1].innerText;
links["description[" + i + "]"] = list.childNodes[i].childNodes[2].innerText;
links["url[" + i + "]"] = list.childNodes[i].childNodes[3].innerText;
}
Finally, call the action in your JS:
//This is where I don't know what to do with my array. Now you do!
// presumes jQuery -- this is much easier with jQuery
$.post("/path/to/DoStuff", links, function() {
// success!
},
'json');
Unfortunately, JavaScript does not have a built-in function for serializing a structure to JSON. So if you want to POST some JSON in an Ajax query, you'll either have to munge the string yourself or use a third-party serializer. (jQuery has a a plugin or two that does it, for example.)
That said, you usually don't need to send JSON to the HTTP server to process it. You can simply use an Ajax POST request and encode the form the usual way (application/x-www-form-urlencoded).
You can't send structured data like nested arrays this way, but you might be able to get away with naming the fields in your links structure with a counter. (links.id_1, links.id_2, etc.)
If you do that, then with something like jQuery it's as simple as
jQuery.post( '/foo/yourapp', links, function() { alert 'posted stuff' } );
Then you would have to restructure the data on the server side.
I am using a jQuery Ajax control from this site http://abeautifulsite.net/2008/03/jquery-file-tree/
I have it all working. I tried to ask a support question but never heard back, thinking maybe someone on here can shed some light on the situation.
Basically what I am trying to do, is on a file selection run an action that returns a JsonResult, that gives more details about the file and then show them to the screen in a container. While I debug, the method gets hit, returns the correct data. After the return in the ajax call i get a error in firebug say the recursionlimit exceeded. I am not sure how to get around this...I thought I could use the callback of the fileTree(options, callback) method provided but that is not fired on selection of the file only the initialization of the file tree. Any ideas?
Heres what I did via JavaScript
function initFileTree() {
$('#fileTree').fileTree({ root: '/', script: '/Scripts/filetree/jqueryFileTree.aspx', multiFolder: false, expandEasing: 'easeOutBounce', collapseEasing: 'easeOutBounce' }, function(file) {
getFileDetails(file);
});
}
function getFileDetails(file) {
// alert(file);
$.getJSON('/Files.mvc/GetFileDetails', { Data: file }, function(data) {
$('#fileDetail').html('<h6>Selected File: ' + data.Length + '</h6>');
}, 'json');
}
Here is my action that take the data and returns a JsonResult
public virtual JsonResult GetFileDetails(string data)
{
string pageMessage = null;
FileInfo fileInfo = null;
try
{
fileInfo = new FileInfo(data);
}
catch (Exception e)
{
pageMessage = e.Message;
}
return Json(fileInfo);
}
Apparently returning a FileInfo obj is not acceptable for a JsonResult. Simplifying the return, I changed it to:
return Json("helloWorld");
and all my problems went away. Not sure why it cares that I was attempting to return a FileInfo type but either way problem solved when I changed it to return a string. So now I just create a small wrapper class to hold the data I want to pass back and life is good.
Thanks! Hope this helps someone else.