Consume ASMX service using Sencha 2 - c#

I am just begining to learn Sencha.
I have an asmx that returns a List so the xml looks like;
<Result>
<string>One</string>
<string>Two><string>
</Results>
Now all I want to do is show that in a List.
So my Sench code looks like;
Ext.define('ListItem', {
extend: 'Ext.data.Model',
config: {
fields: ['text']
}
});
var treeStore = Ext.create('Ext.data.TreeStore', {
model: 'ListItem',
defaultRootProperty: 'items',
proxy: {
type: 'ajax',
url: 'http://localhost:81/MyASMX.asmx/Test'
}
});
Ext.application({
name: 'Sencha',
launch: function () {
Ext.create('Ext.NestedList', {
fullscreen: true,
store: treeStore,
detailCard: {
html: 'You are viewing the detail card!'
}
});
}
});
But I get an empty list with a title bar that is also empty.

With .Asmx you can also bind xml to your treestore
here is the code that might be help you
function BindData(dataxml)
{
dataxml = dataxml.replace(/>/g, ">");
dataxml = dataxml.replace(/</g, "<");
var doc;
if (window.ActiveXObject) { //IE
var doc = new ActiveXObject("Microsoft.XMLDOM");
doc.async = "false";
doc.loadXML(dataxml);
} else { //Mozilla
var doc = new DOMParser().parseFromString(dataxml, "text/xml");
}
var store = new Ext.getStore('treestore');
store.removeAll();
var DataLen = doc.getElementsByTagName('FirstNode').length;
for (var i = 0; i < DataLen; i++) {
var arrnodename = doc.getElementsByTagName('nodeName')[i].firstChild.nodeValue.replace(/\"/g, '');
var arrnodename2 = doc.getElementsByTagName('nodeName2')[i].firstChild.nodeValue.replace(/\"/g, '');
store.add({ C1: arrnodename[0], C2: arrnodename2[0]});
}
}

Related

JSON 404 error when I deploy on server with ASP.NET MVC 5

If I run the web application locally, it works fine, the markers and lines are displayed fine. If I deploy it and go to the server, http://localhost/map/markers and http://localhost/map/lines cannot be found. I have already added
<staticContent>
<remove fileExtension=".json" />
<mimeMap fileExtension=".json" mimeType="application/json" />
</staticContent>
in Web.config. What am I doing wrong? Here's the code:
MapController.cs
public class MapController : Controller
{
private DbData dbData;
private MapObjects mapObjects;
public MapController()
{
dbData = new DbData();
mapObjects = dbData.ReceiveDataFromDb();
}
public JsonResult Markers()
{
var points = mapObjects.Points;
/*using (var context = new ecc_web_page.DAL.MapContext()) {
IQueryable<Point> linqQuery = from p in context.PlaceMarker.OfType<Point>().Include("Coordinate") select p;
points = linqQuery.ToList();
}*/
var output = new List<dynamic>();
foreach (var point in points)
{
if (point.Coordinate != null)
output.Add(new { name = point.Name, lng = point.Coordinate.Longitude, lat = point.Coordinate.Latitude, z = 0, url = point.ExternalReference });
}
foreach (var s in output) {
}
return Json(output, JsonRequestBehavior.AllowGet);
}
public JsonResult Lines()
{
var lines = mapObjects.Lines;
/*using (var context = new ecc_web_page.DAL.MapContext())
{
IQueryable<LineString> linqQuery = from p in context.PlaceMarker.OfType<LineString>().Include("Coordinates") select p;
lines = linqQuery.ToList();
}*/
var output = new List<dynamic>();
foreach (var line in lines)
{
var coordinates = new List<dynamic>();
if (line.Coordinates != null)
{
foreach (var coord in line.Coordinates)
{
coordinates.Add(new { lng = coord.Longitude, lat = coord.Latitude });
}
}
output.Add(new { id = line.ID, coords = coordinates });
}
return Json(output, JsonRequestBehavior.AllowGet);
}
}
map.ts
var fetch: any;
var google: any;
var Promise: any;
var markersPromise = fetch(window.location.origin + "/map/markers").then(response => response.json());
var linesPromise = fetch(window.location.origin + "/map/lines").then(response => response.json());
function initMap() {
const standardMarker = "http://maps.google.com/mapfiles/ms/icons/red-dot.png";
const noticeMarker = "http://maps.google.com/mapfiles/ms/icons/blue-dot.png";
var map = new google.maps.Map(document.getElementById('map'), {
center: { lat: 0, lng: -180 },
zoom: 1
});
Promise.all([markersPromise, linesPromise]).then(values => {
var addedMarkers = [];
var bounds = new google.maps.LatLngBounds();
for (let marker of values[0]) {
const addedMarker = new google.maps.Marker({
position: { lat: marker.lat, lng: marker.lng },
map: map,
animation: google.maps.Animation.DROP,
title: marker.name,
icon: standardMarker,
url: marker.url
});
addedMarkers.push(addedMarker);
bounds.extend(addedMarker.getPosition());
addedMarker.addListener('click', function () {
/*document.getElementById("terminal-title").innerHTML = marker.name;
document.getElementById("terminal-view-btn").onclick = function () {
var query = '/Home/TerminalView?terminalUrl=' + marker.url;
window.location.href = query;*/
document.getElementById("terminal-iframe-wrap").style.display = 'inline';
document.getElementById("all-terminals-view").style.display = 'none';
(<HTMLIFrameElement>document.getElementById("terminal-iframe")).src = marker.url;
});
}
for (let line of values[1]) {
const coords = [];
for (let linePoint of line.coords) {
const latLng = { lat: linePoint.lat, lng: linePoint.lng };
coords.push(latLng);
bounds.extend(latLng);
}
const addedLine = new google.maps.Polyline({
path: coords,
geodesic: true,
strokeColor: "#FF0000",
strokeOpacity: 1.0,
strokeWeight: 2,
map: map
});
}
map.fitBounds(bounds);
setInterval(() => {
var randomMarker = addedMarkers[Math.floor((Math.random() * addedMarkers.length))];
randomMarker.setAnimation(google.maps.Animation.BOUNCE);
randomMarker.setIcon(noticeMarker);
setTimeout(() => {
randomMarker.setAnimation(null);
randomMarker.setIcon(standardMarker);
}, 1400);
}, 5000);
}, reason => {
console.log(reason);
});
};
just try with your hosted server link instead of window.location.origin
I don't know why or how, but after deploying a bunch of times I got the 403.14 error (Forbidden). I changed the application pool defaults to v4.0 and everything worked after that. Here is how I did it.

Customizing the JSON received from Web API

I need to add one more node to Json string.
Following is the code from where I am reading the data.
var url = "https://xyz_12232_abc/0908978978979.json";
var sys = new WebClient();
var content = sys.DownloadString(url);
I received following output from above code:
{
"2312312312313":
{
"emailId":"abc#gmail.com",
"model":"XYZ001",
"phone":"+654784512547",
"userName":"User1"
},
"23456464512313":
{
"emailId":"abcd#gmail.com",
"model":"XYZ002",
"phone":"+98745114474",
"userName":"User2"
},
"45114512312313":
{
"emailId":"abcde#gmail.com",
"model":"XYZ3",
"phone":"+214784558741",
"userName":"User3"
}
}
But, I want this output like below:
{
"Records": [
{
"UID":"2312312312313":,
"emailId":"abc#gmail.com",
"model":"XYZ001",
"phone":"+654784512547",
"userName":"User1"
},
{
"UID":"23456464512313":,
"emailId":"abcd#gmail.com",
"model":"XYZ002",
"phone":"+98745114474",
"userName":"User2"
},
{
"UID":"45114512312313":,
"emailId":"abcde#gmail.com",
"model":"XYZ3",
"phone":"+214784558741",
"userName":"User3"
}
]
}
Now, how can it be achieved ?
You can use Json.NET to massage the data into your desired output:
var jsonStr = #"..."; // your JSON here
var obj = JsonConvert.DeserializeObject<Dictionary<string, JObject>>(jsonStr);
var formattedObj = new
{
Records = obj.Select(x =>
{
x.Value.AddFirst(new JProperty("UID", x.Key));
return x.Value;
})
};
// serialize back to JSON
var formattedJson = JsonConvert.SerializeObject(formattedObj);

How can I get all HTML attributes with GeckoFX/C#

In C# viaGeckoFx, I have not found a method to find all attributes of an element.
To do this, I made ​​a JavaScript function. Here is my code
GeckoWebBrowser GeckoBrowser = ....;
GeckoNode NodeElement = ....; // HTML element where to find all HTML attributes
string JSresult = "";
string JStext = #"
function getElementAttributes(element)
{
var AttributesAssocArray = {};
for (var index = 0; index < element.attributes.length; ++index) { AttributesAssocArray[element.attributes[index].name] = element.attributes[index].value; };
return JSON.stringify(AttributesAssocArray);
}
getElementAttributes(this);
";
using (AutoJSContext JScontext = new AutoJSContext(GeckoBrowser.Window.JSContext)) { JScontext.EvaluateScript(JStext, (nsISupports)NodeElement.DomObject, out JSresult); }
Do you have others suggestions to achieve this in C# (with no Javascript)?
The property GeckoElement.Attributes allows access to an elements attributes.
So for example (this is untested and uncompiled code):
public string GetElementAttributes(GeckoElement element)
{
var result = new StringBuilder();
foreach(var a in element.Attributes)
{
result.Append(String.Format(" {0} = '{1}' ", a.NodeName, a.NodeValue));
}
return result.ToString();
}

passing json values to highcharts from .net code behind

var Javascriptxvalue= $.parseJSON($("#hdnXaxis").val());
var Javascriptyvalue= $.parseJSON($("#hdnYaxis").val());
$(document).ready(DrawMyGraph1);
function DrawMyGraph1() {
chart = new Highcharts.Chart(
{
chart: {
type: 'column',
renderTo: 'container3',
defaultSeriesType: 'area'
},
title: {
text: ''
},
subtitle: {
text: ''
},
xAxis: {
categories: Javascriptxvalue,
labels: {
enabled: false
}
},
yAxis: {
title: {
text: 'No of Patients'
}
},
credits: {
enabled: false
},
tooltip: {
formatter: function () {
return this.series.name + ' - ' + Highcharts.numberFormat(this.y, 0);
}
},
series: Javascriptyvalue
});
}
c# code
void FastMovingStocksBarChart(string date1, string date2, string selperiod, string sql)
{
DataSet dschart = new DataSet();
dschart = _obj_MIS.DoctorpatientreportChart(date1, date2, selperiod,sql);
List lstXaxis = new List();
List lstcolors = new List();
lstcolors.Add("#3366DD");
//lstcolors.Add("#FFEE22");
//lstcolors.Add("#33BBCC");
lstcolors.Add("#CC0022");
//lstcolors.Add("#FF0000");
lstcolors.Add("#339900");
lstcolors.Add("#FF7700");
lstcolors.Add("#33BBCC");
lstcolors.Add("#99EEEE");
lstcolors.Add("#6699FF");
lstcolors.Add("#9966BB");
lstcolors.Add("#99BB66");
lstcolors.Add("#FF7700");
lstcolors.Add("#FFEE22");
lstcolors.Add("#FFCBB9");
lstcolors.Add("EAEC93");
lstcolors.Add("D7FBE6");
lstcolors.Add("FFCACA");
for (int i = 0; i < dschart.Tables[0].Rows.Count; i++)
{
lstXaxis.Add(dschart.Tables[0].Rows[i]["Doctor Name"].ToString());
}
List<ChartEx> lstseries = new List<ChartEx>();
int count = 0;
for (int i = 0; i < dschart.Tables[0].Rows.Count; i++)
{
ChartEx oEx = new ChartEx();
oEx.name = dschart.Tables[0].Rows[i]["Doctor Name"].ToString();
//oEx.data.Add(Convert.ToInt32(dschart.Tables[0].Rows[i]["Patients"]));
oEx.data = new List<int>() { Convert.ToInt32(dschart.Tables[0].Rows[i]["Patients"]) };
oEx.color = lstcolors[count];
lstseries.Add(oEx);
count++;
if (count >= lstcolors.Count)
count = 0;
}
//Convert X axis data to JSON
JavaScriptSerializer oSerializer1 = new JavaScriptSerializer();
hdnXaxis.Value = oSerializer1.Serialize(lstXaxis);
//Convert Y axis data to JSON
JavaScriptSerializer oSerializer2 = new JavaScriptSerializer();
hdnYaxis.Value = oSerializer1.Serialize(lstseries);
}
I am not getting the values for "Javascriptxvalue" and "Javascriptyvalue" inside the chart function
can anyone help me
Regards
Prabhu
Presumably, 'hdnXaxis' is the id of a HiddenFieldControl server control? Perhaps the id is not what you think
var Javascriptxvalue= $.parseJSON($("#"+ <%= hdnXaxis.ClientId %>).val());
Instead of passing strings via an input, you could use server tags to directly inject the values into the page. Like this:
<%= "alert('" + MyPublicProperty + "')" %>
This should alert you to the value of the property defined in your code behind. You could then set it to a js variable like so:
<%= "var Javascriptxvalue = '" + xProperty + "';" %>
You will need to run this bit of code directly in an aspx/ascx/razor page to set the variables though, I think it's better than relying on a control with a particular id though.

Why do I get an "$ is not defined" error?

I got an ActionResult TabNotes which returns a View for a tab which shows notes from a database in a grid. On the tab is a button for ActionResult CreateNote, which returns a PartialView and after saving the note I redirect back to the ActionResult TabNotes with
return RedirectToAction("TabNotes", new { modelEntity = "Phrase", id = itemId});
However, when it goes to the action result TabNotes using this redirect it does not show the grid. The javascript gives the following error
Uncaught ReferenceError: $ is not defined (anonymous function)
Uncaught ReferenceError: ko is not defined (anonymous function)
This does not happen the first time it goes to ActionResult. Using breakpoints the following part of the ActionResult TabNotes:
[...]
Model.Grid.url = Url.Action("TabNoteData", new { id = Model.meta.entity, itemId = Model.meta.id.Value});
}
return View("TabNotes", Model);
}
gives the same input values in Model for the first time and the second time. Where can this error come from?
Edit: Firebug shows the following errors:
prompt aborted by user
throw Components.Exception...by user", Cr.NS_ERROR_NOT_AVAILABLE); nsPrompter.js (regel 462 <Systeem>
$ is not defined
$(document).ready(function(){$('#tblTN...tes/44?cmd=refresh" id="TNPhrase44"> 44?mod...=Phrase (regel 2)
ko is not defined
var viewModel=ko.mapping.fromJ...],"buttons":[],"PostAction":null}}); 44?mod...=Phrase (regel 12)
Below is the javascript and code
#model test.Web.Framework.Areas.Administration.Models.TabNotesModel
#using (UI.DocumentReadyScript())
{
if (Model.meta.id.HasValue)
{
UI.jQuery("#tbl" + Model.meta.modelname).flexigrid(Model.Grid);
}
}
<form method="post" action="#Url.Action("TabNotes", new { cmd = "refresh" })" id="#Model.meta.modelname">
<div class="ui-state-highlight ui-corner-all highlight" data-bind="visible: meta.message">
<span class="ui-icon ui-icon-info"></span><strong data-bind="text: meta.message">
</strong>
</div>
#using (UI.BeginBlock("Administation.TabNotes", UI.Label("Notes", "Notes").ToString(), test.Web.Framework.Core.enumIcons.pencil, false, false))
{
<table id="#("tbl" + Model.meta.modelname)">
</table>
}
</form>
<script type="text/javascript">
(function() {
var viewModel=ko.mapping.fromJS(#Html.Raw(UI.JavascriptEncode(Model)));
viewModel.getData=function() { return ko.mapping.toJSON( this ); };
viewModel.setData=function(data){
$('#tbl'+this.meta.modelname()).flexigrid( data.Grid);
ko.mapping.updateFromJS(this,data);
};
$('##Model.meta.modelname').koform({viewmodel: viewModel , validate : {errorElement:'p' } } );
$('##Model.meta.modelname').koform('applyBindings');
$('#load-partial').click(function() {
$('#partial').load('#Url.Action("CreateNote", "Entity", new {itemId = #Model.meta.id, modelEntity = "Phrase"})');
});
})();
</script>
<div id="partial"></div>
<button type="button" id="load-partial">Create Note</button>
'
public ActionResult CreateNote(
[ModelBinder(typeof(Models.JsonModelBinder))]
NoteModel Model, string cmd, long? itemId, string modelEntity)
{
if (cmd == "Save")
{
Model.meta.message = "Note saved";
test.Database.User User = UserRepository.GetUser(1);
Entity entity = NotesRepository.GetEntity("Phrase");
NotesRepository.StoreNote(Model.subject, Model.text, User, entity, itemId);
return RedirectToAction("TabNotes", new { modelEntity = "Phrase", id = itemId});
}
Model.meta.modelname = "CreateNote";
Model.meta.JsViewModelType = "EditNoteModel";
Model.meta.PostAction = Url.Action("CreateNote", new { cmd = "Save", itemId = itemId});
return PartialView("CreateNotePartial",Model);
}
'
public ActionResult TabNotes([ModelBinder(typeof(Models.JsonModelBinder))]
TabNotesModel Model, string cmd, string modelEntity, long? id)
{
if (modelEntity != null)
{
Model.meta.entity = modelEntity;
}
Entity entity = NotesRepository.GetEntity(Model.meta.entity);
if (id.HasValue)
{
Model.meta.id = id;
}
if (Model.meta.id.HasValue)
{
Model.meta.modelname = "TN" + Model.meta.entity + Model.meta.id.Value.ToString();
Dictionary<string, object> defaultValues = new Dictionary<string, object>();
defaultValues.Add("Entity", entity.EntityId);
defaultValues.Add("ItemId", Model.meta.id.Value);
Entity noteEntity = NotesRepository.GetEntity("Note");
var grid = UI.GetEntityFlexiGrid(noteEntity, true, true, true, true, defaultValues);
grid.buttons.Clear();
//grid.buttons.Add(new Button { onpress = "CreateNote", action = Url.Action("CreateNote"), name = "CreateNote", postdata = new { meta = Model.meta }});
grid.title = "";
Model.Grid = grid;
Model.Grid.url = Url.Action("TabNoteData", new { id = Model.meta.entity, itemId = Model.meta.id.Value});
}
return View("TabNotes", Model);
}
'
public GridResult TabNoteData(string id, long itemId, FlexigridRequest request, string cmd)
{
GridResult returnValue = null;
var entity = NotesRepository.GetEntity(id);
Entity noteEntity = NotesRepository.GetEntity("Note");
//var Acess = UIRepository.GetEntityAccess(id);
FlexigridConfiguration grid;
Dictionary<string, object> defaultValues = new Dictionary<string, object>();
defaultValues.Add("Entity", entity.EntityId);
defaultValues.Add("ItemId",itemId);
grid = UI.GetEntityFlexiGrid(noteEntity, true, true, true, true, defaultValues);
IQueryable q = NotesRepository.GetNotes(entity.EntityId, itemId);
var sortField = entity.EntityFields.SingleOrDefault(c => c.Name == request.sortname);
if (sortField == null)
{
request.sortname = grid.sortname;
}
IQueryable qdata = null;
if (!string.IsNullOrEmpty(request.sortname) && request.sortname != "undefined")
{
switch (request.sortorder)
{
case enumFlexigridRequestSortOrder.asc:
qdata = q.OrderBy(request.sortname + " ascending");
break;
case enumFlexigridRequestSortOrder.desc:
qdata = q.OrderBy(request.sortname + " descending");
break;
}
}
if (!string.IsNullOrEmpty(request.query) && !string.IsNullOrEmpty(request.qtype))
{
qdata = qdata.Where(request.qtype.SanitizeFieldExpression() + ".Contains(#0)", request.query);
}
if (request.q != null && request.q.Length > 0)
{
for (int i = 0; i < request.q.Length; i++)
{
var type = UIRepository.GetType(id);
var property = type.GetProperty(request.q[i]);
System.ComponentModel.TypeConverter tc = System.ComponentModel.TypeDescriptor.GetConverter(property.PropertyType);
string sv = request.v[i];
if (sv == null || sv == "null")
{
qdata = qdata.Where(request.q[i].SanitizeFieldExpression() + "=#0", (object)null);
}
else
{
object v = tc.ConvertFromString(sv);
qdata = qdata.Where(request.q[i].SanitizeFieldExpression() + "=#0", v);
}
}
}
string settingName = "Grid." + id + ".Rp";
var setting = UIRepository.GetQuery<test.Database.UserSetting>().SingleOrDefault(uc => uc.CreatedById == CurrentUser.UserId && uc.Name == settingName);
if (setting == null)
{
setting = UIRepository.Create<test.Database.UserSetting>();
setting.Name = settingName;
setting.Value = request.rp.ToString();
UIRepository.Add(setting);
}
else
{
if (request.rp.ToString() != setting.Value)
{
setting.Value = request.rp.ToString();
UIRepository.Update(setting);
}
}
int rowId = 0;
var datarows = new List<object>();
foreach (var record in qdata.Skip((request.page - 1) * request.rp).Take(request.rp).GetData())
{
var cellValues = new List<object>();
foreach (var gc in grid.colModel.OrderBy(c => c.di))
{
cellValues.Add(gc.ToString(UI, record));
}
var row = new { id = rowId, cell = cellValues.ToArray() };
datarows.Add(row);
rowId++;
}
returnValue = Grid(request.page, qdata.Count(), datarows.ToList());
return returnValue;
}
That error can only be caused be one of three things:
Your JavaScript file is not being properly loaded into your page
You have a botched version of jQuery. This could happen because someone edited the core file, or a plugin may have overwritten the $ variable.
You have JavaScript running before the page is fully loaded, and as such, before jQuery is fully loaded.
You should check the Firebug net panel to see if the file is actually being loaded properly. If not, it will be highlighted red and will say "404" beside it. If the file is loading properly, that means that the issue is number 2.
Make sure all javascript code is being run inside a code block such as:
$(document).ready(function () {
//your code here
});
This will ensure that your code is being loaded after jQuery has been initialized.
One final thing to check is to make sure that you are not loading any plugins before you load jQuery. Plugins extend the "$" object, so if you load a plugin before loading jQuery core, then you'll get the error you described.
So to avoid that you can use a "bodyguard" function like the following:
( function($) {
//We can now use $ as I implemented the bodyguard!
$(document).ready(function() {
//your code...
});
} ) ( jQuery );

Categories