Thursday, April 25, 2019

HTML Drag n Drop text or Image

HTML5 supports drag and drop, that allows user to move a content from one side to another. Here I demonstrate drag and drop a text from one <div> to another <div>. 


please download full script from Download Source Code
below javascript code will do drag drop

<script>
function allowDrop(ev) {
ev.preventDefault();
}

function drag(ev, ctrl) {
ev.dataTransfer.setData("text", ev.target.id);
}

function drop(ev) {
ev.preventDefault();
var data = ev.dataTransfer.getData("text");
ev.target.appendChild(document.getElementById(data));
}
</script>

ev.PreventDefault() -   will prevent fire default event

ev.dataTransfer.setData("text", ev.target.id) - will set data type and value of dragged data

Below is HTML tag

<h2>Drag and Drop Text</h2>

<div id="div1" ondrop="drop(event)" ondragover="allowDrop(event)">
<div id="drag001" draggable="true" ondragstart="drag(event, this)" >Drag Item 1</div>
<div id="drag002" draggable="true" ondragstart="drag(event, this)" >Drag Item 2</div>
<div id="drag003" draggable="true" ondragstart="drag(event, this)" >Drag Item 3</div>
</div>

<div id="div2" ondrop="drop(event)" ondragover="allowDrop(event)"></div>

ondrop - event fires when release mouse left button
ondragover - event fires when mouse move over the control/HTML tag

draggable="true" - make the <div> element draggable
ondragstart="drag(event, this)" - fires when user start dragging

finally add below style to <div> tag so that it will show as box
<style>
#div1, #div2 {
float: left;
width: 100px;
height: 75px;
margin: 10px;
padding: 10px;
border: 1px solid black;
}
</style>

Monday, April 22, 2019

HTML internal storage with IndexedDB

One of the challenge in modern web application is to store data in client side, it can help to avoid un-necessary service call to server. IndexedDB is one of the mechanism which will store data in client browser (hence it is crucial that browser should support it). Below are some of scenario for keeping data local

1. Text Translation - load all translated text in browser and avoid service call for text translation
2. work offline - this will help to reduce round trip. Load all data at the time of application load (ex: Types/Categories etc) so that we dont needs to call service to fetch again.
3. Work Offline - store all data in indexedDB, and continue process, once everything is completed, single click can save data in your SQL/Oracle DB.

Fact about IndexedDB

1. It is not a RDBMS
2. Data are stored in the form of key/value
3. SQL query will not work
4. IndexedDB is not a replacement of your DB
5. User can group a set of key/value and Keypath will represent each key/value pair

lets start practical :)

below is HTML will create IndexedDB and store (try this in your chrome)
Full Source code available here

<html>
<head>
<meta http-equiv = "Content-Type" content = "text/html; charset = utf-8" />
<script type = "text/javascript">
//prefixes of implementation that we want to test
window.indexedDB = window.indexedDB || window.mozIndexedDB ||
window.webkitIndexedDB || window.msIndexedDB;
//prefixes of window.IDB objects
window.IDBTransaction = window.IDBTransaction ||
window.webkitIDBTransaction || window.msIDBTransaction;
window.IDBKeyRange = window.IDBKeyRange || window.webkitIDBKeyRange ||
window.msIDBKeyRange
if (!window.indexedDB) {
window.alert("Your browser doesn't support a stable version of IndexedDB.")
}
var db;
var request = window.indexedDB.open("empDB", 1);
request.onerror = function(event) {
console.log("error: ");
};
request.onsuccess = function(event) {
db = request.result;
console.log("db Created success: "+ db);
};
request.onupgradeneeded = function(event) {
var db = event.target.result;
var objectStore = db.createObjectStore("empstore", {keyPath: "empid"});
}
</script>
</head>
<body> </body>
</html>

save as HTML file and run.
Once page loaded, you will be seeing blank screen :), lets see what is happening indexedDB, press F12 and select application tab, your IndexedDB, store are ceated now :)

















lets go through the code. Below code creates new Indexed DB empDB (line no: 17)
var request = window.indexedDB.open("empDB", 1);

below line will be creating an object store named empStore (line no 27). I set keypath as empID. KeyPath (empID) is one of property in key/value collection, which will represent the entire group (like PK in RDBMS)

var objectStore = db.createObjectStore("empstore", {keyPath: "empid"});

Now I am going to add/Find/Delete data from my IndexedDB

below, i am adding HTML tag to add/Find/Delete. I am adding 3 textbox which will have empID, Name and Age.

<body>
<label>Emp ID</label><input type="text" id="txtEmpID"><br/>
<label>Emp Name</label><input type="text" id="txtEmpName"><br/>
<label>Emp Age</label><input type="text" id="txtAge"><br/><br/>

<button onclick = "add()">Add data </button>
<button onclick = "read()">Find </button>
<button onclick = "remove()">Delete data </button>
</body>

Add to IndexedDB
function add() {

var _empID = txtEmpID.value;
var _empName=txtEmpName.value;
var _empAge=txtAge.value;
var request = db.transaction(["empstore"], "readwrite")
.objectStore("empstore")
.add({ empid: _empID.toString(), name: _empName.toString(), age: _empAge.toString()});
request.onsuccess = function(event) {
alert("Employee has been added to your database.");
};
request.onerror = function(event) {
alert("Unable to add data\r\nEmployee is aready exist in your database! ");
}
}

now refresh your indexedDB you could find the entry in key/value pair form like below





Find


function read() {
var _empID = txtEmpID.value;
var transaction = db.transaction(["empstore"]);
var objectStore = transaction.objectStore("empstore");
var request = objectStore.get(_empID.toString());
request.onerror = function(event) {
alert("Unable to retrieve daa from database!");
};
request.onsuccess = function(event) {
// Do something with the request.result!
if(request.result) {
alert("Name: " + request.result.name + ", Age: " + request.result.age );
} else {
alert("Employee couldn't be found in your database!");
}
};
}

Delete
function remove() {
var _empID = txtEmpID.value;
var request = db.transaction(["empstore"], "readwrite")
.objectStore("empstore")
.delete(_empID.toString());
request.onsuccess = function(event) {
alert("EMployee has been removed from your database.");
};
request.onerror = function(event) {
alert("Employee not found ");
}
}

Thursday, April 11, 2019

ASP.Net MVC file downloader to download file at user machine

Here is a simple source what will download file in user machine on a Asp.Net web application.
This can be implement in Angular application also.

Step 1 - new action in asp.net MVC controller


Byte[] dashboardfileBytes = File.ReadAllBytes(Full File LOCATION);

response = new HttpResponseMessage(HttpStatusCode.OK);
response.Content = new ByteArrayContent(updatefilebytes);
response.Content.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment");
response.Content.Headers.ContentDisposition.FileName = repsourceFileInfo[0].Name;
response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/xlsm");


Step 2 - download from client side

download is very simple, you have a add a <a> tag and in href property you needs to send Asp.Net MVC url for the action you created above

ex:
<a hreff="mycontroller\FileDownloadAction" >download File </a>

the same logic you can implement in angular, instead of calling asp.net MVC controoler\action url, you can use WebAPI url.

Wednesday, April 10, 2019

Call WEB API service using .Net code

This is a simple example calling Web API service from your .net application. Here i am following C# code.

We can achieve API service calling using WebClient.

Step 1
Refer System.Net.WebClient.dll in your project

Step2 - Source code

using System.Net;

public Class WebAPIHelper{

       public string callService() {

             WebClient client = new WebClient();
             client.Headers.Add("Content-type", "application/JSON");
              client.Encoding = Encoding.UTF8;

              //If your API and application is running in same IIS server use below credential otherwise
               //you have to set proper credential
              client.Credentials = CredentialCache.DefaultCredentials;

              string url = "https://url API url";
              string data = client.DownloadString(url);
              return data;
      }
      

}

Wednesday, April 3, 2019

Procedure or function 'usp_myprocedureName' expects parameter '@param', which was not supplied

I came with an SQL exception "Procedure or function 'usp_myprocedureName' expects parameter '@param', which was not supplied".

Normally this exception is caused when the parameter is not exists in your SQLcommand object or spelling mistake in parameter name. I check my .net code and confirmed parameter is exists!!!, then i go to SQL server and manually executed my SP with same parameter I copied from my .net code like below

execute usp_myStoreProcedure @Param = 'xxxxx'

it got executed !!!, to re-produce the issue i put NULL and empty string for @Param like below,

execute usp_myStoreProcedure @Param = ''
execute usp_myStoreProcedure @Param = NULL

still it executed with no exception.

i am confused, where was the problem then ??? 😬

Finally I found the issue 😍

The problem is here, when I set @param as NULLs from my .net SQL Command object, this NULL value is not sending to SQL and hence the issue. To check what is happening in SQL, I profile SQL, after execute my command, I found SQL server executes below command if @param becomes NULL.

exec [usp_myStoreProcedure @param=default

I resolved my issue by validate NULL, if @param value is null I skip execute stored procedure. you could resolve by your own logic.

The intention behind this post is to let you know above exception can throw even your SQL parameter has a NULL value.