I have a session value and a function in a apsx.cs page and I am using jquery webmethod to insert data into database.
Now i want to access session value and function in webmethod but it gives some error.
Below is my Page load code:
int nUserId = Convert.ToInt16(Session["UId"]);
And a Function :
public int CalcUser()
{
return Convert.ToInt16(Session["UId"]) * 2;
}
Now below is my Webmethod:
[WebMethod]
public static void Save()
{
UserInfo objUser = new UserInfo();
objUser.Useid = Convert.ToInt16(Session["UId"]);
objUser.CalcUser = CalcUser();
... Save into Database
}
So how can I use session value and function in webmwthod.
Thanks
You need to explicitly state that you want to use Session with your ASP.NET AJAX Page Method by using the EnableSession= true value in the WebMethod attribute, like this:
[WebMethod(EnableSession = true)]
public static void Save()
{
UserInfo objUser = new UserInfo();
objUser.Useid = Convert.ToInt16(HttpContext.Current.Session["UId"]);
objUser.CalcUser = CalcUser();
... Save into Database
}
Note: You must fully qualify the namespace of the session (HttpContext.Current.Session).
To use the CalcUser() function you need to make it static and fully qualify the Session object, like this:
public static int CalcUser()
{
return Convert.ToInt16(HttpContext.Current.Session["UId"]) * 2;
}
Note: ASP.NET AJAX Page Methods only have access to static methods, as there is no instance of the page (or any class for that matter).
You need to use [WebMethod(EnableSession = true)] on webmethod
Then you can use like Context.Session["key"]
[WebMethod]
[WebMethod(EnableSession = true)]
public static void Save()
{
UserInfo objUser = new UserInfo();
objUser.Useid = Convert.ToInt16(Context.Session["UId"]);
objUser.CalcUser = CalcUser();
... Save into Database
}
Related
I get the json value using the retrofit library at application launch and I want to send it to the global variable in the class. How can I do it?
Domain is coming, I can see it on the screen with toast message
public void onCreate() {
setRetrofitSettings();
}
public void setRetrofitSettings(){
retrofit = new Retrofit.Builder()
.baseUrl(baseUrl)
.addConverterFactory(GsonConverterFactory.create())
.build();
timeApi = retrofit.create(TimeApi.class);
timeTurkeyCall = timeApi.getTime();
timeTurkeyCall.enqueue(new Callback<TimeTurkey>() {
#Override
public void onResponse(Call<TimeTurkey> call, Response<TimeTurkey> response) {
if (response.isSuccessful()){
timeTurkey = response.body();
Global.APIURL = String.valueOf(timeTurkey.getDateTime());
// I want to send the value here.
}
}
#Override
public void onFailure(Call<TimeTurkey> call, Throwable t) {
System.out.println(t.toString());
}
});
}
I want to send post value to global class
I want the incoming data to be assigned to the API_URL variable from here
public class Global {
public static final String API_URL;
}
I want the incoming domain to be active as long as the application is open.
I want to pass the url of a webpage containing a <span id="spanID"> value </span> tag to a method like setTextBoxText(string url, string id) which is written in a wpf application codeBehind (MainWindow.xaml.cs) and set the Text of a specific TextBox Control to the span value, without loading the webpage. (for Ex. tracking price of a product in amazon)
I prefer to execute JavaScript code to get value of html elements and set the content of wpf controls to the result of the js code (function)
something like this:
public partial class MainWindow : Window
{
string url = "https://websiteaddress.com/rest";
setTextBoxText(url, "spanID");
static void setTextBoxText(string url, string id)
{
// code to get document by given url
txtPrice.Text = getHtmlElementValue(id);
}
string getHtmlElementValue(string id)
{
// what code should be written here?
// any combination of js and c#?
// var result = document.getElementById(id).textContent;
// return result;
}
}
You can use the HttpClient to load the HTML content of an URL and then process the DOM object in a JavaScript like syntax by wrapping the response into a mshtml.HTMLDocument - requires reference to Microsoft.mshtml.dll:
private mshtml.HTMLDocument HtmlDocument { get; set; }
private async Task SetTextBoxTextAsync(string url, string id)
{
await UpdateHtmlDocumentAsync(url);
var value = GetHtmlElementValueById(id);
txtPrice.Text = value;
}
public async Task UpdateHtmlDocumentAsync(string url)
{
using (HttpClient httpClient = new HttpClient())
{
byte[] response = await httpClient.GetByteArrayAsync(url);
string httpResponseText = Encoding.GetEncoding("utf-8").GetString(response, 0, response.Length - 1);
string htmlContent = WebUtility.HtmlDecode(httpResponseText);
this.HtmlDocument = new HTMLDocument();
(this.HtmlDocument as IHTMLDocument2).write(htmlContent);
}
}
public string GetHtmlElementValueById(string elementId)
=> this.HtmlDocument.getElementById(elementId).innerText;
I've been given a script function and would like to partially translate it to C# in a Blazor app
<script>
function pay() {
var token = document.getElementById('token').value;
var card = document.getElementById('card').value;
var exp = document.getElementById('exp').value;
var cvv = document.getElementById('cvv').value;
var paymentData = {
ssl_txn_auth_token: token,
ssl_card_number: card,
ssl_exp_date: exp ,
ssl_cvv2cvc2: cvv
};
ConvergeEmbeddedPayment.pay(paymentData);
return false;
}
</script>
I want to call the script (that is inside the script above)
ConvergeEmbeddedPayment.pay(paymentData);
Directly from c# . Like so
await JsRuntime.InvokeVoidAsync("ConvergeEmbeddedPayment.pay", paymentData);
There is some good information here:
https://learn.microsoft.com/en-us/aspnet/core/blazor/call-javascript-from-dotnet?view=aspnetcore-3.1
But it stops short of helping me.
What kind of variable should I pass in the paymentData parameter? And how should I pass it?
I've tried var , object and string and also tried JsonSerializer.Serialize( ); but no luck
Based on suggestion from #BurningKarl I tried Dictionary and object[] but
I get an error saying the content is missing or "Expected BEGIN_OBJECT but was STRING "
Looks like you have to create your own c# class that mimics the payment data object in your Javascript.
Something like this
public class PaymentData
{
public string ssl_txn_auth_token {get; set;}
public string ssl_card_number{get; set;}
public string ssl_exp_date{get; set;}
public string ssl_cvv2cvc2{get; set;}
}
Then you have to create an instance of this class and pass it to InvokeVoidAsync as an argument.
var data = new PaymentData ()
{
ssl_txn_auth_token = "authtokenvalue",// you have to get it from control
ssl_card_number = "card number",
ssl_exp_date: "date", // probably it should be daytime or similar
ssl_cvv2cvc2 = "111"
}
await JsRuntime.InvokeVoidAsync("ConvergeEmbeddedPayment.pay", data);
I have some belows , please help me how i can get Session in Javascript code from Controller ?
public ActionResult Login(FormCollection f)
{
string sAcount = f["txtAccount"].ToString();
string sPassword = f.Get("txtPassword").ToString();
tblCustom cs = db.tblCustoms.SingleOrDefault(n=>n.Account==sAccount && n.Password==sPassword);
if (cs != null)
{
Session["Account"] = cs;
return View();
}
return View();
}
and JS code is
<script >
$('#btnSendMsg').click(function () {
var msg = $("#txtMessage").val();
alert('Hello' + Session["Account"] );
});
<script/>
the result is alert stil is not working, help me.
You should not update sessions many times, the type of data stored in Sessions are User Roles, Page Permissions and other global information. Once the login is done you should set login cookie. For login, you should use FormsAuthentication cookie.
Follow set Forms authentication to set forms authentication cookie.
Or check this link Create Forms Authentication cookie.
In the page use
alert("#HttpContext.Current.User.Identity.Name");
Although this doesn't directly answer your question, the preferred approach is to create ViewModels while passing and retrieving parameters.
Create a LoginViewModel:
public class LoginViewModel {
public tblCustoms Customs { get; set; }
//other stuff you have, you might consider moving account and password here too,
//instead of capturing with textbox names
//public string Account { get; set; }
//public string Password { get; set }
}
Pass that instead to the view.
public ActionResult Login(FormCollection f)
{
string sAcount = f["txtAccount"].ToString();
string sPassword = f.Get("txtPassword").ToString();
var cs = db.tblCustoms.SingleOrDefault(n=>n.Account==sAccount && n.Password==sPassword);
if (cs != null)
{
Session["Account"] = cs;
//return View(); you don't need this line
}
return View(new LoginViewModel() { Customs = cs });
}
Add to top of your view:
#model YourNameSpace.LoginViewModel
And in the javascript:
<script>
$('#btnSendMsg').click(function () {
var msg = $("#txtMessage").val();
alert('Hello ' + #Model.Customs );
});
<script/>
As an alternative to all of these, you can use ViewBag.
In the controller method, assign it to any name:
ViewBag.Customs = cs;
Then call it in the view:
alert('Hello ' + #ViewBag.Customs );
In order to use Session in your view, try this:
#Session["Account"].ToString();
Recently I have encounter a problem with the web application. I'm using the spring mvc restful application together with hibernate as jpa.
The client could build a xml file using this format:
<SCCF>
<registerSCCF>...</registerSCCF>
...
<registerSCCF>...</registerSCCF>
</SCCF>
The web app will then mapping every data inside registerSCCF tag to a class and save it in the database.
Now I am suffering with the problem that when i test it using soapui and multithreading test, i always get the exception
[ERROR] an assertion failure occured (this may indicate a bug in Hibernate, but is more likely due to unsafe use of the session)
org.hibernate.AssertionFailure: null id in draft.persistence.entity.dcrm.CustomersNoneSSO entry (don't flush the Session after an exception occurs)
or
Caused by: org.hibernate.HibernateException: Flush during cascade is dangerous
or
org.hibernate.SessionException: Session is closed!
Here is the service layer code:
#Transactional("dcrm")
public boolean postSCCFService(SCCFVO sccf){
CustomersNoneSSO cns = new CustomersNoneSSO();
cns.setAppid(sccf.getAppid());
cns.setCustomer_name(sccf.getCustomer_name());
cns.setCustomer_gender(sccf.getCustomer_gender());
cns.setContact_mobile(sccf.getContact_mobile());
cns.setContact_email(sccf.getContact_email());
cns.setAddress_province(sccf.getAddress_province());
cns.setAddress_city(sccf.getAddress_city());
cns.setCustomer_address(sccf.getCustomer_address());
cns.setCustomer_occupation(sccf.getCustomer_occupation());
cns.setPurchase_brand(sccf.getPurchase_brand());
cns.setPurchase_model(sccf.getPurchase_model());
cns.setPurchase_date(sccf.getPurchase_date());
cns.setPurchase_budget(sccf.getPurchase_budget());
cns.setOwncar_selected(sccf.getOwncar_selected());
cns.setOwncar_model(sccf.getOwncar_model());
cns.setTestdrive_permission(sccf.getTestdrive_permission());
cns.setMarketing_permission(sccf.getMarketing_permission());
Timestamp t = new Timestamp(new Date().getTime());
cns.setInsert_timestamp(t);
cns.setUpdate_timestamp(t);
cnsDao.makePersistent(cns);
}
if i set all the setter to static values like:
cns.setContact_email("test#test.test");
instead of using the value from the parameter, then the app runs well with the multithreading test.
There is the controller calls the service method:
#RequestMapping(value = "/test",method=RequestMethod.POST)
public #ResponseBody SCCFResponseList getPostResults(#RequestBody SCCFVOList sccf){
...
for(SCCFVO sccfvo : sccf.getSCCFVOList()){
...
boolean result = sccfservice.postSCCFService(sccfvo);
...
}
...
}
public class SCCFVOList {
And here is the request body class:
#XmlElement(name="registerSCCF")
public class SCCFVOList {
private Vector<SCCFVO> SCCFVOList = null;
public Vector<SCCFVO> getSCCFVOList(){
return SCCFVOList;
}
public void setSCCFVOList(Vector<SCCFVO> SCCFVOList){
this.SCCFVOList = SCCFVOList;
}
}
And here the dao
public class CNSDao extends GenericHibernateDAO<CustomersNoneSSO, Long> {}
public abstract class GenericHibernateDAO<T, ID extends Serializable>
implements GenericDAO<T, ID> {
private Class<T> persistentClass;
private Session session;
SessionFactory sessionFactory;
public void setSessionFactory(SessionFactory sessionFactory){
this.sessionFactory = sessionFactory;
}
public GenericHibernateDAO() {
this.persistentClass = (Class<T>) ((ParameterizedType) getClass()
.getGenericSuperclass()).getActualTypeArguments()[0];
}
#SuppressWarnings("unchecked")
public void setSession(Session s) {
this.session = s;
}
protected Session getSession() {
session = sessionFactory.getCurrentSession();
if (session == null)
throw new IllegalStateException(
"Session has not been set on DAO before usage");
return session;
}
public Class<T> getPersistentClass() {
return persistentClass;
}
#SuppressWarnings("unchecked")
public T makePersistent(T entity) {
getSession().saveOrUpdate(entity);
return entity;
}
public void makeTransient(T entity) {
getSession().delete(entity);
}
...
}
There should be something wrong either the controller method or the service method. Still no idea what was wrong.
Your dao is flawed.
Your dao is a singleton, there is only one. The Hibernate Session object isn't thread safe and shouldn't be used across threads.
You have 1 dao, 2 threads, Thread one gets instance X1 of a session, Thread two resets it to instance X2 now suddenly they share the same session, not to mention Thread 1 might even be operating on 2 different sessions.
As I mentioned in the comments NEVER store the Session in an instance variable. Remove it.
public abstract class GenericHibernateDAO<T, ID extends Serializable> implements GenericDAO<T, ID> {
private Class<T> persistentClass;
private SessionFactory sessionFactory;
public GenericHibernateDAO() {
this.persistentClass = (Class<T>) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0];
}
public void setSessionFactory(SessionFactory sessionFactory){
this.sessionFactory = sessionFactory;
}
protected Session getSession() {
return sessionFactory.getCurrentSession();
}
Also I would suggest dropping this and instead use Spring Data JPA saves you the trouble of creating and maintaining your own generic dao. (You mention you use JPA, if the entities are annotated it should be quite easy to do).