I have a webservice written in c# used by a Windows phone cliente and working.
So i develop a html5/jquery to use that same asmx service and Works!
When i try to access this html page from a remote machine(other than the host for the pages and servisse) it fails.
is there any special configuration for this scenario?
The only difference is, changed from localhost in the address of the ajax call to webservice to the fixed ip of the host, same i did to publish to the phone device.
Here is the code
$.ajax({
url: "http://localhost:8000/services/webservice.asmx/RetornaPedidoPorMesa",
type: "POST",
dataType: "text",
data: { NumeroMesa: parseInt(querystring("numeroMesa")),
CodigoSeguranca: parseInt(querystring("codigo")) },
success: function (response) {
var xml = $(response);
if (xml.find("Retorno").text() != "") {
var list = $("#pedido").find('ul');
$("#ulPedido li").remove();
list.append("<li>Voçê não tem permissão para acessar o pedido</li>");
} else {
if (xml.find("Total") != "") {
var list = $("#pedido").find('ul');
$("#ulPedido li").remove();
list.append("<li>" + "Mesa " + querystring("numeroMesa") + " - " + "R$ " + xml.find("Total").first().text() + "</li>");
}
if (xml.find("Items") != "") {
if (xml.find("RetornoItems") != "") {
var list = $("#produtos").find('ul');
$("#ulProdutos li").remove();
$(xml.find("RetornoItems")).each(function myfunction() {
if (parseInt($(this).find("Quantidade").first().text()) > 0)
list.append("<li>" + $(this).find("Descricao").text() + "<div style='float:right\;margin-left:30px;margin-top:10px'>" + parseInt($(this).find("Quantidade").first().text()) + " x R$ " + $(this).find("ValorUnitario").first().text() + " = R$ " + $(this).find("Total").first().text() + "</div></li>");
});
}
}
}
},
error: function (response) {
alert("erro de acesso ao serviço.");
}
});
Any help? thanks in advance...
Related
I'm building an application to configure some software components from a web GUI.
For one of my configuration components, I'm loading an executable to pick an sftp folder. This sftp path is stored together with other variables in a json file, which is then displayed in the input fields.
The cshtml code:
<button class="btn btn-primary" onclick="browseSftp()">Select SFTP folder</button>
function browseSftp() {
window.$.ajax({
type: "POST",
url: "/BackupConfiguration?handler=BrowseSftp",
contentType: "application/json; charset=utf-8",
beforeSend: function (xhr) {
xhr.setRequestHeader("XSRF-TOKEN",
window.$('input:hidden[name="__RequestVerificationToken"]').val());
},
data: JSON.stringify({
autoBackup: $('input[name="FormData.autoBackup"]:checked').val(),
backupTime: $('#FormData_backupTime').val(),
keepAllBackups: $('input[name="FormData.keepAllBackups"]:checked').val(),
backupsKept: $('#FormData_backupsKept').val(),
hostName: $('#FormData_hostName').val(),
hostKey: $('#FormData_hostKey').val(),
port: $('#FormData_port').val(),
username: $('#FormData_username').val(),
password: $('#FormData_password').val(),
remoteFolder: $('#FormData_remoteFolder').val(),
localFolder: $('#FormData_localFolder').val(),
isLocal: $('input[name="FormData.isLocal"]:checked').val(),
}),
success: function (response) {
alert("success");
}
});
};
in my cshtml.cs code:
public void OnPostBrowseSftp([FromBody] FormData formData)
{
//string[] args = { FormData.autoBackup, FormData.backupTime, FormData.keepAllBackups, FormData.backupsKept, FormData.hostName, FormData.hostKey, FormData.port, FormData.username, FormData.password, FormData.remoteFolder, FormData.localFolder, "TRUE" };
string[] args = {FormData.hostName, FormData.username, FormData.password};
if(formData.autoBackup == null)
{
formData.autoBackup = "false";
}
if(formData.keepAllBackups == null)
{
formData.keepAllBackups = "false";
}
var process = System.Diagnostics.Process.Start(_browseSftpScript, formData.hostName + " " + formData.username + " " + formData.password + " " + formData.autoBackup + " " + formData.backupTime + " " + formData.keepAllBackups + " " + formData.backupsKept + " " + formData.port + " " + formData.isLocal + " " + _jsonPath);
process.WaitForExit();
Response.Redirect("/backupConfiguration");
}
Just re initializing the page with the onGet function would cause the fields to be populated, but somehow this is not done, only if I manually select another page and go back it's done:
public void OnGet()
{
if (HttpContext.Session.GetString(SettingName) == null || HttpContext.Session.GetString(SettingName) != "AlreadyLoaded")
{
HttpContext.Session.SetString(SettingName, "AlreadyLoaded");
if (System.IO.File.Exists(_systemSettingJsonPath))
{
FormData = SettingsService.GetData<FormData>(_systemSettingJsonPath);
SettingsService.SaveData(FormData, _jsonPath);
}
else
{
FormData = SettingsService.GetData<FormData>(_jsonPath);
}
}
else
{
FormData = SettingsService.GetData<FormData>(_jsonPath);
}
}
If I have a look at my logs, I think it's because the onGet function is called before the browseSftp request is finished.
2021-11-25 17:31:22.922 +01:00 [Microsoft.AspNetCore.Routing.EndpointMiddleware] [INF] Executed endpoint '/BackupConfiguration'
2021-11-25 17:31:22.922 +01:00 [Microsoft.AspNetCore.Hosting.Diagnostics] [INF] Request finished HTTP/1.1 POST http://localhost:5000/BackupConfiguration?handler=BrowseSftp application/json;+charset=UTF-8 228 - 200 - text/html;+charset=utf-8 705431.7372ms
I would expect that this would cause the process to be finished, and therefore the request to be done:
process.WaitForExit();
Response.Redirect("/backupConfiguration");
So to put it short, my goal is to trigger a reload of the page, after the process is finished.
Thanks for your input on this !
I am working on EF 4.1 code first development with MVC and c#.
This is my Requirement:
Is there any way to map 2 properties of my model class for same database column ?
B'cos I am having data retrieval issue like below.
Currently mapped property for db column having some complex calculation.
So that When I call it from my UI as a ajax call it retrieves calculated value as 0.0, b'cos of that calculation delay (when i put a debug and then slow the things it will correctly generate value).
If I set another field which does not having any calculation it shows correctly.
How to overcome above issue ?
Part of my model code as below.
public class Invoice
{
public Invoice() { Id = Guid.NewGuid(); Created = DateTime.Now; }
public Guid Id { get; set; }
public decimal LatestTotal { get; set; }
[NotMapped]
public decimal Total
{
get
{
return (LatestTotal = this.CalculateTotal());
}
}
}
Problematic property is LatestTotal
Action Method Looks like below
public ActionResult GetServiceAndRetailSalesDetails(Guid invoiceOrSaleId, string providerKey, DateTime checkoutDate, double checkoutTime)
{
var items = new List<CheckOutServiceAndRetailItem>();
TimeSpan timeResult = TimeSpan.FromHours(checkoutTime);
var checkOut = checkoutDate + timeResult;
var serviceDetails = Repository.GetAllPayableItems(checkOut, invoiceOrSaleId).ToList();
foreach (var s in serviceDetails)
{
var item = new CheckOutServiceAndRetailItem
{
AllocationOrInvoiceOrSaleId = s.Allocation.AllocationId,
Name = s.Allocation.Service.Name,
Price = s.LatestTotal,
//Price = s.Total,
Class = s.Allocation.Service.IsAnExtra ? "RetailOrExtraService" : "",
};
items.Add(item);
}
return Json(items, JsonRequestBehavior.AllowGet);
}
Ajax call from UI looks like below.
$.ajax({
type: "GET",
url: "/Portal/GetServiceAndRetailSalesDetails",
dataType: 'json',
contentType: "application/json; charset=UTF-8",
data: { invoiceOrSaleId: invoiceOrSaleId, providerKey: providerKey, checkoutDate: checkoutDate, checkoutTime: checkoutTime },
success: function (response) {
make = "<table id='tblPayment'>";
var totalToBepaid = 0.0;
toBePaidItems = [];
$.each(response, function (index, sr) {
if (unPaid) {
make += "<tr id=" + sr.AllocationOrInvoiceOrSaleId + " class=" + sr.Class + ">" + "<td style='padding-right:100px'>" + sr.Name + "</td><td class='colTotal' style='padding-right:45px'>" + '$ ' + sr.Price.toFixed(2) + "</td><td></tr>";
} else {
make += "<tr id=" + sr.AllocationOrInvoiceOrSaleId + " class=" + sr.Class + ">" + "<td style='padding-right:100px'>" + sr.Name + "</td><td class='colTotal' style='padding-right:45px'>" + '$ ' + sr.Price.toFixed(2) + "</td></tr>";
}
totalToBepaid += sr.Price;
//insert into array
toBePaidItems.push(sr.AllocationOrInvoiceOrSaleId);
});
var lateFee = parseFloat($("#hdnLateFee").val());
if (lateFee > 0) {
totalToBepaid += lateFee;
make += "<tr class='Fees'><td style='padding-right:100px'>Late Pickup Fee</td><td class='colTotal' style='padding-right:45px'>" + '$ ' + lateFee + "</td></tr>";
}
make += "</table>";
$("#serviceAndRetailDetails").html(make);
}
});
UI Image as below (when I put a brake point and run then correct value shows)
I'm currently working on an ASP.NET project where I'm using the Google Maps API to show a marker for every company that's registrated in the database.
Everything works just fine, but when I click on a marker the tooltip/dialogbox for the last company in my company list always shows up and not the actualy company mark that's been clicked on.
I can't really get my head around why it is always the last marker that shows up. Here's my updated code:
JavaScript.Text = #"<script type='text/javascript'>
function load() {
if (GBrowserIsCompatible()) {
var map = new GMap2(document.getElementById('map'));
map.setCenter(new GLatLng(56.4, 10.57983), 9);
map.enableScrollWheelZoom();
}
}
</script> ";
foreach (MemberProfile m in relatedMembers)
{
XmlDocument doc = new XmlDocument();
string address = m.Address;
string zip = m.Zip;
string city = m.City;
string navn = m.Name;
string tlf = m.Phone;
doc.Load("http://maps.googleapis.com/maps/api/geocode/xml?address=" + zip + "+" + city + "+" + address + "+DK&sensor=true&key=ABQIAAAAEaY4JLb9fZFGMlDKuMUlWBRSvyGIkBO7X03pzlT7Z30EPXHR8BS0rXL_ShFm2gc79lZTw2Zak88wng");
XmlNode latNode = doc.SelectSingleNode("GeocodeResponse/result/geometry/location/lat/text()");
XmlNode lonNode = doc.SelectSingleNode("GeocodeResponse/result/geometry/location/lng/text()");
if (latNode != null && lonNode != null)
{
JSAddMarkers.Text += #"<script type='text/javascript'>
var marker = new GMarker(new GLatLng(" + latNode.Value + "," + lonNode.Value + ")); "
+ "var html = '<b>" + navn + "</b><br />" + address + "<br /> " + zip + " " + city + "<br />" + tlf + "'; " + "GEvent.addListener(marker, 'click', function() { marker.openInfoWindowHtml(html); });"
+ "map.addOverlay(marker);"
+ "</script>";
}
If any of you out there can spot the reason why, I would be happy to hear from you! Any help/hint is appreciated :-)
All the best,
Bo
try this
var point =new GLatLng(" + latNode.Value + "," + lonNode.Value + ");
var marker = createMarker(point, address,zip,city,navn);
map.addOverlay(marker);
function createMarker(point, address, zip,city, navn) {
var marker = new GMarker(point, customIcons[type]);
var html = "Address:<b style='padding-left:6px'>" + address+ "</b><br/>zip:<b style='padding-left:6px'>"+ zip+ "</b><br/>city:<b style='padding-left:6px'>"+ city+ "</b>";
GEvent.addListener(marker, 'mouseover', function() {
marker.openInfoWindowHtml(html);
});
GEvent.addListener(marker, "mouseout", function() {
marker.closeInfoWindow();
});
return marker;
}
I have a jQuery method that calls a .asmx web service. The jQuery method only executes one time but the web service executes multiple times.
this is the jQuery code that call the web service
// Expand copy to group modal groups
$(".groupZones .expand").live('click', function() {
$(this).siblings('.contract').show();
$(this).css('display', 'none');
$(this).parent().parent().siblings('.groupDetails').css('display', 'block');
$(this).parent().parent().siblings('.groupDetails').find('ul.device').find('ul .list').after('');
var cwpUserId = $('#ctl00_cphBody_hfCwpId').val();
var groupId = $(this).parent().siblings('.add').find('input').val();
sortOn = "Location";
var mode = "dayparts";
var groupUl = $(this).parent().parent().siblings('.groupDetails').find('ul').find('ul li.head');
var groupDetails = $(this).parent().parent().siblings('.groupDetails');
//Get the zone details..
// Load.
$.ajax({
type: "POST",
url: "ajax/DaypartMessagingGroups.asmx/GetDetailsForCopyToGroup",
data: "{'groupId':" + groupId + ",'cwpUserId':" + cwpUserId + ",'pageNum':0,'pageSize':5, 'sortOn':'" + sortOn + "','sortDirection':'" + sortDirection + "','mode':'" + mode + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
//$(btn).parents("ul.list-group-zones").children("li:.head").after(msg.d);
$(groupUl).after(msg.d);
$('.location').find('.contract').hide();
var copyZonePerPage = 5;
//var copyZoneItemsCount = $(groupUl).siblings('#hfAllGroupZones').val();
var copyZoneItemsCount = $('#hfAllGroupZones').val();
var copyZonePages = Math.ceil(copyZoneItemsCount / copyZonePerPage);
var copyZoneHtml = '';
var copyZoneCurLink = 0;
var current_copyzone_pagination_set = 1;
var num_of_pagination_shown = 0;
alert('Line 2113 CBG');
if (copyZonePages > 20) {
//var pagesAdded = (parseInt(current_copyzone_pagination_set) - 1) * 10;
while (num_of_pagination_shown < 20) {
copyZoneHtml += '<a class="page_link_clicked" longdesc="' + copyZoneCurLink + '">' + (copyZoneCurLink + 1) + '</a>';
copyZoneCurLink++;
num_of_pagination_shown++;
}
copyZoneHtml += '<a class="page_link" id="btnNextZoneSet" longdesc="' + copyZoneCurLink + '">...</a>';
}
else {
while (copyZonePages > copyZoneCurLink) {
copyZoneHtml += '<a class="page_link_clicked" longdesc="' + copyZoneCurLink + '">' + (copyZoneCurLink + 1) + '</a>';
copyZoneCurLink++;
}
}
$(groupUl).parent().parent().find('ul li.footer').html(copyZoneHtml);
$('.page_link_clicked[longdesc=0]').addClass('current');
},
error: function(err) {
var err = eval("(" + err.responseText + ")");
if (ShowModalLogin(err.ExceptionType)) {
alert("An error occurred.");
}
}
});
});
after doing more test i see that post is actually being repeated numberous times.
http://api.jquery.com/live/ states that
To stop further handlers from executing after one bound using .live(), the handler must return false. Calling .stopPropagation() will not accomplish this.
I am not sure if that applies here, but you could add a
return false;
at the end of your click handler and see if it works.
I need to separate IE and FF browsers from others
it's a pseudo-code :
If (CurrentBrowser == IE(6+) or FF(2+) )
{
...
}
else
{
...
}
in protected void Page_Load() event (think so)
if ((Request.Browser.Type == "IE") || (Request.Browser.Type == "FF"))
{
WebMsgBox.Show("1111");
}
no effects :-/ what is IE and FF types?
if (Request.Browser.Type.Contains("Firefox")) // replace with your check
{
...
}
else if (Request.Browser.Type.ToUpper().Contains("IE")) // replace with your check
{
if (Request.Browser.MajorVersion < 7)
{
DoSomething();
}
...
}
else { }
Here's a way you can request info about the browser being used, you can use this to do your if statement
System.Web.HttpBrowserCapabilities browser = Request.Browser;
string s = "Browser Capabilities\n"
+ "Type = " + browser.Type + "\n"
+ "Name = " + browser.Browser + "\n"
+ "Version = " + browser.Version + "\n"
+ "Major Version = " + browser.MajorVersion + "\n"
+ "Minor Version = " + browser.MinorVersion + "\n"
+ "Platform = " + browser.Platform + "\n"
+ "Is Beta = " + browser.Beta + "\n"
+ "Is Crawler = " + browser.Crawler + "\n"
+ "Is AOL = " + browser.AOL + "\n"
+ "Is Win16 = " + browser.Win16 + "\n"
+ "Is Win32 = " + browser.Win32 + "\n"
+ "Supports Frames = " + browser.Frames + "\n"
+ "Supports Tables = " + browser.Tables + "\n"
+ "Supports Cookies = " + browser.Cookies + "\n"
+ "Supports VBScript = " + browser.VBScript + "\n"
+ "Supports JavaScript = " +
browser.EcmaScriptVersion.ToString() + "\n"
+ "Supports Java Applets = " + browser.JavaApplets + "\n"
+ "Supports ActiveX Controls = " + browser.ActiveXControls
+ "\n";
MSDN Article
Try the below code
HttpRequest req = System.Web.HttpContext.Current.Request
string browserName = req.Browser.Browser;
private void BindDataBInfo()
{
System.Web.HttpBrowserCapabilities browser = Request.Browser;
Literal1.Text = "<table border=\"1\" cellspacing=\"3\" cellpadding=\"2\">";
foreach (string key in browser.Capabilities.Keys)
{
Literal1.Text += "<tr><td>" + key + "</td><td>" + browser[key] + "</tr>";
}
Literal1.Text += "</table>";
browser = null;
}
I would not advise hacking browser-specific things manually with JS. Either use a javascript library like "prototype" or "jquery", which will handle all the specific issues transparently.
Or use these libs to determine the browser type if you really must.
Also see Browser & version in prototype library?
For browser compatibility you can use this code. This method returns browser name and version :
private string GetBrowserNameWithVersion
{
var userAgent = Request.UserAgent;
var browserWithVersion = "";
if (userAgent.IndexOf("Edge") > -1)
{
//Edge
browserWithVersion = "Edge Browser Version : " + userAgent.Split(new string[] { "Edge/" }, StringSplitOptions.None)[1].Split('.')[0];
}
else if (userAgent.IndexOf("Chrome") > -1)
{
//Chrome
browserWithVersion = "Chrome Browser Version : " + userAgent.Split(new string[] { "Chrome/" }, StringSplitOptions.None)[1].Split('.')[0];
}
else if (userAgent.IndexOf("Safari") > -1)
{
//Safari
browserWithVersion = "Safari Browser Version : " + userAgent.Split(new string[] { "Safari/" }, StringSplitOptions.None)[1].Split('.')[0];
}
else if (userAgent.IndexOf("Firefox") > -1)
{
//Firefox
browserWithVersion = "Firefox Browser Version : " + userAgent.Split(new string[] { "Firefox/" }, StringSplitOptions.None)[1].Split('.')[0];
}
else if (userAgent.IndexOf("rv") > -1)
{
//IE11
browserWithVersion = "Internet Explorer Browser Version : " + userAgent.Split(new string[] { "rv:" }, StringSplitOptions.None)[1].Split('.')[0];
}
else if (userAgent.IndexOf("MSIE") > -1)
{
//IE6-10
browserWithVersion = "Internet Explorer Browser Version : " + userAgent.Split(new string[] { "MSIE" }, StringSplitOptions.None)[1].Split('.')[0];
}
else if (userAgent.IndexOf("Other") > -1)
{
//Other
browserWithVersion = "Other Browser Version : " + userAgent.Split(new string[] { "Other" }, StringSplitOptions.None)[1].Split('.')[0];
}
return browserWithVersion;
}
I tried and found the solution for the same
public static string GetBrowserDetails()
{
string BrowserDetails = HttpContext.Current.Request.Browser.Browser + " - " + HttpContext.Current.Request.Browser.Version + "; Operating System : " + HttpContext.Current.Request.Browser.Platform;
return BrowserDetails;
}
OUTPUT :
Chrome - 88.0; Operating System : WinNT
use from
Request.Browser
this link will help you :
Detect the browser using ASP.NET and C#