Websocket on C++ and Javascript not responding - tcp

I want to have a simple broadcast C/C++ server that will receive client's messages and send them back to all other connected parts, including the sender. I have the following codes:
Server-side (C++):
#include <boost/asio.hpp>
#include <boost/bind.hpp>
#include <boost/thread.hpp>
#include <iostream>
#include <memory>
#include <set>
#include <websocketpp/config/asio_no_tls.hpp>
#include <websocketpp/server.hpp>
typedef websocketpp::server<websocketpp::config::asio> server;
using websocketpp::connection_hdl;
using websocketpp::lib::placeholders::_1;
using websocketpp::lib::placeholders::_2;
using websocketpp::lib::bind;
class broadcast_server {
public:
broadcast_server() {
m_server.init_asio();
m_server.set_open_handler(bind(&broadcast_server::on_open,this,::_1));
m_server.set_close_handler(bind(&broadcast_server::on_close,this,::_1));
m_server.set_message_handler(bind(&broadcast_server::on_message,this,::_1,::_2));
}
void on_open(connection_hdl hdl) {
m_connections.insert(hdl);
}
void on_close(connection_hdl hdl) {
m_connections.erase(hdl);
}
void on_message(connection_hdl hdl, server::message_ptr msg) {
for (auto it : m_connections) {
m_server.send(it,msg);
}
}
void run(uint16_t port) {
m_server.listen(port);
m_server.start_accept();
m_server.run();
}
private:
typedef std::set<connection_hdl,std::owner_less<connection_hdl>> con_list;
server m_server;
con_list m_connections;
};
int main() {
broadcast_server server;
server.run(xxxx);
}
Client-side (Javascript):
<html>
<head>
<title>Websocket chat example</title>
<style type="text/css">
html, body {
font: normal 0.9em arial, helvetica;
}
#log {
width: 600px;
height: 300px;
border: 1px solid #7F9DB9;
overflow: auto;
}
#msg {
width: 400px;
}
</style>
<script type="text/javascript">
var socket;
function init() {
var host = "ws://xxx.xxx.xxx.xxx:xxxx/echobot";
try {
socket = new WebSocket(host);
log('WebSocket - status ' + socket.readyState);
socket.onopen = function(msg) {
log("Welcome - status " + this.readyState);
};
socket.onmessage = function(msg) {
log("Received: " + msg.data);
};
socket.onclose = function(msg) {
log("Disconnected - status " + this.readyState);
};
} catch (ex) {
log(ex);
}
$("msg").focus();
}
function send() {
var txt, msg;
txt = $("msg");
msg = txt.value;
if (!msg) {
alert("Message can not be empty");
return;
}
txt.value = "";
txt.focus();
try {
socket.send(msg);
log('Sent: ' + msg);
} catch (ex) {
log(ex);
}
}
function quit() {
if (socket != null) {
log("Goodbye!");
socket.close();
socket = null;
}
}
function reconnect() {
quit();
init();
}
// Utilities
function $(id) {
return document.getElementById(id);
}
function log(msg) {
$("log").innerHTML += "<br>" + msg;
}
function onkey(event) {
if (event.keyCode == 13) {
send();
}
}
</script>
</head>
<body onload="init()">
<h3>WebSocket v2.00</h3>
<div id="log"></div>
<input id="msg" type="textbox" onkeypress="onkey(event)" />
<button onclick="send()">Send</button>
<button onclick="quit()">Quit</button>
<button onclick="reconnect()">Reconnect</button>
</body>
</html>
The messages sent by the client reach the server perfectly and it outputs the following:
[2015-07-11 03:59:27] [frame_header] Dispatching write containing 1 message(s) containing 2 header bytes and 12 payload bytes
[2015-07-11 03:59:27] [frame_header] Header Bytes:
[0] (2) 81 0C
[2015-07-11 03:59:27] [frame_payload] Payload Bytes:
[0] (12) [1] Test_message
Anyway, the client does not appear to receive anything from the broadcast server. The server can handle multiple connections perfectly, but simply the clients do not output its answers.

Related

Counting the number of transmissions in TinyOS 2.x

I'm trying to implement an application in NesC able to count the number of transmissions performed along the simulation, however I'm facing many difficulties. No approach that I tryed works. Could anyone help me? this is my application:
module FloodingC {
uses {
interface Boot;
interface SplitControl as AMControl;
interface Timer<TMilli> as MilliTimer;
interface Receive;
interface AMSend;
interface Packet;
interface AMPacket;
interface RootControl;
interface PacketAcknowledgements as PackAck;
}
}
implementation {
message_t packet;
bool locked = FALSE;
uint16_t flag;
event void Boot.booted() {
flag = 0;
call AMControl.start();
}
event void AMControl.startDone(error_t err) {
if(err == SUCCESS) {
if(TOS_NODE_ID == 1)
call RootControl.setRoot();
call MilliTimer.startOneShot(1024);
}
else {
call AMControl.start();
}
}
event void AMControl.stopDone(error_t err) {
}
void sendMsg(){
floodingMsg_t* msg = (floodingMsg_t* ) call Packet.getPayload(&packet, sizeof(floodingMsg_t));
if(msg == NULL) {
return;
}
flag = 1;
msg->nodeid = TOS_NODE_ID;
msg->counter = 1;
call PackAck.requestAck(&packet);
if(call AMSend.send(AM_BROADCAST_ADDR, &packet, sizeof(floodingMsg_t)) == SUCCESS) {
locked = TRUE;
}
}
event void MilliTimer.fired() {
if(locked) {
return;
}
else {
if (call RootControl.isRoot()){
sendMsg();
}
}
}
event void AMSend.sendDone(message_t *msg, error_t error){
if (call PackAck.wasAcked(msg) == SUCCESS){
locked = FALSE;
}
else{
sendMsg();
}
}
event message_t* Receive.receive(message_t* msg, void* payload, uint8_t len) {
floodingMsg_t* newMsg = (floodingMsg_t* )payload;
if (locked == TRUE) return msg;
if(flag == 0) {
flag = 1;
newMsg->nodeid = TOS_NODE_ID;
newMsg->counter++;
call AMSend.send(AM_BROADCAST_ADDR, msg, call Packet.maxPayloadLength());
}
return msg;
}
}
Thanks
You can count them using a BaseStation sniffer (included in tinyos), or adding a sequence number on your transmitted packet.

calculate time zone from lat/lon [duplicate]

Given the latitude and longitude of a location, how does one know what time zone is in effect in that location?
In most cases, we are looking for an IANA/Olson time zone id, although some services may return just a UTC offset, or some other time zone identifier. Please read the timezone tag info for details.
Time Zone Location Web Services
Google Maps Time Zone API
Bing Maps Time Zone API
Azure Maps Time Zone API
GeoNames Time Zone API
TimeZoneDB API
AskGeo - commercial (but arguably more accurate than GeoNames)
GeoGarage Time Zone API - commercial, focusing on Nautical time zones.
Raw Time Zone Boundary Data
Timezone Boundary Builder - builds time zone shapefiles from OpenStreetMaps map data. Includes territorial waters near coastlines.
The following projects have previously been sources of time zone boundary data, but are no longer actively maintained.
tz_world - the original shapefile data from Eric Muller
whereonearth-timezone - GeoJSON version with WOEDB data merged in
Time Zone Geolocation Offline Implementations
Implementations that use the Timezone Boundary Builder data
node-geo-tz - JavaScript library (Node.js only)
timespace - JavaScript library
tz-lookup-oss - JavaScript library
GeoTimeZone - .NET library
Geo-Timezone - PHP library
timezonefinder - Python library
ZoneDetect - C library
Timeshape - Java library
TimeZoneMap - Java and Android library
lutz - R library
go-tz - Go library
Timezone lookup - Go library
docker-timezone-lookup - docker container wrapping node-geo-tz
tzf - Go library
tzfpy - Python port of tzf library
tzf-rs - Rust port of tzf library
Implementations that use the older tz_world data
latlong - Go library (Read this post also.)
TimeZoneMapper - Java library
tzwhere - JavaScript/Node library
pytzwhere - Python library
timezone_finder - Ruby library
LatLongToTimeZone - Java and Swift libraries
What Time is it here? - Blog post describing PHP and MongoDB
rundel/timezone - R library
Libraries that call one of the web services
timezone - Ruby gem that calls GeoNames
AskGeo has its own libraries for calling from Java or .Net
GeoNames has client libraries for just about everything
Self-hosted web services
geo2tz - based on Timezone lookup, available via Docker image
Other Ideas
Find the nearest city with an R-Tree
Find the nearest city with MySQL
Please update this list if you know of any others
Also, note that the nearest-city approach may not yield the "correct" result, just an approximation.
Conversion To Windows Zones
Most of the methods listed will return an IANA time zone id. If you need to convert to a Windows time zone for use with the TimeZoneInfo class in .NET, use the TimeZoneConverter library.
Don't use zone.tab
The tz database includes a file called zone.tab. This file is primarily used to present a list of time zones for a user to pick from. It includes the latitude and longitude coordinates for the point of reference for each time zone. This allows a map to be created highlighting these points. For example, see the interactive map shown on the moment-timezone home page.
While it may be tempting to use this data to resolve the time zone from a latitude and longitude coordinates, consider that these are points - not boundaries. The best one could do would be to determine the closest point, which in many cases will not be the correct point.
Consider the following example:
                           
The two squares represent different time zones, where the black dot in each square is the reference location, such as what can be found in zone.tab. The blue dot represents the location we are attempting to find a time zone for. Clearly, this location is within the orange zone on the left, but if we just look at closest distance to the reference point, it will resolve to the greenish zone on the right.
How about this solution for node.js
https://github.com/mattbornski/tzwhere
And its Python counterpart:
https://github.com/pegler/pytzwhere
We at Teleport just started opening up our API's and one of the usecases is also exposing TZ information for coordinates.
For example one could request all our available TZ information for coordinates in following manner:
curl -s https://api.teleport.org/api/locations/59.4372,24.7453/?embed=location:nearest-cities/location:nearest-city/city:timezone/tz:offsets-now | jq '._embedded."location:nearest-cities"[0]._embedded."location:nearest-city"._embedded."city:timezone"'
This would return the following
{
"_embedded": {
"tz:offsets-now": {
"_links": {
"self": {
"href": "https://api.teleport.org/api/timezones/iana:Europe%2FTallinn/offsets/?date=2015-09-07T11%3A20%3A09Z"
}
},
"base_offset_min": 120,
"dst_offset_min": 60,
"end_time": "2015-10-25T01:00:00Z",
"short_name": "EEST",
"total_offset_min": 180,
"transition_time": "2015-03-29T01:00:00Z"
}
},
"_links": {
"self": {
"href": "https://api.teleport.org/api/timezones/iana:Europe%2FTallinn/"
},
"tz:offsets": {
"href": "https://api.teleport.org/api/timezones/iana:Europe%2FTallinn/offsets/{?date}",
"templated": true
},
"tz:offsets-now": {
"href": "https://api.teleport.org/api/timezones/iana:Europe%2FTallinn/offsets/?date=2015-09-07T11%3A20%3A09Z"
}
},
"iana_name": "Europe/Tallinn"
}
For the example I used ./jq for JSON parsing.
Here's how you can use Google's script editor to get the timezoneName and timeZoneId inside a gsheet.
Step 1. Get an API key for Google's timezone API
Step 2. Create a new gsheet. Underneath the 'tools' menu click 'script editor'. Add the following code:
function getTimezone(lat, long) {
var apiKey = 'INSERTAPIKEYHERE'
var url = 'https://maps.googleapis.com/maps/api/timezone/json?location=' + lat + ',' + long + '&timestamp=1331161200&key=' + apiKey
var response = UrlFetchApp.fetch(url);
var data = JSON.parse(response.getContentText());
return data["timeZoneName"];
}
Step 3. Save and publish your getTimezone() function and use it as shown in the image above.
You can use geolocator.js for easily getting timezone and more...
It uses Google APIs that require a key. So, first you configure geolocator:
geolocator.config({
language: "en",
google: {
version: "3",
key: "YOUR-GOOGLE-API-KEY"
}
});
Get TimeZone if you have the coordinates:
geolocator.getTimeZone(options, function (err, timezone) {
console.log(err || timezone);
});
Example output:
{
id: "Europe/Paris",
name: "Central European Standard Time",
abbr: "CEST",
dstOffset: 0,
rawOffset: 3600,
timestamp: 1455733120
}
Locate then get TimeZone and more
If you don't have the coordinates, you can locate the user position first.
Example below will first try HTML5 Geolocation API to get the coordinates. If it fails or rejected, it will get the coordinates via Geo-IP look-up. Finally, it will get the timezone and more...
var options = {
enableHighAccuracy: true,
timeout: 6000,
maximumAge: 0,
desiredAccuracy: 30,
fallbackToIP: true, // if HTML5 fails or rejected
addressLookup: true, // this will get full address information
timezone: true,
map: "my-map" // this will even create a map for you
};
geolocator.locate(options, function (err, location) {
console.log(err || location);
});
Example output:
{
coords: {
latitude: 37.4224764,
longitude: -122.0842499,
accuracy: 30,
altitude: null,
altitudeAccuracy: null,
heading: null,
speed: null
},
address: {
commonName: "",
street: "Amphitheatre Pkwy",
route: "Amphitheatre Pkwy",
streetNumber: "1600",
neighborhood: "",
town: "",
city: "Mountain View",
region: "Santa Clara County",
state: "California",
stateCode: "CA",
postalCode: "94043",
country: "United States",
countryCode: "US"
},
formattedAddress: "1600 Amphitheatre Parkway, Mountain View, CA 94043, USA",
type: "ROOFTOP",
placeId: "ChIJ2eUgeAK6j4ARbn5u_wAGqWA",
timezone: {
id: "America/Los_Angeles",
name: "Pacific Standard Time",
abbr: "PST",
dstOffset: 0,
rawOffset: -28800
},
flag: "//cdnjs.cloudflare.com/ajax/libs/flag-icon-css/2.3.1/flags/4x3/us.svg",
map: {
element: HTMLElement,
instance: Object, // google.maps.Map
marker: Object, // google.maps.Marker
infoWindow: Object, // google.maps.InfoWindow
options: Object // map options
},
timestamp: 1456795956380
}
I wrote a package https://github.com/ringsaturn/tzf support get timezone in Go&Python and very fast:
package main
import (
"fmt"
"github.com/ringsaturn/tzf"
)
func main() {
finder, err := tzf.NewDefaultFinder()
if err != nil {
panic(err)
}
fmt.Println(finder.GetTimezoneName(116.6386, 40.0786))
}
Python https://github.com/ringsaturn/tzfpy sample:
from tzfpy import get_tz
print(get_tz(121.4737, 31.2305))
Rust https://github.com/ringsaturn/tzf-rs sample:
use tzf_rs::DefaultFinder;
fn main() {
let finder = DefaultFinder::new();
print!("{:?}\n", DefaultFinder.get_tz_name(116.3883, 39.9289));
}
It's indeed important to recognize that this a more complicated problem than most would suspect. In practice many of us are also willing to accept a working set of code that works for "as many cases as possible", where at least its fatal issues can be identified and minimized collectively. So I post this with all of that and the spirit of the OP in mind. Finally, for practical value to others who are trying to convert GPS to timezone with the end goal of having a location-sensitive time object (and more importantly to help advance the quality of average implementations with time objects that follow from this wiki) here is what I generated in Python (please feel free to edit):
import pytz
from datetime import datetime
from tzwhere import tzwhere
def timezoned_unixtime(latitude, longitude, dt):
tzw = tzwhere.tzwhere()
timezone_str = tzw.tzNameAt(latitude, longitude)
timezone = pytz.timezone(timezone_str)
timezone_aware_datetime = timezone.localize(dt, is_dst=None)
unix_time = (timezone_aware_datetime - datetime(1970, 1, 1, tzinfo=pytz.utc)).total_seconds()
return unix_time
dt = datetime(year=2017, month=1, day=17, hour=12, minute=0, second=0)
print timezoned_unixtime(latitude=40.747854, longitude=-74.004733, dt=dt)
There are several sources online that have geojson data for timezones (here's one, here's another)
Use a geometry library to create polygon objects from the geojson coordinates (shapely [python], GEOS [c++], JTS [java], NTS [.net]).
Convert your lat/lng to a point object (however your library represents that) and check if it intersects the timezone polygon.
from shapely.geometry import Polygon, Point
def get_tz_from_lat_lng(lat, lng):
for tz, geojson in timezones.iteritems():
coordinates = geojson['features'][0]['geometry']['coordinates']
polygon = Polygon(coordinates)
point = Point(lng, lat)
if polygon.contains(point):
return tz
disclosure: I am the author of the docker-image described below
I have wrapped https://github.com/evansiroky/node-geo-tz in a very simple docker-container
https://hub.docker.com/repository/docker/tobias74/timezone-lookup
You can start the docker-container with
docker run -p 80:3000 tobias74/timezone-lookup:latest
This exposes the lookup-service on your localhost on port 3000. You can then do a timezone-lookup by
curl "localhost:3000/timezone?latitude=12&longitude=34"
Try this code for use Google Time Zone API from Java with current NTP Time Client and correct UTC_Datetime_from_timestamp convert:
String get_xml_server_reponse(String server_url){
URL xml_server = null;
String xmltext = "";
InputStream input;
try {
xml_server = new URL(server_url);
try {
input = xml_server.openConnection().getInputStream();
final BufferedReader reader = new BufferedReader(new InputStreamReader(input));
final StringBuilder sBuf = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null)
{
sBuf.append(line);
}
}
catch (IOException e)
{
Log.e(e.getMessage(), "XML parser, stream2string 1");
}
finally {
try {
input.close();
}
catch (IOException e)
{
Log.e(e.getMessage(), "XML parser, stream2string 2");
}
}
xmltext = sBuf.toString();
} catch (IOException e1) {
e1.printStackTrace();
}
} catch (MalformedURLException e1) {
e1.printStackTrace();
}
return xmltext;
}
private String get_UTC_Datetime_from_timestamp(long timeStamp){
try{
Calendar cal = Calendar.getInstance();
TimeZone tz = cal.getTimeZone();
int tzt = tz.getOffset(System.currentTimeMillis());
timeStamp -= tzt;
// DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss",Locale.getDefault());
DateFormat sdf = new SimpleDateFormat();
Date netDate = (new Date(timeStamp));
return sdf.format(netDate);
}
catch(Exception ex){
return "";
}
}
class NTP_UTC_Time
{
private static final String TAG = "SntpClient";
private static final int RECEIVE_TIME_OFFSET = 32;
private static final int TRANSMIT_TIME_OFFSET = 40;
private static final int NTP_PACKET_SIZE = 48;
private static final int NTP_PORT = 123;
private static final int NTP_MODE_CLIENT = 3;
private static final int NTP_VERSION = 3;
// Number of seconds between Jan 1, 1900 and Jan 1, 1970
// 70 years plus 17 leap days
private static final long OFFSET_1900_TO_1970 = ((365L * 70L) + 17L) * 24L * 60L * 60L;
private long mNtpTime;
public boolean requestTime(String host, int timeout) {
try {
DatagramSocket socket = new DatagramSocket();
socket.setSoTimeout(timeout);
InetAddress address = InetAddress.getByName(host);
byte[] buffer = new byte[NTP_PACKET_SIZE];
DatagramPacket request = new DatagramPacket(buffer, buffer.length, address, NTP_PORT);
buffer[0] = NTP_MODE_CLIENT | (NTP_VERSION << 3);
writeTimeStamp(buffer, TRANSMIT_TIME_OFFSET);
socket.send(request);
// read the response
DatagramPacket response = new DatagramPacket(buffer, buffer.length);
socket.receive(response);
socket.close();
mNtpTime = readTimeStamp(buffer, RECEIVE_TIME_OFFSET);
} catch (Exception e) {
// if (Config.LOGD) Log.d(TAG, "request time failed: " + e);
return false;
}
return true;
}
public long getNtpTime() {
return mNtpTime;
}
/**
* Reads an unsigned 32 bit big endian number from the given offset in the buffer.
*/
private long read32(byte[] buffer, int offset) {
byte b0 = buffer[offset];
byte b1 = buffer[offset+1];
byte b2 = buffer[offset+2];
byte b3 = buffer[offset+3];
// convert signed bytes to unsigned values
int i0 = ((b0 & 0x80) == 0x80 ? (b0 & 0x7F) + 0x80 : b0);
int i1 = ((b1 & 0x80) == 0x80 ? (b1 & 0x7F) + 0x80 : b1);
int i2 = ((b2 & 0x80) == 0x80 ? (b2 & 0x7F) + 0x80 : b2);
int i3 = ((b3 & 0x80) == 0x80 ? (b3 & 0x7F) + 0x80 : b3);
return ((long)i0 << 24) + ((long)i1 << 16) + ((long)i2 << 8) + (long)i3;
}
/**
* Reads the NTP time stamp at the given offset in the buffer and returns
* it as a system time (milliseconds since January 1, 1970).
*/
private long readTimeStamp(byte[] buffer, int offset) {
long seconds = read32(buffer, offset);
long fraction = read32(buffer, offset + 4);
return ((seconds - OFFSET_1900_TO_1970) * 1000) + ((fraction * 1000L) / 0x100000000L);
}
/**
* Writes 0 as NTP starttime stamp in the buffer. --> Then NTP returns Time OFFSET since 1900
*/
private void writeTimeStamp(byte[] buffer, int offset) {
int ofs = offset++;
for (int i=ofs;i<(ofs+8);i++)
buffer[i] = (byte)(0);
}
}
String get_time_zone_time(GeoPoint gp){
String erg = "";
String raw_offset = "";
String dst_offset = "";
double Longitude = gp.getLongitudeE6()/1E6;
double Latitude = gp.getLatitudeE6()/1E6;
long tsLong = 0; // System.currentTimeMillis()/1000;
NTP_UTC_Time client = new NTP_UTC_Time();
if (client.requestTime("pool.ntp.org", 2000)) {
tsLong = client.getNtpTime();
}
if (tsLong != 0)
{
tsLong = tsLong / 1000;
// https://maps.googleapis.com/maps/api/timezone/xml?location=39.6034810,-119.6822510&timestamp=1331161200&sensor=false
String request = "https://maps.googleapis.com/maps/api/timezone/xml?location="+Latitude+","+ Longitude+ "&timestamp="+tsLong +"&sensor=false";
String xmltext = get_xml_server_reponse(request);
if(xmltext.compareTo("")!= 0)
{
int startpos = xmltext.indexOf("<TimeZoneResponse");
xmltext = xmltext.substring(startpos);
XmlPullParser parser;
try {
parser = XmlPullParserFactory.newInstance().newPullParser();
parser.setInput(new StringReader (xmltext));
int eventType = parser.getEventType();
String tagName = "";
while(eventType != XmlPullParser.END_DOCUMENT) {
switch(eventType) {
case XmlPullParser.START_TAG:
tagName = parser.getName();
break;
case XmlPullParser.TEXT :
if (tagName.equalsIgnoreCase("raw_offset"))
if(raw_offset.compareTo("")== 0)
raw_offset = parser.getText();
if (tagName.equalsIgnoreCase("dst_offset"))
if(dst_offset.compareTo("")== 0)
dst_offset = parser.getText();
break;
}
try {
eventType = parser.next();
} catch (IOException e) {
e.printStackTrace();
}
}
} catch (XmlPullParserException e) {
e.printStackTrace();
erg += e.toString();
}
}
int ro = 0;
if(raw_offset.compareTo("")!= 0)
{
float rof = str_to_float(raw_offset);
ro = (int)rof;
}
int dof = 0;
if(dst_offset.compareTo("")!= 0)
{
float doff = str_to_float(dst_offset);
dof = (int)doff;
}
tsLong = (tsLong + ro + dof) * 1000;
erg = get_UTC_Datetime_from_timestamp(tsLong);
}
return erg;
}
And use it with:
GeoPoint gp = new GeoPoint(39.6034810,-119.6822510);
String Current_TimeZone_Time = get_time_zone_time(gp);
Ok here is the short Version without correct NTP Time:
String get_xml_server_reponse(String server_url){
URL xml_server = null;
String xmltext = "";
InputStream input;
try {
xml_server = new URL(server_url);
try {
input = xml_server.openConnection().getInputStream();
final BufferedReader reader = new BufferedReader(new InputStreamReader(input));
final StringBuilder sBuf = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null)
{
sBuf.append(line);
}
}
catch (IOException e)
{
Log.e(e.getMessage(), "XML parser, stream2string 1");
}
finally {
try {
input.close();
}
catch (IOException e)
{
Log.e(e.getMessage(), "XML parser, stream2string 2");
}
}
xmltext = sBuf.toString();
} catch (IOException e1) {
e1.printStackTrace();
}
} catch (MalformedURLException e1) {
e1.printStackTrace();
}
return xmltext;
}
long get_time_zone_time_l(GeoPoint gp){
String raw_offset = "";
String dst_offset = "";
double Longitude = gp.getLongitudeE6()/1E6;
double Latitude = gp.getLatitudeE6()/1E6;
long tsLong = System.currentTimeMillis()/1000;
if (tsLong != 0)
{
// https://maps.googleapis.com/maps/api/timezone/xml?location=39.6034810,-119.6822510&timestamp=1331161200&sensor=false
String request = "https://maps.googleapis.com/maps/api/timezone/xml?location="+Latitude+","+ Longitude+ "&timestamp="+tsLong +"&sensor=false";
String xmltext = get_xml_server_reponse(request);
if(xmltext.compareTo("")!= 0)
{
int startpos = xmltext.indexOf("<TimeZoneResponse");
xmltext = xmltext.substring(startpos);
XmlPullParser parser;
try {
parser = XmlPullParserFactory.newInstance().newPullParser();
parser.setInput(new StringReader (xmltext));
int eventType = parser.getEventType();
String tagName = "";
while(eventType != XmlPullParser.END_DOCUMENT) {
switch(eventType) {
case XmlPullParser.START_TAG:
tagName = parser.getName();
break;
case XmlPullParser.TEXT :
if (tagName.equalsIgnoreCase("raw_offset"))
if(raw_offset.compareTo("")== 0)
raw_offset = parser.getText();
if (tagName.equalsIgnoreCase("dst_offset"))
if(dst_offset.compareTo("")== 0)
dst_offset = parser.getText();
break;
}
try {
eventType = parser.next();
} catch (IOException e) {
e.printStackTrace();
}
}
} catch (XmlPullParserException e) {
e.printStackTrace();
erg += e.toString();
}
}
int ro = 0;
if(raw_offset.compareTo("")!= 0)
{
float rof = str_to_float(raw_offset);
ro = (int)rof;
}
int dof = 0;
if(dst_offset.compareTo("")!= 0)
{
float doff = str_to_float(dst_offset);
dof = (int)doff;
}
tsLong = (tsLong + ro + dof) * 1000;
}
return tsLong;
}
And use it with:
GeoPoint gp = new GeoPoint(39.6034810,-119.6822510);
long Current_TimeZone_Time_l = get_time_zone_time_l(gp);
If you want to use geonames.org then use this code. (But geonames.org is very slow sometimes)
String get_time_zone_time_geonames(GeoPoint gp){
String erg = "";
double Longitude = gp.getLongitudeE6()/1E6;
double Latitude = gp.getLatitudeE6()/1E6;
String request = "http://ws.geonames.org/timezone?lat="+Latitude+"&lng="+ Longitude+ "&style=full";
URL time_zone_time = null;
InputStream input;
// final StringBuilder sBuf = new StringBuilder();
try {
time_zone_time = new URL(request);
try {
input = time_zone_time.openConnection().getInputStream();
final BufferedReader reader = new BufferedReader(new InputStreamReader(input));
final StringBuilder sBuf = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sBuf.append(line);
}
} catch (IOException e) {
Log.e(e.getMessage(), "XML parser, stream2string 1");
} finally {
try {
input.close();
} catch (IOException e) {
Log.e(e.getMessage(), "XML parser, stream2string 2");
}
}
String xmltext = sBuf.toString();
int startpos = xmltext.indexOf("<geonames");
xmltext = xmltext.substring(startpos);
XmlPullParser parser;
try {
parser = XmlPullParserFactory.newInstance().newPullParser();
parser.setInput(new StringReader (xmltext));
int eventType = parser.getEventType();
String tagName = "";
while(eventType != XmlPullParser.END_DOCUMENT) {
switch(eventType) {
case XmlPullParser.START_TAG:
tagName = parser.getName();
break;
case XmlPullParser.TEXT :
if (tagName.equalsIgnoreCase("time"))
erg = parser.getText();
break;
}
try {
eventType = parser.next();
} catch (IOException e) {
e.printStackTrace();
}
}
} catch (XmlPullParserException e) {
e.printStackTrace();
erg += e.toString();
}
} catch (IOException e1) {
e1.printStackTrace();
}
} catch (MalformedURLException e1) {
e1.printStackTrace();
}
return erg;
}
And use it with:
GeoPoint gp = new GeoPoint(39.6034810,-119.6822510);
String Current_TimeZone_Time = get_time_zone_time_geonames(gp);
https://en.wikipedia.org/wiki/Great-circle_distance
And here is a good implementation using JSON data:
https://github.com/agap/llttz
public TimeZone nearestTimeZone(Location node) {
double bestDistance = Double.MAX_VALUE;
Location bestGuess = timeZones.get(0);
for (Location current : timeZones.subList(1, timeZones.size())) {
double newDistance = distanceInKilometers(node, current);
if (newDistance < bestDistance) {
bestDistance = newDistance;
bestGuess = current;
}
}
return java.util.TimeZone.getTimeZone(bestGuess.getZone());
}
protected double distanceInKilometers(final double latFrom, final double lonFrom, final double latTo, final double lonTo) {
final double meridianLength = 111.1;
return meridianLength * centralAngle(latFrom, lonFrom, latTo, lonTo);
}
protected double centralAngle(final Location from, final Location to) {
return centralAngle(from.getLatitude(), from.getLongitude(), to.getLatitude(), to.getLongitude());
}
protected double centralAngle(final double latFrom, final double lonFrom, final double latTo, final double lonTo) {
final double latFromRad = toRadians(latFrom),
lonFromRad = toRadians(lonFrom),
latToRad = toRadians(latTo),
lonToRad = toRadians(lonTo);
final double centralAngle = toDegrees(acos(sin(latFromRad) * sin(latToRad) + cos(latFromRad) * cos(latToRad) * cos(lonToRad - lonFromRad)));
return centralAngle <= 180.0 ? centralAngle : (360.0 - centralAngle);
}
protected double distanceInKilometers(final Location from, final Location to) {
return distanceInKilometers(from.getLatitude(), from.getLongitude(), to.getLatitude(), to.getLongitude());
}
}
From Guppy:
import geocoders
g = geocoders.GoogleV3()
place, (lat, lng) = g.geocode('Fairbanks')
print place, (lat, lng)
Fairbanks, AK, USA (64.8377778, -147.7163889)
timezone = g.timezone((lat, lng))
print timezone.dst
Bound method America/Anchorage.dst of DstTzInfo
America/Anchorage' LMT-1 day, 14:00:00 STD
by using latitude and longitude get time zone of current location below code worked for me
String data = null;
LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
Location ll = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
double lat = 0,lng = 0;
if(ll!=null){
lat=ll.getLatitude();
lng=ll.getLongitude();
}
System.out.println(" Last known location of device == "+lat+" "+lng);
InputStream iStream = null;
HttpURLConnection urlConnection = null;
try{
timezoneurl = timezoneurl+"location=22.7260783,75.8781553&timestamp=1331161200";
// timezoneurl = timezoneurl+"location="+lat+","+lng+"&timestamp=1331161200";
URL url = new URL(timezoneurl);
// Creating an http connection to communicate with url
urlConnection = (HttpURLConnection) url.openConnection();
// Connecting to url
urlConnection.connect();
// Reading data from url
iStream = urlConnection.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(iStream));
StringBuffer sb = new StringBuffer();
String line = "";
while( ( line = br.readLine()) != null){
sb.append(line);
}
data = sb.toString();
br.close();
}catch(Exception e){
Log.d("Exception while downloading url", e.toString());
}finally{
try {
iStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
urlConnection.disconnect();
}
try {
if(data!=null){
JSONObject jobj=new JSONObject(data);
timezoneId = jobj.getString("timeZoneId");
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
format.setTimeZone(TimeZone.getTimeZone(timezoneId));
Calendar cl = Calendar.getInstance(TimeZone.getTimeZone(timezoneId));
System.out.println("time zone id in android == "+timezoneId);
System.out.println("time zone of device in android == "+TimeZone.getTimeZone(timezoneId));
System.out.println("time fo device in android "+cl.getTime());
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
For those of us using Javascript and looking to get a timezone from a zip code via Google APIs, here is one method.
Fetch the lat/lng via geolocation
fetch the timezone by pass that
into the timezone API.
Using Luxon here for timezone conversion.
Note: my understanding is that zipcodes are not unique across countries, so this is likely best suited for use in the USA.
const googleMapsClient; // instantiate your client here
const zipcode = '90210'
const myDateThatNeedsTZAdjustment; // define your date that needs adjusting
// fetch lat/lng from google api by zipcode
const geocodeResponse = await googleMapsClient.geocode({ address: zipcode }).asPromise();
if (geocodeResponse.json.status === 'OK') {
lat = geocodeResponse.json.results[0].geometry.location.lat;
lng = geocodeResponse.json.results[0].geometry.location.lng;
} else {
console.log('Geocode was not successful for the following reason: ' + status);
}
// prepare lat/lng and timestamp of profile created_at to fetch time zone
const location = `${lat},${lng}`;
const timestamp = new Date().valueOf() / 1000;
const timezoneResponse = await googleMapsClient
.timezone({ location: location, timestamp: timestamp })
.asPromise();
const timeZoneId = timezoneResponse.json.timeZoneId;
// adjust by setting timezone
const timezoneAdjustedDate = DateTime.fromJSDate(
myDateThatNeedsTZAdjustment
).setZone(timeZoneId);
If you prefer to avoid a web service, you can retrieve that information from the browser like this:
var d = new Date();
var usertime = d.toLocaleString();
//some browsers / OSs provide the timezone name in their local string
var tzsregex = /\b(ACDT|ACST|ACT|ADT|AEDT|AEST|AFT|AKDT|AKST|AMST|AMT|ART|AST|AWDT|AWST|AZOST|AZT|BDT|BIOT|BIT|BOT|BRT|BST|BTT|CAT|CCT|CDT|CEDT|CEST|CET|CHADT|CHAST|CIST|CKT|CLST|CLT|COST|COT|CST|CT|CVT|CXT|CHST|DFT|EAST|EAT|ECT|EDT|EEDT|EEST|EET|EST|FJT|FKST|FKT|GALT|GET|GFT|GILT|GIT|GMT|GST|GYT|HADT|HAEC|HAST|HKT|HMT|HST|ICT|IDT|IRKT|IRST|IST|JST|KRAT|KST|LHST|LINT|MART|MAGT|MDT|MET|MEST|MIT|MSD|MSK|MST|MUT|MYT|NDT|NFT|NPT|NST|NT|NZDT|NZST|OMST|PDT|PETT|PHOT|PKT|PST|RET|SAMT|SAST|SBT|SCT|SGT|SLT|SST|TAHT|THA|UYST|UYT|VET|VLAT|WAT|WEDT|WEST|WET|WST|YAKT|YEKT)\b/gi;
//in other browsers the timezone needs to be estimated based on the offset
var timezonenames = {"UTC+0":"GMT","UTC+1":"CET","UTC+2":"EET","UTC+3":"EEDT","UTC+3.5":"IRST","UTC+4":"MSD","UTC+4.5":"AFT","UTC+5":"PKT","UTC+5.5":"IST","UTC+6":"BST","UTC+6.5":"MST","UTC+7":"THA","UTC+8":"AWST","UTC+9":"AWDT","UTC+9.5":"ACST","UTC+10":"AEST","UTC+10.5":"ACDT","UTC+11":"AEDT","UTC+11.5":"NFT","UTC+12":"NZST","UTC-1":"AZOST","UTC-2":"GST","UTC-3":"BRT","UTC-3.5":"NST","UTC-4":"CLT","UTC-4.5":"VET","UTC-5":"EST","UTC-6":"CST","UTC-7":"MST","UTC-8":"PST","UTC-9":"AKST","UTC-9.5":"MIT","UTC-10":"HST","UTC-11":"SST","UTC-12":"BIT"};
var timezone = usertime.match(tzsregex);
if (timezone) {
timezone = timezone[timezone.length-1];
} else {
var offset = -1*d.getTimezoneOffset()/60;
offset = "UTC" + (offset >= 0 ? "+" + offset : offset);
timezone = timezonenames[offset];
}
//there are 3 variables can use to see the timezone
// usertime - full date
// offset - UTC offset time
// timezone - country
console.log('Full Date: ' + usertime);
console.log('UTC Offset: ' + offset);
console.log('Country Code Timezone: ' + timezone);
In my current case it is printing:
Full Date: ‎27‎/‎01‎/‎2014‎ ‎16‎:‎53‎:‎37
UTC Offset: UTC-3
Country Code Timezone: BRT
Hope it can be helpful.
function jsonpRequest(url, data)
{
let params = "";
for (let key in data)
{
if (data.hasOwnProperty(key))
{
if (params.length == 0)
{
params += "?";
}
else
{
params += "&";
}
let encodedKey = encodeURIComponent(key);
let encodedValue = encodeURIComponent(data[key]);
params += encodedKey + "=" + encodedValue;
}
}
let script = document.createElement('script');
script.src = url + params;
document.body.appendChild(script);
}
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition);
} else {
x.innerHTML = "Geolocation is not supported by this browser.";
}
}
let lat_ini=[]; let lon_ini=[];
function showPosition(position) {
lat_ini= position.coords.latitude;
lon_ini= position.coords.longitude;
}
////delay time between lines
function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
///////
function getGMT()
{
getfinalGMT()
getLocation()
async function sample() {
await sleep(2000);
let lat_str=lat_ini.toString();
let lng_str=" "+lon_ini.toString();
let url = "https://api.opencagedata.com/geocode/v1/json";
let data = {
callback: "displayGMT",
q: lat_str + lng_str,
key: "fac4471073a347019196c1291e6a97d7"
}
jsonpRequest(url, data)
}
sample();
}
let your_GMT=[];
function displayGMT(data)
{
your_GMT=(Number(data.results[0].annotations.timezone.offset_string))
console.log(your_GMT)
}
/////
function getfinalGMT()
{
let lat=document.getElementById("lat_id").value; let lng=document.getElementById("lng_id").value;
let lat_str=lat.toString();
let lng_str=" "+lng.toString();
let url = "https://api.opencagedata.com/geocode/v1/json";
let data = {
callback: "displayfinalGMT",
q: lat + lng_str,
key: "fac4471073a347019196c1291e6a97d7"
}
jsonpRequest(url, data)
}
let final_GMT=[];
function displayfinalGMT(data)
{
final_GMT=(Number(data.results[0].annotations.timezone.offset_string))
console.log(final_GMT)
}
/////clock
const hourHand = document.querySelector('[data-hour-hand]')
const minuteHand = document.querySelector('[data-minute-hand]')
const secondHand = document.querySelector('[data-second-hand]')
let dif_overall=[];
function setClock() {
let gmt_diff=Number(your_GMT-final_GMT)/100
if (gmt_diff>12){
dif_overall=gmt_diff-12
}
else{
dif_overall=gmt_diff
}
console.log(dif_overall)
const currentDate = new Date()
const secondsRatio = currentDate.getSeconds() / 60
const minutesRatio = (secondsRatio + currentDate.getMinutes()) / 60
const hoursRatio = (minutesRatio + currentDate.getHours() - dif_overall ) / 12
setRotation(secondHand, secondsRatio)
setRotation(minuteHand, minutesRatio)
setRotation(hourHand, hoursRatio)
}
function setRotation(element, rotationRatio) {
element.style.setProperty('--rotation', rotationRatio * 360)
}
function activate_clock(){
setClock()
setInterval(setClock, 1000)
}
*, *::after, *::before {
box-sizing: border-box;
}
body {
background: linear-gradient(to right, hsl(200, 100%, 50%), hsl(175, 100%, 50%));
display: flex;
justify-content: center;
align-items: center;
min-height: 100vh;
overflow: hidden;
}
.clock {
width: 200px;
height: 200px;
background-color: rgba(255, 255, 255, .8);
border-radius: 50%;
border: 2px solid black;
position: relative;
}
.clock .number {
--rotation: 0;
position: absolute;
width: 100%;
height: 100%;
text-align: center;
transform: rotate(var(--rotation));
font-size: 1.5rem;
}
.clock .number1 { --rotation: 30deg; }
.clock .number2 { --rotation: 60deg; }
.clock .number3 { --rotation: 90deg; }
.clock .number4 { --rotation: 120deg; }
.clock .number5 { --rotation: 150deg; }
.clock .number6 { --rotation: 180deg; }
.clock .number7 { --rotation: 210deg; }
.clock .number8 { --rotation: 240deg; }
.clock .number9 { --rotation: 270deg; }
.clock .number10 { --rotation: 300deg; }
.clock .number11 { --rotation: 330deg; }
.clock .hand {
--rotation: 0;
position: absolute;
bottom: 50%;
left: 50%;
border: 1px solid white;
border-top-left-radius: 10px;
border-top-right-radius: 10px;
transform-origin: bottom;
z-index: 10;
transform: translateX(-50%) rotate(calc(var(--rotation) * 1deg));
}
.clock::after {
content: '';
position: absolute;
background-color: black;
z-index: 11;
width: 15px;
height: 15px;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
border-radius: 50%;
}
.clock .hand.second {
width: 3px;
height: 45%;
background-color: red;
}
.clock .hand.minute {
width: 7px;
height: 40%;
background-color: black;
}
.clock .hand.hour {
width: 10px;
height: 35%;
background-color: black;
}
/* Background Styles Only */
#import url('https://fonts.googleapis.com/css?family=Raleway');
* {
font-family: Raleway;
}
.side-links {
position: absolute;
top: 15px;
right: 15px;
}
.side-link {
display: flex;
align-items: center;
justify-content: center;
text-decoration: none;
margin-bottom: 10px;
color: white;
width: 180px;
padding: 10px 0;
border-radius: 10px;
}
.side-link-youtube {
background-color: red;
}
.side-link-twitter {
background-color: #1DA1F2;
}
.side-link-github {
background-color: #6e5494;
}
.side-link-text {
margin-left: 10px;
font-size: 18px;
}
.side-link-icon {
color: white;
font-size: 30px;
}
<input type="text" id="lat_id" placeholder="lat"><br><br>
<input type="text" id="lng_id" placeholder="lng"><br><br>
<button class="text" onClick="getLocation()">Location</button>
<button class="text" onClick="getGMT()"> GMT</button>
<button class="text" onClick="activate_clock()"> Activate</button>
<div class="clock">
<div class="hand hour" data-hour-hand></div>
<div class="hand minute" data-minute-hand></div>
<div class="hand second" data-second-hand></div>
<div class="number number1">1</div>
<div class="number number2">2</div>
<div class="number number3">3</div>
<div class="number number4">4</div>
<div class="number number5">5</div>
<div class="number number6">6</div>
<div class="number number7">7</div>
<div class="number number8">8</div>
<div class="number number9">9</div>
<div class="number number10">10</div>
<div class="number number11">11</div>
<div class="number number12">12</div>
</div>

How to check file size of each file before uploading multiple files in ajaxtoolkit ajaxfileupload control in asp.net?

<cc1:AjaxFileUpload ID="AjaxFileUpload1" AllowedFileTypes="jpg,jpeg"
runat="server" MaximumNumberOfFiles="4" OnUploadComplete="AjaxFileUpload1_UploadComplete"
/>
Code behind file
protected void AjaxFileUpload1_UploadComplete(object sender, AjaxControlToolkit.AjaxFileUploadEventArgs e)
{
if (e.FileSize > 10)
{
string filePath = e.FileName;
AjaxFileUpload1.SaveAs(Server.MapPath(filePath));
}
else
{
}
}
I want to check that all the files size should not exceed a particular value before the files upload event.
Try this way:
Server side:
protected void AjaxFileUpload1_UploadComplete(object sender, AjaxControlToolkit.AjaxFileUploadEventArgs e)
{
try
{
string savePath = MapPath("~/Images/" + e.FileName);
// dont save file & return if condition not matched.
if (e.FileSize > 72000) // use same condition in client side code
{
return;
}
AjaxFileUpload1.SaveAs(savePath);
}
catch (Exception ex)
{
throw ex;
}
}
and on client side:
<script type="text/javascript">
function UploadComplete(sender, args) {
var filesize = args.get_fileSize();
var fileId = args.get_fileId();
var status = document.getElementById('AjaxFileUpload1_FileItemStatus_' + fileId);
var container = document.getElementById('AjaxFileUpload1_FileInfoContainer_' + fileId);
if (filesize > 72000) { // same condition used for server side
document.getElementById('lblStatus').innerText = "error";
if (status.innerText) {
status.innerText = " (Error)";
}
if (status.textContent) {
status.textContent = " (Error)";
}
container.style.color = 'Red';
}
}
</script>
<cc1:AjaxFileUpload ID="AjaxFileUpload1" AllowedFileTypes="jpg,jpeg" runat="server" MaximumNumberOfFiles="4" OnUploadComplete="AjaxFileUpload1_UploadComplete" OnClientUploadComplete="UploadComplete" />
Hope this helps!!
<script type="text/javascript">
$(".ajax__fileupload_dropzone").bind("drop", function () {
checkfilesize();
});
$(".ajax__fileupload_queueContainer").bind("click", function () {
checkfilesize();
});
$(".ajax__fileupload_uploadbutton").bind("mouseenter", function () {
checkfilesize();
});
function checkfilesize() {
var total_filesize_num = 0;
var myElements = $(".filesize");
if (myElements.length == 0) {
$(".ajax__fileupload_uploadbutton").css("visibility", "hidden");
return;
}
for (var i = 0; i < myElements.length; i++) {
var filesize = myElements.eq(i).html(); //$(".filesize").html();
total_filesize_num = total_filesize_num + filesize_tonum(filesize);
}
if (total_filesize_num > 5) {
$(".ajax__fileupload_uploadbutton").css("visibility", "hidden");
alert('Maximum file size is 5MB only! Please select another one.');
return;
} else {
$(".ajax__fileupload_uploadbutton").css("visibility", "visible");
}
}
function countsumfilesize() {
var sumfilesize = 0;
var myElements = $(".filesize");
for (var i = 0; i < myElements.length; i++) {
alert(myElements.eq(i).html());
}
}
function filesize_tonum(filesize) {
var filesize_num = 0;
if (filesize.indexOf("kb") > 0) {
var space = filesize.lastIndexOf(" ");
filesize_num = parseFloat("0." + filesize.substr(0, filesize.length - space + 1));
}
else if (filesize.indexOf("MB") > 0) {
var space = filesize.lastIndexOf(" ");
filesize_num = parseFloat(filesize.substr(0, filesize.length - space + 1));
}
return filesize_num;
}
</script>
<ajaxToolkit:AjaxFileUpload ID="AjaxFileUploadImage" runat="server" OnClientUploadComplete="uploadComplete" MaximumNumberOfFiles="1" AllowedFileTypes="gif,png,jpg,jpeg" onchange="checkfilesize(); return false;" />
See the code below:
public void afuUpload_UploadedComplete(object sender, AsyncFileUploadEventArgs e)
{
try
{
string savePath = MapPath("~/Uploads/" + Path.GetFileName(e.filename));
if (int.Parse(e.filesize) > 3000000)
{
return;
}
afuUpload.SaveAs(savePath);
}
catch (Exception ex)
{
throw ex;
}}
The idea is to prevent the file is uploaded to the server. In the proposed solution, when the flow code has reached afuUpload_UploadedComplete, the file was uploaded to server, but has not yet been recorded in the path you specify. For example, if the limit is 20 megabytes and the selected file is 22 megabytes, when the code reaches afuUpload_UploadedComplete, 22 Megabytes already been uploaded to the server.
The solution sought is that the validation is done on the client side (JavaScript) and that prevents the code arrives to CodeBehind on the server.
In my case, I tried to OnClientUploadComplete generating an exception when the file size limit is exceeded, but it did not work and the code is still reaching the CodeBehind. The other problem is that when the exception occurs, the JavaScript function OnClientUploadError is not firing to intercept the exception generated in OnClientUploadComplete function.
Controller
[HttpPost]
public ActionResult Create(string Album, Photo photo, IEnumerable<HttpPostedFileBase> files, DateTime? datec, string NewAlbum = null)
{
.....
foreach (var file in files)
{
decimal sum = file.ContentLength / 1048;
if (sum > 4000)
{
errorlist2 += "Sorry " + file.FileName + " has exceeded its file limit off 4 MB <br/>";
}
}
if (errorlist2 != "")
{
ViewBag.Error = errorlist2;
return View(photo);
}
// we dont want put the message in the loop it will come out on first max limit , rather find all files in excess, then we can pass the message
//also make sure your web config is set for a limit on max size
//using the normal html multi uploaded
// <input type="file" name="files" id="files" required multiple="multiple" accept=".jpg, .png, .gif" size="4" />

signalR - how to call server method from client - code not working

When I try calling SendNewOrderConfirmation on the server side from the client I get
"undefined" is not a function
on line chat.SendNewOrderConfirmation(data);
does anyone know why is this happening?
Thank you
on the server side
public class DriverChat : Hub, IDisconnect
{
public void Start(Driver d)
{
...
}
public void SendNewOrderConfirmation(OrderDriverData data)
{
LogFile.LogResponseTime(data.orderId, data.driverId);
}
}
on the client side
function begin(args) {
try {
//alert('begin');
chat = $.connection.driverChat;
chat.refresh = function () {
ready++;
};
chat.disconnect = function () {
alert('Server has disconnected');
};
$.connection.hub.start(function () {
chat.start(args);
ready++;
// alert('signalR started');
});
} catch (e) {
alert(e.message);
return e.message;
}
}
function confirmNewOrder(data) {
try{
alert('sending cofirmation');
chat.SendNewOrderConfirmation(data);
alert('confirmation sent');
} catch (e) {
alert(e);
}
};
}
Depending on the version of SignalR which you are using, the answer could be different.
To begin with, if you are on a version prior to v1 Alpha, then your code should be;
chat.sendNewOrderConfirmation(data);
Notice the lowercase s.
If you are on version v1 Alpha or greater, then you code should be;
chat.server.sendNewOrderConfirmation(data);
You have to register the hub's javascript generated file. Add this to your page (or your master page):
<script src="<%: ResolveUrl("~/signalr/hubs") %>"></script>

PhoneGap File Transfer Error (code: 3, http_status: 404) on iPhone

I am trying to create an iOS app using PhoneGap that will allow a user to upload photos to a web server. Here is my code.
<!DOCTYPE html>
<html>
<head>
<title>Capture Photo</title>
<script type="text/javascript" charset="utf-8" src="cordova-1.9.0.js"></script>
<script type="text/javascript" charset="utf-8">
// Wait for PhoneGap to load
document.addEventListener("deviceready", onDeviceReady, false);
// PhoneGap is ready
function onDeviceReady() {
// Do cool things here...
}
function getImage() {
// Retrieve image file location from specified source
navigator.camera.getPicture(uploadPhoto, function(message) {
alert('get picture failed');
},{
quality: 50,
destinationType: navigator.camera.DestinationType.FILE_URI,
sourceType: navigator.camera.PictureSourceType.PHOTOLIBRARY
}
);
}
function uploadPhoto(imageURI) {
var options = new FileUploadOptions();
options.fileKey="recFile";
options.fileName=imageURI.substr(imageURI.lastIndexOf('/')+1);
options.mimeType="image/jpeg";
var params = new Object();
params.value1 = "test";
params.value2 = "param";
options.params = params;
var ft = new FileTransfer();
ft.upload(imageURI, "http://someWebSite.com/Testing/SaveImage.asmx/SaveImage", win, fail, options, true);
}
function win(r) {
console.log("Code = " + r.responseCode);
console.log("Response = " + r.response);
console.log("Sent = " + r.bytesSent);
}
function fail(error) {
alert("An error has occurred: Code = " + error.code);
alert("source = " + error.source);
alert("http_status = " + error.http_status);
console.log("upload error source " + error.source);
console.log("upload error target " + error.target);
}
</script>
</head>
<body>
<button onclick="getImage();">Upload a Photo</button>
</body>
Is anything wrong with my index.html file, or is the problem with the ASMX file?
Whenever I try to test this out on a 4th generation iPod Touch, I get the following error message:
2012-07-09 16:24:03.257 Test1[916:707] File Transfer Finished with response code 404
2012-07-09 16:24:03.260 Test1[916:707] FileTransferError {
code = 3;
"http_status" = 404;
source = "http://someWebSite.com/Testing/SaveImage.asmx/SaveImage";
target = "file://localhost/var/mobile/Applications/5DD01E68-02F7-410B-996A- 2D70BF1A61D3/tmp/cdv_photo_046.jpg";}
2012-07-09 16:24:07.137 Test1[916:707] ERROR: Plugin 'Debug Console' not found, or is not a CDVPlugin. Check your plugin mapping in Cordova.plist.
You can follow this example Upload image from android phonegap to a server using asmx
Or
A simple example
the js
<!DOCTYPE HTML>
<html>
<head>
<title>Cordova</title>
<link rel="stylesheet" href="style.css" media="screen" />
<script type="text/javascript" charset="utf-8" src="cordova-2.0.0.js"></script>
<script type="text/javascript" charset="utf-8" src="jquery-1.7.2.min.js"></script>
<script type="text/javascript" charset="utf-8">
var pictureSource; // picture source
var destinationType; // sets the format of returned value
document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady() {
pictureSource = navigator.camera.PictureSourceType;
destinationType = navigator.camera.DestinationType;
}
</script>
</head>
<body>
<script type="text/javascript" charset="utf-8">
var myData = "";
$(document).ready(function() {
$("#getDataFromServer").click(function() {
var imageData = myData;
$.ajax({
type : "POST",
url : 'http://my.domain.name/saveImage.ashx',
data : {
image : imageData
},
beforeSend : function() {
$("#comment2").text("Start ajax " + imageData.length);
},
success : function(data) {
$("#comment2").text("Uploaded! " + data);
},
error : function(request, error) {
$("#comment2").text("Error! " + error);
}
});
});
})
function capturePhotoEdit(source) {
navigator.camera.getPicture(onPhotoDataSuccess, onFail, {
quality : 50,
destinationType : destinationType.DATA_URL,
sourceType : source
});
}
function onFail(message) {
alert('Failed because: ' + message);
}
function onPhotoDataSuccess(imageData) {
console.log(imageData);
var smallImage = document.getElementById('smallImage');
smallImage.style.display = 'block';
smallImage.src = "data:image/jpeg;base64," + imageData;
myData = imageData;
$("#comment").text(imageData.length);
}
</script>
<h1>Hello World</h1>
<p>
<a href="#" onclick="capturePhotoEdit(pictureSource.PHOTOLIBRARY);">get
image</a>
</p>
<p>
send image
</p>
<span id="comment2"></span>
<img style="display: none; width: 100px; height: 100px;"
id="smallImage" src="" />
<span id="imagename"></span>
<span id="comment"></span>
the asp.net handler saveImage.ashx
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.IO;
using System.Text;
namespace Recepies
{
/// <summary>
/// Summary description for saveImage
/// </summary>
public class saveImage : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
try
{
string filePath = "";
filePath = context.Server.MapPath(".");
string fileName = RandomString(10);
string myImage = context.Request.Form["image"];
if (myImage.Length > 0)
{
File.WriteAllBytes(filePath + "/upload/" + fileName + ".jpg", Convert.FromBase64String(myImage));
context.Response.ContentType = "text/plain";
context.Response.Write("File was saved - " + fileName + ".jpg");
}
else
{
context.Response.ContentType = "text/plain";
context.Response.Write("File was not saved");
}
}
catch (Exception ex)
{
context.Response.ContentType = "text/plain";
context.Response.Write(ex.Message);
}
}
private static Random random = new Random((int)DateTime.Now.Ticks);//thanks to McAden
private string RandomString(int size)
{
StringBuilder builder = new StringBuilder();
char ch;
for (int i = 0; i < size; i++)
{
ch = Convert.ToChar(Convert.ToInt32(Math.Floor(26 * random.NextDouble() + 65)));
builder.Append(ch);
}
return builder.ToString();
}
public bool IsReusable
{
get
{
return false;
}
}
}
}
I've been having the same issue (on iOS7). The solution that worked for me was to add the "saveToPhotoAlbum" parameter.
navigator.camera.getPicture(success, fail, {
quality: 80,
destinationType: Camera.DestinationType.FILE_URI,
sourceType: Camera.PictureSourceType.CAMERA,
saveToPhotoAlbum: true
});

Resources