I am using FineUploader plug-in to upload some files to the server. For some reason, Request.Files array comes empty like in every 10 in 100 page loads. It's null sometimes. After hit Ctrl+F5, everything works properly. I know that FineUploader is no longer supported. But it's probably not related with FineUploader.
ServerSide Code:
var request = controllerContext.RequestContext.HttpContext.Request;
var formUpload = request.Files.Count > 0;
// find filename
var xFileName = request.Headers["X-File-Name"];
var qqFile = request["qqfile"];
var formFilename = formUpload ? request.Files[0].FileName : null;
var upload = new FineUpload
{
Filename = xFileName ?? qqFile ?? formFilename,
InputStream = formUpload ? request.Files[0].InputStream : request.InputStream
};
return upload;
Client Side JavaScript code:
<script>
var uploader = new qq.FineUploader({
debug: true,
multiple: false,
element: document.getElementById('fine-uploader'),
request: {
endpoint: '/SystemDefinitions/ProcessImportFile',
params: { "operationType": $("#operationType").val() }
},
deleteFile: {
enabled: true,
endpoint: '/SystemDefinitions/DeleteFile'
},
retry: {
enableAuto: false
},
failedUploadTextDisplay: {
mode: 'custom', // Display error responses from the server.
responseProperty: 'error' // Default is 'error', change this to match the
// property that contains the error message from
// your server
},
callbacks: {
onComplete: function (id, name, xhr) {
if (xhr.errorMessage !== "") {
showResult("Error", xhr.errorMessage);
return false;
}
},
onSubmit: function (id, fileName) {
var newParams = {
operationType: $("#operationType option:selected").val()
},
finalParams = defaultParams;
qq.extend(finalParams, newParams);
this.setParams(finalParams);
}
}
});
</script>
I use soap header in c# like this :
MeyerWebService.WebServiceEmployees tasnifWS = new MeyerWebService.WebServiceEmployees();
tasnifWS.UserDetailsValue = new UserDetails()
{
userName = "**",
password = "**"
};
But I dont know how to do this in react-native
You can use a simple module for making SOAP requests with WSSecurity
npm install react-native-soap-request --save
Example
const soapRequest = new SoapRequest({
security: {
username: 'username',
password: 'password'
},
targetNamespace: 'http://soap.acme.com/2.0/soap-access-services',
commonTypes: 'http://soap.acme.com/2.0/soap-common-types',
requestURL: soapWebserviceURL
});
const xmlRequest = soapRequest.createRequest({
'soap:ProductRegistrationRequest': {
attributes: {
'xmlns:soap': 'http://soap.acme.com/2.0/soap-access-services',
'xmlns:cmn': 'http://soap.acme.com/2.0/soap-common-types'
},
'soap:productId': {
'cmn:internalId': {
'cmn:id': productId
}
},
'soap:userId': {
'cmn:internalId': {
'cmn:id': userId
}
}
}
});
const response = await soapRequest.sendRequest();
I have written a WCF service which in theory, should accept a JSON object from Ajax and return true or false as a response to indicate the JSON object was accepted from service and sent to the database.
This is how the interface is implemented in IService
[OperationContract]
[WebInvoke(Method ="POST",ResponseFormat=WebMessageFormat.Json,RequestFormat =WebMessageFormat.Json,UriTemplate ="InsertPatient")]
String InsertPatient(Patient PatientObj);
The contract is implemented as follows
public String InsertPatient(Patient PatientObj)
{
PatientContext pat = new PatientContext();
Boolean boolObj = new Boolean();
string JsonString = "";
if (pat.Patients.Where(x => x.Username == PatientObj.Username).Any())
{
// Username already taken;
boolObj = false;
JsonString =JsonConvert.ToString(boolObj);
return JsonString;
}
else
{ //Initiate to add user to login table
Login log = new Login();
log.Username = PatientObj.Username;
log.Password = PatientObj.Password;
log.User_Type = PatientObj.User_Type;
if (InsertLogin(log)) //if login added
{
pat.Patients.Add(PatientObj); //add user to patient table
pat.SaveChanges();
boolObj = true;
JsonString = JsonConvert.ToString(boolObj);
return JsonString;
}
else //login was not added
{
boolObj = false;
JsonString = JsonConvert.ToString(boolObj);
return JsonString;
}
}
}
and finally the Ajax script is implemented as follows
<script>
$(document).ready(function () {
$("form").submit(function () {
var L_Username = $("#UN").val();
var L_User_Type = "patient";
var L_Name = $("#name").val();
var L_Birthday = $("#bday").val();
var L_Gender = $("input[name='optradio']:checked").val();
var L_Contact = $("#cNo").val();
var L_Password = $("#password").val();
var L_Address = $("#adress").val();
var jsondata = {
Username: L_Username,
User_Type: L_User_Type,
Address: L_Address,
Birthday: L_Birthday,
Contact: L_Contact,
Gender: L_Gender,
Name: L_Name,
Password: L_Password
};
console.log(JSON.stringify(jsondata));
$.ajax({
url: "http://localhost:50709/Service1.svc/rest/InsertPatient",
type: "POST",
contentType: "application/json",
dataType: "json",
data: JSON.stringify(jsondata),
success: function (resultdata) {
alert("inserted");
},
error: function (e) {
alert("Something went wrong");
}
});
});
});
</script>
When I test this through POST-man , I get the correct response as true or false. But when I run this from the website itself. Ajax always throw the error alert, but the values get successfully added to the tables.
What am I doing wrong , please help. Thank you in advance.
I am trying to load my typeahead.js by using bloohound's remote function where i can call my Web Method. I have seen similar threads where a querystring is being used :
Integrating Typeahead.js with ASP.Net Webmethod
Typeahead.js and Bloodhound.js integration with C# WebForms WebMethod
http://yassershaikh.com/using-twitter-typeahead-js-with-asp-net-mvc-web-api/
And many more....
However, i cannot find an example where ajax is used to call the webmethod from typeahead.js.
So this is what i have currently and it works:
WebMethod
[WebMethod]
public static string GetEmployeeTypeahead()
{
JavaScriptSerializer jss = new JavaScriptSerializer();
jss.MaxJsonLength = 100000000;
string json;
using (var rep = new RBZPOS_CSHARPEntities())
{
var result = rep.Employees
.Where(x => x.EMPLOYEESTATE == 1)
.Select(x => new {
x.EMPLOYEEID,
x.FULLNAME,
x.MANNO,
x.NRC
}).ToList();
json = jss.Serialize(result);
}
return json;
}
The Client
function LoadEmployeeJSON() {
$.ajax({
type: "POST",
url: "/WebMethods/Test.aspx/GetEmployeeTypeahead",
data: "{}",
contentType: "application/json",
dataType: "json",
success: function (msg) {
empList = $.parseJSON(msg.d); //otherwise does not work
LoadEmployeeTypeahead();
},
error: function (msg) {
alert("error:" + JSON.stringify(msg));
}
});
}
function LoadEmployeeTypeahead() {
var empData = empList;
var fullname = new Bloodhound({
datumTokenizer: function (d) {
return Bloodhound.tokenizers.whitespace(d.FULLNAME)
},
queryTokenizer: Bloodhound.tokenizers.whitespace,
local: empData,
limit: 10
});
fullname.initialize();
// Make the code less verbose by creating variables for the following
var fullnameTypeahead = $('#<%=txtFullName.ClientID %>.typeahead');
// Initialise typeahead for the employee name
fullnameTypeahead.typeahead({
highlight: true
}, {
name: 'FULLNAME',
displayKey: 'FULLNAME',
source: fullname.ttAdapter(),
templates: {
empty: [
'<div class="empty-message">',
'No match',
'</div>'
].join('\n'),
suggestion: function (data) {
return '<h6 class="">' + data.FULLNAME + "<span class='pull-right text-muted small'><em>" + data.NRC + "</em></span>" + '</h6>';
}
}
});
var fullnameSelectedHandler = function (eventObject, suggestionObject, suggestionDataset) {
/* See comment in previous method */
$('#<%=txtFullName.ClientID %>').val(suggestionObject.FULLNAME);
$('#<%=txtEmployeeID.ClientID %>').val(suggestionObject.EMPLOYEEID);
$('#<%=txtManNo.ClientID %>').val(suggestionObject.MANNO);
$('#<%=txtNRC.ClientID %>').val(suggestionObject.NRC);
};
// Associate the typeahead:selected event with the bespoke handler
fullnameTypeahead.on('typeahead:selected', fullnameSelectedHandler);
}
function clearAndReInitilize() {
$('.typeahead').typeahead('destroy');
$('.typeahead').val('');
}
So as you can see i am making a local call instead of remote.
How can i get the remote function to call my webthod and fill the typeahead without using any querystrings
Okay finally got it to work via an ashx generic handler. So instead of using a web method i used the following ashx handler:
public class Employess : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
JavaScriptSerializer jss = new JavaScriptSerializer();
jss.MaxJsonLength = Int32.MaxValue;
string json;
string prefixText = context.Request.QueryString["query"];
using (var rep = new RBZPOS_CSHARPEntities())
{
var result = rep.Employees
.Where(x => x.EMPLOYEESTATE == 1 && x.FULLNAME.Contains(prefixText.ToUpper()))
.Select(x => new
{
x.EMPLOYEEID,
x.FULLNAME,
x.MANNO,
x.NRC
}).ToArray();
json = jss.Serialize(result);
}
context.Response.ContentType = "text/javascript";
context.Response.Write(json);
}
public bool IsReusable
{
get
{
return false;
}
}
}
Below is the jquery and the ajax call to the ashx handler
$(document).ready(function () {
$(document).ajaxStart($.blockUI).ajaxStop($.unblockUI);
LoadEmployeeTypeahead();
// LoadEmployeeJSON();
});
function LoadEmployeeTypeahead() {
//var empData = empList;
var fullname = new Bloodhound({
remote: {
url: '/Employess.ashx?query=%QUERY',
wildcard: '%QUERY'
},
datumTokenizer: function (d) {
//var employees = $.parseJSON(msg.d);
return Bloodhound.tokenizers.whitespace(d.FULLNAME)
},
queryTokenizer: Bloodhound.tokenizers.whitespace,
limit: 10
});
fullname.initialize();
// Make the code less verbose by creating variables for the following
var fullnameTypeahead = $('#<%=txtFullName.ClientID %>.typeahead');
// Initialise typeahead for the employee name
fullnameTypeahead.typeahead({
highlight: true
}, {
name: 'FULLNAME',
displayKey: 'FULLNAME',
source: fullname.ttAdapter(),
templates: {
empty: [
'<div class="empty-message">',
'No match',
'</div>'
].join('\n'),
suggestion: function (data) {
return '<h6 class="">' + data.FULLNAME + "<span class='pull-right text-muted small'><em>" + data.MANNO + "</em></span><span class='pull-right text-muted small'><em>" + data.NRC + "</em></span>" + '</h6>';
}
}
});
var fullnameSelectedHandler = function (eventObject, suggestionObject, suggestionDataset) {
/* See comment in previous method */
$('#<%=txtFullName.ClientID %>').val(suggestionObject.FULLNAME);
$('#<%=txtEmployeeID.ClientID %>').val(suggestionObject.EMPLOYEEID);
$('#<%=txtManNo.ClientID %>').val(suggestionObject.MANNO);
$('#<%=txtNRC.ClientID %>').val(suggestionObject.NRC);
};
// Associate the typeahead:selected event with the bespoke handler
fullnameTypeahead.on('typeahead:selected', fullnameSelectedHandler);
}
I want to import the data from JSON file into my VS2012 c# code so that I can plot my highcharts based on the data in JSON file.
I have checked many video on youtube and file docs but couldnt locate single code that runs and give an output as required.
Do give me a sample code that will map a data from JSON file, use it in vs2012 and plot the highcharts.
----------------Updated Question-------------
Below is the function I am trying to call in java-script where I want to evoke data from JSON format, but I am not able to call my function, below is my code
<script>
$(document).ready(function () {
var options = {
chart: {
renderTo: 'container',
type: 'spline'
},
series: [{}]
};
alert("outside");
$.getJSON('data.json', function (data) {
alert("INside");
options.series[0].data = data;
var chart = new Highcharts.Chart(options);
});
});
</script>
and want to pass the data to the highcharts ,Since I am novice, any help will be greatly appreciated.
==============EDIT 2 =====================================
the Json file am trying to use for the data is in following format.
[
[1,12],
[2,5],
[3,18],
[4,13],
[5,7],
[6,4],
[7,9],
[8,10],
[9,15],
[10,22]
]
Thank You.
If JSON file is not rendering on the browser and your are getting 404 error then you might be facing the mime type handling problem, please refer the below link which resolves the issue,
getJSON method does not work
ASP.NET MVC Server Code:
namespace ABPMVCTest.Web.Controllers
{
[AbpMvcAuthorize]
public class HomeController : ABPMVCTestControllerBase
{
static Random _ran=new Random();
public ActionResult Index()
{
return View();
}
public ContentResult GetJsonResult()
{
var dataList = new List<ChartDataFormat>();
GetData(dataList, "总收入");
GetData(dataList, "投币收入");
GetData(dataList, "扫码充电收入");
GetData(dataList, "售线收入");
var dataJsonStr=JsonConvert.SerializeObject(dataList,new JsonSerializerSettings(){ContractResolver = new CamelCasePropertyNamesContractResolver()});
return Content(dataJsonStr);
}
private static List<ChartDataFormat> GetData(List<ChartDataFormat> dataList, string key)
{
var list = new List<int>();
for (int i = 0; i < 7; i++)
{
list.Add(_ran.Next(1, 3000));
}
dataList.Add(new ChartDataFormat
{
Name = key,
Data = list
});
return dataList;
}
}
class ChartDataFormat
{
public string Name { get; set; }
public List<int> Data { get; set; }
}
}
Client javascript Code:
$(function() {
Highcharts.setOptions({
lang: {
printChart: '打印图表',
downloadJPEG: '下载为JPEG图片',
downloadPDF: '下载为PDF',
downloadPNG: '下载为PNG图片',
downloadSVG: '下载为SVG矢量图',
months: ["一月", "二月", "三月", "四月", "五月", "六月", "七月", "八月", "九月", "十月", "十一月", "十二月"],
weekdays: ["周日", "周一", "周二", "周三", "周四", "周五", "周六"],
shortMonths: ["1月", "2月", "3月", "4月", "5月", "6月", "7月", "8月", "9月", "10月", "11月", "12月"],
}
});
var nowDate = new Date();
var option = {
chart: {
type: 'area'
},
title: {
text: '收入趋势图'
},
subtitle: {
text: '没有选择时间范围的话,默认显示当日/月前后3天/月的数据'
},
credits: {
enabled:false
},
xAxis: {
type: 'datetime',
tickmarkPlacement: 'on',
title: {
enabled: false
},
dateTimeLabelFormats: {
day: "%Y-%m-%d",
week: "%A",
month: "%Y-%m",
year: "%Y"
}
},
yAxis: {
title: {
text: '单位:元'
},
labels: {
formatter: function() {
return this.value;
}
}
},
tooltip: {
shared: true,
valueSuffix: ' 元',
dateTimeLabelFormats: {
day: "%Y-%m-%d,%A",
week: "%A开始, %Y-%m-%d",
month: "%Y-%m",
year: "%Y"
}
},
plotOptions: {
area: {
stacking: 'normal',
lineColor: '#666666',
lineWidth: 1,
marker: {
lineWidth: 1,
lineColor: '#666666'
}
},
series: {
pointStart:Date.UTC(nowDate.getFullYear(),nowDate.getMonth(),nowDate.getDate()-3) ,
pointInterval: 24 * 36e5 //一天
}
},
series: [{}]
}
var url = "/Home/GetJsonResult";
$.getJSON(url, function(data) {
option.series = data;
$('#container').highcharts(option);
});
});