How to init an alasql database? - alasql

I try to use alaSQL, but not working well for me.
My scenario is create a localstorage db when is not exists.
In this case i "init" the database.
It means i create all tables and insert some records.
Finally i select some data and send to the "display".
First run is everything ok,
but next time (when i click the browser's refresh button) i get an error message. "Error: Table does not exist: cities", but i created erlier.
Why can i get this message?
Please check my example:
<!DOCTYPE html>
<html>
<head>
<title>ALASQL</title>
<script type="text/javascript" src="https://cdn.jsdelivr.net/npm/alasql"></script>
<script>
var db;
function log(msg) {
console.log("log: "+msg);
};
function initDB() {
log("initDB");
alasql.options.autocommit = true;
alasql("CREATE localStorage DATABASE IF NOT EXISTS lsdb");
alasql("ATTACH localStorage DATABASE lsdb AS db");
db = alasql.Database("db");
try {
db.exec("CREATE TABLE params (par string, val string)");
log("creDB");
db.exec("insert into params values ('db','1.0')");
db.exec("CREATE TABLE cities (id number, city string, pop number)");
db.exec("INSERT INTO cities VALUES (1,'Paris',2249975),(2,'Berlin',3517424),(3,'Madrid',3041579)");
}
catch (err) {
log(err);
};
};
function getData(sql) {
log("getData");
res = db.exec(sql);
return res;
};
function onLoad() {
initDB();
try {
res = getData("SELECT * FROM cities WHERE pop > 3500000 ORDER BY pop DESC");
document.getElementById("res").textContent = JSON.stringify(res, null, 2);
}
catch (err) {
document.getElementById("res").textContent = err;
};
};
</script>
</head>
<body onload="onLoad()">
<xmp id="res"></xmp>
</body>
</html>
Thanks for any advice.
Joe

Related

Active Directory how to get user from distinguishedName

I need some help on retrieving a user with distinguishedName in asp.net mvc project. I have a search function that has 2 properties to load, "displayName" and "distinguishedName". Once I find, I return a view with a list containing these two parameters for each user found. Then I want to be able to click on a user and immediately show their information. So how do I load the information about the user once I only have these two parameters passed through?
Here is the function that initially searches:
public List<string> SearchUserByName(string name){
try{
DirectoryEntry ldapConnection = createDirectoryEntry();
DirectorySearcher search = new DirectorySearcher(ldapConnection);
search.PropertiesToLoad.Add("displayName");
search.PropertiesToLoad.Add("distinguishedName");
resultCollection = search.FindAll();
if (resultCollection.Count == 0)
{
return null;
}
else
{
foreach(SearchResult sResult in resultCollection)
{
if (sResult.Properties["distinguishedName"][0].Equals(null) ||
sResult.Properties["displayName"][0].Equals(null))
continue;
displayName.Add(sResult.Properties["distinguishedName"][0].ToString());
displayName.Add(sResult.Properties["displayName"][0].ToString());
}
}
ldapConnection.Close();
ldapConnection.Dispose();
search.Dispose();
return displayName;
}
catch (Exception e)
{
Console.WriteLine("Exception caught:\n\n" + e.ToString());
}
return null;
}
Now my view:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Résultat de recherche d'utilisateurs</title>
</head>
<body>
<h2> Résultat de recherche d'utilisateurs</h2>
#{
var incLoop = 0;
var incArr = 0;
var list = (List<string>)ViewData["Names"];
var size = list.Count();
string[] objSID = new string[size];
foreach (var link in list)
{
if (incLoop % 2 == 0)
{
objSID[incArr] = link;
incArr++;
}
else
{
#link<br/>
}
incLoop++;
}
}
</body>
</html>
If you click on #link in the tag, you get the information, which is shown in the next view. I've also split my list to not show the distinguishedName in the search result view.
What I have done for now, is researching the Active Directory when you click on the link, but it seems like bad practice (searching twice for one result). Any ideas?
Thank you, hope it's clear

How to save current URL to a cookie, and restore with javascript onclick

Can anyone help me to create a cookie to save the users current URL with location.href when they click a button, in effect a "save progress" button. Then have another load button to take the user to what had been saved in this cookie,
<!DOCTYPE html>
<html>
<head>
<script>
function newDoc()
{
window.location.assign(location.href)
}
</script>
</head>
<body>
<input type="button" value="Load Progress" onclick="newDoc()">
</body>
</html>
is this possible?
Many thanks.
You can create cookie using javascript.
You can use following function to make it easy.
You can read, right, delete cookies by using following functions.
/***create cookie using createCookie later you can read it eg. var url = readCookie("currenturl");***/
function newDoc(){ createCookie("currenturl", document.URL, 1);
}
function createCookie(name,value,days) { if (days) { var date = new Date();
date.setTime(date.getTime()+(days*24*60*60*1000));
var expires = "; expires="+date.toGMTString();
}
else var expires = "";
document.cookie = name+"="+value+expires+"; path=/";
}
function readCookie(name) { var nameEQ = name + "="; var ca = document.cookie.split(';');
for(var i=0;i < ca.length;i++) {
var c = ca[i];
while (c.charAt(0)==' ') c = c.substring(1,c.length);
if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
}
return null;
}
function eraseCookie(name) { createCookie(name,"",-1);
}

Not receiving JSONP callback

I am following the sample code/tutorial for ASP.NET MVC and JSONP blog post: http://blogorama.nerdworks.in/entry-EnablingJSONPcallsonASPNETMVC.aspx
I have taken the code sample and have modified it for my own consumption.
When I hit the page, it fires off my controller's action but the $.getJSON(call, function (rsp).. is not firing at all.
Controller action
[JsonpFilter]
public JsonpResult GetMyObjects(int id)
{
List<MyObject> list = MyDAO.GetMyObjects(id);
return new JsonpResult
{
Data = list,
JsonRequestBehavior = JsonRequestBehavior.AllowGet
};
}
HTML Page
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
</head>
<body>
<script type="text/javascript">
var url = "http://localhost/MySite.ContentDelivery/MyController/GetMyObjects/?";
function getObjects() {
//
// build the URL
//
debugger;
var call = url + "id=48&jsoncallback=?";
//
// make the ajax call
//
$.getJSON(call, function (rsp) {
debugger;
alert(rsp);
if (rsp.stat != "ok") {
//
// something went wrong!
//
$("#myDiv").append(
"<label style=\"background-color:red;color:white;padding: 25px;\">Whoops! It didn't work!" +
" This is embarrassing! Here's what the system had to " +
" say about this - " + rsp.message + "</label>");
}
else {
//
// build the html
//
var html = "";
$.each(rsp.list.myObject, function () {
var obj = this;
html += "<span" + obj.Name + "</span> <br />";
});
//
// append this to the div
//
$("#myDiv").append(html);
}
});
}
//
// get the offers
//
$(document).ready(function() {
alert('go..');
$(getOobjects);
});
</script>
<div id="myDiv"></div>
</body>
</html>
tl;dr why is my getJson() not firing while my getObjects() fires and executes the MVC controller action.
Replace:
var call = url + "id=48&jsoncallback=?";
with:
var call = url + "id=48&callback=?";
The custom JsonpResult you are using relies on a query string parameter called callback and not jsoncallback:
Callback = context.HttpContext.Request.QueryString["callback"];
Also you have decorated your controller action with a [JsonpFilter] attribute and returning a JsonpResult. As explained in the article you must have read you should choose one:
[JsonpFilter]
public ActionResult GetMyObjects(int id)
{
List<MyObject> list = MyDAO.GetMyObjects(id);
return Json(list, JsonRequestBehavior.AllowGet);
}
or the other:
public ActionResult GetMyObjects(int id)
{
List<MyObject> list = MyDAO.GetMyObjects(id);
return new JsonpResult
{
Data = list,
JsonRequestBehavior = JsonRequestBehavior.AllowGet
};
}
but do not mix the two.

ASP.NET MVC refresh header issue

I want to call an action method (DownloadPictures) after i redirect to a different page, so i use the refresh header
UrlHelper url = new UrlHelper(Request.RequestContext);
Response.AddHeader("REFRESH" , "1;URL=" + url.Action("DownloadPictures" , "Cart" , new { isFree = true }));
return Redirect(returnUrl != null ? returnUrl : url.Action("Index", "Home"));
And my Download Pictures method looks like this with a breakpoint set on the first line, but this method never gets called
public ActionResult DownloadPictures ( bool? isFree ) {
Cart cart = (Cart)HttpContext.Session["_cart"];
....
//The Download Picture Method returns a File (a zip file)
}
Any help would be appreciated. Thanks
Most browsers ignore the refresh header
Use another method like javascript etc
e.g.
<html>
<head>
<script type="text/javascript">
function delayRedirect()
{
window.location = "/DownloadPictures";
}
</script>
</head>
<body onLoad="setTimeout('delayRedirect()', 1000)">
...
</body>
</html>

ASP.NET MVC two user control

I have two user controls on the page and one of the user control has this text aread.
which is used to add a note and but when they click add note button the page reloads.
I do not want the page to reload ,i was looking for an example which this is done without
postback.
Thanks
i tired doing this using JSON , but it throws the following error
The HTTP verb POST used to access path '/Documents/TestNote/Documents/AddNote' is not allowed.
<script type="text/javascript">
$(document).ready(function() {
$("#btnAddNote").click(function() {
alert("knock knock");
var gnote = getNotes();
//var notes = $("#txtNote").val();
if (gnote == null) {
alert("Note is null");
return;
}
$.post("Documents/AddNote", gnote, function(data) {
var msg = data.Msg;
$("#resultMsg").html(msg);
});
});
});
function getNotes() {
alert("I am in getNotes function");
var notes = $("#txtNote").val();
if (notes == "")
alert("notes is empty");
return (notes == "") ? null : { Note: notes };
}
</script>
</asp:Content>
Something like this would give you the ability to send data to an action do some logic and return a Json result then you can update your View accordingly.
Javascript Function
function AddNote(){
var d = new Date(); // IE hack to prevent caching
$.getJSON('/MyController/MyAction', { data: "hello world", Date: d.getTime() }, function(data) {
alert(data);
// call back update your view here
});
}
MyController Action
public virtual JsonResult MyAction(string data)
{
// do stuff with your data here, which right now my data equals hello world for this example
return Json("ReturnSomeObject");
}
What you want is AJAX update. There will always be a postback (unless you are satisfied with simple Javascript page update that does not save on the server), but it won't be the flashing screen effect any more.

Resources