Add javascript to generated html test page for Silverlight project - visual-studio

VS2010, Silverlight 4.0.
Does anyone know if there is a way to have Visual Studio add javascript (or anything for that matter) to the html test page it generates when compiling a silverlight project for debug? Does it use a template, and if so, where is it?

Really interesting question!
I've tried to do something like that and finally found raw but pretty working solution:
First of all you should set specific page by using Properties -> Debug -> Specific Page.
My page example:
<!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>SilverlightApplication1</title>
<script type="text/javascript">
</script>
</head>
<body>
<div id="fillWithData">
</div>
<form id="form1" runat="server" style="height:100%">
<div id="silverlightControlHost" style="height: 100%; text-align:center">
<object data="data:application/x-silverlight-2," type="application/x-silverlight-2" width="30%" height="30%">
<param name="source" value="file:///C:/Users/Igor/Documents/Visual Studio 2010/Projects/MobileTest/SilverlightApplication1/Bin/Debug/SilverlightApplication1.xap"/>
<param name="onError" value="onSilverlightError" />
<param name="background" value="white" />
<param name="minRuntimeVersion" value="4.0.50826.0" />
<param name="autoUpgrade" value="true" />
<a href="http://go.microsoft.com/fwlink/?LinkID=149156&v=4.0.50826.0" style="text-decoration:none">
<img src="http://go.microsoft.com/fwlink/?LinkId=161376" alt="Get Microsoft Silverlight" style="border-style:none"/>
</a>
</object><iframe id="_sl_historyFrame" style="visibility:hidden;height:0px;width:0px;border:0px"></iframe></div>
</form>
</body>
</html>
NOTE: blank script and div elements is important! we'll load dynamic js/html into them.
My silverlight xaml.cs:
public partial class MainPage : UserControl
{
public MainPage()
{
InitializeComponent();
Loaded += new RoutedEventHandler(MainPage_Loaded);
}
void MainPage_Loaded(object sender, RoutedEventArgs e)
{
HtmlDocument hostPage = HtmlPage.Document;
ScriptObject obj = hostPage.GetElementsByTagName("script")[0];
obj.SetProperty("innerHTML", "function alertonclick() { alert('Amazing! I am dynamic javascript!'); }");
HtmlElement ipAddressHtml = hostPage.GetElementById("fillWithData");
ipAddressHtml.SetProperty("innerHTML", #"<input id=""Button1"" type=""button"" value=""button"" onclick=""alertonclick();"" />");
}
}
VERY IMPORTANT NOTE: I've tested this code and it works only under Opera.
If you need to test something using some other browser then you sould inline javascript directly into element.
Example:
public partial class MainPage : UserControl
{
public MainPage()
{
InitializeComponent();
Loaded += new RoutedEventHandler(MainPage_Loaded);
}
void MainPage_Loaded(object sender, RoutedEventArgs e)
{
HtmlDocument hostPage = HtmlPage.Document;
HtmlElement ipAddressHtml = hostPage.GetElementById("fillWithData");
ipAddressHtml.SetProperty("innerHTML", #"<input id=""Button1"" type=""button"" value=""button"" onclick=""alert('Amazing! I am dynamic javascript!');"" />");
}
}
This code works well under IE/FF/Chrome/Opera (of course :) ).
As for me I like first example with both dynamic js and html. And I'm pretty sure that it's possible to fix it and make acceptable by other browser not just Opera.
I hope that my examples will help you =)

Related

How to read the value from the username text box of my login page loaded in the xamarin android web view

I'm trying to get the value in the user name text box from my login page after the user entered it in a web page using webview in Xamarin android.
I tried using "document.getelementbyid('useranme').values"
but it is always returning null values. Can any one please help ?
You can use Js call method in C#.
For example, I create login.html in assests folder:
<html>
<head>
<meta http-equiv="content-type" content="text/html" />
<meta name="author" content="lolkittens" />
<script charset="utf-8" type="text/javascript">
function check() {
var username = document.getElementById("ID").value;
var password = document.getElementById("Pass").value;
alert("Username: " + username + " Password: " + password);
return CSharp.ShowToast(username);
}
</script>
<title>Untitled 1</title>
<div id="main" style="width: 300px; height: 200px;">
<form name="MainForm" id="MainForm">
<input id="ID" name="ID" type="text" size="20" />
<input id="Pass" name="Pass" type="password" size="20" />
</form>
<button value="click Me" onclick="check()"> Click Me </button>
</div>
In Mainactivity.cs,
public class MainActivity : AppCompatActivity
{
private WebView webview;
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
// Set our view from the "main" layout resource
SetContentView(Resource.Layout.activity_main);
webview = FindViewById<WebView>(Resource.Id.webview);
WebSettings settings = webview.Settings;
settings.JavaScriptEnabled = true;
// load the javascript interface method to call the foreground method
webview.AddJavascriptInterface(new MyJSInterface(this), "CSharp");
webview.SetWebViewClient(new WebViewClient());
//webview.EvaluateJavascript("javascript: check();", new EvaluateBack());
webview.LoadUrl("file:///android_asset/login.html");
}
}
Create C# class that to return value.
class MyJSInterface : Java.Lang.Object
{
Context context;
public MyJSInterface(Context context)
{
this.context = context;
}
[JavascriptInterface]
[Export]
public void ShowToast(string msg)
{
Toast.MakeText(context, msg, ToastLength.Short).Show();
}
}
Please don't forget add Mono.Android.Export.dll in your reference.
More about call C# method, please take a look:
https://github.com/xamarin/docs-archive/tree/master/Recipes/android/controls/webview/call_csharp_from_javascript
If my reply helps, please remember to mark my reply as answer, thanks.
Eventually I have found the solution for my problem.
I have user OnLoadResource function in webview which helped me to get the datas I was searching for
public override void OnLoadResource(WebView view, string url)
{
try
{
view.EvaluateJavascript("document.getElementById('username').value;", this);
}
catch (Java.Lang.Exception oe)
{
}
base.OnLoadResource(view, url);
}
Thanks.

Rendering html entities in webforms DropDownList control

I am trying to use html entities in in a DropDownList control. The reason I am using entities is because I want to display units with superscripts such as m²/s or kg/m³. sup is not an option because it doesn't work inside a select option tag. I have created a small example that illustrates my problem. Here is my aspx page:
<!DOCTYPE html>
<html lang="en">
<head runat="server">
<meta charset="utf-8" />
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<select>
<option value="1">M³/min</option>
<option value="2">M³/s</option>
</select>
<asp:DropDownList ID="drp" runat="server"></asp:DropDownList>
</div>
</form>
</body>
</html>
and here is my code behind:
public partial class MyPage: System.Web.UI.Page
{
private class idAndUnit
{
public int Id { get; set; }
public string Unit { get; set; }
}
protected void Page_Load(object sender, EventArgs e)
{
var units = new List<idAndUnit>()
{
new idAndUnit
{
Id = 1,
Unit = "M³/min"
},
new idAndUnit
{
Id = 2,
Unit = "M³/min"
}
};
drp.DataSource = units;
drp.DataTextField = "Unit";
drp.DataValueField = "Id";
drp.DataBind();
}
}
If you run the page and look at the source html it generates you see the following:
<select>
<option value="1">M³/min</option>
<option value="2">M³/s</option>
</select>
<select name="drp" id="drp">
<option value="1">M&#179;/min</option>
<option value="2">M&#179;/min</option>
As you can see the DropDownList version has changed M³/min into M³/min.I'm not sure why this change happens presumably either to be helpful in some way or perhaps a security reason for preventing xss or something like that. Is it possible to prevent this behaviour here so I can get the output I'm after?
Just figured it out
using HttpUtility.HtmlDecode("M³/min") fixes it.

cmd or powershell command from html with no window

is there a way to active a powershell or a cmd command from html file without opening a console window ?
for example the following code runs the l.bat file i have without showing the output but still there is a powershell window which is open while the file runs
code:
<OBJECT id=z classid="clsid:adb880a6-d8ff-11cf-9377-00aa003b7a11" width=5 height=5>
<PARAM name="Command" value="ShortCut">
<PARAM name="Button" value="Bitmap::shortcut">
<PARAM name="Item1" value=",powershell.exe ,Start-Process &#45WindowStyle hidden 'l'">
</OBJECT>
any idea?
if you want run script or bat file in html file or in ur site want run script
you can use visual studio and add Web Application called PowerShellExecution
default.aspx
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="PowerShellExecution.Default" %>
<!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 id="Head1" runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<table>
<tr><td> </td><td><h1 align="left">PowerShell Command Harness</h1></td></tr>
<tr><td> </td><td> </td></tr>
<tr><td> </td><td>PowerShell Command</td></tr>
<tr><td>
<br />
</td><td>
<asp:TextBox ID="Input" runat="server" TextMode="MultiLine" Width="433px" Height="73px" ></asp:TextBox>
</td></tr>
<tr><td>
</td><td>
<asp:Button ID="ExecuteCode" runat="server" Text="Execute" Width="200" onclick="ExecuteCode_Click" />
</td></tr>
<tr><td> </td><td><h3>Result</h3></td></tr>
<tr><td>
</td><td>
<asp:TextBox ID="ResultBox" TextMode="MultiLine" Width="700" Height="200" runat="server"></asp:TextBox>
</td></tr>
</table>
</div>
</form>
</body>
</html>
Tools menu select Library Package Manager >> Package Manager Console
Package Manager Console execute “Install-Package System.Management.Automation”
After a successful execution of that package install, you’ll want to add the reference to your Default.aspx.cs file:
using System.Management.Automation;
in ur Default.aspx.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Management.Automation;
using System.Text;
namespace PowerShellExecution
{
public partial class Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void ExecuteCode_Click(object sender, EventArgs e)
{
// Clean the Result TextBox
ResultBox.Text = string.Empty;
// Initialize PowerShell engine
var shell = PowerShell.Create();
// Add the script to the PowerShell object
shell.Commands.AddScript(Input.Text);
// Execute the script
var results = shell.Invoke();
// display results, with BaseObject converted to string
// Note : use |out-string for console-like output
if (results.Count > 0)
{
// We use a string builder ton create our result text
var builder = new StringBuilder();
foreach (var psObject in results)
{
// Convert the Base Object to a string and append it to the string builder.
// Add \r\n for line breaks
builder.Append(psObject.BaseObject.ToString() + "\r\n");
}
// Encode the string in HTML (prevent security issue with 'dangerous' caracters like < >
ResultBox.Text = Server.HtmlEncode(builder.ToString());
}
}
}
}
“PowerShell Command” window Get-EventLog Security -Newest 10 (or your favorite cmdlet for a test).
or put script on that just change
//shell.Commands.AddScript(Input.Text);
shell.Commands.AddScript("C:\\Scripts\\PowerShell\\PowerShellScript.ps1")
but for run script you should run
Set-ExecutionPolicy bypass
in your powershell 32 bit and 64 bit
64 bit
C:\Windows\System32\WindowsPowerShell\v1.0
32 bit
C:\Windows\SysWOW64\WindowsPowerShell\v1.0
you should run visual studio and publish in your iis very simple to add feature iis
for dns you can use
C:\Windows\System32\drivers\etc
in host file like
127.0.0.1 soheil.com
I hope i understand ur needs
Regards

How to Preview uploaded image using telerik RadAsyncUpload and RadBinaryImage in ASP Update Panel?

I have a web form in asp.net contains a RadAsyncfileupload and a RadBinaryImage inside an Asp Update Panel like following
<body>
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<div>
<asp:UpdatePanel runat="server">
<ContentTemplate>
<telerik:RadAsyncUpload ID="RadAsyncUpload1" runat="server">
</telerik:RadAsyncUpload>
<telerik:RadBinaryImage ID ="RadBinaryImage1" runat ="server" Width= "100px" Height="100px"/>
</ContentTemplate>
</asp:UpdatePanel>
</div>
</form>
</body>
in code behind
protected void RadAsyncUpload1_FileUploaded(object sender, Telerik.Web.UI.FileUploadedEventArgs e)
{
if (RadAsyncUpload1.UploadedFiles.Count == 1)
{
byte[] image;
long fileLength = RadAsyncUpload1.UploadedFiles[0].InputStream.Length;
image = new byte[fileLength];
RadAsyncUpload1.UploadedFiles[0].InputStream.Read(image, 0, image.Length);
RadBinaryImage1.DataValue = image;
}
}
but in runtime program controller does not fire RadAsyncUpload1_FileUploaded event
I have searched the Telerik forum and found that I should do something to script manager but I need some help on how to do it the reason is that in order to fire this event whole page should post back anyway some scripts can help me or any other ways!
mention that I need byte array of the image to save it in DB.
Thanks in advance
Saeed Soleimanifar
http://demos.telerik.com/aspnet-ajax/asyncupload/examples/persistuploadedfiles/defaultvb.aspx?#qsf-demo-source
I just added the same functionality by using this , if you find any problem let me know...
OR
Here is the part that does the magic
Page Source :
<telerik:RadScriptBlock ID="RadScriptBlock1" runat="server">
<script type="text/javascript">
function updatePictureAndInfo() {
__doPostBack('btnImgUpload', 'RadButton1Args');
}
</script>
</telerik:RadScriptBlock>
<telerik:RadBinaryImage runat="server" ID="imgBinaryPhoto" ImageUrl="~/Images/default-profile-pic.png"
Width="100px" Height="100px" ResizeMode="Fit" AlternateText="No picture available"
CssClass="preview"></telerik:RadBinaryImage>
<br />
<telerik:RadAsyncUpload ID="upldPhoto" runat="server" AllowedFileExtensions=".jpg,.png,.gif,jpeg,.tiff"
MaxFileInputsCount="1" MultipleFileSelection="Disabled">
</telerik:RadAsyncUpload>
<asp:Button ID="btnImgUpload" runat="server" Text="Upload" CssClass="button" OnClientClick="updatePictureAndInfo(); return false;" />
Code Behind:
Protected Sub FileUploaded() Handles upldPhoto.FileUploaded
Dim bitmapImage As Bitmap = ResizeImage(upldPhoto.UploadedFiles(0).InputStream)
Dim stream As System.IO.MemoryStream = New System.IO.MemoryStream()
bitmapImage.Save(stream, System.Drawing.Imaging.ImageFormat.Bmp)
imgBinaryPhoto.DataValue = stream.ToArray()
End Sub

Loop through XML elements in XmlDataSource in code behind

I have an XmlDataSource and a GridView on my page. On the Page_Load event, I apply an XPath to filter the xml elements according to the input of the user, LexiqueXmlDataSource.XPath = 'Some_XPath_here'; and it works just ok.
What I want is to access the elements that the XmlDataSource returns from codebehind after applying the XPath expression (and hence get their number).
I tried the GetXmlDocument() method but it returns the whole original Xml file rather than the filtered elements with XPath.
EDIT:
here is some code and the scenario I want:
protected void Page_Load(object sender, EventArgs e)
{
string xpath = "/lexique/item[starts-with(#acronym, '" + filter + "')]";
LexiqueXmlDataSource.XPath = xpath;
// Here the XmlDataSource have filtered the xml elements to return to the GridView
//I want to know how many element passed this filter using the XmlDataSource itself
}
Thank you.
Here is what I could come up with.
For the number of hits. Use the GridView row count. Indeed the GetXmlDocument.ChildNodes.Count always return the number of lexical items, not the number of hits whan the XPath expression is applied.
Test XML
<?xml version="1.0" encoding="utf-8" ?>
<lexique>
<item acronym="WPF" value="Windows Presentation Foundation"/>
<item acronym="SO" value="StackOverflow"/>
</lexique>
Minimalist ASP.net Page
<%# Page Language="vb" AutoEventWireup="false" CodeBehind="xmlgrid.aspx.vb" Inherits="WebApplication1.WebForm1" %>
<!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></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Label ID="FilterLabel" runat="server" Text="Acronym starting with:"></asp:Label>
<asp:TextBox ID="FilterTextBox" runat="server"></asp:TextBox>
<asp:XmlDataSource ID="LexiqueXmlDataSource" runat="server" DataFile="~/lexique.xml">
</asp:XmlDataSource>
<asp:GridView ID="LexiqueGrid" runat="server" AllowSorting="true" BorderStyle="Groove">
<Columns>
<asp:TemplateField HeaderText="Acronym">
<ItemTemplate>
<%# XPath("/lexique/item/#acronym")%>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Value">
<ItemTemplate>
<%# XPath("/lexique/item/#value")%>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:Label ID="Hits" runat="server" Text="Acronyms found"></asp:Label>
<asp:Button ID="Submit" runat="server" Text="Search" />
</div>
</form>
</body>
</html>
Code Behind
Public Class WebForm1
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim XPath As String
If String.IsNullOrEmpty(FilterTextBox.Text) Then
XPath = "/lexique/item"
Else
XPath = "/lexique/item[starts-with(#acronym, '" + FilterTextBox.Text + "')]"
End If
LexiqueXmlDataSource.XPath = XPath
LexiqueXmlDataSource.DataBind()
LexiqueGrid.DataSource = LexiqueXmlDataSource
LexiqueGrid.DataBind()
Hits.Text = "Selected " & LexiqueGrid.Rows.Count & " out of " &
LexiqueXmlDataSource.GetXmlDocument.ChildNodes.Count & "Acronyms loaded."
End Sub
End Class
If I understand correctly you want to know the number of returned elements. Would the XPath expression 'count(Some_XPath_here)' not give this number of hits ?
here is some code and the scenario I
want:
protected void Page_Load(object sender, EventArgs e)
{
string xpath = "/lexique/item[starts-with(#acronym, '" + filter + "')]";
LexiqueXmlDataSource.XPath = xpath;
// Here the XmlDataSource have filtered the xml elements to return to the GridView
//I want to know how many element passed this filter using the XmlDataSource itself
}
Just use and evaluate this XPath expression:
string xpath2 = "count(/lexique/item[starts-with(#acronym, '" + filter + "')])";

Resources