problem with ajax or maybe with postmapping - json

So, i am trying to use ajax and it seems I am not able to run
searchRequest.open("POST", "/test?q=" + $("#q").val(), true);
from my jsp file.
<script>
//testView.jsp
function search() {
const searchRequest = new XMLHttpRequest();
searchRequest.open("POST", "/test?q=" + $("#q").val(), true);
alert("???")
searchRequest.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=utf8");
alert("??")
searchRequest.onreadystatechange = () => {
if(searchRequest.readyState == 4 && searchRequest.status == 200) {
console.log("gwew", searchRequest.responseText);
const table = $("#ajaxTable")[0]; // dom 반환
table.innerHTML = "";
const object = JSON.parse(searchRequest.responseText);
alert(q)
....
this is my jsp file, and I have a testController.java like this.
#Controller
public class testController {
#GetMapping(value = "/test")
public String test(){
System.out.println("GET");
return "testView";
}
#PostMapping(value = "/test",
consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE,
produces = MediaType.APPLICATION_JSON_VALUE)
#ResponseBody
public String testing(#RequestParam(required = false) String q) {
System.out.println("POST");
return q;
}
}
Not sure where I am getting wrong. Am I getting problem on #Postmapping?

Related

SignalR + Win RT(Windows 8.1) + using unsigned certificate not working [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
After searching for more than 4 hours, making a Win RT + SignalR work with a selfsigned certificate. Found it! So I share a solution here.
You get the error:
The underlying connection was closed: Could not establish trust relationship for the SSL/TLS secure channel.
The remote certificate is invalid according to the validation procedure.
public class DefaultHttpClientUnsigned : DefaultHttpClient
{
protected override HttpMessageHandler CreateHandler()
{
var filter = new HttpBaseProtocolFilter();
filter.IgnorableServerCertificateErrors.Add(ChainValidationResult.Expired);
filter.IgnorableServerCertificateErrors.Add(ChainValidationResult.Untrusted);
filter.IgnorableServerCertificateErrors.Add(ChainValidationResult.InvalidName);
filter.IgnorableServerCertificateErrors.Add(ChainValidationResult.IncompleteChain);
var handler = new WinRtHttpClientHandler(filter);
return handler;
}
}
Then for creating the connection:
var connection = new HubConnection(address);
var client = new DefaultHttpClientUnsigned();
connection.Start(client);
// https://www.nuget.org/packages/WinRtHttpClientHandler
The source code for the WinRtHttpClientHandler (if it's not available anymore)
public class WinRtHttpClientHandler : HttpMessageHandler
{
private static readonly Version NoVersion = new Version(0, 0);
private static readonly Version Version10 = new Version(1, 0);
private static readonly Version Version11 = new Version(1, 1);
private readonly rt.HttpClient _client;
private bool _disposed = false;
public WinRtHttpClientHandler(IHttpFilter httpFilter)
{
_client = new rt.HttpClient(httpFilter);
}
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
CheckDisposed();
var rtMessage = await ConvertHttpRequestMessaageToRt(request, cancellationToken).ConfigureAwait(false);
var resp = await _client.SendRequestAsync(rtMessage).AsTask(cancellationToken).ConfigureAwait(false);
var netResp = await ConvertRtResponseMessageToNet(resp, cancellationToken).ConfigureAwait(false);
return netResp;
}
internal static async Task<rt.HttpRequestMessage> ConvertHttpRequestMessaageToRt(HttpRequestMessage message, CancellationToken token)
{
var rt = new rt.HttpRequestMessage()
{
Method = new rt.HttpMethod(message.Method.Method),
Content = await GetContentFromNet(message.Content).ConfigureAwait(false),
RequestUri = message.RequestUri,
};
CopyHeaders(message.Headers, rt.Headers);
foreach (var prop in message.Properties)
rt.Properties.Add(prop);
return rt;
}
internal static async Task<HttpRequestMessage> ConvertRtRequestMessageToNet(rt.HttpRequestMessage message, CancellationToken token)
{
var req = new HttpRequestMessage()
{
Method = new HttpMethod(message.Method.Method),
RequestUri = message.RequestUri,
Content = await GetNetContentFromRt(message.Content, token).ConfigureAwait(false),
};
foreach (var header in message.Headers)
req.Headers.TryAddWithoutValidation(header.Key, header.Value);
foreach (var prop in message.Properties)
req.Properties.Add(prop);
return req;
}
internal static void CopyHeaders(IEnumerable<KeyValuePair<string, IEnumerable<string>>> source, IDictionary<string, string> destination)
{
var headers = from kvp in source
from val in kvp.Value
select new KeyValuePair<string, string>(kvp.Key, val);
foreach (var header in headers)
destination.Add(header);
}
internal static async Task<rt.IHttpContent> GetContentFromNet(HttpContent content)
{
if (content == null)
return null;
var stream = await content.ReadAsStreamAsync().ConfigureAwait(false);
var c = new rt.HttpStreamContent(stream.AsInputStream());
CopyHeaders(content.Headers, c.Headers);
return c;
}
internal static async Task<HttpContent> GetNetContentFromRt(rt.IHttpContent content, CancellationToken token)
{
if (content == null)
return null;
var str = await content.ReadAsInputStreamAsync().AsTask(token).ConfigureAwait(false);
var c = new StreamContent(str.AsStreamForRead());
foreach (var header in content.Headers)
c.Headers.TryAddWithoutValidation(header.Key, header.Value);
return c;
}
internal static async Task<HttpResponseMessage> ConvertRtResponseMessageToNet(rt.HttpResponseMessage message, CancellationToken token)
{
var resp = new HttpResponseMessage((HttpStatusCode)(int)message.StatusCode)
{
ReasonPhrase = message.ReasonPhrase,
RequestMessage = await ConvertRtRequestMessageToNet(message.RequestMessage, token).ConfigureAwait(false),
Content = await GetNetContentFromRt(message.Content, token).ConfigureAwait(false),
Version = GetVersionFromEnum(message.Version),
};
foreach (var header in message.Headers)
resp.Headers.TryAddWithoutValidation(header.Key, header.Value);
return resp;
}
internal static Version GetVersionFromEnum(rt.HttpVersion version)
{
switch (version)
{
case rt.HttpVersion.None:
return NoVersion;
break;
case rt.HttpVersion.Http10:
return Version10;
break;
case rt.HttpVersion.Http11:
return Version11;
break;
default:
throw new ArgumentOutOfRangeException("version");
}
}
private void CheckDisposed()
{
if (_disposed)
throw new ObjectDisposedException("WinRtHttpClientHandler");
}
protected override void Dispose(bool disposing)
{
if (disposing && !_disposed)
{
_client.Dispose();
_disposed = true;
}
base.Dispose(disposing);
}
}
Hope this helps some people out there.

The operation cannot be completed because the DbContext has been disposed In Mqsql and Entity Framework

I am doing From dropdown selection, I fill textboxes with the Json Value. Action() Method work fine It return Json value but page not populate these value to TextBoxes control. When i use Developer Tool then i get, it throw a Error "The operation cannot be completed because the DbContext has been disposed."
Controller
private hcEntities db = new hcEntities();
// GET: Chains
public ActionResult Index()
{
ViewData["chain_name"] = new SelectList(db.chains, "code", "name");
return View(db.chains.ToList());
}
//Action Function callby javascript
[HttpPost]
public ActionResult Action(string code)
{
using (var ObjDb = new hcEntities())
{
var query = from c in ObjDb.chains
where c.code == code
select c;
return Json(query);//Return Json Result
}
}
View:-
<script type="text/javascript">
function Action(code) {
$.ajax({
url: '#Url.Action("Action", "Chains")',
type: "POST",
data: { "code": code },
"success": function (data) {
if (data != null) {
var vdata = data;
$("#ChainName").val(vdata[0].name);
$("#ChainCode").val(vdata[0].code);
$("#username").val(vdata[0].username);
}
}
});
}
Try return Json(query.FirstOrDefault());
Use IDisposable again in the GET Controller:
// GET: Chains
public ActionResult Index()
{
using (var ObjDb = new hcEntities())
{
ViewData["chain_name"] = new SelectList(ObjDb.chains, "code", "name");
return View(ObjDb.chains.ToList());
}
}

How to update data continuously in UI text box control using windows phone application

Im developing a small Tcp Client Socket application in windows phone. Actually i have a text box, in that whatever the data received from a TCP server, should update continuously in UI text box control.
while (val)
{
result = Receive();
Dispatcher.BeginInvoke((Action)(() =>
{
txtOutput.Text += result;
}));
}
Here in above code, method receive() will receive string data and should update in textbox control but it is not happening,no data is updating to it.
Can any one suggest, how can i resolve this.
Just telling you what i have been advised, "avoid Dispatcher, CoreDispatcher, etc. There are always better solutions."
Below is the piece of code worked for me for both wp8 and wp8.1 WinRT app,
IProgress<object> progress = new Progress<object>(_ => UpdateTicker());
Task.Run(async () =>
{
while (val)
{
progress.Report(null);
}
});
where UpdateTicker() method contains your instructions, in this case...
public void UpdateTicker()
{
result = Receive();
txtOutput.Text += result;
}
Hope this helps...
Thanks for everyone, who given a valuable response for my post.
Hi Nishchith,
I tried your code, but it dint works for me
Here is my logic used to update textbox continuously with data received from TCP server.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using PhoneApp3.Resources;
using System.Net.Sockets;
using System.Threading;
using System.Text;
using Windows.Phone.Networking;
using System.Threading.Tasks;
namespace PhoneApp3
{
public partial class MainPage : PhoneApplicationPage
{
Socket _socket = null;
static ManualResetEvent _clientDone = new ManualResetEvent(false);
const int TIMEOUT_MILLISECONDS = 1000;
const int MAX_BUFFER_SIZE = 2048;
const int ECHO_PORT = 9055; // The Echo protocol uses port 7 in this sample
const int QOTD_PORT = 49152; // The Quote of the Day (QOTD) protocol uses port 17 in this sample
string result = string.Empty;
public MainPage()
{
InitializeComponent();
}
private void btnEcho_Click(object sender, RoutedEventArgs e)
{
SocketClient client = new SocketClient();
Connect(txtRemoteHost.Text, ECHO_PORT);
//close();
}
public void Connect(string hostName, int portNumber)
{
DnsEndPoint hostEntry = new DnsEndPoint(hostName, portNumber);
_socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
SocketAsyncEventArgs socketEventArg = new SocketAsyncEventArgs();
socketEventArg.RemoteEndPoint = hostEntry;
socketEventArg.Completed += new EventHandler<SocketAsyncEventArgs>(delegate(object s, SocketAsyncEventArgs e)
{
result = e.SocketError.ToString();
_clientDone.Set();
});
_clientDone.Reset();
Thread.Sleep(2000);
_socket.ConnectAsync(socketEventArg);
Thread.Sleep(5000);
_clientDone.WaitOne(TIMEOUT_MILLISECONDS);
bool val;
if (result == "Success")
{
val = true;
}
else
{
val = false;
}
IProgress<object> progress = new Progress<object>(_ => UpdateTicker());
Task.Run(async () =>
{
while (val)
{
progress.Report(null);
}
});
}
public void UpdateTicker()
{
result = Receive();
string[] strsplit = result.Split(' ');
txtOutput.Text = strsplit[1];
}
public string Receive()
{
string response = "Operation Timeout";
if (_socket != null)
{
SocketAsyncEventArgs socketEventArg = new SocketAsyncEventArgs();
socketEventArg.RemoteEndPoint = _socket.RemoteEndPoint;
socketEventArg.SetBuffer(new Byte[MAX_BUFFER_SIZE], 0, MAX_BUFFER_SIZE);
socketEventArg.Completed += new EventHandler<SocketAsyncEventArgs>(delegate(object s, SocketAsyncEventArgs e)
{
if (e.SocketError == SocketError.Success)
{
// Retrieve the data from the buffer
response = Encoding.UTF8.GetString(e.Buffer, e.Offset, e.BytesTransferred);
response = response.Trim('\0');
}
else
{
response = e.SocketError.ToString();
}
_clientDone.Set();
});
_clientDone.Reset();
Thread.Sleep(1000);
_socket.ReceiveAsync(socketEventArg);
Thread.Sleep(1000);
_clientDone.WaitOne(TIMEOUT_MILLISECONDS);
}
else
{
response = "Socket is not initialized";
}
return response;
}
public void Close()
{
if (_socket != null)
{
_socket.Close();
}
}
}
}

How can I properly localize Razor Views in ServiceStack

I am currently getting the prefered Culture from the Accept-Language-HTTP-Header and storing it in the AuthUserSession.
In AppHost.Configure:
PreRequestFilters.Add((httpReq, httpResp) =>
{
var session = httpReq.GetSession();
if (session is AuthUserSession)
{
var auths = ((AuthUserSession)session);
if (auths.Culture == null)
{
//parse languages
var languages = httpReq.Headers["Accept-Language"];
//auths.Culture = Helpers.CultureHelper.GetBestAcceptLanguageMatch(languages);
auths.Culture = "en-US";
httpReq.SaveSession(session, new TimeSpan(0, 20, 0));
}
}
});
My current solution to Render a View in the users prefered Culture is to change the current Threads UICulture from the Razor view:
#inherits ViewPage<LandingPage.ServiceModel.Operations.AskQuestions>
#{
var session = GetSession<ServiceStack.ServiceInterface.Auth.AuthUserSession>();
var prevCulture = System.Threading.Thread.CurrentThread.CurrentUICulture;
System.Threading.Thread.CurrentThread.CurrentUICulture = System.Globalization.CultureInfo.GetCultureInfo(session.Culture);
//access a Resource
ViewBag.Title = Resources.AskTitle;
}
Views Content
#{
System.Threading.Thread.CurrentThread.CurrentUICulture = prevCulture;
}
This seems unelegant and clumsy. What would be a better way to do this?
*edit:
I am looking for two hook points: one just before the View gets called, and one right after it got rendered. These should keep the interference with other Requests that get served to zero.
I discovered today that a custom IServiceRunner supplies just the right hooks (see https://github.com/ServiceStack/ServiceStack/wiki/Customize-HTTP-Responses).
As the one above it only works, when the page is served by a Service, because the RequestFilters and the ServiceRunner are not even touched when a ContentPage is requested.
It might be of interest, that the RequestFilter is another hook point, that is called before the Execution of the View. But the same seems true for the ResponseFilter. A small test in which I tried to reset the CurrentUICulture in the ResponseFilter rendered my page unlocalized.
In AppHost
public override void Configure(Funq.Container container)
{
//plugins
Plugins.Add(new RazorFormat());
Plugins.Add(new AuthFeature(() =>
new AuthUserSession(),
new IAuthProvider[] {
new BasicAuthProvider()
}));
//request filters
PreRequestFilters.Add((httpReq, httpResp) =>
{
var session = httpReq.GetSession();
if (session is AuthUserSession)
{
var auths = ((AuthUserSession)session);
if (auths.Culture == null)
{
var languages = httpReq.Headers["Accept-Language"];
auths.Culture = Helpers.CultureHelper.GetBestAcceptLanguageMatch(languages);
httpReq.SaveSession(session, new TimeSpan(0, 20, 0));
}
httpReq.SetItem("Culture", auths.Culture);
}
});
//funq
var userRep = new InMemoryAuthRepository();
container.Register<IUserAuthRepository>(userRep);
container.Register<ICacheClient>(c => new MemoryCacheClient());
}
//use a custom IServiceRunner
public override ServiceStack.ServiceHost.IServiceRunner<TRequest> CreateServiceRunner<TRequest>(ActionContext actionContext)
{
var runner = base.CreateServiceRunner<TRequest>(actionContext);
return new CultureAwareServiceRunner<TRequest>(this, actionContext);
}
CultureAwareServiceRunner.cs
public class CultureAwareServiceRunner<T> : ServiceRunner<T>
{
public CultureAwareServiceRunner(AppHost appHost, ServiceStack.WebHost.Endpoints.ActionContext actionContext) :
base(appHost, actionContext)
{ }
public override void OnBeforeExecute(IRequestContext requestContext, T request)
{
var httpReq = requestContext.Get<IHttpRequest>();
httpReq.SetItem("PreviousCulture", Thread.CurrentThread.CurrentUICulture);
string culture = httpReq.GetItem("Culture") as string;
if (culture != null)
Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo(culture);
base.OnBeforeExecute(requestContext, request);
}
public override object OnAfterExecute(IRequestContext requestContext, object response)
{
var httpReq = requestContext.Get<IHttpRequest>();
var prevCulture = httpReq.GetItem("PreviousCultureCulture") as CultureInfo;
if (prevCulture != null)
Thread.CurrentThread.CurrentUICulture = prevCulture;
return base.OnAfterExecute(requestContext, response);
}
}

How to map poco to JSON using Automapper

In my MVC 2 application I have a typical method that calls a web service, builds a JSON data object and returns it to the view.
Everything works fine, but I was wondering if there is a way to do the mapping with Automapper so I can remove the ugly code from my controller. Thanks in advance
Here is my Action method
public virtual ActionResult AllErrors(string sidx, string sord,
int page=1, int rows=10)
{
var pageSize = rows;
var pageNumber = page;
var orderBy = string.Format("{0} {1}", sidx, sord);
var result = errorService.GetPagedOpenErrors(pageSize, page, orderBy);
var errors = new List<IngestionErrorDataContract>(result.IngestionErrors);
var totalPages = (int) Math.Ceiling(result.TotalRows/(float) pageSize);
int index = 0;
var list = new List<object>();
errors.ForEach(e => list.Add(
new {
i = index++,
cell = new[]
{
e.IngestionErrorId.ToString(),
e.RunId.ToString(),
e.ProcessDate.ToShortDateString(),
e.Status,
e.ErrorDetails
}
}));
var jsonData = new
{
total = totalPages,
page = pageNumber,
records = result.TotalRows,
rows = list.ToArray()
};
return Json(jsonData, JsonRequestBehavior.AllowGet);
}
I solved it using the ConstructUsing method of AutoMapper.
Here is my map
public void CreateMap()
{
Mapper.CreateMap<List<IngestionErrorDataContract>, object[]>()
.ConvertUsing(
errors =>
{
int index = 0;
var list = new List<object>();
errors.ForEach(e => list.Add(
new
{
i = index++,
cell = new[]
{
e.IngestionErrorId.ToString(),
e.RunId.ToString(),
e.ProcessDate.ToShortDateString(),
e.Status,
e.ErrorDetails
}
}));
return list.ToArray();
});
}
and here is my action method now
public virtual ActionResult AllErrors(string sidx, string sord, int page=1, int rows=10)
{
var pageSize = rows;
var pageNumber = page;
var orderBy = string.Format("{0} {1}", sidx, sord);
var result = errorService.GetPagedOpenErrors(pageSize, page, orderBy);
var errors = new List<IngestionErrorDataContract>(result.IngestionErrors);
var totalPages = (int) Math.Ceiling(result.TotalRows/(float) pageSize);
var jsonData = new
{
total = totalPages,
page = pageNumber,
records = result.TotalRows,
rows = mapper.Map<List<IngestionErrorDataContract>,object[]>(errors)
};
return Json(jsonData, JsonRequestBehavior.AllowGet);
}
Much better I think