I am trying to insert multiple images in a single row in a field in oracle database, please suggest how to achieve it. Below are the details
image is rendering on the browser and I want to store multiple image through it in oracle db. Each image will have an id generating dynamically
aspx code:
<%# Page Language="C#" AutoEventWireup="true" CodeFile="Default2.aspx.cs" Inherits="Default2" %>
<!DOCTYPE html>
<html>
<head>
<style>
input[type="file"] {
display:block;
}
.imageThumb {
max-height: 75px;
border: 2px solid;
margin: 10px 10px 0 0;
padding: 1px;
}
</style>
<title></title>
</head>
<body>
<form id="form1" runat="server">
Find the bellow HTML code
<h2>preview multiple images before upload using jQuery</h2>
<input type="file" id="files" name="files[]" multiple />
<asp:Button ID="Button3" runat="server" BorderColor="#CCFF66"
ForeColor="#0066FF" Text="Insert Data" />
</form>
<script src="http://code.jquery.com/jquery-1.11.1.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function () {
var a = 0;
if (window.File && window.FileList && window.FileReader) {
$("#files").on("change", function (e) {
var files = e.target.files,
filesLength = files.length;
if (filesLength == 1) {
a = a + 1;
}
for (var i = 0; i < filesLength ; i++) {
var f = files[i]
var fileReader = new FileReader();
fileReader.onload = (function (e) {
var file = e.target;
$("<img></img>", {
class: "imageThumb",
Id: "img"+ a.toString(),
src: e.target.result,
title: file.name
}).insertAfter("#files");
});
fileReader.readAsDataURL(f);
}
});
} else { alert("Your browser doesn't support to File API") }
});
</script>
</body>
</html>
for saving image into oracle db I am using ajax and created webservice to push data into db:
[WebMethod]
public static void SaveUser(User user)
{
String connectionString = ConfigurationManager.ConnectionStrings["conndbprodnew"].ConnectionString;
using (OracleConnection con = new OracleConnection(connectionString))
{
using (OracleCommand cmd = new OracleCommand("INSERT INTO par_cinfo(Product_Id,IMAGETYPE ) VALUES (:IMAGETYPE )", con))
{
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("IMAGETYPE ", user.IMAGETYPE);
cmd.Connection = con;
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
}
}
}
public class User
{
public decimal Product_Id { get; set; }
public Image IMAGETYPE { get; set; }
}
jQuery ajax on button click to send data to webservices:
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript" src="http://cdn.jsdelivr.net/json2/0.1/json2.js"></script>
<script type="text/javascript">
$(function () {
$("[id*=Button3]").bind("click", function () {
var user = {};
user.Product_Id = 1;
user.IMAGETYPE= "here dynamic image id which is uploaded should be present "
$.ajax({
type: "POST",
url: "Default.aspx/SaveUser",
data: '{user: ' + JSON.stringify(user) + '}',
//data: JSON.stringify({user:user}),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
alert("User has been added successfully.");
window.location.reload();
}
});
return false;
});
});
</script>
The table which I created in oracle is as follows simply for entering the data in the table:
Create table par_cinfo
(
Product_Id NUMBER(10) NOT NULL PRIMARY KEY,
IMAGETYPE BLOB
)
Related
I want to upload some files to iis 7 by formdata with ajax ,but they are cut into less than 80kb,while it’s alright in debug mode
It can work correctly when the first time I run the IIS, only once.
there is the source code of Up.html, I have removed all the useless function:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<script src="../../js/jquery-1.4.4.min.js" type="text/javascript"></script>
<script type="text/javascript">
function UploadFiles() {
var formData = new FormData();
var files = $('#fileExcel')[0].files;
for (var i = 0; i < files.length; i++) {
formData.append("file[]", files[i]);
}
$.ajax({
url: 'Up.ashx',
type: 'POST',
data: formData,
async: false,
cache:false,
processData: false,
contentType: false,
success: function() {
formData = null;
}
});
}
</script>
</head>
<body>
<form action="Up.ashx" method="post"></form>
<input id="fileExcel" name="file" type="file" multiple="multiple"/>
<button id="btnUpload" onclick="UploadFiles()">上传</button>
</body>
</html>
And there is the code of Up.ashx,I have removed all the useless function:
using System.IO;
using System.Web;
public class Up : IHttpHandler {
public void ProcessRequest (HttpContext context) {
context.Response.ContentType = "text/plain";
HttpFileCollection files = context.Request.Files;
if (files.Count<1)
{
context.Response.Write("no file");
context.Response.End();
}
string category = this.GetType().ToString();
string filePath = HttpContext.Current.Server.MapPath("~/FileUpload/" + category + "/");
if (!Directory.Exists(filePath))
{
Directory.CreateDirectory(filePath);
}
for (int i = 0; i < files.Count; i++)
{
HttpPostedFile file = files[i];
file.SaveAs(filePath+file.FileName);
}
context.Response.Write(files.Count + " files");
context.Response.End();
}
public bool IsReusable {
get {
return false;
}
}
}
When I modified the code like this, it works, I just don't know why.
public Dictionary<string,string> ReceiveFiles(HttpContext context)
{
// return files info as Dictionary
Dictionary<string,string> result = new Dictionary<string, string>();
string category = this.GetType().ToString();
string filePath = HttpContext.Current.Server.MapPath("~/FileUpload/" + category + "/");
if (!Directory.Exists(filePath))
{
Directory.CreateDirectory(filePath);
}
// the key statement👇,I just don't know why it works
string savePath = context.Request["path"];//"path" can be instead to any keystring,T^T!
string[] files = context.Request.Files.AllKeys;
foreach (string str in files)
{
HttpPostedFile file = context.Request.Files.Get(str);
try
{
file.SaveAs(filePath + file.FileName);
result.Add(file.FileName,filePath+file.FileName);
//context.Response.Write("上传成功!");
}
catch (Exception ex)
{
context.Response.Write("上传失败!错误信息:" + ex.Message.ToString());
return null;
}
}
return result;
}
I am trying to pass some JavaScript variable value from .aspx file to .ashx file when user uploads a document in the web form.
The web form is a .aspx file and the uploading functionality is in .ashx file. So I need to pass the variables from .aspx file to .ashx file.
I was able to pass three variables but when I try to pass the fourth one then it does not work. It does not give any error but just do not pass any of the variables. When I debug the code I can see the debugger does not enters the process of upload. And the upload button also changes
This is my .aspx page code.
<%# Page Title="" Language="VB" MasterPageFile="~/_resx/E4.master" AutoEventWireup="true" CodeFile="new.aspx.vb" Inherits="E4_Jobs_new" ValidateRequest="false" %>
<asp:Content ID="Content1" ContentPlaceHolderID="MainContent" runat="Server">
<script type="text/javascript">
var id = '<%= ModeID%>', mode = '<%= Mode%>', employer = '<%= Employer.Name %>', jtitle = document.getElementById(<%= txtTitle.ClientID%>);
</script>
<asp:RequiredFieldValidator runat="server" ControlToValidate="txtTitle" Display="None" ErrorMessage="xx" ValidationGroup="NewJob" EnableViewState="False" />
<div class="form-element">
<input type="text" id="txtTitle" runat="server" maxlength="64" /></div>
<div class="m-accor-body">
<ul id="attachmentList">
<% For Each additionalDoc As DataRow In Vacancy.Attachemnts.Rows%>
<li id="da<%= additionalDoc.Item("id") %>">
<span><%= additionalDoc.Item("name") %></span>
<span class="rd" data-did="<%= additionalDoc.Item("id")%>"> remove</span>
</li>
<%Next%>
</ul>
<div id="queue"></div>
<input id="file_upload" name="file_upload" type="file">
</div>
</asp:Content>
And this is the code in the .aspx file where I am passing the variables into .ashx file
$(function () {
dimNav('vacancy');
$('#file_upload').uploadify({
'buttonClass': 'button2',
'buttonText': 'Select a PDF or DOCX file to upload..',
'width': 250,
'fileTypeExts': '*.pdf; *.doc; *.docx',
'formData': {
'draftId': id,
'type': mode,
'employer': employer,
'jtitle': jtitle
},
'uploadLimit': 6,
'swf': '/_resx/uploadify.swf',
'uploader': '/e4/jobs/upload-job-attachments.ashx',
'onUploadSuccess': function (file, data, response) {
$('#attachmentList').append('<li id="da' + data + '"><span>' + file.name + '</span><span class="rd" data-did="' + data + '"> remove</span></li>');
}
});
});
The first three variables values are obtained differently than the fourth one. In the fourth one I used javascript function to get the value (as it is the input value given by the user. Not a value stored already in database. ) .
This is my code for in the upload-job-attachments.ashx file where I retrieve the values
Public Class upload_job_attachments : Implements IHttpHandler
Public Sub ProcessRequest(ByVal context As HttpContext) Implements IHttpHandler.ProcessRequest
context.Response.ContentType = "text/plain"
context.Response.Expires = -1
Try
Dim Id As Integer = CInt(context.Request("draftid"))
Dim type As String = CStr(context.Request("type"))
Dim empname As String = CStr(context.Request("employer"))
Dim postedFile As HttpPostedFile = context.Request.Files("Filedata")
********** other lines of code ***********
End Sub
End Class
what can I do to overcome the problem. I am weak in advanced javascript functionalities. I appreciate your help
Addition
The whole script looks like
$(function () {
dimNav('vacancy');
var jobTitle = $('#' + '<%= txtTitle.ClientID%>').val();
$('#file_upload').uploadify({
'buttonClass': 'button2',
'buttonText': 'Select a PDF or DOCX file to upload..',
'width': 250,
'fileTypeExts': '*.pdf; *.doc; *.docx',
'formData': {
'draftId': id,
'type': mode,
'employer': employer,
'jtitle': jobTitle
},
'uploadLimit': 6,
'swf': '/_resx/uploadify.swf',
'uploader': '/e4/jobs/upload-job-attachments.ashx',
'onUploadSuccess': function (file, data, response) {
$('#attachmentList').append('<li id="da' + data + '"><span>' + file.name + '</span><span class="rd" data-did="' + data + '"> remove</span></li>');
alert($('#' + '<%= txtTitle.ClientID%>').val());
}
});
$('body').on('click', '.rd', function () {
var el = $(this);
$.post('delete-job-attachment.ashx?id=' + el.attr('data-did'), '{}', function () {
$('#da' + el.attr('data-did')).remove();
});
});
$('.price-button').click(function () { $(this).next('.price-list').fadeToggle('slow'); });
$('.m-lists table tr:nth-child(4) td:nth-child(1)').prepend('<div>Multiple job posting</div>');
$('.jMedias').change(function () {
suffleMedias();
});
var suffleMedias = function () {
var mids = [];
$('.jMedias:checked').each(function () {
mids.push($(this).val());
});
$('.mediaLists').val(mids.toString());
};
$('.jType').change(function () {
suffleJobType();
});
$('input:radio.p-option-radio').change(function () {
var pOption = $(this).val();
$('.p-option').val(pOption);
});
var suffleJobType = function () {
var type = $('.jType').val();
if (type == 0) {
$('#contractLength, #jobHour').slideUp();
} else if (type == 1) {
$('#jobHour').slideDown();
$('#contractLength').slideUp();
} else if (type == 2) {
$('#jobHour').slideDown();
$('#contractLength').slideUp();
} else if (type == 3) {
$('#contractLength, #jobHour').slideDown();
}
};
var suffleFeeType = function () {
var fType = $('.feeType').val();
if (fType == 0) {
$('#salaryRateMax, #salaryRateMin, #agencyFee').slideDown();
} else if (fType == 1) {
if (parseFloat($('.referrerPercentage option:selected').text()) > 0) {
} else {
$('#salaryRateMax, #salaryRateMin').slideUp();
}
$('#agencyFee').slideDown();
} else if (fType == 2) {
$('#agencyFee').slideUp();
if (parseFloat($('.referrerPercentage option:selected').text()) > 0) {
} else {
$('#salaryRateMax, #salaryRateMin').slideUp();
}
}
};
$('.feeType').change(function () {
suffleFeeType();
});
$('.referrerPercentage').change(function () {
if (parseFloat($('.referrerPercentage option:selected').text()) > 0) {
$('#salaryRateMax, #salaryRateMin').slideDown();
} else {
if ($('.feeType').val() == 1) {
$('#salaryRateMax, #salaryRateMin').slideUp();
}
}
});
$('.calcFee').change(function () {
CalculateAndDisplayFees();
});
$('.rAgency').chosen().change(function () {
if ($(this).val() != '-1') {
$('.psls').val('-1').trigger("liszt:updated");
$('.retained').val('1');
}
});
$('.psls').chosen().change(function () {
if ($(this).val() != '-1') {
$('.rAgency').val('-1').trigger("liszt:updated");
$('.retained').val('0');
}
});
var setPublishOption = function () {
var p = $('.p-option').val();
var $radios = $('input:radio.p-option-radio');
$radios.filter('[value=' + p + ']').attr('checked', true);
};
suffleJobType();
suffleFeeType();
suffleMedias();
CalculateAndDisplayFees();
setPublishOption();
});
If, for instance, the jtitle field needs to come from an input control, you can do:
'formData': {
'jtitle': $("#somecontrol").val()
}
Which will get the value from a control. Is that what you mean?
its me again. Im currently trying to build an multiple file uploader for my site but dont know how to get/handle all files. I think showing you the code first will be a better explanation:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>NDSLR - Demo Upload</title>
</head>
<body>
<script type="text/javascript">
function fileChange()
{
//FileList Objekt aus dem Input Element mit der ID "fileA"
var fileList = document.getElementById("fileA").files;
//File Objekt (erstes Element der FileList)
var file = fileList[0];
//File Objekt nicht vorhanden = keine Datei ausgewählt oder vom Browser nicht unterstützt
if(!file) {
return;
}
var x = substr(file.name, -4);
document.getElementById("status").innerHTML = x;
/*
if (x != ".pdf") {
document.getElementById("fileA").files = null;
file = null;
fileList = null;
alert("Wrong Data");
return;
} */
document.getElementById("fileName").innerHTML = 'Dateiname: ' + file.name;
document.getElementById("fileSize").innerHTML = 'Dateigröße: ' + file.size + ' B';
document.getElementById("progress").value = 0;
document.getElementById("prozent").innerHTML = "0%";
}
var client = null;
function uploadFile()
{
//Wieder unser File Objekt
for(i=0;i < document.getElementById("fileA").files; i++) {
var file = document.getElementById("fileA").files[i];
//FormData Objekt erzeugen
var formData = new FormData();
//XMLHttpRequest Objekt erzeugen
client = new XMLHttpRequest();
var prog = document.getElementById("progress");
if(!file)
return;
prog.value = 0;
prog.max = 100;
//Fügt dem formData Objekt unser File Objekt hinzu
formData.append("datei", file);
client.onerror = function(e) {
alert("onError");
};
client.onload = function(e) {
document.getElementById("prozent").innerHTML = "100%";
prog.value = prog.max;
};
client.upload.onprogress = function(e) {
var p = Math.round(100 / e.total * e.loaded);
document.getElementById("progress").value = p;
document.getElementById("prozent").innerHTML = p + "%";
};
client.onabort = function(e) {
alert("Upload abgebrochen");
};
client.open("POST", "upload.php");
client.send(formData);
}
}
}
function uploadAbort() {
if(client instanceof XMLHttpRequest)
//Briecht die aktuelle Übertragung ab
client.abort();
}
</script>
<form action="" method="post" enctype="multipart/form-data">
<input name="file[]" type="file" multiple="multiple" id="fileA" onchange="fileChange();"/>
<input name="upload[]" value="Upload" type="button" accept=".dem" onclick="uploadFile();" />
<input name="abort" value="Abbrechen" type="button" onclick="uploadAbort();" />
</form>
<div id="status"></div>
<div id="fileName"></div>
<div id="fileSize"></div>
<div id="fileType"></div>
<progress id="progress" style="margin-top:10px"></progress> <span id="prozent"></span>
</div>
</body>
</html>
So this is my HTML Code and following up my upload.php:
<?php
if (isset($_FILES['datei']))
{
move_uploaded_file($_FILES['datei']['tmp_name'], 'upload/'.$_FILES['datei']['name']);
}
?>
My Problem currently is, that i dont know how to implement the multiple upload or better said, how to upload all files at all.
There are some tutorials in the internet, that you can simply find by googling "multiple file upload". Anyway here is one of the examples:
The HTML
<!-- IMPORTANT: FORM's enctype must be "multipart/form-data" -->
<form method="post" action="upload-page.php" enctype="multipart/form-data">
<input name="filesToUpload[]" id="filesToUpload" type="file" multiple="" />
</form>
Listing Multiple Files with JavaScript
//get the input and UL list
var input = document.getElementById('filesToUpload');
var list = document.getElementById('fileList');
//empty list for now...
while (list.hasChildNodes()) {
list.removeChild(ul.firstChild);
}
//for every file...
for (var x = 0; x < input.files.length; x++) {
//add to list
var li = document.createElement('li');
li.innerHTML = 'File ' + (x + 1) + ': ' + input.files[x].name;
list.append(li);
}
The input.files property provides an array of files for which you can check the length; if there's a length, you can loop through each file and access the file paths and names.
Receiving and Handling Files with PHP
if(count($_FILES['uploads']['filesToUpload'])) {
foreach ($_FILES['uploads']['filesToUpload'] as $file) {
//do your upload stuff here
echo $file;
}
}
PHP creates an array of the files uploaded with the given INPUT's name. This variable will always be an array within PHP.
Source
Demo
This is uploading using ajax. There are other ways such the use of iframe and jquery's $.load().
ajax_upload.js
Hmm... FormData is not IE-safe. So, you may want to resort to iframe & $.load().
function doUpload(fle_id, url_upld)
{
var upldLimit = 2000000; // 2mb by default;
if( $('#'+fle_id)[0] == undefined || $('#'+fle_id)[0].files.length == 0 ) {
alert('nothing to upload');
return;
}
// put files to formData
var tfSize = 0; // in bytes
var fd = new FormData();
$.each($('#'+fle_id)[0].files, function(i, file) {
fd.append(i, file);
tfSize = tfSize + file.size;
});
// you may check file size before sending data
if(tfSize > upldLimit) {
alert('File upload exceeded the '+(upldLimit/1000000)+' MB limit.');
return;
}
// actual data transfer
$.ajax({
url: url_upld,
cache: false,
data: fd,
type: 'POST',
contentType : false,
processData : false,
success: function(data){
alert(data);
},
error: function(jqXHR, textStatus, errorMessage) {
alert(errorMessage);
}
});
}
upload_form.html
Let's use jquery to make things simple.
<script type="text/javascript" src="jquery.min.js"></script>
<script type="text/javascript" src="ajax_upload.js"></script>
<script type="text/javascript">
$(function(){
$('form').submit(function(e){
if( e.preventDefault ) e.preventDefault(); // chrome/firefox
else e.cancelBubble(); // IE
// supply file input id and upload url
doUpload( 'fle', $(this).attr('action') );
});
});
</script>
Upload
<form action="ajax_upload.php"
method="post"
enctype="multipart/form-data"
accept-charset="utf-8"
>
<input type="file" id="fle" name="fle[]" multiple >
<button type="submit">Upload</button>
</form>
ajax_upload.php
<?php
if(count($_FILES) == 0) {
echo 'Nothing uploaded.';
exit;
}
$upldPath = 'E:/stack/upload/';
foreach($_FILES as $file) {
if ($file['error'] == UPLOAD_ERR_OK) {
try {
if( !move_uploaded_file( $file["tmp_name"], $upldPath . $file['name']) ) {
// abort even if one file cannot be moved.
echo 'Cannot upload one of the files.';
exit;
}
}
catch(Exception $e) {
echo 'Cannot upload the files.';
exit;
}
} else {
// abort even if one file has error.
echo 'Cannot upload one of the files.';
exit;
}
}
echo 'Upload successful!';
?>
Here is a simple approach to solving this issue.
This FormData append method works on IE 10 up and any other browser.
let files = []
let formData = new FormData
let filesInput = document.getElementById('files')
function prepareFiles() {
files = filesInput.files
}
function uploadFiles() {
// Arrange the files as form data to be sent to php
files = Array.from(files)
files.forEach(file => formData.append('files[]', file))
// See all selected files
console.log('Files')
console.log(formData.getAll('files[]'))
// Then send to php with jquery, axios e.t.c
console.log('Server response')
$.post('/pathtophpscript', formData, (response) => {
console.log(response)
}).catch(error => console.log(error))
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="file" name="uploads" id="files" onchange="prepareFiles()" multiple>
<br/><br/>
<input type="submit" name="Upload" onclick="uploadFiles()">
hello everybody I'm new here and I'm new to jquery too
I apply this article to my website to upload multiple data at once
using-dropzone-js-file-image-upload-in-asp-net-webform-c
while I'm using this code when I click on the dropzone area it's uploading the photos directly to ~/work/
so what I hope so is to use a button with id=post
to upload these images in dropzone area only after click on it
so here is my code:
here is the header:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<link href="css/dropzone.css" rel="stylesheet" type="text/css" />
<script src="js/dropzone.js" type="text/javascript"></script>
the html part:
<div id="dZUpload" class="dropzone ">
<div class="dz-default dz-message"></div>
</div>
the javascript part:
<script>
$(document).ready(function () {
Dropzone.autoDiscover = false;
//Simple Dropzonejs
$("#dZUpload").dropzone({
url: 'FileUploader.ashx',
addRemoveLinks: true,
maxFiles: 3,
success: function (file, response) {
var imgName = response;
file.previewElement.classList.add("dz-success");
console.log("Successfully uploaded :" + imgName);
},
error: function (file, response) {
file.previewElement.classList.add("dz-error");
}
});
});
</script>
and finally the Generic Handler "
FileUploader.ashx
:
<%# WebHandler Language="C#" Class="FileUploader" %>
using System;
using System.Web;
using System.IO;
public class FileUploader : IHttpHandler {
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/plain";
string dirFullPath = HttpContext.Current.Server.MapPath("~/work/");
string[] files;
int numFiles;
files = System.IO.Directory.GetFiles(dirFullPath);
numFiles = files.Length;
numFiles = numFiles + 1;
string str_image = "";
foreach (string s in context.Request.Files)
{
HttpPostedFile file = context.Request.Files[s];
// int fileSizeInBytes = file.ContentLength;
string fileName = file.FileName;
string fileExtension = file.ContentType;
if (!string.IsNullOrEmpty(fileName))
{
fileExtension = Path.GetExtension(fileName);
str_image = "WorkPhoto_" + numFiles.ToString() + fileExtension;
string pathToSave_100 = HttpContext.Current.Server.MapPath("~/work/") + str_image;
file.SaveAs(pathToSave_100);
}
}
context.Response.Write(str_image);
}
public bool IsReusable {
get {
return false;
}
}
}
Here i think this will solve your Problems:
<script>
$(document).ready(function () {
Dropzone.autoDiscover = false;
//Simple Dropzonejs
var myDropzone = new Dropzone("#dZUpload", {
url: 'FileUploader.ashx', autoProcessQueue: false, addRemoveLinks: true, maxFiles: 3,
success: function (file, response) {
var imgName = response;
file.previewElement.classList.add("dz-success");
console.log("Successfully uploaded :" + imgName);
},
error: function (file, response) {
file.previewElement.classList.add("dz-error");
},
});
$('#button').on('click', function (e) {
myDropzone.processQueue();
});
});
I am working on a web application developed using Asp.Net MVC which on which I have a page on which data gets updated at realtime whenever data is modified on the database. I have some source on line and tried to implement this feature but it resulted in huge invalid data on the webpage.
I am using SQL dependency and SignalR to achieve this as follows
In Global.asax, I have the following
protected void Application_Start()
{
SqlDependency.Start(ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString);
}
protected void Application_End()
{
SqlDependency.Stop(ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString);
}
and in Models section I have the following classes
public class JobInfo
{
public int JobID { get; set; }
public string Name { get; set; }
public DateTime LastExecutionDate { get; set; }
public string Status { get; set; }
}
public class JobInfoRepository
{
public IEnumerable<JobInfo> GetData()
{
using (var connection = new SqlConnection(ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString))
{
connection.Open();
using (SqlCommand command = new SqlCommand(#"SELECT [JobID],[Name],[LastExecutionDate],[Status]
FROM [dbo].[JobInfo]", connection))
{
// Make sure the command object does not already have
// a notification object associated with it.
command.Notification = null;
SqlDependency dependency = new SqlDependency(command);
dependency.OnChange += new OnChangeEventHandler(dependency_OnChange);
if (connection.State == ConnectionState.Closed)
connection.Open();
using (var reader = command.ExecuteReader())
return reader.Cast<IDataRecord>()
.Select(x => new JobInfo(){
JobID = x.GetInt32(0),
Name = x.GetString(1),
LastExecutionDate = x.GetDateTime(2),
Status = x.GetString(3) }).ToList();
}
}
}
private void dependency_OnChange(object sender, SqlNotificationEventArgs e)
{
JobHub.Show();
}
}
I have created a SignalR Hub class as follows which has the Show() function used in the above class
using Microsoft.AspNet.SignalR.Hubs;
public class JobHub : Hub
{
public static void Show()
{
IHubContext context = GlobalHost.ConnectionManager.GetHubContext<JobHub>();
context.Clients.All.displayStatus();
}
}
And I have the controller in which I am calling GetData() method defined in the JobInfoRepository class
public class JobInfoController : Controller
{
// GET: /JobInfo/
JobInfoRepository objRepo = new JobInfoRepository();
public IEnumerable<JobInfo> Get()
{
return objRepo.GetData();
}
}
I have created an Action named JobInfo in HomeController and returned the following view
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>JobStatus</title>
<link href="#Url.Content("~/Content/Site.css")" rel="stylesheet" type="text/css" />
<script src="#Url.Content("~/Scripts/jquery-1.9.1.min.js")" type="text/javascript"></script>
</head>
<body>
<div>
<table id="tblJobInfo" class="clientTable" style="text-align:center;margin-left:10px"></table>
</div>
</body>
</html>
#section scripts {
<script src="~/Scripts/jquery.signalR-2.0.1.min.js"></script>
<script src="/signalr/hubs"></script>
<script src="~/App/JobInfo.js"></script>
}
to retrieve the data and supply it to tblJobInfo id in the above html, a java script function is used
$(function () {
// Proxy created on the fly
var job = $.connection.jobHub;
// Declare a function on the job hub so the server can invoke it
job.client.displayStatus = function () {
getData();
};
// Start the connection
$.connection.hub.start();
getData();
});
function getData() {
var $tbl = $('#tblJobInfo');
$.ajax({
url: '../JobInfo/',
type: 'GET',
datatype: 'json',
success: function (data) {
if (data.length > 0) {
$tbl.empty();
$tbl.append(' <tr><th>ID</th><th>Name</th><th>Status</th></tr>');
var rows = [];
for (var i = 0; i < data.length; i++) {
rows.push(' <tr><td>' + data[i].JobID + '</td><td>' + data[i].Name + '</td><td>' + data[i].Status + '</td></tr>');
}
$tbl.append(rows.join(''));
}
}
});
}
As in the demo I found it to be working fine but when I go to http://localhost:57044/Home/JobInfo/ I get invalid data on the page besides not getting the realtime notifications as in the following image
reference to the source I found online is http://techbrij.com/database-change-notifications-asp-net-signalr-sqldependency