I'm writing a Gtk-rs application. I have a background thread sending events to the main Gtk thread through a MPSC channel.
What should I do with unrecoverable errors inside this background thread?
I don't want to handle them (To panic! or Not to panic!).
Currently, the thread will panic, but the main application won't stop. I'd like the whole application to crash with the error.
let (sender, receiver) = glib::MainContext::channel(glib::PRIORITY_DEFAULT);
// Spawn the thread and move the sender in there
thread::spawn(move || {
loop {
let msg = do_work().unwrap();
sender.send(msg).unwrap();
}
});
receiver.attach(None, move |msg| {
...
glib::Continue(true)
});
I don't want to send a Result through the channel because it wouldn't work for panics in called functions.
Joining the thread would solve the problem, but I don't think I can do it with Gtk-rs since it is blocking.
This question is similar to How can I cause a panic on a thread to immediately end the main thread?, but I wonder there is a better solution for Gtk-rs.
Changing the panic handler with set_hook would solve the problem.
fn change_panic_behaviour() {
let hook = std::panic::take_hook();
std::panic::set_hook(Box::new(move |error| {
hook(error);
std::process::exit(1);
}));
}
Related
openapi: "3.0.0"
Swagger-jsdoc: "^6.2.5",
Swagger-ui-express: "^4.3.0",
Node: v18.8.0
I have a payload with a field called raw_data who is super long. So I decided to use an external value and call it in swaggerUI
I'm using this URL: https://mywebsite/tremorData.json which its being called. It is just a JSON file. Is possible that the problems is caused by the JSON file not being parsed?
I tried several things but it never works. In case you know how to add big payload in swaggerUI I'm open to other options.
this is my code:
/**
* #swagger
* /data/tremor:
* post:
*
* security:
* - bearerAuth: []
*
* tags: [data/ Tremor]
*
* requestBody:
* required: true
* content:
* application/json:
* examples:
* jsonObject:
* summary: A sample object
* externalValue: 'https://mywebsite/tremorData.json'
*
* responses:
* 200:
* description: Successful operation
* 400:
* description: validation Fail /or/ Unexpected token, in JSON at position 108
*/
the render in swaggerUI :
The "could not render" error happens because the requestBody does not have a schema. Adding a minimal schema, e.g. just type: object without any properties (which means "arbitrary object") will avoid the rendering error.
* requestBody:
* required: true
* content:
* application/json:
* schema: # <-----
* type: object # <-----
* examples:
...
As for externalValue, it's the correct way to reference external examples, but unfortunately it's not supported by Swagger UI yet. You can track this issue for status updates:
https://github.com/swagger-api/swagger-ui/issues/5433
I am new in C# . I have developed own webbrowser with Gecko webBrowser control. But I'm unable to open a particular link for first time, and it return alert for timeout. I handled timeout alert messagebox too.
When I have implemented
private void gWebBrowser_DocumentCompleted(object sender, Gecko.Events.GeckoDocumentCompletedEventArgs e)
I found out that first time page was not properly loaded.
How can i use auto Reload or timer in it?
My code is:
public partial class Embedded_Browser : Form
{
public Embedded_Browser()
{
string GeminiURL = "NA";
InitializeComponent();
Xpcom.Initialize("Firefox");
GeckoPreferences.User["dom.max_script_run_time"] = 0; //let js run as long as it needs to; prevents timeout errors
GeckoPreferences.User["security.warn_viewing_mixed"] = false;
GeckoPreferences.User["browser.download.manager.showAlertOnComplete"] = false;
GeckoPreferences.User["privacy.popups.showBrowserMessage"] = false;
GeckoPreferences.User["browser.xul.error_pages.enabled"] = false;
GeckoPreferences.User["browser.cache.memory.enable"] = false;
gWebBrowser.NSSError += new EventHandler<GeckoNSSErrorEventArgs>(gWebBrowser_NSSError); //Bypass SSL certificate issues
gWebBrowser.NavigationError += new EventHandler<GeckoNavigationErrorEventArgs>(gWebBrowser_NavigationError); //If there are any issues encountered during page loads
gWebBrowser.Navigated += new EventHandler<GeckoNavigatedEventArgs>(gWebBrowser_Navigated); //React appropriately to URL navigation
string sUserAgent = "Mozilla/5.0 (Windows; U; Windows NT 6.1; pl; rv:1.9.1) Gecko/20090624 Firefox/3.5 (.NET CLR 3.5.30729)";
Gecko.GeckoPreferences.User["general.useragent.override"] = sUserAgent;
var observerService = Xpcom.GetService<nsIObserverService>("#mozilla.org/observer-service;1");
observerService.AddObserver(new Observer(), "http-on-modify-request", false);
if (Environment.Is64BitOperatingSystem)
{
RegistryKey MyReg = Registry.LocalMachine.OpenSubKey("SOFTWARE\\Wow6432Node\\Jekson\\AppConfig", true);
GeminiURL = (string)MyReg.GetValue("Browse_URL", "NA");
}
else
{
RegistryKey MyReg = Registry.LocalMachine.OpenSubKey("SOFTWARE\\Jekson\\AppConfig", true);
GeminiURL = (string)MyReg.GetValue("Browse_URL", "NA");
}
gWebBrowser.Navigate(GeminiURL);
textBox1.Text = GeminiURL;
PromptFactory.PromptServiceCreator = () => new NoPromptService();
// System.Threading.Thread.Sleep(5000);
if(NoPromptService.isPrompt == 1){
gWebBrowser.Reload();
gWebBrowser.Navigate(GeminiURL);
MessageBox.Show("Hello!");
}
}
Please Help me. thanks in advance
I have used timer control for making Web browser auto refresh for first time.
After 5ms web browser auto refresh once.
My code is:
private void timer1_Tick(object sender, EventArgs e)
{
gWebBrowser.Navigate("google.com"); //You can pass any url here which you want to load
if (count == 0)
{
timer1.Enabled = false;
}
count++;
}
How to download a file using Ajax in MVC. If no data to generate file then show error label.
I'm trying using action result method which returns File. I can download file . but don't want to refresh the page if no file to download.
My code is like
public ActionResult Excel(MyViewModel model)
{
var result = // DB call to get data
if (no data)
{
return **something**
}
else
{
byte[] excelContent =//passing result to my method( returns xls file in byte)
return File(
excelContent, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
reportName + " Report " + startDate + " - " + endDate + ".xlsx");
}
}
What should I return for something
For now I'm returning emptyResult for something hence I got blank page if no data.
Ajax doesn't support file download.
This code works if I submit the form and there is data.
Suggest something in which page will not get refresh and both task get achieved.
1. File download if data
2. Show error label if no data
If get file using Ajax then best way to create API
Function return type is FileResult
var exportToExcel = function (inputData, fileName) {
var path = "url";
var form = $("<form></form>");
form.attr("enctype", "application/x-www-form-urlencoded");
form.attr("method", "post");
form.attr("action", path);
form.attr("accept-charset", "UTF-8");
var field = $("<input></input>");
field.attr("type", "hidden");
field.attr("name", "data");
field.attr("value", escape(JSON.stringify(inputData)));
form.append(field);
var field2 = $("<input></input>");
field2.attr("name", "fileName");
field2.attr("value", fileName);
form.append(field2);
$(document.body).append(form);
form.submit().remove();
};
var downloadFile = function (inputData) {
// checkFileHasResult is ajax call result if true or false
checkFileHasResult(inputData).then(function (hasFile) {
if (hasFile === true) {
// give file name with extension
exportToExcel(inputData, "asdfasdf.csv");
}
});
};
Doing a quick search in Google, brought up quite a few results, as this question.
In JQuery, you could just point you 'window.location' to your action method in the controller, that returns a FileResult. This will download the file for you.
I would suggest, you return message to an ajax call, stating whether your download was successful or not, and then you can set some sort of text on the front end to notify the user that this process was unsuccessful.
Here is how I would have accomplished this. You can tweak it to work for you. Here is an example of the controller methods.
[HttpGet]
public JsonResult ExportCollection()
{
//Build your excel file, and save it to disk somewhere on server.
//you can also save it in session, depending on size
//Build up response Messages based on success or not
//return json object with your file path
return Json(new { responseMessage = responseMessage }, JsonRequestBehavior.AllowGet);
}
public ActionResult Download(string fileName)
{
return File(model.FilePath, "application/vnd.ms-excel", fileName);
}
And then, call these actions from client side using JQuery and an Ajax call.
$(document).on("click", "#YourButton", function () {
var url = "/YourController/ExportCollection/"
$("#responseText").text("We're getting things ready. Please wait...");
$('#loadingImage').show();
$.ajax({
url: url,
type: "get",
success: function (responseMessage) {
patientCollectionExportSuccess(responseMessage);
}
});
})
//Function responsible for exporting
function patientCollectionExportSuccess(dataReceived) {
var respMessage = dataReceived.responseMessage;
if (respMessage != null) {
if (respMessage != "Error: Not Exported.") {
$("#responseText").text("Download completed.");
$('#loadingImage').hide();
//set window.location to redirect to FileResult, which will download file
window.location = '/PatientListingQuery/Download?fileName=' + respMessage ;
}
else {
$("#responseText").text("Download unsuccessful.");
$('#loadingImage').hide();
$("#responseText").text(dataReceived.responseMessage);
}
}
}
Thanks guys
I got solution
It works for me smoothly ....
my form action is pointing to another method, so updated action before submitting the form. and after file download, i'm setting it to old form action.
$(document).ready(function () {
$('#excel-button').on('click', function () {
$.ajax({
url: '/MyController/IsData',
type: 'POST',
data: $("#myForm").serialize(),
success: function (response) {
if (response == "True") {
var oldUrl="";
var form1 = $('#myForm');
var frm = document.getElementById('myForm') || null;
if (frm) {
oldUrl = frm.action;
frm.action = '/MyController/GenerateExcel';
}
form1.submit();
frm.action = oldUrl;
$('.error-Message').hide();
} else {
$('.error-Message').show();
}
}
});
});
Hey I used the code below to implement concurrent stack. In the below code lock has been acquired individually for push and pop but doesn't this make Push and pop interfere with each other. In-order for a stack implementation to be correct Pop must not happen along with push but before or after push(am I correct?).But if two threads call push and pop in some order will this program preserve the order?
public class ConcurrentStackL
{
object _objLock;
internal class Node
{
internal T _item;
internal Node _next;
public Node(T item, Node next) { _item = item; _next = next; }
}
private Node _head = null;
private bool _isEmpty;
public ConcurrentStackL()
{
_head = new Node(default(T), _head);
_objLock = new object();
_isEmpty = true;
}
public void Push(T item)
{
lock (_objLock)
{
_head = new Node(item, _head);
if (!_isEmpty)
_isEmpty = false;
}
}
public T Pop()
{
T item;
lock (_objLock)
{
if (_head._next == null)
throw new IndexOutOfRangeException("Stack is empty");
item = _head._item;
_head = _head._next;
if (_head._next == null)
_isEmpty = true;
}
return item;
}
}
From My Understanding of mutexes and concurrent locks yes it should preserve the ordering. As far as I am aware that when you lock a mutex another thread cannot also lock that mutex and proceed. As a result it stops its execution until the mutex is unlocked and it can continue. The fact that 2 threads cannot access the stack at the same time and the second thread is forced to wait should preserve the order of pops and pushes.
If you want strict FIFO ordering for threads approaching a synchronized block, you will not get it with intrinsic locks like you have here. That is if many threads a waiting for synchronized(_objLock) to be available, a thread that arrives later may enter the block before one that arrived earlier.
This is called thread barging and is permitted as intrinsic locking is unfair. If you want a fair lock than you would need to use new ReentrantLock(true) where true indicates the lock is fair.
What the locking here gives you is the assurance that any thread which is in the synchronized block will be the only thread executing. That is, the order of push and pop will be preserved for each thread as it sees the stack in the current state.
So I have a method that is correctly creating a CSV file with a bunch of data when called by doGet(HttpServletRequest request, HttpServletResponse response) which is called when I create a button like this:
link = new HtmlOutputLink();
HtmlGraphicImage img = new HtmlGraphicImage();
img.setStyle("background-color: #FFFFFF;");
img.setTitle("Click to Export these requests to csv file");
img.setValue("../images/Export.PNG");
link.getChildren().add(img);
link.setValue(resp.encodeURL(Constants.TXT_ALL_DIV_TEAM_EXPORT_LINK));
cell = new DataTableCell();
cell.setType(CellType.DATA);
cell.setFormat(new Format(Format.CENTER));
cell.addElement(link);
headerRow.addElement(cell);
When the button is clicked the doGet method then calls the method which creates the CSV file (which, again, is working correctly called from doGet).
However, I have to change this from an image to a CommandButton, the command button is a custom class that extends the javax.faces.component.html.HtmlCommandButton package, so now I have this:
HtmlOutputLink link = new HtmlOutputLink();
CommandButton alertsButton = new CommandButton();
alertsButton.setId(UI_EXPORT_ID);
alertsButton.setValue(UI_EXPORT_TXT);
alertsButton.setOnclick("javascript:showWaitLayer();jsCBDupdateComponent('" + "form" + "', this );");
alertsButton.setBlockSubmit(true);
alertsButton.setImmediate(true);
alertsButton.addActionListener(this);
link.getChildren().add(alertsButton);
cell = new DataTableCell();
cell.setType(CellType.DATA);
cell.setFormat(new Format(Format.CENTER));
cell.addElement(link);
headerRow.addElement(cell);
When this button is clicked it calls processAction() in which I instantiate the HttpServletResponse used to pass in to the working method.
FacesContext context = FacesContext.getCurrentInstance();
HttpServletResponse response = (HttpServletResponse) context.getExternalContext().getResponse();
response.setContentType("application/octet-stream");
HomeController homeController = (HomeController) context.getApplication().createValueBinding("#{HomeController}").getValue(context);
homeController.createExportFile(response);
EDIT: Adding the createExportFile method with lots taken out for readability.
EDIT2: I've changed the createExportFile so that no HttpServletResponse needs to be passed in. This way the method doesn't have any dependencies on passed in parameters. Both of the buttons (the one with the img and the one that is the CommandButton) call this method and run through without errors in the exact same method. Only the img button creates the excel file though.
public void createExportFile()
throws IOException, PersistenceException, SQLException {
FacesContext context = FacesContext.getCurrentInstance();
HttpServletResponse resp = (HttpServletResponse) context.getExternalContext().getResponse();
resp.setContentType("application/octet-stream");
resp.setContentLength(500 * this.getWorkAllDivDeptList().size());
resp.setHeader("Content-Disposition", "attachment; filename=\""
+ "AllDivTeam.csv" + "\""); Map<String, HashSet<String>> stateDateMap = new HashMap<String, HashSet<String>>();
ArrayList<DynamicFieldInfo> txtFieldAllList = new ArrayList<DynamicFieldInfo>();
RequestReader kanbanReader;
try {
//Get all of the data from the DB
} catch (MidTierException mte) {
mte.printStackTrace();
}
String rowTxt = getExportRowHdrTxt(txtFieldAllList, addlColCnt);
response.getOutputStream().write(rowTxt.getBytes(), 0, rowTxt.length());
kanbanReader = new RequestReader("");
for (AllActiveWorkListInfo bwi : (ArrayList<AllActiveWorkListInfo>) this
.getFilteredAllDivDeptList()) {
HashSet<String> set = (HashSet<String>) stateDateMap.get(bwi.getMID());
if (null != set && !set.isEmpty()) {
Iterator<String> itr = set.iterator();
while (itr.hasNext()) {
rowTxt = getExportRowTxt(bwi, txtFieldAllList,
kanbanReader, (String) itr.next());
response.getOutputStream().write(rowTxt.getBytes(), 0,
rowTxt.length());
}
} else {
rowTxt = getExportRowTxt(bwi, txtFieldAllList, kanbanReader, "");
response.getOutputStream().write(rowTxt.getBytes(), 0,
rowTxt.length());
}
if (count++ == 200) {
response.getOutputStream().flush();
}
}
response.getOutputStream().flush();
response.getOutputStream().close();
}
Adding Headers:
(Request-Line) POST /kanban/faces/kanbanRepAllDivDeptTickets HTTP/1.1
Accept */*
Accept-Encoding gzip, deflate
Accept-Language en-us
Cache-Control no-cache
Connection Keep-Alive
Content-Length 530
Content-Type application/x-www-form-urlencoded
Cookie _cbdModemCheck=false; JSESSIONID=08ADA3D60982F9D13478AF729D6E5205; s_fid=24245A567AE4BB33-0F8E3B5CF3FBEED7
Host localhost:8080
Referer http://localhost:8080/kanban/faces/kanbanRepAllDivDeptTickets
User-Agent Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.1; WOW64; Trident/5.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; .NET4.0C; .NET4.0E; InfoPath.3)
When I debug it goes through all of the process to create the csv exactly like when called from doGet but it never opens the dialog to download or cancel. It's throwing no exceptions and I'm completely out of ideas.
Does anyone see where I'm making an incorrect assumption?
Thanks for your time,
Mike
You are no where writing the file to the output stream. You should write your file to the output stream for that.
This is the sample code worked for me. Hope it helps you.
int BUFSIZE = 4096;
int length = 0;
ServletOutputStream outStream = response.getOutputStream();
String mimeType = "text/csv";
response.setContentType(mimeType);
response.setContentLength((int)document.length());
String documentName = document.getName();
response.setHeader("Content-Disposition", "attachment; filename=\"" + yourCsvFileName + "\"");
byte[] byteBuffer = new byte[BUFSIZE];
DataInputStream in = new DataInputStream(new FileInputStream(document));
while((null != in) && ((length = in.read(byteBuffer)) != -1)) {
outStream.write(byteBuffer, 0, length);
}
in.close();
outStream.close();