Embedding Cgi video in site - c#

Hello All I have various web cameras i would like to embed in my site
http://81.137.212.183:4483/GetData.cgi
The problem is at times the cameras go down so i need to check they are active in c# before attempting to render:
<img height="240" width="320" src="http://81.137.212.183:4483/GetData.cgi" />
Please can someone advise how i can check the cgi is active in c# or any other recommendation. If i simple load the cgi and it is down it causes the browser to crash
One recommendation was to use the code below:
The problem with the below approach is the site is forever loading and a fav icon is never shown as can be seen http://www.camsecure.co.uk/
newImage = new Image();
function LoadNewImage() {
var unique = new Date();
document.images.webcam.src = newImage.src;
newImage.src = "http://collectart.dyndns.org:4484/Jpeg/CamImg.jpg?time=" + unique.getTime();
}
function InitialImage() {
var unique = new Date();
newImage.onload = LoadNewImage();
newImage.src = "http://collectart.dyndns.org:4484/Jpeg/CamImg.jpg?time=" + unique.getTime();
document.images.webcam.src = "http://collectart.dyndns.org:4484/Jpeg/CamImg.jpg?time=" + unique.getTime();
document.images.webcam.onload = "";
}

First off, you need to put some security over that first link. It appears the camera settings are public and available to anyone.
If the only problem is the long loading times slowing the rest of the site down, you could load the images in an iframe rather than directly in an image tag -- then the hang is only in the iframe:
<iframe src="http://81.137.212.183:4483/Simple/home.htm?IMG"></iframe>
To check the IP camera is up, you could simply try to get it's host page:
using System.Net.Http;
...
var uri = new Uri("http://81.137.212.183:4483/Simple/index.htm");
var task = new HttpClient().GetAsync(uri);
if (task.Wait(TimeSpan.FromSeconds(1)) && task.Result.IsSuccessStatusCode)
{
// SUCCESS!
}
else
{
// FAILURE... try next camera
}
However, it looks like the image .cgi location can still fail if the camera is available. In that case it would be best to load in an iframe even if you get success.

Related

How to create HTML page by code [duplicate]

How would I open a new window in JavaScript and insert HTML data instead of just linking to an HTML file?
I would not recomend you to use document.write as others suggest, because if you will open such window twice your HTML will be duplicated 2 times (or more).
Use innerHTML instead
var win = window.open("", "Title", "toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=yes,resizable=yes,width=780,height=200,top="+(screen.height-400)+",left="+(screen.width-840));
win.document.body.innerHTML = "HTML";
You can use window.open to open a new window/tab(according to browser setting) in javascript.
By using document.write you can write HTML content to the opened window.
When you create a new window using open, it returns a reference to the new window, you can use that reference to write to the newly opened window via its document object.
Here is an example:
var newWin = open('url','windowName','height=300,width=300');
newWin.document.write('html to write...');
Here's how to do it with an HTML Blob, so that you have control over the entire HTML document:
https://codepen.io/trusktr/pen/mdeQbKG?editors=0010
This is the code, but StackOverflow blocks the window from being opened (see the codepen example instead):
const winHtml = `<!DOCTYPE html>
<html>
<head>
<title>Window with Blob</title>
</head>
<body>
<h1>Hello from the new window!</h1>
</body>
</html>`;
const winUrl = URL.createObjectURL(
new Blob([winHtml], { type: "text/html" })
);
const win = window.open(
winUrl,
"win",
`width=800,height=400,screenX=200,screenY=200`
);
You can open a new popup window by following code:
var myWindow = window.open("", "newWindow", "width=500,height=700");
//window.open('url','name','specs');
Afterwards, you can add HTML using both myWindow.document.write(); or myWindow.document.body.innerHTML = "HTML";
What I will recommend is that first you create a new html file with any name.
In this example I am using
newFile.html
And make sure to add all content in that file such as bootstrap cdn or jquery, means all the links and scripts. Then make a div with some id or use your body and give that a id. in this example I have given id="mainBody" to my newFile.html <body> tag
<body id="mainBody">
Then open this file using
<script>
var myWindow = window.open("newFile.html", "newWindow", "width=500,height=700");
</script>
And add whatever you want to add in your body tag. using following code
<script>
var myWindow = window.open("newFile.html","newWindow","width=500,height=700");
myWindow.onload = function(){
let content = "<button class='btn btn-primary' onclick='window.print();'>Confirm</button>";
myWindow.document.getElementById('mainBody').innerHTML = content;
}
myWindow.window.close();
</script>
it is as simple as that.
You can also create an "example.html" page which has your desired html and give that page's url as parameter to window.open
var url = '/example.html';
var myWindow = window.open(url, "", "width=800,height=600");
Use this one. It worked for me very perfect.
For New window:
new_window = window.open(URL.createObjectURL(new Blob([HTML_CONTENT], { type: "text/html" })))
for pop-up
new_window = window.open(URL.createObjectURL(new Blob([HTML_CONTENT], { type: "text/html" })),"width=800,height=600")
Replace HTML_CONTENT with your own HTML Code
Like:
new_window = window.open(URL.createObjectURL(new Blob(["<h1>Hello</h1>"], { type: "text/html" })))
if your window.open() & innerHTML works fine, ignore this answer.
following answer only focus on cross-origin access exception
#key-in_short,workaround:: [for cross-origin access exception]
when you exec code in main.html -- which tries to access file window_ImageGallery.html by using window.open() & innerHTML
for anyone who encounter cross-origin access exception
and you dont want to disable/mess_around_with Chrome security policy
-> you may use query string to transfer the html code data, as a workaround.
#details::
#problem-given_situation,#problem-arise_problem::
say you exec following simple window.open command as other answer suggested.
let window_Test = window.open('window_ImageGallery.html', 'Image Enlarged Window' + $(this).attr('src'), 'width=1000,height=800,top=50,left=50');
window_Test.document.body.innerHTML = 'aaaaaa';
you may encounter following cross-origin access exception
window_Test.document.body.innerHTML = 'aaaaaa'; // < Exception here
Uncaught DOMException: Blocked a frame with origin "null" from accessing a cross-origin frame.
=> #problem-solution-workaround::
you may use query string to transfer the html code data, as a workaround. <- Transfer data from one HTML file to another
#eg::
in your main.html
// #>> open ViewerJs in a new html window
eleJq_Img.click(function() {
// #>>> send some query string data -- a list of <img> tags, to the new html window
// #repeat: must use Query String to pass html code data, else you get `Uncaught DOMException: Blocked a frame with origin "null" from accessing a cross-origin frame.` (cross origin access issue)
let id_ThisImg = this.id;
let ind_ThisImg = this.getAttribute('data-index-img');
let url_file_html_window_ImageGallery = 'window_ImageGallery.html'
+ '?queryStr_html_ListOfImages=' + encodeURIComponent(html_ListOfImages)
+ '&queryStr_id_ThisImg=' + encodeURIComponent(id_ThisImg)
+ '&queryStr_ind_ThisImg=' + encodeURIComponent(ind_ThisImg);
// #>>> open ViewerJs in a new html window
let window_ImageGallery = window.open(url_file_html_window_ImageGallery, undefined, 'width=1000,height=800,top=50,left=50');
});
in your window_ImageGallery.html
window.onload = function () {
// #>> get parameter from URL
// #repeat: must use Query String to pass html code data, else you get `Uncaught DOMException: Blocked a frame with origin "null" from accessing a cross-origin frame.` (cross origin access issue)
// https://stackoverflow.com/questions/17502071/transfer-data-from-one-html-file-to-another
let data = getParamFromUrl();
let html_ListOfImages = decodeURIComponent(data.queryStr_html_ListOfImages);
let id_ThisImgThatOpenedTheHtmlWindow = decodeURIComponent(data.queryStr_id_ThisImg);
let ind_ThisImgThatOpenedTheHtmlWindow = decodeURIComponent(data.queryStr_ind_ThisImg);
// #>> add the Images to the list
document.getElementById('windowImageGallery_ContainerOfInsertedImages').innerHTML = html_ListOfImages;
// -------- do your stuff with the html code data
};
function getParamFromUrl() {
let url = document.location.href;
let params = url.split('?')[1].split('&');
let data = {};
let tmp;
for (let i = 0, l = params.length; i < l; i++) {
tmp = params[i].split('=');
data[tmp[0]] = tmp[1];
}
return data
}
#minor-note::
(seems) sometimes you may not get the cross-origin access exception
due to, if you modify the html of 'window_ImageGallery.html' in main.html before window_ImageGallery.html is loaded
above statement is based on my test
& another answer -- window.open: is it possible open a new window with modify its DOM
if you want to make sure to see that Exception,
you can try to wait until the opening html window finish loading, then continue execute your code
#eg::
use defer() <- Waiting for child window loading to complete
let window_ImageGallery = window.open('window_ImageGallery.html', undefined, 'width=1000,height=800,top=50,left=50');
window_ImageGallery.addEventListener("unload", function () {
defer(function (){
console.log(window_ImageGallery.document.body); // < Exception here
});
});
function defer (callback) {
var channel = new MessageChannel();
channel.port1.onmessage = function (e) {
callback();
};
channel.port2.postMessage(null);
}
or use sleep() with async What is the JavaScript version of sleep()?
eleJq_Img.click(async function() {
...
let window_Test = window.open( ...
...
await new Promise(r => setTimeout(r, 2000));
console.log(window_Test.document.body.innerHTML); // < Exception here
});
or you get null pointer exception
if you try to access elements in window_ImageGallery.html
#minor-comment::
There are too many similar Posts about the cross-origin issue. And there are some posts about window.open()
Idk which post is the best place to place the answer. And I picked here.

Invalid paths using CloudFront create invalidation in C#

I am trying to invalidate CloudFront objects in C#/.NET and gettign the following exception:
Your request contains one or more invalid invalidation paths.
My Function:
public bool InvalidateFiles(string[] arrayofpaths)
{
for (int i = 0; i < arrayofpaths.Length; i++)
{
arrayofpaths[i] = Uri.EscapeUriString(arrayofpaths[i]);
}
try
{
Amazon.CloudFront.AmazonCloudFrontClient oClient = new Amazon.CloudFront.AmazonCloudFrontClient(MY_AWS_ACCESS_KEY_ID, MY_AWS_SECRET_KEY, Amazon.RegionEndpoint.USEast1);
CreateInvalidationRequest oRequest = new CreateInvalidationRequest();
oRequest.DistributionId = ConfigurationManager.AppSettings["CloudFrontDistributionId"];
oRequest.InvalidationBatch = new InvalidationBatch
{
CallerReference = DateTime.Now.Ticks.ToString(),
Paths = new Paths
{
Items = arrayofpaths.ToList<string>(),
Quantity = arrayofpaths.Length
}
};
CreateInvalidationResponse oResponse = oClient.CreateInvalidation(oRequest);
oClient.Dispose();
}
catch
{
return false;
}
return true;
}
The array passed to the function contains a single Url like so:
images/temp_image.jpg
The image exists in the S3 bucket and loaded in the browser in the CloudFront URL.
What am I doing wrong?
You invalidation file paths need a / at the front of the string.
If you are in doubt, you can log onto AWS Management, go to Cloudfront, select the distribution you are trying to invalidate files from, select Distribution setting and go to the Invalidations tab.
You can then create validations manually, which allows you to check that your paths are correct.
When you send invalidation request to some object in CloudFront, you still can see your picture in the browser in the CloudFront URL even when invalidation completed, because invalidation does not delete object from S3 bucket and with new request to this image from you browser CloudFront again cached these URl to images/temp_image.jpg in edge locations.
Invalidation of object will be seen, when you update image with the same name.
Your Invalidation function is correct.
Have you tried adding the forward slash at the beginning of the path? (/images/temp_image.jpg)

Navigating to DNN Module

I'm forming a newsletter with links to various html modules within my DNN website. I have access to each of their ModuleID's and I'm wanting to use that to get the url. The current approach (made by a third party developer) worked, but only to a degree. The url's are incorrectly formed when the Modules are located deeper in the website.
For example module located at www.website.com/website/articles.aspx is works fine, but a module located www.website.com/website/articles/subarticles.aspx won't. I know this is because the url is incorrectly formed.
Here's the current code:
DotNetNuke.Entities.Modules.ModuleController objModCtrlg = new DotNetNuke.Entities.Modules.ModuleController();
DotNetNuke.Entities.Modules.ModuleInfo dgfdgdg = objModCtrlg.GetModule(ContentMID);
TabController objtabctrll = new TabController();
TabInfo objtabinfoo = objtabctrll.GetTab(tabidfrcontent);
string tabnamefremail= objtabinfoo.TabName;
moduletitlefrEmail = dgfdgdg.ModuleTitle;
string readmorelinkpath = basePath + "/" + tabnamefremail + ".aspx";
ContentMID is the current module ID I'm looking at. I've tried to use Globals.NavigateURL, but that always crashes with Object reference not set to an instance of an object. error. Same thing when I use objtabinfoo.FullUrl so I'm currently at a loss as to how I get the specific modules URL.
EDIT: Here's some more code as to how the tabId is retrieved.
IDictionary<int, TabInfo> dicTabInfo12 = new Dictionary<int, TabInfo>();
ContentMID = Convert.ToInt32(dsNewsList.Tables[0].Rows[i]["ModuleID"]);
dicTabInfo12 = objTabctrl.GetTabsByModuleID(ContentMID);
if (dicTabInfo12.Count > 0)
{
string tester = ""; //Debug
foreach (KeyValuePair<int, TabInfo> item1 in dicTabInfo12)
{
tabidfrcontent = item1.Key;
}
}
You really should be using NavigateUrl to build the links ance if you have the tabid, you are golden.
string readMoreLinkPath = NavigateUrl(tabidfrcontent);
Nice and simple
Okay, colleague suggested this and it works great within a scheduler.
string linkPath = basePath + "/Default.aspx?TabID=" + tabID;
Will Navigate you to the correct tab ID. So this would be the best solution if you're forced to work within a scheduler where you can't use NavigateUrl without some major workarounds.

C# How to Embed Video by URL (like Facebook)?

I'm trying to allow users to post videos on my site by supplying only the URL. Right now I'm able to allow YouTube videos by just parsing the URL and obtaining the ID, and then inserting that ID into their given "embed" code and putting that on the page.
This limits me to only YouTube videos however, what I'm looking to do is something similar to facebook where you can put in the YouTube "Share" URL OR the url of the page directly, or any other video url, and it loads the video into their player.
Any idea how they do this? or any other comparable way to just show a video based just on a URL? Keep in mind that youtube videos (which would probably be most popular anyway) don't give the video url, but the url to the video on the YouTube page (which is why their embed code is needed with just the ID).
Hopefully this made sense, and I hope somebody might be able to offer me some advice on where to look!
Thanks guys.
I would suggest adding support for OpenGraph attributes, which are common among content services which work to enable other sites to embed their content. The information on the pages will be contained in their <meta> tags, which means you would have to load the URL via something like the HtmlAgilityPack:
var doc = new HtmlDocument();
doc.Load(webClient.OpenRead(url)); // not exactly production quality
var openGraph = new Dictionary<string, string>();
foreach (var meta in doc.DocumentNode.SelectNodes("//meta"))
{
var property = meta["property"];
var content = meta["content"];
if (property != null && property.Value.StartsWith("og:"))
{
openGraph[property.Value]
= content != null ? content.Value : String.Empty;
}
}
// Supported by: YouTube, Vimeo, CollegeHumor, etc
if (openGraph.ContainsKey("og:video"))
{
// 1. Get the MIME Type
string mime;
if (!openGraph.TryGetValue("og:video:type", out mime))
{
mime = "application/x-shockwave-flash"; // should error
}
// 2. Get width/height
string _w, _h;
if (!openGraph.TryGetValue("og:video:width", out _w)
|| !openGraph.TryGetValue("og:video:height", out _h))
{
_w = _h = "300"; // probably an error :)
}
int w = Int32.Parse(_w), h = Int32.Parse(_h);
Console.WriteLine(
"<embed src=\"{0}\" type=\"{1}\" width=\"{2}\" height=\"{3}\" />",
openGraph["og:video"],
mime,
w,
h);
}

Telerik upload manager - Folder creates and deletes but refresh images stays

Having problems with the documentmanager upload trying to upload PDF's.
The problem happens when creating or deleting folders. The get create/deleted in the correct location but the refresh/processing image stays, crashing the tool from navigating the folder structure. See screen shot:
There is a Javascript error :
this._clientParameters.get_value is not a function
CODE
FileManagerDialogParameters documentManagerParameters = new FileManagerDialogParameters();
documentManagerParameters.ViewPaths = new string[] { uploadPath };
documentManagerParameters.UploadPaths = new string[] { uploadPath };
documentManagerParameters.DeletePaths = new string[] { uploadPath };
documentManagerParameters.SearchPatterns = pattern;
documentManagerParameters.MaxUploadFileSize = maxFileSize;
if (string.IsNullOrEmpty(dialog))
{
// use a default
dialog = "~/modules/uploadcentre/dialogs/default/";
}
documentManagerParameters["ExternalDialogsPath"] = dialog;
DialogDefinition documentManager = new DialogDefinition(typeof(DocumentManagerDialog), documentManagerParameters)
{
ClientCallbackFunction = "DocumentManagerFunction",
Width = Unit.Pixel(694),
Height = Unit.Pixel(440)
};
DialogOpener1.DialogDefinitions.Add("DocumentManager", documentManager);
Telerik.web.ui version 2011.1.519.40
Thanks in advance
Peter
Please, see the following forum thread which discusses the same JS error:
DocumentManager open with DialogOpener javascript error - http://www.telerik.com/community/forums/aspnet-ajax/editor/documentmanager-open-with-dialogopener-javascript-error.aspx
If you need further help, please open a support ticket from www.telerik.com and send a sample fully working project that demonstrates the problem.
Best regards,
Rumen
http://www.telerik.com/community/forums/aspnet-ajax/editor/document-manage-refreshing-image-stays-on.aspx

Categories