when I use from javascript works perfectly but when I click link button nothing happens. how can I fix pushing message from code behind?
<div class="container">
<input type="text" id="message" />
<input type="button" id="sendmessage" value="Send" />
<input type="hidden" id="displayname" />
<ul id="discussion">
</ul>
</div>
<asp:LinkButton ID="LinkButton1" runat="server" OnClick="LinkButton1_Click">LinkButton</asp:LinkButton>
<script src="Scripts/jquery-1.6.4.min.js"></script>
<script src="Scripts/jquery.signalR-2.2.0.min.js"></script>
<script src="signalr/hubs"></script>
<script type="text/javascript">
$(function () {
var chat = $.connection.chatHub;
chat.client.broadcastMessage = function (name, message) {
// Html encode display name and message.
var encodedName = $('<div />').text(name).html();
var encodedMsg = $('<div />').text(message).html();
// Add the message to the page.
$('#discussion').append('<li><strong>' + encodedName
+ '</strong>: ' + encodedMsg + '</li>');
};
// Get the user name and store it to prepend to messages.
$('#displayname').val(prompt('Enter your name:', ''));
// Set initial focus to message input box.
$('#message').focus();
// Start the connection.
$.connection.hub.start().done(function () {
$('#sendmessage').click(function () {
// Call the Send method on the hub.
chat.server.send($('#displayname').val(), $('#message').val());
// Clear text box and reset focus for next comment.
$('#message').val('').focus();
});
});
});
</script>
protected void LinkButton1_Click(object sender, EventArgs e)
{
var context = GlobalHost.ConnectionManager.GetHubContext<ChatHub>();
context.Clients.All.Send("asf", "111");
}
public class ChatHub : Hub
{
public void Send(string name, string message)
{
Clients.All.broadcastMessage(name, message);
}
}
[assembly: OwinStartup(typeof(signalRtest.Startup))]
namespace signalRtest
{
public class Startup
{
public void Configuration(IAppBuilder app)
{
app.MapSignalR();
}
}
}
Related
I need to get a list of innerHTML strings from a website (for example facebook) to my .NET application.
Is there a way to get results from the following function into my application (i would put this data into a list) :
var data = new Array();
for(i=0; i<document.getElementsByClassName("class-name").length;i++)
data.push(document.getElementsByClassName("class-name")[i].innerHTML);
The code above outputs exactly the data i need, now my question is if it's possible to somehow get this data into my c# list?
This is how I'd like it to look :
var JS_DATA = data; //get the js array as a variable
static List<string> data = new List<string>(); //make a new list
foreach (string str in JS_DATA)
data.Add(String.Format("{0}", str)); //add the whole js array to the list
Here is an example:
see hidden Field array_store
Client side:
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script type="text/javascript">
var array_store;
window.onload = function () {
array_store = document.getElementById("array_store");
document.getElementById("array_disp").innerHTML = array_store.value;
};
function UpdateArray() {
var arr;
if (array_store.value == "") {
arr = new Array();
} else {
arr = array_store.value.split(",");
}
arr.push((arr.length + 1).toString());
array_store.value = arr.join(",");
};
</script>
</head>
<body>
<form id="form1" runat="server">
<span id="array_disp"></span>
<br />
<asp:Button ID="btnSubmit" runat="server" Text="Submit" OnClientClick="UpdateArray()" />
<input type="hidden" id="array_store" name = "ArrayStore" value = '<%=this.ArrayStore %>' />
</form>
</body>
</html>
C#:
protected string ArrayStore = "";
protected void Page_Load(object sender, EventArgs e)
{
this.ArrayStore = Request.Form["ArrayStore"];
}
I include the reference in the begeining of HTML
<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script src="~/Scripts/jquery.signalR-2.1.2.min.js"></script>
<script src="signalr/hubs"></script>
I add angular js file here:
<script src="~/ScriptsNg/Controller/TransacCltr.js"></script>
<script src="~/ScriptsNg/Services/CrudService.js"></script>
<div ng-app="myapp">
<div class="row" ng-controller="TransacCtrl">
<div class="modal-footer">
<button type="button" class="btn btn-success" data-dismiss="modal" ng-click="SaveUpdate()">Save</button>
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
In my TransacCltr.js file I write this code:
app.controller('TransacCtrl', ['$scope', 'CrudService', 'Notification',
function ($scope, CrudService, Notification) {
$scope.transac = {};
$scope.btnText = "Save";
//method
$scope.SaveUpdate = SaveUpdate;
$scope.GetServiceTypeList = GetServiceTypeList;
$scope.StatusOk = StatusOk;
init();
function init()
{
initilize();
}
function initilize()
{
Connect();
}
var SignalrConnection;
function Connect() {
SignalrConnection = $.connection.myHub;
//connecting the client to the signalr hub
$.connection.hub.start().done(function () {
alert("Connected to Signalr Server");
}).fail(function () {
alert("failed in connecting to the signalr server");
})
}
function SaveUpdate() {
var Temperature = parseInt($scope.transac.TrancAmount);
//calling the ChangeWeather function on the signalr server
SignalrConnection.server.change_weather(Temperature)
}
}
}
}]);
$.connection.myHub; this is shown me undefined.Why it show this?
if it is undefined how it will be defined.If I use it normal jquery function it does not show this message.But If I use it in angularjs then shows the error message.How I can solve this error?Any help is greately apprecited.
My Hub Class this is given below:
public class MyHub : Hub
{
static int Temperature;
[HubMethodName("change_weather")]
public void ChangeWeather(int temperature)
{
//change the temperature
Temperature = temperature;
Clients.Others.NotifyUser(temperature);
}
[HubMethodName("get_weather")]
public void GetWeather()
{
//pushing the data only to the user which has called this method.
Clients.Caller.NotifyUser(Temperature);
}
}
I have an autocomplete search box that culled up the thumbnail of images stored in the database. The problem is that the .jpg extension shows up each times the image name appears in the autocomplete search box. Is there anyway I can modify these codes to prevent the .jpg extension from appearing? Below is my existing code using javascript and ashx.
Thank you in advance!
the aspx:
<script src="scripts/jquery-1.4.1.min.js" type="text/javascript"></script>
<script src="scripts/jquery.autocomplete.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function () {
$("#<%=txtSearch.ClientID%>").autocomplete("Search.ashx", {
width: 200,
formatItem: function (data, i, n, value) {
return "<img style = 'width:50px;height:50px' src= 'Images/" + value.split(",")[1] + "'/> " + value.split(",")[0];
},
formatResult: function (data, value) {
return value.split(",")[0];
}
});
});
</script>
<style type="text/css">
.Gridview {
font-family: Verdana;
font-size: 10pt;
font-weight: normal;
color: black;
}
</style>
</head>
<body>
<form id="form1" runat="server">
<div>
Search here:
<asp:TextBox ID="txtSearch" runat="server" />
<br />
</div>
<div>
<asp:FileUpload ID="fileuploadimages" runat="server" />
<br />
<asp:Button ID="btnSubmit" runat="server" Text="Submit" OnClick="btnSubmit_Click" />
</div>
<div>
</div>
<asp:Label ID="lblResult" runat="server"></asp:Label>
</form>
</body>
</html>
the ashx:
public class Search : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
string searchText = context.Request.QueryString["q"];
string strcon = ConfigurationManager.ConnectionStrings["dbconnection"].ConnectionString;
SqlConnection connection = new SqlConnection(strcon);
connection.Open();
SqlCommand cmd = new SqlCommand("select ID,ImageName,ImagePath from ImagesPath where ImageName Like #Search + '%'", connection);
cmd.Parameters.AddWithValue("#Search", searchText);
StringBuilder sb = new StringBuilder();
using (SqlDataReader dr = cmd.ExecuteReader())
{
while (dr.Read())
{
sb.Append(string.Format("{0},{1}{2}", dr["ImageName"], dr["ImageName"], Environment.NewLine));
}
}
connection.Close();
context.Response.Write(sb.ToString());
}
public bool IsReusable
{
get
{
return false;
}
}
}
Do a search and replace, either in the ashx
dr["ImageName"].ToString().Replace(".jpg", "");
Or in the database
select ID, REPLACE(ImageName, '.jpg', '') AS ImageName, ImagePath from ImagesPath
Or if you have more than one extension, you can also do this
Path.GetFileNameWithoutExtension(dr["ImageName"].ToString())
This filters out the extension of every file, and the path should it be present:
string file = #"c:\folder\testFile.jpg";
string result = Path.GetFileNameWithoutExtension(file);
//result: testFile
Translated to your snippet it would look something like this.
while (dr.Read())
{
string file = Path.GetFileNameWithoutExtension(dr["ImageName"].ToString());
sb.Append(string.Format("{0},{1}{2}", file, file, Environment.NewLine));
}
I'm trying to call a COM C# Object from javascript code and get an object that doesn't contain the COM object functions.
I created a setup project for the C# COM library. The library is signed for COM interop, and the setup project output is signed for COM register on the machine it deployed at.
I see that the TLB is properly exported.
C# Code:
using System;
using System.Runtime.InteropServices;
namespace YaronTestCOM
{
[Guid("BD145EEC-ACAC-4FDB-B766-0F15CE07990F")]
[ComVisible(true)]
[ClassInterface(ClassInterfaceType.None)]
[ComSourceInterfaces(typeof(IComEvents))]
public class YaronComObject : IComObject, IObjectSafety
{
[ComVisible(false)]
public delegate void YaronFirstEventHandler(string args);
public event YaronFirstEventHandler YaronFirstEvent;
public int YaronFirstComCommand(string arg)
{
if (YaronFirstEvent != null)
YaronFirstEvent(arg);
return (int)DateTime.Now.Ticks;
}
public void Dispose()
{
}
}
[Guid("A3576AA4-9DE0-422D-BAA3-3FFB862E8007")]
[InterfaceType(ComInterfaceType.InterfaceIsDual)]
[ComVisible(true)]
public interface IComObject
{
[DispId(0x10000001)]
int YaronFirstComCommand(string arg);
[DispId(0x10000002)]
void Dispose();
}
[Guid("B551EC8B-4D19-4781-938C-9E50E70D37CD")]
[ComVisible(true)]
[InterfaceType(ComInterfaceType.InterfaceIsIDispatch)]
public interface IComEvents
{
[DispId(0x00000001)]
void YaronFirstEvent(string args);
}
}
HTML+Javascrip Code:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<object id="publisher" name="publisher" classid="clsid:BD145EEC-ACAC-4FDB-B766-0F15CE07990F"></object>
<title>Sender Test</title>
<script type="text/javascript" src="jquery-1.7.2.min.js"></script>
<script language="javascript" type="text/javascript">
$(document).ready(function () {
var msgTxt = $("#msgTxt");
$("#btnSend").click(function () {
var msg = msgTxt.val();
//publisher.YaronFirstComCommand is undefined!!!
var result = publisher.YaronFirstComCommand(msg);
alert('The message ' + msg + 'has been sent and returned ' + result);
});
});
</script>
</head>
<body>
<div>
<input type='text' id='msgTxt' />
<input type='button' value='Send Message' id='btnSend' />
</div>
</body>
Any ideas?
I am playing with Augmented Reality using Wikitude SDK for Google GLASS and it works fine. The data are loaded as it is supposed and on marker click i am showing a sidebar on the android device, however i am facing an issue when i try to TAP a marker on google glass. Tapping marker on device works fine with Wikitude AR Android SDK but how can i do the same using Wikitude for Google Glass.
As it is said in documentation the onMarkerSelectedfn function is the function which fires when a marker is selected on cam and yes that is working fine in the android device. But it is not working on google glass. Is there any special thing that i should do to work on Google glass too?
Shortly, how can i show details of the marker, on marker tap event, in another LiveCard or ImmersiveCard on Google Glass using Wikitude Augmented Reality SDK for Google Glass? or How to implement Browsing POI Presenting Details in that way that will work also in Google Glass?
onMarkerSelected: function onMarkerSelectedFn(marker) is the function triggered when POI Marker is selected.
Some sources that i found here describes same what i want to achieve however till that time this feature was not available on the SDK (i dont know if still not available as in documentation was not written). However any idea will be appriciated
Here is the WIkitude Google Glass Documentation
Here is the js function:
// fired when user pressed maker in cam
onMarkerSelected: function onMarkerSelectedFn(marker) {
World.currentMarker = marker;
// update panel values
$("#poi-detail-title").html(marker.poiData.name);
$("#poi-detail-description").html(marker.poiData.address);
//var distanceToUserValue = (marker.distanceToUser > 999) ? ((marker.distanceToUser / 1000).toFixed(2) + " km") : (Math.round(marker.distanceToUser) + " m");
$("#poi-detail-distance").html(marker.poiData.distance+" m");
// show panel
$("#panel-poidetail").panel("open", 123);
$( ".ui-panel-dismiss" ).unbind("mousedown");
$("#panel-poidetail").on("panelbeforeclose", function(event, ui) {
World.currentMarker.setDeselected(World.currentMarker);
});
},
Here is the Activity that shows the Markers:
public class RealityActivity extends Activity {
private Context context;
private GestureDetector mGestureDetector;
private ArchitectView architectView;
private double lat = 0.0;
private double lng = 0.0;
public static final String WIKITUDE_SDK_KEY = "API_KEY";
public long lastCalibrationToastShownTimeMillis = System.currentTimeMillis();
public String url = "5_1/index.html";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.reality);
getActionBar().hide();
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
context = this;
Bundle args = getIntent().getExtras();
if (args != null) {
lat = args.getDouble("lat");
lng = args.getDouble("lng");
}
architectView = (ArchitectView) findViewById(R.id.architectView);
final ArchitectView.ArchitectConfig config = new ArchitectView.ArchitectConfig(WIKITUDE_SDK_KEY);
architectView.onCreate(config);
architectView.registerSensorAccuracyChangeListener(sensorAccuracyChangeListener);
mGestureDetector = createGestureDetector();
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
architectView.onPostCreate();
try {
architectView.load(url);
activateArchitectView();
} catch (IOException e) {
Log.v("log", "Could not load architect: " + e.getMessage());
}
}
ArchitectView.SensorAccuracyChangeListener sensorAccuracyChangeListener = new ArchitectView.SensorAccuracyChangeListener() {
#Override
public void onCompassAccuracyChanged(int accuracy) {
/* UNRELIABLE = 0, LOW = 1, MEDIUM = 2, HIGH = 3 */
if (accuracy < SensorManager.SENSOR_STATUS_ACCURACY_MEDIUM && !isFinishing() && System.currentTimeMillis() - lastCalibrationToastShownTimeMillis > 5 * 1000) {
Log.v("log", "ArchitectView.SensorAccuracyChangeListener");
lastCalibrationToastShownTimeMillis = System.currentTimeMillis();
}
}
};
private void activateArchitectView() {
new Timer().schedule(new TimerTask() {
#Override
public void run() {
runOnUiThread(new Runnable() {
#Override
public void run() {
architectView.setLocation(lat, lng, 100);
String params = getPoiInformation().toString();
callJavaScript("World.loadPoisFromJsonData", new String[]{params});
}
});
}
}, 3000);
}
private void callJavaScript(final String methodName, final String[] arguments) {
final StringBuilder argumentsString = new StringBuilder("");
for (int i = 0; i < arguments.length; i++) {
argumentsString.append(arguments[i]);
if (i < arguments.length - 1) {
argumentsString.append(", ");
}
}
if (this.architectView != null) {
final String js = (methodName + "( " + argumentsString.toString() + " );");
Log.v("log", "YER: " + js);
this.architectView.callJavascript(js);
}
}
private JSONArray getPoiInformation() {
JSONArray pois = new JSONArray();
List<MyModel> sliced = new ArrayList<MyModel>(FindModel.model);
if (FindModel.model.size() > 10) {
sliced = FindModel.model.subList(0, 10);
}
for (MyModel model : sliced) {
HashMap<String, String> poi = new HashMap<String, String>();
poi.put("id", String.valueOf(model.id));
poi.put("name", model.name);
poi.put("address", model.address);
poi.put("distance", String.valueOf(((int) model.distance)));
poi.put("lat", String.valueOf(model.lat));
poi.put("lng", String.valueOf(model.lng));
pois.put(new JSONObject(poi));
}
return pois;
}
#Override
public void onLowMemory() {
super.onLowMemory();
if (architectView != null) {
architectView.onLowMemory();
}
}
#Override
protected void onResume() {
super.onResume();
if (architectView != null) {
architectView.onResume();
if (sensorAccuracyChangeListener != null) {
architectView.registerSensorAccuracyChangeListener(sensorAccuracyChangeListener);
}
}
}
#Override
protected void onPause() {
super.onPause();
if (architectView != null) {
architectView.onPause();
if (sensorAccuracyChangeListener != null) {
architectView.unregisterSensorAccuracyChangeListener(sensorAccuracyChangeListener);
}
}
}
#Override
protected void onDestroy() {
super.onDestroy();
if (architectView != null) {
architectView.onDestroy();
}
}
private GestureDetector createGestureDetector() {
GestureDetector gestureDetector = new GestureDetector(context);
//Create a base listener for generic gestures
gestureDetector.setBaseListener( new GestureDetector.BaseListener() {
#Override
public boolean onGesture(Gesture gesture) {
if (gesture == Gesture.TAP) {
// do something on tap
Toast.makeText(context, "TAP", Toast.LENGTH_SHORT).show();
return true;
} else if (gesture == Gesture.TWO_TAP) {
// do something on two finger tap
Toast.makeText(context, "TWO_TAP", Toast.LENGTH_SHORT).show();
return true;
} else if (gesture == Gesture.SWIPE_RIGHT) {
// do something on right (forward) swipe
Toast.makeText(context, "SWIPE_RIGHT", Toast.LENGTH_SHORT).show();
return true;
} else if (gesture == Gesture.SWIPE_LEFT) {
// do something on left (backwards) swipe
Toast.makeText(context, "SWIPE_LEFT", Toast.LENGTH_SHORT).show();
return true;
}
return false;
}
});
gestureDetector.setFingerListener(new GestureDetector.FingerListener() {
#Override
public void onFingerCountChanged(int previousCount, int currentCount) {
// do something on finger count changes
}
});
gestureDetector.setScrollListener(new GestureDetector.ScrollListener() {
#Override
public boolean onScroll(float displacement, float delta, float velocity) {
// do something on scrolling"
return false;
}
});
return gestureDetector;
}
/*
* Send generic motion events to the gesture detector
*/
#Override
public boolean onGenericMotionEvent(MotionEvent event) {
if (mGestureDetector != null) {
return mGestureDetector.onMotionEvent(event);
}
return false;
}
}
and here is the index.html page:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<meta http-equiv="Content-Type"
content="application/json; charset=utf-8">
<meta
content="width=device-width,initial-scale=1,maximum-scale=5,user-scalable=yes"
name="viewport">
<script src="architect://architect.js"></script>
<!-- positioning of poi-radar -->
<link rel="stylesheet" href="css/poi-radar.css" />
<!-- jquery mobile CSS -->
<link rel="stylesheet" href="jquery/jquery.mobile-1.3.2.min.css" />
<!-- required to set background transparent & enable "click through" -->
<link rel="stylesheet"
href="jquery/jquery-mobile-transparent-ui-overlay.css" />
<!-- jquery JS files -->
<script type="text/javascript" src="jquery/jquery-1.9.1.min.js"></script>
<script type="text/javascript" src="jquery/jquery.mobile-1.3.2.min.js"></script>
<!-- marker representation-->
<script src="js/marker.js"></script>
<!-- World logic-->
<script type="text/javascript" src="js/presentingPoiDetails.js"></script>
<!-- radar component -->
<script type="text/javascript" src="js/radar.js"></script>
<script>
$( document ).ready(function() {
//alert("onReady");
//console.log("onReady");
//AR.logger.activateDebugMode();
$("#log").css({ opacity: 0 });
$("#footer").css({ opacity: 0 });
$(document).click(function (e) {
//alert("click");
if(e){
console.log("onclick");
alert(e);
}
});
$('#log').click(function (e) {
if(e){
console.log("onclick");
var offset = $(this).offset();
var left = e.clientX - offset.left);
var top = e.clientY - offset.top);
alert(left+":"+top);
}
});
});
</script>
</head>
<body>
<div data-role="page" id="page1" style="background: none;">
<!-- the radar div - Wikitude SDK radar will be drawn into this div -->
<div class="radarContainer_left" id="radarContainer"></div>
<div id="log" style="float: right;">log data</div>
<!-- transparent footer-->
<div id="footer" data-role="footer" class="ui-bar" data-theme="f"
data-position="fixed" style="text-align: center;">
<!-- small status-button -->
<a style="text-align: right;" id="popupInfoButton" href="#popupInfo"
data-rel="popup" data-role="button" class="ui-icon-alt"
data-inline="true" data-transition="pop" data-icon="alert"
data-theme="e" data-iconpos="notext">Log</a> <br />
<!-- popup displayed when button clicked -->
<div data-role="popup" id="popupInfo" class="ui-content"
data-theme="e" style="max-width: 350px;">
<p style="text-align: right;" id="status-message">Trying to find
out where you are</p>
</div>
</div>
<div
id="panel-poidetail"
data-role="panel"
data-position="right"
data-display="overlay"
data-theme="a" >
<div data-role="header">
Close
<h1>Detay</h1>
Path
</div>
<div data-role="content">
<b>Cami<b>
<br/>
<span id="poi-detail-title">Test Name</span>
<br/>
<br/>
<b>Test Address</b>
<br/>
<span id="poi-detail-description">Test Desc</span>
<br/>
<br/>
<b>Test Distance</b>
<br/>
<span id="poi-detail-distance">240 m</span>
<br/>
<br/>
</div>
</div>
</div>
</body>
</html>