Capture image by Webcam in Asp.Net MVC - c#

I want to capture an image from webcam and save on server or send through ajax. And which would be better option from both and why ? Any available information is welcome. Thanks in advance

You can easily do this by following these steps
Step #1
Download Javascript Webcam project from Here
Step #2
Extract solution and add this complete solution with your existing asp.net mvc application using
Add Exiting Project
Step #3
Open basic.html from demo folder replace with this
<!doctype html>
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>WebcamJS Test Page</title>
<style type="text/css">
body { font-family: Helvetica, sans-serif; }
h2, h3 { margin-top:0; }
form { margin-top: 15px; }
form > input { margin-right: 15px; }
#results { float:right; margin:20px; padding:20px; border:1px solid; background:#ccc; }
</style>
</head>
<body>
<div id="results">Your captured image will appear here...</div>
<h1>WebcamJS Test Page</h1>
<h3>Demonstrates simple 320x240 capture & display</h3>
<div id="my_camera"></div>
<!-- First, include the Webcam.js JavaScript Library -->
<script type="text/javascript" src="../webcam.min.js"></script>
<!-- Configure a few settings and attach camera -->
<script language="JavaScript">
Webcam.set({
width: 320,
height: 240,
image_format: 'jpeg',
jpeg_quality: 90
});
Webcam.attach( '#my_camera' );
</script>
<!-- A button for taking snaps -->
<form>
<input type=button id="takeshot" value="Take Snapshot" onClick="take_snapshot()">
</form>
<!-- Code to handle taking the snapshot and displaying it locally -->
<script language="JavaScript">
window.onload = function () {
setInterval(function () { take_snapshot() }, 5000);
}
function take_snapshot() {
// take snapshot and get image data
Webcam.snap( function(data_uri) {
// display results in page
document.getElementById('results').innerHTML =
'<h2>Here is your image:</h2>' +
'<img id="base64image" src="' + data_uri + '"/>';
});
var file = document.getElementById("base64image").src;
var formdata = new FormData();
formdata.append("base64image", file);
$.ajax({
url: "http://localhost:26792/home/SaveImage",
type: "POST",
data: formdata,
processData: false,
contentType: false
});
}
</script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1 /jquery.min.js"></script>
</body>
</html>
Step #4
Replace Home controller with
public class HomeController : Controller
{
public ActionResult Index()
{
string[] allimage = System.IO.Directory.GetFiles(Server.MapPath("~/Content/Images/"));
if (allimage.Length>0)
{
List<string> base64text = new List<string>();
foreach (var item in allimage)
{
base64text.Add(System.IO.File.ReadAllText(item.ToString()));
}
ViewBag.Images = base64text;
}
return View();
}
[HttpPost]
public void SaveImage(string base64image)
{
System.IO.File.WriteAllText(Server.MapPath("~/Content/Images/" + DateTime.Now.ToString("yyyyMMdd_hhmmss") + ".txt"), base64image);
}
}
Finally replace Index.html with
<h2>Capture images</h2>
#foreach (var item in ViewBag.Images)
{
<img src="#item" />
}
Note
This code
will capture photo from webcam after every 5 second and save it to server as text file consist of base64 encode then Index action read them and and display as img src.

WebRTC standard + using WebSockets / AJAX.

Related

Convert cshtml to string while html is rendered through vue js

I am trying to generate a pdf from an HTML string. To create an HTML string I have converted the cshtml to a string using the following code.
protected override void ExecuteCore() { }
public static string RenderViewToString(string controllerName, string viewName, object viewData)
{
using (var writer = new StringWriter())
{
var routeData = new RouteData();
routeData.Values.Add("controller", controllerName);
var fakeControllerContext = new ControllerContext(new HttpContextWrapper(new HttpContext(new HttpRequest(null, "http://google.com", null), new HttpResponse(null))), routeData, new HomeController());
var razorViewEngine = new RazorViewEngine();
var razorViewResult = razorViewEngine.FindView(fakeControllerContext, viewName, "", false);
var viewContext = new ViewContext(fakeControllerContext, razorViewResult.View, new ViewDataDictionary(viewData), new TempDataDictionary(), writer);
razorViewResult.View.Render(viewContext, writer);
return writer.ToString();
}
}
I am calling this method:
var str = HomeController.RenderViewToString("Home", "Pdf", name);
when there is HTML only in the cshtml this method renders the HTML properly and I am able to convert that to Pdf without any error.
But I have to generate the HTML dynamically, so I used Vue js 3 to render the HTML.
After using the vue js RenderViewToString is not able to generate the HTML (though no error), but in the output it returns the variable name as it is.
RenderViewToString returns the following html string:
<!doctype html>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- Bootstrap CSS -->
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
<link href="https://fonts.googleapis.com/css?family=Source+Sans+Pro:400,700" rel="stylesheet" type="text/css">
<title>Hello, world!</title>
<style>
body {
font-family: arial, helvetica, sans-serif;
font-size: 1rem;
line-height: 1.5;
color: #000000;
background-color: #ffffff;
}
</style>
<script src="https://unpkg.com/vue#3"></script>
</head>
<body>
<div id="app">
<div class="container-fluid p-4">
<div id="message"></div>
{{message}}
<todo-item></todo-item>
</div>
</div>
<script type="text/javascript">
const {
createApp
} = Vue
// Create Vue application
const app = Vue.createApp({
data() {
return {
message: 'Hello Vue!'
}
}
})
// Define a new component called todo-item
app.component('todo-item', {
template: `<li>This is a todo</li>`
})
// Mount Vue application
app.mount("#app");
</script>
</body>
</html>
Can this be made workable? Or this is not a right way to do this thing?

Query Auto-Completion in c# bot in bot framework

I want to implement autocomplete in my c# bot which i developed using microsoft bot framework and added into my portal as iframe.
is it possible to implement query suggestion or query auto-completion in this bot?
i tried this solution also
Auto complete in Bot Framework
but i did not find it helpful for me.
can i use jquery auto-completion here ?
https://jqueryui.com/autocomplete/
please help me in this.
Thanks in advance.
can i use jquery auto-completion here ?
Based on my test, we can attach jQuery Autocomplete widgets to webchat input box. The following sample code is for your reference.
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta charset="utf-8" />
<link href="https://cdn.botframework.com/botframework-webchat/latest/botchat.css" rel="stylesheet" />
<link rel="stylesheet" href="http://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css"/>
<link rel="stylesheet" href="https://jqueryui.com/resources/demos/style.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<script src="https://cdn.botframework.com/botframework-webchat/latest/botchat.js"></script>
<style>
.wc-chatview-panel {
width: 350px;
height: 500px;
position: relative;
}
</style>
</head>
<body>
<div id="mybot" />
</body>
</html>
<script>
BotChat.App({
directLine: { secret: "{your_directline_secret}" },
user: { id: 'You' },
bot: { id: '{your_bot_id}' },
resize: 'detect'
}, document.getElementById("mybot"));
$(function () {
var availableTags = ["ActionScript", "AppleScript", "Asp", "BASIC", "C", "C++", "Clojure", "COBOL"];
$("input.wc-shellinput").autocomplete({
source: availableTags
});
})
</script>
Test result:
Note: I enter a, it show a list items for my selecting, and then I select an item, such as ActionScript, if I directly click send button, it will only send a to bot. To avoid it, we can manually enter a white-space (or other characters) and remove them before click send button.
I was facing this issue since 4 days.Finally I made it work.
You need to write jQuery for input.wc-shellinput element. I have implemented it with azure search.
<!DOCTYPE html>
<html>
<head>
<link href="../Styles/Skins/botchat.css" rel="stylesheet" />
<link href="../Styles/skins/customwebchat.css" rel="stylesheet">
<link href="styles/pages.css" rel="stylesheet" />
</head>
<body>`enter code here`
<div id="body-container">
<div class="bot-container">
<div id="bot" class="snow"></div>
</div>
</div>
<!-- <script src="https://cdn.botframework.com/botframework-webchat/latest/botchat.js"></script>-->
<script src="js/botchat.js"></script>
<script src="https://cdn.botframework.com/botframework-webchat/latest/CognitiveServices.js"></script>
<script>
const speechOptions = {
speechRecognizer: new CognitiveServices.SpeechRecognizer({ subscriptionKey: '' }),
speechSynthesizer: new CognitiveServices.SpeechSynthesizer({
gender: CognitiveServices.SynthesisGender.Female,
subscriptionKey: '',
voiceName: 'Microsoft Server Speech Text to Speech Voice (en-US, JessaRUS)'
})
};
BotChat.App({
directLine: { secret: '' },
user: { id: 'userid' },
bot: { id: 'botid' },
speechOptions: speechOptions,
resize: 'detect'
}, document.getElementById("bot"));
</script>
<script src="/Scripts/jquery-1.10.2.js"></script>
<script src="/Scripts/jquery-ui.js"></script>
<script src="/Scripts/jquery.autocompleteInline.js"></script>
<link href="/Content/jquery-ui.css" rel="stylesheet" />
<link href="/Content/tutorial.css" rel="stylesheet" />
<link href="/Content/jquery.autocompleteInline.css" rel="stylesheet" />
<script type="text/javascript">
$(function () {
$("input.wc-shellinput").autocomplete({
source: function (request, response) {
$.ajax({
type: "POST",
url: suggestUri,
dataType: "json",
headers: {
"api-key": searchServiceApiKey,
"Content-Type": "application/json",
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Methods": "GET,PUT,POST,DELETE"
},
data: JSON.stringify({
top: 5,
fuzzy: false,
suggesterName: "", //Suggester Name according to azure search index.
search: request.term
}),
success: function (data) {
if (data.value && data.value.length > 0) {
userinput = data.value;
console.log(userinput);
response(data.value.map(x => x["#search.text"]));
}
}
});
},
minLength: 3,
position: {
my: "left top",
at: "left bottom",
collision: "fit flip"
},
select: function (Event, ui) {
$(document).ready(function () {
var input = document.getElementsByClassName("wc-shellinput")[0];
var lastValue = input.value;
input.value = ui.item.value;
var event = new CustomEvent('input', { bubbles: true });
// hack React15
event.simulated = true;
// hack React16
var tracker = input._valueTracker;
if (tracker) {
tracker.setValue(lastValue);
}
input.dispatchEvent(event);
})
$('wc-textbox').val("");
Event.preventDefault();
$(".wc-send:first").click();
}
});
});
</script>
<script>
var searchServiceName = "";
var searchServiceApiKey = "";
var indexName = "";
var apiVersion = "";
var suggestUri = "https://" + searchServiceName + ".search.windows.net/indexes/" + indexName + "/docs/suggest?api-version=" + apiVersion;
var autocompleteUri = "https://" + searchServiceName + ".search.windows.net/indexes/" + indexName + "/docs/autocomplete?api-version=" + apiVersion;
var searchUri = "https://" + searchServiceName + ".search.windows.net/indexes/" + indexName + "/docs/search?api-version=" + apiVersion;
</script>
</body>
</html>

Print Preview of gridview is not center allign

I am trying to print one gridview . For that I gave a button and on button click I call javascript for printing tha grid.
function doPrint() {
var prtContent = document.getElementById('<%= grdHistoricalData.ClientID %>');
prtContent.border = 0; //set no border here
var WinPrint = window.open('', '', 'left=50,top=100,border=1px,width=1000,textAlign=center,height=1000,toolbar=0,scrollbars=1,status=0,resizable=1');
WinPrint.document.write(prtContent.outerHTML);
WinPrint.document.close();
WinPrint.focus();
WinPrint.print();
WinPrint.close();
}
This code is working fine but only thing is that print preview of gridview data is displaying left align.Normally Girdview Data is showing center align but when we print data shows in left align.
Gridview normal appearance
Print Preview of Gridview
Please help to do center align in print preview of Gridview.
There are several solutions I use in different circumstances.
1) external file. Load a small file to a iframe and call for data from parent.
<!--print.html -->
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Printer version</title>
<script type="text/javascript">
window.onload = function () {
var a = this.parent.getContent();
document.body.innerHTML = a;
}
function printMe() {
window.print();
}
</script>
<link href="/Styles/print.css" media="print" rel="stylesheet" />
</head>
<body>
</body>
</html>
Parent document.
<div id="divPrint" style="display:none;">
<div class="popup">
<div style="overflow:hidden;">Printer Version
<div style="float:right;">
<input type="button" ID="btnPrnClose" value="X" onclick="return closePrint()" />
</div>
</div>
<iframe id="frPrint" style="width:100%;"></iframe>
</div>
</div>
</div>
<script type="text/javascript">
function getContent() {
return '<div>' +
'<div class="right no-print" onclick="printMe();" style="cursor: pointer;" title="Print"> \
<img alt="Print" src="/images/printer.png" /></div>' + document.getElementById('gvOuterContainer').innerHTML+ '</div>';
}
function closePrint() {
document.getElementById('divPrint').style.display = 'none';
}
function PrintMessage() {
document.getElementById('divPrint').style.display = '';
document.getElementById('frPrint').src = "print.html?a=" + Math.random();//force no-cache
return false;
}
</script>
2) Print from the page.
<style type="text/css" media="print">
*
{
border: none!important;
}
.noprint,.popup
{
display: none!important;
}
#scrollContainer
{
width: auto!important;
}
.pop-show
{
display: table!important;
left: 0;
margin-left: 0;
top: 0;
width: 100%!important;
z-index: 100;
}
/* and so on */
</style>
Details may differ.
Finally got answer , I need to set gridview property that resolve this issue
<asp:TemplateField ItemStyle-HorizontalAlign="Center">

How to display a website in a iframe

I am trying to display a website in an iframe using Razor asp.net but I'm getting the following error: Refused to display 'https://www.google.ro/?gws_rd=cr,ssl&ei=y359VYr9L4PlUeaLg5gG' in a frame because it set 'X-Frame-Options' to 'SAMEORIGIN'.
This is the code:
#{
ViewBag.Title = "About Us";
}
<script type="text/javascript">
$(function () {
$('#myButton').click(function () {
$('#myFrame').attr('src', "http://www.google.com");
});
});
</script>
<iframe id="myFrame"></iframe>
<button id="myButton">
Refresh IFrame
</button>
The page you are trying to show have set a header that prevents it from being showed in an iframe - there is no way to show this in an iframe.
Try using the object tags.
<!--[if IE]>
<object classid="clsid:25336920-03F9-11CF-8FD0-00AA00686F13" data="http://www.google.com">
<p>backup content</p>
</object>
<![endif]-->
<!--[if !IE]> <-->
<object type="text/html" data="http://www.google.com" style="width:100%; height:100%">
<p>backup content</p>
</object>
<!--> <![endif]-->
EDIT: Or you can generate it with jquery:
<script>$("#testLoad").load("http://www.google.com/");</script>
<div id="testLoad"></div>
I finished this by simply adding:
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript"
src="http://maps.google.com/maps/api/js?sensor=false">
</script>
<script type="text/javascript">
function initialize() {
var position = new google.maps.LatLng(-34.397, 150.644);
var myOptions = {
zoom: 10,
center: position,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(
document.getElementById("map_canvas"),
myOptions);
var marker = new google.maps.Marker({
position: position,
map: map,
title:"This is the place."
});
var contentString = 'Hello <strong>World</strong>!';
var infowindow = new google.maps.InfoWindow({
content: contentString
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.open(map,marker);
});
}
</script>
</head>
<body onload="initialize()">
<div id="map_canvas" style="width:500px; height:500px"></div>
</body>
</html>
You can use Google custom search.
It's working fine with me.
It sends X-Frame-Options: ALLOWALL which allows you to embed this site in your IFRAME. See https://productforums.google.com/forum/?hl=en#!category-topic/websearch/how-do-iusing-google-search/pjHnvDST2D4 for more info.

Custom Alert Box Shows up Incorrectly

I am using slayeroffice's custom alert box, slayeroffice(period)com/code/custom_alert/. (Can't post more than two links) On my browser it shows up like this. The alert box is the blue one in the middle of the screen.
http://i.stack.imgur.com/u1TEz.png
On my local it shows up like this, I highlighted the alert box. I wish i could image link this.
It works on the same version version of browser but one of them is on local.
http://i.stack.imgur.com/0xehV.png
What am I doing wrong?
Here's my code integrated with slayeroffice's code.
<%# Page Language="C#" AutoEventWireup="true" CodeFile="Test1.aspx.cs" Inherits="Test1" %>
<%# Register Assembly="System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
Namespace="System.Web.UI" TagPrefix="asp" %>
<!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 runat="server">
<title>Untitled Page</title>
</head>
<body>
<script type="text/javascript">
function showPopUp(){
setTimeout(function() {alert("Warning");}, 5000);
}
function delayer(){
showPopUp();
}
// constants to define the title of the alert and button text.
var ALERT_TITLE = "Oops!";
var ALERT_BUTTON_TEXT = "Ok";
// over-ride the alert method only if this a newer browser.
// Older browser will see standard alerts
if(document.getElementById) {
window.alert = function(txt) {
createCustomAlert(txt); //overrides alert method
}
}
function createCustomAlert(txt) {
// shortcut reference to the document object
d = document;
// if the modalContainer object already exists in the DOM, bail out.
if(d.getElementById("modalContainer")) return;
// create the modalContainer div as a child of the BODY element
mObj = d.getElementsByTagName("body")[0].appendChild(d.createElement("div"));
mObj.id = "modalContainer";
// make sure its as tall as it needs to be to overlay all the content on the page
mObj.style.height = document.documentElement.scrollHeight + "px";
// create the DIV that will be the alert
alertObj = mObj.appendChild(d.createElement("div"));
alertObj.id = "alertBox";
// MSIE doesnt treat position:fixed correctly, so this compensates for positioning the alert
if(false) alertObj.style.top = document.documentElement.scrollTop + "px";
// center the alert box
alertObj.style.left = (d.documentElement.scrollWidth - alertObj.offsetWidth)/2 + "px";
// create an H1 element as the title bar
h1 = alertObj.appendChild(d.createElement("h1"));
h1.appendChild(d.createTextNode(ALERT_TITLE));
// create a paragraph element to contain the txt argument
msg = alertObj.appendChild(d.createElement("p"));
msg.innerHTML = txt;
// create an anchor element to use as the confirmation button.
btn = alertObj.appendChild(d.createElement("a"));
btn.id = "closeBtn";
btn.appendChild(d.createTextNode(ALERT_BUTTON_TEXT));
btn.href = "#";
// set up the onclick event to remove the alert when the anchor is clicked
btn.onclick = function() { removeCustomAlert();return false; }
}
// removes the custom alert from the DOM
function removeCustomAlert() {
document.getElementsByTagName("body")[0].removeChild(document.getElementById("modalContainer"));
}
</script>
<form id="form1" runat="server">
<div>
</div>
<asp:Button ID="Button1" runat="server" Text="Button" OnClientClick="delayer();return false;" />
</form>
</body>
</html>
You are missing the styles:
<style type="text/css">
#modalContainer {
background-color:transparent;
position:absolute;
width:100%;
height:100%;
top:0px;
left:0px;
z-index:10000;
background-image:url(tp.png); /* required by MSIE to prevent actions on lower z-index elements */
}
#alertBox {
position:relative;
width:300px;
min-height:100px;
margin-top:50px;
border:2px solid #000;
background-color:#F2F5F6;
background-image:url(alert.png);
background-repeat:no-repeat;
background-position:20px 30px;
}
#modalContainer > #alertBox {
position:fixed;
}
#alertBox h1 {
margin:0;
font:bold 0.9em verdana,arial;
background-color:#78919B;
color:#FFF;
border-bottom:1px solid #000;
padding:2px 0 2px 5px;
}
#alertBox p {
font:0.7em verdana,arial;
height:50px;
padding-left:5px;
margin-left:55px;
}
#alertBox #closeBtn {
display:block;
position:relative;
margin:5px auto;
padding:3px;
border:2px solid #000;
width:70px;
font:0.7em verdana,arial;
text-transform:uppercase;
text-align:center;
color:#FFF;
background-color:#78919B;
text-decoration:none;
}
</style>

Categories

Resources