functionality is not working for newly created menu - javascript

I'm working on creating the Link menu on the Oxygen Web-Author, there is already having two menu's called "ulink" and "uri". When I include the third menu called xref, the functionality of xref is not working fine, It's taking "ulink" functionality in the oxygen framework.js.
var insertWebLinkActionId =
sync.docbook.DocbookExtension.prototype.version == 5 ? "insert.web.link" : "insert.web.ulink";
var originalInsertWebLinkAction = actionsManager.getActionById(insertWebLinkActionId);
if(originalInsertWebLinkAction) {
var webLinkOperationClass = sync.docbook.DocbookExtension.prototype.version == 5 ?
"ro.sync.ecss.extensions.docbook.link.InsertExternalLinkOperation" :
"ro.sync.ecss.extensions.docbook.link.InsertULink";
var insertWebLinkAction = new sync.actions.InsertWebLink(
originalInsertWebLinkAction,
webLinkOperationClass,
editor,
'url_value');
actionsManager.registerAction(insertWebLinkActionId, insertWebLinkAction);
}
Here they already inserted menu by using the above code, in that insert.web.link and insert.web.ulink represent the corresponding menu from the translation.xml
<key type="action" value="insert.web.ulink">
<comment>Insert Link action name.</comment>
<val lang="en_US">Web Link (ulink)...</val>
</key>
...
<key type="action" value="insert.cross.reference.xref">
<comment>Insert Link action name.</comment>
<val lang="en_US">Cross reference (xref)...</val>
</key>
So I want to insert the Xref menu to the javascript, the Xref menu and class path represent insert.cross.reference.xref and
ro.sync.ecss.extensions.docbook.link.InsertXrefOperation correspondingly.

You can implement your own version of the "Insert Cross Reference (xref)" action in your DocBook framework extension. To do this you need to:
Create a custom action that prompts the user to choose the destination file and the ID of the target element. The code for this action needs to be added in the "web" folder of you framework in a new JS file. You can find below a minimal working example:
var DocBookCrossRefXrefAction = function (editor) {
sync.actions.AbstractAction.call(this);
this.editor = editor;
this.xrefTargetsDialog = null;
};
DocBookCrossRefXrefAction.prototype =
Object.create(sync.actions.AbstractAction.prototype);
DocBookCrossRefXrefAction.prototype.constructor = DocBookCrossRefXrefAction;
DocBookCrossRefXrefAction.prototype.getDisplayName = function () {
return 'Insert cross reference (xref)';
};
DocBookCrossRefXrefAction.prototype.actionPerformed = function (callback) {
// This callback might have to be called at a later point, so save it until then.
this.callback = callback || function () {};
var chooser = workspace.getUrlChooser();
var context = new sync.api.UrlChooser.Context(sync.api.UrlChooser.Type.EXTERNAL_REF);
chooser.chooseUrl(context, this.showXrefTargetChooser.bind(this),
sync.api.UrlChooser.Purpose.CHOOSE);
};
DocBookCrossRefXrefAction.prototype.showXrefTargetChooser = function (url) {
if (url) {
// Create a dialog to display all targets, so the user can select one to insert
// cross reference.
this.xrefTargetsDialog = this.createXrefTargetsDialog();
this.populateXrefTargetsDialog(url);
this.xrefTargetsDialog.onSelect(function (key, e) {
if (key === 'ok') {
e.preventDefault();
this.xrefTargetChosen();
} else {
this.callback();
}
}.bind(this));
this.xrefTargetsDialog.show();
} else {
this.callback();
}
};
DocBookCrossRefXrefAction.prototype.createXrefTargetsDialog = function () {
var dialog = workspace.createDialog();
dialog.setTitle('Choose cross reference');
dialog.setButtonConfiguration(sync.api.Dialog.ButtonConfiguration.OK_CANCEL);
dialog.setPreferredSize(700, 500);
dialog.setResizable(true);
return dialog;
};
DocBookCrossRefXrefAction.prototype.populateXrefTargetsDialog = function (url) {
this.editor.getActionsManager()
.invokeOperation('ro.sync.servlet.operation.FindXrefTargetsOperation', {url: url})
.then(function(str) { return JSON.parse(str);})
.then(this.xrefTargetsReceived.bind(this))
};
DocBookCrossRefXrefAction.prototype.xrefTargetsReceived = function (targets) {
var container = this.xrefTargetsDialog.getElement();
if (!targets || !targets.length) {
container.textContent = 'No cross reference targets found in the chosen file';
} else {
for (var i = 0; i < targets.length; i++) {
var radio = document.createElement('input');
radio.name = 'docbook-ref-table-radio';
radio.type = 'radio';
radio.dataset.id = targets[i].id;
var label = document.createElement('label');
label.style = 'display: block';
label.appendChild(radio);
label.appendChild(document.createTextNode(targets[i].nodeName + ' (#' +
targets[i].id + ') - ' + targets[i].content.substring(0, 50)));
container.appendChild(label);
}
}
};
DocBookCrossRefXrefAction.prototype.xrefTargetChosen = function() {
var targetRadio = this.xrefTargetsDialog.getElement().querySelector(
'input[name="docbook-ref-table-radio"]:checked');
if (targetRadio) {
this.editor.getActionsManager().invokeOperation('InsertFragmentOperation',
{fragment: '<xref linkend="' + targetRadio.dataset.id + '"/>'})
.then(this.xrefInserted.bind(this));
}
};
DocBookCrossRefXrefAction.prototype.xrefInserted = function () {
this.xrefTargetsDialog && this.xrefTargetsDialog.dispose();
this.callback();
};
DocBookCrossRefXrefAction.prototype.dispose = function() {
this.xrefTargetsDialog && this.xrefTargetsDialog.dispose();
};
goog.events.listen(workspace, sync.api.Workspace.EventType.EDITOR_LOADED, function(e) {
var editor = e.editor;
goog.events.listen(editor, sync.api.Editor.EventTypes.ACTIONS_LOADED, function(e) {
editor.getActionsManager().registerAction('insert.cross.reference.xref',
new DocBookCrossRefXrefAction(editor));
});
});
This action uses a server-side AuthorOperationWithResult to collect xref targets from the file chosen by the user. You can find below the code of this Java operation:
package ro.sync.servlet.operation;
import java.net.URL;
import java.util.ArrayList;
import javax.xml.parsers.DocumentBuilder;
import org.codehaus.jackson.map.ObjectMapper;
import org.w3c.dom.Attr;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import ro.sync.basic.util.URLUtil;
import ro.sync.ecss.extensions.api.ArgumentsMap;
import ro.sync.ecss.extensions.api.AuthorOperationException;
import ro.sync.ecss.extensions.api.webapp.AuthorDocumentModel;
import ro.sync.ecss.extensions.api.webapp.AuthorOperationWithResult;
import ro.sync.ecss.extensions.api.webapp.WebappRestSafe;
import ro.sync.xml.parser.ParserCreator;
#WebappRestSafe
public class FindXrefTargetsOperation extends AuthorOperationWithResult {
#Override
public String doOperation(AuthorDocumentModel model, ArgumentsMap args)
throws AuthorOperationException {
String urlString = (String) args.getArgumentValue("url");
try {
URL url = URLUtil.addAuthenticationInfo(
model.getAuthorAccess().getEditorAccess().getEditorLocation(),
new URL(urlString));
InputSource is = new InputSource(url.toString());
DocumentBuilder docBuilder = ParserCreator.newSchemaAwareDocumentBuilder();
Document document = docBuilder.parse(is);
ArrayList<XrefTarget> xrefTargets = new ArrayList<>();
gatherXrefTargets(document, xrefTargets);
return new ObjectMapper().writeValueAsString(xrefTargets);
} catch (Exception e) {
throw new AuthorOperationException(e.getMessage(), e);
}
}
public static class XrefTarget {
public final String id;
public final String nodeName;
public final String content;
public XrefTarget(Element elem) {
this.id = getIDValue(elem);
this.nodeName = elem.getTagName();
this.content = elem.getTextContent();
}
}
private static void gatherXrefTargets(Node node, ArrayList<XrefTarget> xrefTargets) {
if (node.getNodeType() == Node.ELEMENT_NODE) {
Element elem = (Element) node;
if (getIDValue(elem) != null) {
xrefTargets.add(new XrefTarget(elem));
}
}
NodeList childNodes = node.getChildNodes();
for (int i = 0; i < childNodes.getLength(); i++) {
gatherXrefTargets(childNodes.item(i), xrefTargets);
}
}
public static String getIDValue(Element elem) {
NamedNodeMap attributes = elem.getAttributes();
for (int i = 0; i < attributes.getLength(); i++) {
Attr attribute = (Attr)attributes.item(i);
// There are some ID attributes defined as such in the schema file.
if (attribute.isId() || "xml:id".equals(attribute.getName()) ||
"id".equals(attribute.getName())) {
return attribute.getValue();
}
}
return null;
}
}
You need to compile this Java class and add it as a JAR file in the classpath of your framework. More details here .

Related

How do I activate a SharePoint 2013 workflow with a button (javascript?)

Good morning. I am new to the coding world, so my skills growing daily. I am trying to activate a SharePoint 2013 list workflow by using a button and Javascript. I know there are plenty of examples available, and to be honest, I'm a bit embarrassed about not being able to figure this out myself. All the codes that I have seen to date however have initiation variables in them, but my workflow doesn't. I'm at a loss for how to alter the examples to exclude having initiation variables. Please help. Example code I have looked at:
http://ranaictiu-technicalblog.blogspot.com/2013/06/sharepoint-2013-start-workflow-with.html
https://www.codeproject.com/Articles/607127/Using-SharePoint-2013-Workflow-Services-JS-API#example5
https://sharepoint.stackexchange.com/questions/236329/start-sharepoint-designer-workflow-2013-using-javascript
I used the following code from first link:
//dialog element to show during processing
var dlg = null;
//Subscription id - Workflow subscription id
//list item id for which to start workflow. If site workflow, then send null for itemId
function StartWorkflow(subscriptionId, itemId) {
showInProgressDialog();
var ctx = SP.ClientContext.get_current();
var wfManager = SP.WorkflowServices.WorkflowServicesManager.newObject(ctx, ctx.get_web());
var subscription = wfManager.getWorkflowSubscriptionService().getSubscription(subscriptionId);
ctx.load(subscription, 'PropertyDefinitions');
ctx.executeQueryAsync(
function (sender, args) {
var params= new Object();
//Find initiation data to be passed to workflow.
var formData = subscription.get_propertyDefinitions()["FormData"];
if (formData != null && formData != 'undefined' && formData != "") {
var assocParams = formData.split(";#");
for (var i = 0; i < assocParams.length; i++) {
params[assocParams[i]] = subscription.get_propertyDefinitions()[assocParams[i]];
}
}
if (itemId) {
wfManager.getWorkflowInstanceService().startWorkflowOnListItem(subscription, itemId, params);
}
else {
wfManager.getWorkflowInstanceService().startWorkflow(subscription, params);
}
ctx.executeQueryAsync(
function (sender, args) {
closeInProgressDialog();
},
function (sender, args) {
closeInProgressDialog();
alert('Failed to run workflow');
}
);
},
function (sender, args) {
closeInProgressDialog();
alert('Failed to run workflow');
}
);
}
function closeInProgressDialog() {
if (dlg != null) {
dlg.close();
}
}
function showInProgressDialog() {
if (dlg == null) {
dlg = SP.UI.ModalDialog.showWaitScreenWithNoClose("Please wait...", "Waiting for workflow...", null, null);
}
}
And inserted the following HTML to create the button.
<button onclick="function StartWorkflow('8E645164-959C-4358-B22C-47FDA93F7906',5)">Click Me</button>
I am 100% confident that my subscriptionId and my itemId are correct.
Please help.
Thank you.
My test code for your reference,it's just slightly different from your code:
<input type="button" id="test" value="Click Me" />
<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
<script src="/_layouts/15/sp.workflowservices.js"></script>
<script>
$("#test").click(function(){
console.log(1)
SP.SOD.executeFunc('sp.js', 'SP.ClientContext', init);
function init() {
$.getScript(SP.Utilities.Utility.getLayoutsPageUrl('sp.js'), function () {
$.getScript(SP.Utilities.Utility.getLayoutsPageUrl('sp.workflowservices.js'), function () {
StartWorkflow("SubscriptionId","itemid","siteurl");
});
});
}
//dialog element to show during processing
var dlg = null;
//Subscription id – Workflow subscription id
//list item id for which to start workflow. If site workflow, then send null for itemId
//SiteURL – site collection where the workflow exists
function StartWorkflow(subscriptionId, itemId, SiteURL) {
showInProgressDialog();
var ctx = new SP.ClientContext(SiteURL);
var wfManager = SP.WorkflowServices.WorkflowServicesManager.newObject(ctx, ctx.get_web());
var subscription = wfManager.getWorkflowSubscriptionService().getSubscription(subscriptionId);
ctx.load(subscription, 'PropertyDefinitions');
ctx.executeQueryAsync(
function (sender, args) {
var params = new Object();
//Find initiation data to be passed to workflow.
var formData = subscription.get_propertyDefinitions()["FormData"];
if (formData != null && formData != 'undefined' && formData != "") {
var assocParams = formData.split(";#");
for (var i = 0; i < assocParams.length; i++) {
params[assocParams[i]] = subscription.get_propertyDefinitions()[assocParams[i]];
}
}
if (itemId) {
wfManager.getWorkflowInstanceService().startWorkflowOnListItem(subscription, itemId, params);
}
else {
wfManager.getWorkflowInstanceService().startWorkflow(subscription, params);
}
ctx.executeQueryAsync(
function (sender, args) {
closeInProgressDialog(SiteURL);
},
function (sender, args) {
closeInProgressDialog(SiteURL);
$('#msg')[0].innerHTML = "Woops – something went wrong, the document may have already been reviewed";
}
);
},
function (sender, args) {
closeInProgressDialog(SiteURL);
$('#msg')[0].innerHTML = "Woops – something went wrong, the document may have already been reviewed";
}
);
}
function closeInProgressDialog(SiteURL) {
if (dlg != null) {
dlg.close();
$('#msg')[0].innerHTML = "Thank you – you can now close the page";
}
}
function showInProgressDialog() {
if (dlg == null) {
dlg = SP.UI.ModalDialog.showWaitScreenWithNoClose("Please wait…", "Waiting for workflow…", null, null);
}
}
})
</script>

Display a url response in the front-end

I am able to get my url response in the console tag in google chrome. I need your help in displaying those values in my interface. The provided below code only enables me to display the first value in the url response.
main.js:
try{
var getNameOfEmployee = document.getElementById('getNameOfEmployeeID');
function displayEmployee(){
if (getNameOfEmployee.value != "") {
$("#someform").submit(function (event) {
event.preventDefault();
});
AjaxGet();
}
else{
alert("Please enter any name of employee that you wish to know the extension code of!");
}
}
AjaxGet = function (url, storageLocation, mySuccessCallback) {
var result = $.ajax({
type: "GET",
url: 'http://localhost:8080/employee/' +$("#getNameOfEmployeeID").val(),
param: '{}',
contentType: "application/json",
dataType: "json",
success: function (data) {
storageLocation = data;
globalVariable = data;
console.log(storageLocation);
console.log(storageLocation.empName0.extCode);
var length = Object.keys(storageLocation).length;
var empArray = new Array(length);
}
}).responseText ;
return result;
return storageLocation;
//console.log(result);
} ; }
catch(e){ document.getElementById("demo").innerHTML = e.message; }
My console is as:
empName0
:
{empName: "Aran", extCode: 5500}
empName1
:
{empName: "Bran", extCode: 5900}
empName2
:
{empName: "Cran", extCode: 5750}
Please somebody help me how to get all these results get printed in my index page once the submit button is clicked.
Just now I tried JSON.stringify(storageLocation) and print the results on an alert message. Please provide me an answer to display the results which are now duplicated. If you need my java file which retrieves the data, it follows:
employeeDAO.java :
#Repository public class EmployeeDAO {
private static final Map empMap = new HashMap();
static {
initEmps();
}
private static void initEmps() {
}
public JSONObject getEmployee(String empName){
Map<String ,Employee> empMap2 = new HashMap<String ,Employee>();
String filePath="D:\dummy.xls";
ReadExcelFileAndStore details = new ReadExcelFileAndStore();
List<Employee> myList= details.getTheFileAsObject(filePath);
JSONObject emp1 = new JSONObject();
boolean check=false;
int j=0;
for (int i=0; i<myList.size(); i++) {
if (myList.get(i).getEmpName().toLowerCase().contains(empName.toLowerCase()))
{
emp1.put("empName"+j,myList.get(i));
j++;
check = true;
}
}
if(check == true)
{
//System.out.println("yes");
return emp1;
}
else
{
return null;
}
}
public Employee addEmployee(Employee emp) {
empMap.put(emp.getEmpName(), emp);
return emp;
}
public Employee updateEmployee(Employee emp) {
empMap.put(emp.getEmpName(), emp);
return emp;
}
public void deleteEmployee(String empName) {
empMap.remove(empName);
}
public List<Employee> getAllEmployees() {
String filePath="D:/dummy.xls";
ReadExcelFileAndStore details = new ReadExcelFileAndStore();
return details.getTheFileAsObject(filePath);
}
public List<Employee> getAllImportantEmployees() {
String filePath="D:/dummy.xls";
ReadImportantExtensionSheet impDetails = new ReadImportantExtensionSheet();
return impDetails.getTheFileAsObject(filePath);
} }
You could add some DOM manipulation inside you AJAX success method:
success: function (data) {
storageLocation = data;
console.log(storageLocation.empName0.extCode);
$("#someform #someLabel").val(storageLocation.empName0.extCode);
$("#someform #someOtherLabel").val(storageLocation.empName0.empName);
}
This will wait for the AJAX to complete and then update your page with the results.
You can use a jQuery each function to loop over each element in the results and update their corresponding elements on the page.
success: function (data) {
storageLocation = data;
$.each(storageLocation, function (index, value) {
console.log(value.extCode);
$("#someform #someLabel" + index).val(value.extCode);
$("#someform #someOtherLabel" + index).val(value.empName);
});
}
Have a table in your html
Upon receiving the response populate in UI
This is a sample code, change as per the json structure
function load() {
var resp = '[{"empName":"Aran","extCode":5500},{"empName":"Bran","extCode":5900},{"empName":"Cran","extCode":5750}]';
var emps = JSON.parse( resp );
var i;
for(i=0; i<emps.length; i++) {
$('#empdata').append('<tr><td>'+emps[i]['empName']+'</td><td>'+emps[i]['extCode']+'</td>...</tr>');
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
<table id="empdata" style="border: 1px solid;background-color: #eedaff;">
<th>Name</th><th>Ext</th>
</table>
<button onclick="load();">Load</button>
</body>

MVC, how get model property from response viewModel

I am implementing "show more posts" in my blogs list following
this example but I want to make a change and switch from using ViewData to ViewModel.
This the relevant code:
private void AddMoreUrlToViewData(int entryCount)
{
ViewData["ShowMore "] = Url.Action("Index", "Messaggi", new { entryCount = entryCount + defaultEntryCount });
}
that I switch to
ViewModel.ShowMore = Url.Action("Index", "Messaggi", new { entryCount = entryCount + defaultEntryCount });
the Index action of the example:
public ActionResult Index(int? entryCount)
{
if (!entryCount.HasValue)
entryCount = defaultEntryCount;
int totalItems;
if(Request.IsAjaxRequest())
{
int page = entryCount.Value / defaultEntryCount;
//Retrieve the page specified by the page variable with a page size o defaultEntryCount
IEnumerable<Entry> pagedEntries = GetLatestEntries(page, defaultEntryCount, out totalItems);
if(entryCount < totalItems)
AddMoreUrlToViewData(entryCount.Value);
return View("EntryTeaserList", pagedEntries);
}
//Retrieve the first page with a page size of entryCount
IEnumerable<Entry> entries = GetLatestEntries(1, entryCount.Value, out totalItems);
if (entryCount < totalItems)
AddMoreUrlToViewData(entryCount.Value);
return View(entries);
}
Here I add a lot of code to load the post from the db, the only code I think is relevant is that I swtich return View("EntryTeaserList", pagedEntries); to return View(myViewModel); after setting BlogsList and ShowMore property.
But my problem is in the javascript command:
$(function() {
addMoreLinkBehaviour();
});
function addMoreLinkBehaviour() {
$('#entryTeaserList #moreLink').live("click", function() {
$(this).html("<img src='/images/ajax-loader.gif' />");
$.get($(this).attr("href"), function(response) {
$('#entryTeaserList ol').append($("ol", response).html());
$('#entryTeaserList #ShowMore').replaceWith($("#ShowMore", response));
});
return false;
});
}
where
$('#entryTeaserList #ShowMore').replaceWith($("#ShowMore", response));
to take ViewData property and use it to replace the link.
How can I read the ViewModel Property instead?

WPF Application crashes after overriding CefApp.GetRenderProcessHandler() for JS to C# call

I am developing a wpf application by using Xilium.CefGlue and Xilium.CefGlue.WPF. My WPF application is getting crashed after implementing Xilium.CefGlue.CefApp.GetRenderProcessHandler() in SampleCefApp. Before this implementation the application was working fine without any crashes. Actually I need to call a C# function from html local page by javascript function. This functionality is working fine in 32 bit version but not in 64 bit. The following is my implementation.
internal sealed class SampleCefApp : CefApp
{
public SampleCefApp()
{
}
private CefRenderProcessHandler renderProcessHandler = new Views.DemoRenderProcessHandler();
protected override CefRenderProcessHandler GetRenderProcessHandler()
{
return renderProcessHandler;
}
}
the following message was showing for app crash
<ProblemSignatures>
<EventType>APPCRASH</EventType>
<Parameter0>StreetMap.vshost.exe</Parameter0>
<Parameter1>14.0.23107.0</Parameter1>
<Parameter2>559b788a</Parameter2>
<Parameter3>libcef.DLL</Parameter3>
<Parameter4>3.2743.1449.0</Parameter4>
<Parameter5>57bbfe66</Parameter5>
<Parameter6>80000003</Parameter6>
<Parameter7>0000000000b68267</Parameter7>
</ProblemSignatures>
Is ther any issues for libcef dll while working with 64 bit. Is anybody can help for implementing JS to C# call by using Xilium.CefGlue and Xilium.CefGlue.WPF.
The following reference code i am using for this from the link
https://groups.google.com/forum/#!topic/cefglue/EhskGZ9OndY
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Threading;
using System;
namespace Xilium.CefGlue.Client {
internal sealed class DemoApp: CefApp {
private CefRenderProcessHandler renderProcessHandler = new DemoRenderProcessHandler();
protected override CefRenderProcessHandler GetRenderProcessHandler() {
return renderProcessHandler;
}
}
internal class DemoRenderProcessHandler: CefRenderProcessHandler {
MyCustomCefV8Handler myCefV8Handler = new MyCustomCefV8Handler();
protected override void OnWebKitInitialized() {
base.OnWebKitInitialized();
var nativeFunction = # "nativeImplementation = function(onSuccess) {
native
function MyNativeFunction(onSuccess);
return MyNativeFunction(onSuccess);
};
";
CefRuntime.RegisterExtension("myExtension", nativeFunction, myCefV8Handler);
}
internal class MyCustomCefV8Handler: CefV8Handler {
protected override bool Execute(string name, CefV8Value obj, CefV8Value[] arguments, out CefV8Value returnValue,
out string exception) {
//Debugger.Launch();
var context = CefV8Context.GetCurrentContext();
var taskRunner = CefTaskRunner.GetForCurrentThread();
var callback = arguments[0];
new Thread(() => {
//Sleep a bit: to test whether the app remains responsive
Thread.Sleep(3000);
taskRunner.PostTask(new CefCallbackTask(context, callback));
}).Start();
returnValue = CefV8Value.CreateBool(true);
exception = null;
return true;
}
}
internal class CefCallbackTask: CefTask {
private readonly CefV8Context context;
private readonly CefV8Value callback;
public CefCallbackTask(CefV8Context context, CefV8Value callback) {
this.context = context;
this.callback = callback;
}
protected override void Execute() {
var callbackArguments = CreateCallbackArguments();
callback.ExecuteFunctionWithContext(context, null, callbackArguments);
}
private CefV8Value[] CreateCallbackArguments() {
var imageInBase64EncodedString = LoadImage(# "C:\hamb.jpg");
context.Enter();
var imageV8String = CefV8Value.CreateString(imageInBase64EncodedString);
var featureV8Object = CefV8Value.CreateObject(null);
var listOfFeaturesV8Array = CefV8Value.CreateArray(1);
featureV8Object.SetValue("name", CefV8Value.CreateString("V8"), CefV8PropertyAttribute.None);
featureV8Object.SetValue("isEnabled", CefV8Value.CreateInt(0), CefV8PropertyAttribute.None);
featureV8Object.SetValue("isFromJSCode", CefV8Value.CreateBool(false), CefV8PropertyAttribute.None);
listOfFeaturesV8Array.SetValue(0, featureV8Object);
context.Exit();
return new [] {
listOfFeaturesV8Array,
imageV8String
};
}
private string LoadImage(string fileName) {
using(var memoryStream = new MemoryStream()) {
var image = Bitmap.FromFile(fileName);
image.Save(memoryStream, ImageFormat.Png);
byte[] imageBytes = memoryStream.ToArray();
return Convert.ToBase64String(imageBytes);
}
}
}
}
The HTML file, that I loaded at the first place:
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<title>C# and JS experiments</title>
<script src="index.js"></script>
</head>
<body>
<h1>C# and JS are best friends</h1>
<div id="features"></div>
<div id="image"></div>
</body>
</html>
The JavaScript code:
function Browser() {
}
Browser.prototype.ListAllFeatures = function(onSuccess) {
return nativeImplementation(onSuccess);
}
function App(browser) {
this.browser = browser;
}
App.prototype.Run = function() {
var beforeRun = new Date().getTime();
this.browser.ListAllFeatures(function(features, imageInBase64EncodedString) {
var feautersListString = '';
for (var i = 0; i < features.length; i++) {
var f = features[i];
feautersListString += ('<p>' + 'Name: ' + f.name + ', is enabled: ' + f.isEnabled + ', is called from js code: ' + f.isFromJSCode + '</p>');
}
feautersListString += '<p> The image: </p>';
feautersListString += '<p>' + imageInBase64EncodedString + '</p>';
document.getElementById("features").innerHTML = feautersListString;
var afterRun = new Date().getTime();
document.getElementById("image").innerHTML = '<img src="data:image/png;base64,' + imageInBase64EncodedString + '" />';
var afterLoadedImage = new Date().getTime();
console.log("ELAPSED TIME - INSIDE LIST ALL FEATURES: " + (afterRun - beforeRun));
console.log("ELAPSED TIME - IMAGE IS LOADED TO THE <img> TAG: " + (afterLoadedImage - beforeRun));
});
}
window.onload = function() {
var browser = new Browser();
var application = new App(browser);
//Lets measure
var beforeRun = new Date().getTime();
application.Run();
var afterRun = new Date().getTime();
console.log("ELAPSED TIME - INSIDE ONLOAD: " + (afterRun - beforeRun));
}
Any help is appreciated.
I enabled the cef logging. It shows the following log
[0826/171951:ERROR:proxy_service_factory.cc(128)] Cannot use V8 Proxy resolver in single process mode.
.So I changed the SingleProcess=false in CeffSetting. Now the crashing issue is solved and then the requested webpage is not showing in cefwpfbrowser.
Now I am getting the following message from the log file
[0826/173636:VERBOSE1:pref_proxy_config_tracker_impl.cc(151)] 000000001B2A7CC0: set chrome proxy config service to 000000001B234F60
[0826/173636:VERBOSE1:pref_proxy_config_tracker_impl.cc(276)] 000000001B2A7CC0: Done pushing proxy to UpdateProxyConfig
[0826/173637:VERBOSE1:webrtc_internals.cc(85)] Could not get the download directory.
How to solve the requested page not loading issue in cefwpfbrowser.

Jquery datatable warning

I have a jquery editable table.
In code behind there are three actions.
One to load data for datatable
Another to delete data from datatable
And the last one for Save data.
There is nothing special in these actions.
I have The problem with save data. Data are saved correctly to database and then there is redirection to load data to datable again.
When data are saved correctly do database, there is redirection which load new data to datatable and then i get this warning:
DataTables warning: table id=myDataTable - Requested unknown parameter '0' for row 8. For more information about this error, please see http://datatables.net/tn/4
I have looked this error on that page and i can not still find solution for this bug.
Interesting is when i get this error and i refresh page with datatable this time data are loaded correctly.
I do not know what is going on.
Please help
Here are two problematic actions
[HttpGet]
public ActionResult TesotwanieTabelki(int promotionId)
{
marketPromocji.Areas.DELIVER.Models.PromotionsProductsViewModel promotionProductsViewModelItem =
new marketPromocji.Areas.DELIVER.Models.PromotionsProductsViewModel();
promotionProductsViewModelItem.productDetails =
new List<marketPromocji.Areas.DELIVER.Models.ProductDetails>();
marketPromocji.Models.promocje promocje = unitOfWork.PromocjeRepository.GetByID(promotionId);
aspnet_Users produktyWDanejPromocji=promocje.promocje_produkty.Select(x => x.produkty).First().aspnet_Users; //czyje produkty w danej promocji
ICollection<produkty> produkty = unitOfWork.ProduktyRepository.Get().Where(x => x.aspnet_Users.UserId== produktyWDanejPromocji.UserId).ToList();
List<SelectListItem> selectList=new List<SelectListItem>();
foreach (produkty p in produkty)
{
selectList.Add(new SelectListItem { Text = p.nazwa, Value = p.id.ToString()});
}
promotionProductsViewModelItem.selectList = selectList;
promotionProductsViewModelItem.data_start = promocje.data_start;
promotionProductsViewModelItem.data_koniec = promocje.data_koniec;
promotionProductsViewModelItem.czy_zielony_koszyk = promocje.czy_zielony_koszyk;
promotionProductsViewModelItem.id = promocje.id;
promotionProductsViewModelItem.poziom_dostepnosci = promocje.poziom_dostepnosci;
promotionProductsViewModelItem.wynagrodzenie = promocje.wynagrodzenie;
if (promocje.sposob_wynagrodzenia != null)
{
promotionProductsViewModelItem.sposobWynagrodzenia = promocje.sposob_wynagrodzenia;
}
else
{
promotionProductsViewModelItem.sposobWynagrodzenia = "";
}
ICollection<marketPromocji.Models.promocje_produkty> promocje_produkty = unitOfWork.PromocjeProduktyRepository.Get().Where(x => x.ref_promocja == promotionId).ToList();
foreach (marketPromocji.Models.promocje_produkty item in promocje_produkty)
{
promotionProductsViewModelItem.productDetails.Add(new marketPromocji.Areas.DELIVER.Models.ProductDetails()
{
productId = item.produkty.id,
cena_brutto = item.cena_brutto,
cena_brutto_dla_sklepu = item.cena_brutto_dla_sklepu,
cena_netto = item.cena_netto,
cena_netto_dla_sklepu = item.cena_netto_dla_sklepu,
nazwa = item.produkty.nazwa,
url_obrazka = item.produkty.url_obrazka
});
}
Session[User.Identity.Name] = promotionProductsViewModelItem; //this session is used for datatable update action
return View(promotionProductsViewModelItem);
}
[HttpPost]
public ActionResult AddData(FormCollection formCollection)
{
int promotionId = Convert.ToInt32(formCollection.Get("promotionId"));
string addedProductId = formCollection.Get("Produkty");
int productId = Convert.ToInt32(addedProductId);
marketPromocji.Areas.DELIVER.Models.PromotionsProductsViewModel promotionsProductsViewModel =
(marketPromocji.Areas.DELIVER.Models.PromotionsProductsViewModel)Session[User.Identity.Name];
produkty produkt = new produkty();
produkt = unitOfWork.ProduktyRepository.GetByID(productId);
promocje_produkty promocjeProdukty = new promocje_produkty();
promocjeProdukty.cena_brutto = Convert.ToDecimal(formCollection.Get("cenaZakupuNetto")); //tutaj to jeszcze musze sprawdzic czy to w odpowiedniej kolejnosci jest;/
promocjeProdukty.cena_brutto_dla_sklepu = Convert.ToDecimal(formCollection.Get("cenaZakupuBrutto"));
promocjeProdukty.cena_netto = Convert.ToDecimal(formCollection.Get("cenaSprzedazyNetto"));
promocjeProdukty.cena_netto_dla_sklepu = Convert.ToDecimal(formCollection.Get("cenaSprzedazyBrutto"));
string zielonyKoszyk = formCollection.Get("zielonyKoszyk");
if(zielonyKoszyk==null)
{
promocjeProdukty.czy_zielony_koszyk = false;
}
else
{
promocjeProdukty.czy_zielony_koszyk = true;
}
promocjeProdukty.ref_produkt = productId;
promocjeProdukty.ref_promocja = promotionId;
try
{
unitOfWork.PromocjeProduktyRepository.Insert(promocjeProdukty);
unitOfWork.Save();
}
catch(Exception ex)
{
}
return RedirectToAction("TesotwanieTabelki", new { promotionId=promotionId});
}

Categories

Resources