Programmatically set JWPlayer to play file from database - asp.net

I have a querystring on page load that I use to get the filename and thumbnail image for JWPlayer. It is not getting the filename or thumbname, however. There must be a reason why I can't get it over to my aspx page, from the VB code behind.See code:
Code Behind (VB):
Protected Sub Page_Load(sender As Object, e As System.EventArgs) Handles Me.Load
Dim videoName As String = Request.QueryString("FileName")
Dim thumb As String = Request.QueryString("Thumb")
End Sub
And now I need to get these string variables into the .ASPX page to the JWplayer script, but they do not
.ASPX:
<div id='container'></div>
<script type="text/javascript" src="~/player/jwplayer.js</script>
<script type="text/javascript">
jwplayer("container").setup({
file: videoName,
flashplayer: '~/player/player.swf',
volume: 35,
width: 480,
height: 270,
skin: '~/player/skins/skin.zip',
image: thumb,
})
</script>

This is ho I solved it
Code Behind (VB):
Protected Sub Page_Load(sender As Object, e As System.EventArgs) Handles Me.Load
Dim videoName As String = Request.QueryString("FileName")
Dim thumb As String = Request.QueryString("Thumb")
Dim dur As String = Request.QueryString("Duration").ToString()
txt1.Text = "~contents/published/" & videoName.ToString()
txt2.Text = "~/contents/thumbs/" & thumb.ToString()
txt3.Text = dur.ToString()
End Sub
Now to get the value of the query string to the JWPlayer javascript, I had to add a javascript function inside the JW script and I called it codeAddress(). This kind of documentation is NOT found on the LongTail website or tutorials or anywhere else on the internet that I have found.
.ASPX:
<script type="text/javascript">
function codeAddress() {
var dootoo = document.getElementById('<%=txt1.ClientID%>').value;
var doothree = document.getElementById('<%=txt2.ClientID%>').value;
var doofour = document.getElementById('<%=txt3.ClientID%>').value;
jwplayer("container").setup({
duration: doofour,
file: dootoo,
flashplayer: '~/player/player.swf',
skin: "~/player/skins/newtubedark.zip",
volume: 35,
width: 685,
height: 385,
image: doothree,
})
}
window.onload = codeAddress;
</script>
<asp:textbox id="txt1" runat="server" style="display:none;"></asp:textbox>
<asp:textbox id="txt2" runat="server" style="display:none;"></asp:textbox>
<asp:textbox id="txt3" runat="server" style="display:none;"></asp:textbox>

Related

querystring missing value after postback

I'm using webcam.js to get photos from a webcam using asp.net web form app. The problem is, I want to get the filename based on the "ID" querystring. But everytime I click "shoot" button, the querystring value is nothing.
Here's my complete HTML :
<%# Page Language="vb" AutoEventWireup="false" CodeBehind="Coba.aspx.vb" Inherits="myWebcam.Coba" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script src='<%=ResolveUrl("~/Plugin/jquery.webcam.js")%>' type="text/javascript"></script>
<script type="text/javascript">
var pageUrl = '<%=ResolveUrl("~/Coba.aspx")%>';
$(function (){
$("#Camera").webcam({
width: 320,
height: 240,
mode: "save",
swffile: '<%=ResolveUrl("Plugin/jscam.swf")%>',
onTick: function () { },
onSave: function () {
},
onCapture: function () {
webcam.save(pageUrl);
},
debug: function () { },
onLoad: function () { }
});
});
function Capture() {
webcam.capture();
return false;
};
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<h2>Index</h2>
<input type="button" value="Shoot!" onclick="Capture()" />
<div id="Camera"></div>
</div>
</form>
</body>
</html>
And here is my asp.net codebehind :
Imports System.IO
Imports System.Web.Services
Public Class Coba
Inherits System.Web.UI.Page
Public sID As String
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
sID = Request.QueryString("id")
If Not Page.IsPostBack Then
Capture(Trim(sID))
End If
End Sub
Public Sub Capture(ByVal mID As String)
Dim stream = Request.InputStream
Dim dump As String
If stream.Length > 0 Then
Using reader = New StreamReader(stream)
dump = reader.ReadToEnd()
End Using
Dim path = Server.MapPath("~/" & Trim(mID) & ".jpg")
System.IO.File.WriteAllBytes(path, String_To_Bytes2(dump))
End If
End Sub
Private Function String_To_Bytes2(strInput As String) As Byte()
Dim numBytes As Integer = (strInput.Length) / 2
Dim bytes As Byte() = New Byte(numBytes - 1) {}
For x As Integer = 0 To numBytes - 1
bytes(x) = Convert.ToByte(strInput.Substring(x * 2, 2), 16)
Next
Return bytes
End Function
End Class
The first time I run the page, I can get the "id" value from the querystring. The shoot button trigger the postback and run the "Capture" sub but the "id" querystring returns nothing.
Any solutions for this problem ?
I tried the code and I think there is a mistake concept. The plugin does not seem to append any QueryString. Your ID is always Nothing. I made debugging and found no trace of the addition ID in the QueryString.
The file name is an attribute that you assign yourself with your logic.
Here is a complete example in which the ID is not recovered.
Even in the official page of the plugin there is no reference to the ID through Querystring.
Other things, you should not use the same page for the interface and saving process. The Pageload is always called, and you call Capture(Trim(sID)) even when loads the interface.
I think you must change this line:
var pageUrl = '<%=ResolveUrl("~/Coba.aspx")%>';
In
var pageUrl = '<%=ResolveUrl("~/Coba_SaveImage.aspx")%>';
And all your codebehind go in the page Coba_SaveImage.aspx. In Page Load is not necessary the If Not Page.IsPostBack Then is always a postback.
Hope this help you.

insertText into a CKEditor through Code Behind

I am trying to get CKEditor.NET to insert some text into my CKEditor when the page loads.
Private Sub CKEditor_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles myCKEditor.Load
Dim insertScript As String
insertScript = "<script type=""text/javascript"">window.CKEDITOR.instances.myWidget_myCKEditor.insertText(""test"");</script>"
Dim cManager As ClientScriptManager = Parent.Page.ClientScript
cManager.RegisterStartupScript(Me.GetType, "insertText", insertScript)
End Sub
My page is organized as follows:
myPage (aspx)
myWidget (ascx)
myCKEditor (from an assembly)
I am getting the following error:
TypeError: Cannot read property 'instances' of undefined
It appears that CKEDITOR is not around when this is called. If I open up the JS console and run the insertScript it works as desired.
I have tried attaching this routine to MyBase.Load and Me.Load as well to no avail, and even tried using window.Load = insertScript, all of which produce the same error.
I noticed that no matter what I do, the last thing in the source is the script that initializes CKEditor, ie
....
<script type="text/javascript">window.CKEDITOR.instances.myWidget_myCKEditor.insertText("test");</script>
<script type="text/javascript">
//<![CDATA[
window.CKEDITOR_BASEPATH = '/ckeditor/';
//]]>
</script>
<script src="/ckeditor/ckeditor.js?t=C6HH5UF" type="text/javascript"></script>
<script type="text/javascript">
//<![CDATA[
var CKEditor_Controls=[],CKEditor_Init=[];function CKEditor_TextBoxEncode(d,e){var f;if(typeof CKEDITOR=='undefined'||typeof CKEDITOR.instances[d]=='undefined'){f=document.getElementById(d);if(f)f.value=f.value.replace(/</g,'<').replace(/>/g,'>');}else{var g=CKEDITOR.instances[d];if(e&&(typeof Page_BlockSubmit=='undefined'||!Page_BlockSubmit)){g.destroy();f=document.getElementById(d);if(f)f.style.visibility='hidden';}else g.updateElement();}};(function(){if(typeof CKEDITOR!='undefined'){var d=document.getElementById('myWidget_myCKEditor');if(d)d.style.visibility='hidden';}var e=function(){var f=CKEditor_Controls,g=CKEditor_Init,h=window.pageLoad,i=function(){for(var j=f.length;j--;){var k=document.getElementById(f[j]);if(k&&k.value&&(k.value.indexOf('<')==-1||k.value.indexOf('>')==-1))k.value=k.value.replace(/</g,'<').replace(/>/g,'>').replace(/&/g,'&');}if(typeof CKEDITOR!='undefined')for(var j=0;j<g.length;j++)g[j].call(this);};window.pageLoad=function(j,k){if(k.get_isPartialLoad())setTimeout(i,0);if(h&&typeof h=='function')h.call(this,j,k);};if(typeof Page_ClientValidate=='function'&&typeof CKEDITOR!='undefined')Page_ClientValidate=CKEDITOR.tools.override(Page_ClientValidate,function(j){return function(){for(var k in CKEDITOR.instances){if(document.getElementById(k))CKEDITOR.instances[k].updateElement();}return j.apply(this,arguments);};});setTimeout(i,0);};if(typeof Sys!='undefined'&&typeof Sys.Application!='undefined')Sys.Application.add_load(e);if(window.addEventListener)window.addEventListener('load',e,false);else if(window.attachEvent)window.attachEvent('onload',e);})();CKEditor_Controls.push('myWidget_myCKEditor');
CKEditor_Init.push(function(){if(typeof CKEDITOR.instances['myWidget_myCKEditor']!='undefined' || !document.getElementById('myWidget_myCKEditor')) return;CKEDITOR.replace('myWidget_myCKEditor',{"htmlEncodeOutput" : true}); });
//]]>
</script>
</form>
....
All the evidence suggests that I am invoking the startup script at the wrong time, but I don't know when the "right time" to invoke it is.
Yoy can use jquery windows.ready function as below
insertScript = "<script type=""text/javascript""> <script language="javascript">
$(document).ready(function() {
window.CKEDITOR.instances.myWidget_myCKEditor.insertText('test');
})
})
</script> ";
Dim cManager As ClientScriptManager = Parent.Page.ClientScript
cManager.RegisterStartupScript(Me.GetType, "insertText", insertScript)
It will make sure your javascript fires only when document get ready and not b4 that.
Kind of a cop-out, but I ended up loading what I needed to insert on the page load and defining the script in the .ascx file.
In my myWidget.ascx:
<script type="text/javascript">
function ddChange(obj) {
window.CKEDITOR.instances.myWidget_myCKEditor.insertText(obj.value);
document.getElementById("myWidget_myCannedPicker").selectedIndex = 0;
}
</script>
...
<asp:DropDownList ID="myCannedPicker" Width="400" runat="server" AutoPostBack="false" OnChange="ddChange(this)" /></span></td>
In myWidget.ascx.vb:
Private Sub fillInitialValues()
...
myCannedPicker.DataSource = dt
myCannedPicker.DataValueField = "msg_text"
myCannedPicker.DataTextField = "msg_name"
myCannedPicker.DataBind()
myCannedPicker.Items.Insert(0, New ListItem("Please make a selection:", "0"))
End Sub
Doesn't really answer to the original question, but it was a suitable workaround in my case.

Load DropDownList OnDemand and Expand DropDown after Postback in Asp.Net

Trying to Populate DropDownList when it is clicked (Asp.Net). I have a sample below but I can't get the DropDownList to stay expanded after it is loaded. Does anyone have a solution to load on demand from server other than using 3rd party controls?
JavaScript
<script type="text/javascript">
function LoadOnDemand(ddl) {
if (ddl != "") {
var control = document.getElementById(ddl.id);
__doPostBack(ddl.id, "LoadOnDemand");
}
}
function AfterLoadOnDemand(ddl) {
}
</script>
Markup
<body>
<form id="form1" runat="server">
<div>
<asp:Panel ID="DynamicPanel" runat="server" Width="200">
</asp:Panel>
</div>
</form>
</body>
CodeBehind
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim target As String = Page.Request.Params.Get("__EVENTTARGET")
Dim eventarg As String = Page.Request.Params.Get("__EVENTARGUMENT")
Call CreateDynamicControls()
If IsPostBack Then
If target <> "" Then
If eventarg = "LoadOnDemand" Then
Dim ctrl As Control = FindControl(target)
If ctrl IsNot Nothing Then
If TypeOf ctrl Is DropDownList Then
'Note: values would be from a database or table query.
' and some other logic. Simplified here.
Dim ddl As DropDownList = CType(ctrl, DropDownList)
ddl.Items.Clear()
ddl.Items.Add("one")
ddl.Items.Add("two")
ddl.Items.Add("three")
'remove onfocus from this control so it doen't fire again
'if they click it immediatly after loading
ddl.Attributes.Add("onfocus", "AfterLoadOnDemand(this)")
End If
'reset the LoadOnDemand for all the other DropDownList controls
For Each notFocusedControl As Control In DynamicPanel.Controls
If TypeOf notFocusedControl Is DropDownList Then
Dim ddl As DropDownList = CType(notFocusedControl, DropDownList)
If ddl.ID <> target Then
ddl.Attributes.Add("onfocus", "LoadOnDemand(this)")
End If
End If
Next
End If
End If
End If
End If
End Sub
Protected Sub CreateDynamicControls()
For i As Integer = 0 To 2
Dim ddl As New DropDownList
ddl.ID = "DropDownList" & i
ddl.Width = 150
ddl.Items.Add("Browse me..")
ddl.Attributes.Add("onfocus", "LoadOnDemand(this)")
ddl.AutoPostBack = True
ddl.EnableViewState = True
DynamicPanel.Controls.Add(ddl)
DynamicPanel.Controls.Add(New LiteralControl("<br/><br/>"))
Next
End Sub
The only way I found out how to exand it is by emulation. Here is a link (ExpandSelect) that has a JavaScript function to do exactly that.
And here is another reference link.
I added the following (initialWidth parameter) to the .js file. This keeps the expanded dropdown from shrinking smaller then the initial width of the dropdown.
function ExpandSelect(select, maxOptionsVisible, initialWidth) {
//code - see file
select.style.zIndex = "1000000";
//Added this right after the zIndex
if (dropWidth < initialWidth) {
select.style.width = initialWidth + 'px';
select2.style.width = initialWidth + 'px';
}
//code - see file
}

Update Panel refresh on code behind function call in C# - Ajax

I am using Uploadify v2.1.4 to upload images using ASP.Net C# FM 4.0.
In this page i have other controls also, but i want a functionality in such a way that when i upload images it should automatically refresh the UpdatePanel1 to show image uploaded
Default.aspx FILE
<asp:UpdatePanel ID="UpdatePanel1" runat="server" >
<ContentTemplate>
<asp:DataList ID="DataList1" runat="server" DataSourceID="SqlDataSource1" RepeatDirection="Horizontal" >
<ItemTemplate>
<br /><img src='http://test.kashmirsouq.com/ImageUploads/<%# Eval("ImageID") %>' width="100px" height="100px" vspace="2" hspace="2" border="1" />
<br /><asp:LinkButton ID="lnkBtnDeleteImage" CommandArgument='<%# Eval("sno") %>' CommandName="Delete" runat="server">
Delete</asp:LinkButton>
<br />
</ItemTemplate>
</asp:DataList>
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:SQLConnectionString %>"
SelectCommand="SELECT [sno], [ImageID] FROM [User_Images]">
</asp:SqlDataSource>
</ContentTemplate>
</asp:UpdatePanel>
Page example is here test.kashmirSouq.com
I am calling FileUplaad.aspx file to upload image using jQuery
<script type="text/javascript">
$(document).ready(function () {
$('#fuFiles').uploadify({
'uploader': 'Scripts/uploadify.swf',
'script': 'FileUploads.aspx',
'cancelImg': 'Scripts/cancel.png',
'auto': 'true',
'multi': 'true',
'fileExt': '*.jpg;*.gif;*.png',
'buttonText': 'Browse...',
'queueSizeLimit': 5,
'simUploadLimit': 2
});
});
</script>
and in FileUpload.aspx.cs file i save the file on the server and database,
I need a way so that i can refresh the updatepanel1 from function saveData() which is in FileUpload.aspx.cs
protected int saveData()
{
String strSql = "INSERT INTO HMS_User_Images(ImageID,UserID,ImageCreationDate) ";
strSql += " VALUES ('" + filename + "','123456789', '" + DateTime.Now + "')";
int result = DataProvider.intConnect_Select(strSql);
}
So when i upload images it should refresh do partial page update of the grid. Please give me a example how i can do it using C#
Please advice how i can do this code sample would be highly appreciated.
Regards
If You want to refresh the Update panel , Try This...
UpdatePanel1.Update();
If the page is enabled for partial-page rendering, when you invoke the
Update method, the UpdatePanel control's content is updated in the
browser. Call the Update method if you have server code that must
execute to determine whether an UpdatePanel control should be updated.
If you plan to use the Update method, set the UpdateMode property to
Conditional. If you want the decision to update the panel to be
determined in server logic, make sure that the ChildrenAsTriggers
property is false and that no explicit triggers are defined for the
panel.
In a typical page development scenario, if you define triggers or if
the ChildrenAsTriggers property is true for the UpdatePanel control,
the Update method is automatically called during the page life cycle.
If the ContentTemplate property is not defined for the UpdatePanel
control, no updates of the panel will occur.
Try by showing the image by using the response after the Onupload complete event.So when the user as soon as he uploads you will find the image.
This is the script:
<script type="text/javascript">
$(window).load(
function () {
$("#fileInput1").uploadify({
'uploader': 'scripts/uploadify.swf',
'cancelImg': 'images/cancel.png',
'buttonText': 'Browse Files',
'script': 'Upload.aspx',
'folder': 'uploads',
'fileDesc': 'Image Files',
'fileExt': '*.jpg;*.jpeg;*.gif;*.png',
'queueSizeLimit': 9999,
'simUploadLimit': 2,
'sizeLimit': 4000000,
'multi': true,
'auto': true,
'onComplete': function (event, queueID, fileObj, response, data) {
$("#thumbnail").append(response)
},
'onError': function (event, ID, fileObj, errorObj) {
alert(errorObj.type + ' Error: ' + errorObj.info);
}
});
}
);
</script>
This is the Handler:
<%# WebHandler Language="VB" Class="UploadVB" %>
Imports System
Imports System.Web
Imports System.IO
Imports System.Drawing
Public Class UploadVB : Implements IHttpHandler
Public Sub ProcessRequest(ByVal context As HttpContext) Implements IHttpHandler.ProcessRequest
Dim postedFile As HttpPostedFile = context.Request.Files("Filedata")
Dim savepath As String = ""
Dim tempPath As String = ""
tempPath = System.Configuration.ConfigurationManager.AppSettings("FolderPath")
savepath = context.Server.MapPath(tempPath)
Dim filename As String = postedFile.FileName
If Not Directory.Exists(savepath) Then
Directory.CreateDirectory(savepath)
End If
If Not Directory.Exists(savepath + "\thumbs") Then
Directory.CreateDirectory(savepath + "\thumbs")
End If
postedFile.SaveAs((savepath & "\") + filename)
Dim fullImage As System.Drawing.Image = New System.Drawing.Bitmap((savepath & "\") + filename)
Dim newWidth As Integer = 100
Dim newHeight As Integer = 80
Dim temp As New Bitmap(newWidth, newHeight)
Dim newImage As Graphics = Graphics.FromImage(temp)
newImage.DrawImage(fullImage, 0, 0, newWidth, newHeight)
temp.Save((savepath + "\thumbs" & "\") + "t_" + filename)
context.Response.Write("<a href='" + (tempPath & "/") + filename + "'><img src='" + tempPath + "/thumbs" & "/" + "t_" + filename + "'/></a>")
context.Response.StatusCode = 200
'context.Response.Write("OK")
End Sub
Public ReadOnly Property IsReusable() As Boolean Implements IHttpHandler.IsReusable
Get
Return False
End Get
End Property
End Class
In the above code you can find thumbnails appended as soon as the user uploads you find a thumbnail of the image.

Jquery Auto Complete in asp.net

i want to use jquery ui auto complete plugin in asp.net.
this is my behind code :
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim locations As String() = New String() {"Las Vegas", "Los Angeles", "Tampa", "New York", "s", "sss"}
Dim jsArray As String = GetJSArrayForVBArray(locations)
Me.ClientScript.RegisterArrayDeclaration("usernames", jsArray)
End Sub
Private Function GetJSArrayForVBArray(ByVal vbArray As String()) As String
Dim myResult As New StringBuilder()
For Each item As String In vbArray
With myResult
.Append(",'" & item & "'")
End With
Next
If (myResult.Length > 0) Then
Return myResult.ToString().Substring(1)
Else
Return ""
End If
End Function
this is html code :
<script type="text/javascript">
$(function () {
var availableTags = new Array();
$("#tags").autocomplete({
source: availableTags
});
});
</script>
<label for="tags">Tags: </label>
<input id="tags" />
what is the problem?
it does not work.
when i filling array in aspx page it works but when i want to fill in behind code not.
thanks.
Try changing your JS to this:
<script type="text/javascript">
$(function () {
$("#tags").autocomplete({
source: usernames
});
});
</script>
If I'm guessing at your .Net code correctly, you're registering "usernames" as the javascript array, but trying to use the empty 'availableTags' as your autocomplete source.
Note: this may be completely off-base here - I haven't actually used ClientScript.RegisterArrayDeclaration or the jQuery autocomplete plugin in code I've written before.

Resources