session modify from webmethod - asp.net

is it possible to modify a session from a webmethod, well the complete description is,
I have a button that client side triggered to add data from textboxes into one new row inside a session
The session declared as
public List<Some_Business_Object_Here> A_Session
{
get
{
return (List<Some_Business_Object_Here>)Session["Session_Name_Here"];
}
set
{
Session["Session_Name_Here"] = value;
}
}
and The WebMethod
[WebMethod]
public static string InsertItemDt(List<string> dataIns)
{
BOResponse objRes = new BOResponse();
SomeFormHere form = new SomeFormHere();
Some_Business_Object_Here objDet = new Some_Business_Object_Here();
objDet.Data1 = dataIns[0];
objDet.Data2 = Convert.ToInt32(dataIns[1]);
objDet.Data3 = Convert.ToDecimal(dataIns[2]);
objRes = form.A_Processing_Method(objDet, ListItemDetail);
return new JavaScriptSerializer().Serialize(objRes);
}
and if the method processing to add a new row after some validation
is it possible to do it with this kind of method?
Edit: BOResponse is object for validation, containing only error code and catch error message
so the method be like
Private BOResponse A_Processing_Method (Some_Business_Object_Here obj)
{
try
{
(Some Validation Here...)
if (!validation)
{
MsgCode = 10;
MsgDesc = "Some Custom Error Text Here"
}
else
{
A_Session.Add(obj);
}
}
catch (Exception err)
{
MsgCode = 20;
MsgDesc = err.Message;
}
}

nevermind, seems it's working this way

Related

How to resolve problem to Microsoft.CodeAnalysis.CSharp.Scripting.CSharpScript

[HttpGet("vulnerability")]
public IActionResult vulnerability(string input)
{
object content = 0;
try
{
content = new Microsoft.CodeAnalysis.CSharp.Scripting.CSharpScript(input).EvaluateAsync().Result;
}
catch (Exception)
{
content = "";
}
return View("Example", new { vuln = content });
}
I'm going to implement a "code injection" vulnerability in .net core.
The vulnerable configuration takes input to input and tries to execute it as an eval.
Yes)
Input: 1+1
Result screen: 2
by the way
Microsoft.CodeAnalysis.CSharp.Scripting.CSharpScript(input).EvaluateAsync().Result;
An error occurs in the portion. Occurrence Error - CS0712
EvaluateAsync()
Microsoft.CodeAnalysis.CSharp.Scripting.CSharpScript(input).EvaluateAsync().Result;
An error occurs in the portion. CS0712
EvaluateAsync() Occurrence Error - CS1501
How can I solve this?
I tried to solve the problem by referring to the official document.
Your code should like below:
[HttpGet("vulnerability")]
public async Task<IActionResult> vulnerability(string input)
{
object content = 0;
try
{
content = await CSharpScript.EvaluateAsync(input);
}
catch (Exception)
{
content = "";
}
return Ok(new { vuln = content });
}
And the test result:

Inspite of checking for null with usercontrol checkboxlist is returning object reference not set to an instance of an object

I have a group of 7 checkboxes in checkboxlist user control. I build a string in the selectedIndexchanged event for the boxes checked, pass to ViewState and then pass ViewState to the Property. I do this because in the instance when no checkboxes are selected I want to handle null. The problem is no matter how I check for null, the system is throwing object reference error. This current setup works fine if at least one checkbox is checked but if none are checked it fails. How do I check for null? Should I be checking for null in the property or the host aspx page?
I have researched difference ways to do this and I have tried many. My thought is using IsNullOrEmpty or IsNullOrWhiteSpace would be the correct way to go but neither are working.
User Control class - global variable
private string _daysOffInputString = string.Empty;
User Control Property
public string DaysOffSelectedValues
{
get
{
if (string.IsNullOrEmpty(ViewState["DaysOff"].ToString()))
{
_daysOffInputString = string.Empty;
}
else
{
_daysOffInputString = ViewState["DaysOff"].ToString();
}
return _daysOffInputString;
}
set { _daysOffInputString = value; }
User Control event
protected void CbDaysOff_SelectedIndexChanged(object sender, EventArgs e)
{
CheckBoxList chkbx = (CheckBoxList)sender;
StringBuilder sb = new StringBuilder();
for (int i = 0; i < chkbx.Items.Count; i++)
{
if (chkbx.Items[i].Selected)
{
sb.Append(chkbx.Items[i].Text + ", ");
}
if (!String.IsNullOrEmpty(sb.ToString()))
{
//Remove last comma & space from string
_daysOffInputString = sb.ToString().Substring(0, sb.ToString().Length - 2);
}
else
{
_daysOffInputString = string.Empty;
}
}
ViewState["DaysOff"] = _daysOffInputString;
}
aspx page - snippet where I retrieve uc property value:
case 2:
blnFlag = false;
ucDaysOff uc3 = row.Cells[3].FindControl("ucDaysOff3") as ucDaysOff;
strAnswer = uc3.DaysOffSelectedValues; //e.g. "Sat, Sun"
break;
SOLUTION: In the user control property DaysOffSelectedValues I was casting ViewState["DaysOff"] to string before checking for null which was the problem. Here's the code that works:
public string DaysOffSelectedValues
{
get
{
if (ViewState["DaysOff"] == null)
{
//_daysOffInputString = string.Empty; }
_daysOffInputString = "Nothing to see here.";
}
else
{
_daysOffInputString = ViewState["DaysOff"].ToString();
}
return _daysOffInputString;
}
set { _daysOffInputString = value; }
}
You should always check if the object, in this case ViewState, is null before using it. Lets say ViewState["DaysOff"] has not been created or has been removed.
Then this will throw a nullreference:
string str = String.IsNullOrEmpty(ViewState["DaysOff"].ToString());
Because you are not checking the ViewState object for null, but the string it is supposed to hold.
So do this
if (ViewState["DaysOff"] != null)
{
string str = ViewState["DaysOff"].ToString();
}

release_mode, Pooling, Max Pool size for InMemory SQLite with FluentNHibernate

I'm having some trouble with Sqlite in memory.
I have a class that has a CPF field - similar to US' SSN. As a bussiness rule, the CPF must be unique in the system.
So I've decided to make a check on the class that has this field. Now maybe there's code smell here: I check with the ORM if this is a Conflicting CPF.
private CPF cpf;
public virtual CPF CPF
{
get { return cpf; }
set
{
if (this.ormCreated) //Do not check if it is loaded from the DB. Otherwise, it loops, generating a StackOverflow exception
{
cpf = value;
}
else
{
this.setNewCpf(value);
}
}
}
private void setNewCpf(CPF newCpf)
{
if (this.cpf == newCpf)
{
return;
}
if (Helper.Orm.IsConflictingCpf(newCpf))
{
throw new ConflictingCpfException();
}
else
{
cpf = newCpf;
}
}
And here is the implementation, on the ORM Helper class.
bool OrmHelper.IsConflictingCpf(CPF cpf)
{
int? cpfNumber = cpf.NumeroSemDV;
if (cpfNumber.HasValue)
{
var teste = findByCpfNumber<Client>(cpf);
return
(
findByCpfNumber<Client>(cpf) != null ||
findByCpfNumber<Adversary>(cpf) != null
);
}
else
{
//CPFSemDV = Nullable
return false;
}
}
private PersonType findByCpfNumber<PersonType> (CPF cpf) where PersonType : PessoaFisica
{
int? cpfNumber = cpf.NumeroSemDV;
using (var session = this.NewSession())
using (var transaction = session.BeginTransaction())
{
try
{
var person = session.Query<PersonType>()
.Where(c => c.CPF.NumeroSemDV == cpfNumber)
.FirstOrDefault<PersonType>();
return person;
}
catch (Exception) { transaction.Rollback(); }
finally
{
session.Close();
}
}
return null;
}
The problem happens in my tests. I'm using FluentNHibernate and In memory SQLite.
protected override FluentConfiguration PersistenceProvider
{
get
{
return Fluently
.Configure()
.Database(
SQLiteConfiguration
.Standard
.InMemory()
.ShowSql()
);
}
}
Here is the failing test.
protected override void Given()
{
base.Given();
var clients = new List<Client>();
Client client1 = new Client("Luiz Angelo Heinzen")
{
Capaz = true,
CPF = new CPF(18743509),
eMail = "lah#furb.br"
};
session.Save(client1);
session.Evict(client1);
}
[Then]
public void Motherfaker()
{
Client fromDb;
var clientsFromDb = session.Query<Client>()
.Where(c => c.eMail == "lah#furb.br");
fromDb = clientsFromDb.FirstOrDefault<Client>();
Assert.AreEqual(fromDb.FullName, "Luiz Angelo Heinzen");
}
The reason it fails? In the beginning it was failing because the table didn't exist. In memory sqlite destroys the schema on each new session. So I changed the code to return the same session on the NewSession(). But now it fails with a NHibernate exception: Session is closed. I've tested and if change the findByCpfNumber from this
private PersonType findByCpfNumber<PersonType> (CPF cpf) where PersonType : PessoaFisica
{
int? cpfNumber = cpf.NumeroSemDV;
using (var session = this.NewSession())
using (var transaction = session.BeginTransaction())
{
try
{
var person = session.Query<PersonType>()
.Where(c => c.CPF.NumeroSemDV == cpfNumber)
.FirstOrDefault<PersonType>();
return person;
}
catch (Exception) { transaction.Rollback(); }
finally
{
session.Close();
}
}
return null;
}
to this
private PersonType findByCpfNumber<PersonType> (CPF cpf) where PersonType : PessoaFisica
{
int? cpfNumber = cpf.NumeroSemDV;
//using (var session = this.NewSession())
var session = this.NewSession();
using (var transaction = session.BeginTransaction())
{
try
{
var person = session.Query<PersonType>()
.Where(c => c.CPF.NumeroSemDV == cpfNumber)
.FirstOrDefault<PersonType>();
return person;
}
catch (Exception) { transaction.Rollback(); }
finally
{
//session.Close();
this.CloseSession(session);
}
}
this.CloseSession(session);
return null;
}
the error doesn't happen anymore. Obviously, I'd have to implement the CloseSession method. It would close the Session on the Production database and it would do nothing if Sqlite is being used.
But I'd rather configure SQLite in someway that it wouldn't dispose the session. I've read here about release_mode, Pooling and Max Pool atributes. But I can't seem to find it in the FluentNHibernate so can't even test to see if it would work. I have the FluentNHibernate cloned and it seems to set the release_mode set to on_close, but that doesn't help.
I've even tried:
public override ISession NewSession()
{
if (this.session == null)
{
if (sessionFactory == null)
{
CreateSessionFactory();
}
this.session = sessionFactory.OpenSession();
}
if (!session.IsOpen)
{
sessionFactory.OpenSession(session.Connection);
session.Connection.Open();
}
return session;
}
But it keeps telling me that the Session is closed. So, anyone has any suggestions on how to approach this?
Or does this so smelly that's beyond salvation?
I hope this is clear enough. And forgive my mistakes: I'm from Brazil and not a native english speaker.
Thanks,
Luiz Angelo.
i would check for uniqueness when creating CPFs in the system and have an additional Unique constraint in the database to enforce that. Then if you set cascading to none for each reference to CPF (default is none) it is not possible to assigne newly created duplicate CPFs to an Entity and save it without exception, so it can't happen accidently.
I had the same problem. What's happening is that in-memory SQLite will drop the entire schema when the connection is closed. If you create a session that you hold on to for all tests, it will retain the structure for all other sessions.
For code and a fuller explanation, check out this answer: Random error when testing with NHibernate on an in-Memory SQLite db

ASP.NET custom controls - custom property doesn't hold the assigned value on postaback

I have a custom asp-net control that inherits from another one and its works as expected, though the properties are only set properly if i code them in the markup directly, so for instance if i need set a property at runtime that is some dynamic value, this value is never set or somehow lost.
Here's the markup code:
<!--related form-->
<fw:advancedformdisplay id="formDisp" runat="server" captchaenabled="true" EmailEnabled="true" EnableViewState="true" captchaprivatekey="xxxxxxxxxxxxxxxxxxxx" captchapublickey="xxxxxxxxxxxxx" captchatheme="white" SourceType="MenuItem" SourceMainId="Auto">
</fw:advancedformdisplay>
This is the code of the control:
[DefaultProperty("CaptchaEnabled"),ToolboxData("<{0}:AdvancedFormDisplay runat=server></{0}:AdvancedFormDisplay>"), Description("This is an enhanced FormDisplay control that inlcudes Googles Captcha control is enabled")]
public class AdvancedFormDisplay :SiteBuilder.WebControls.FormDisplay
{
bool _CaptchaEnabled = false, sendEmail = false;
string captchaErrorMessage = "The verification code entered is not valid. Please try again!";
RecaptchaControl captchaControl = null;
string captchaPrivateKey = "", captchaPublicKey = "", captchaTheme = "clean";
string originalFormHtml = string.Empty;
string afterText = string.Empty, beforeText = string.Empty;
Literal litHtmlForm = null;
string captchaErrorClass = "errorCaptcha";
public string EmailBeforeText
{
get { return beforeText; }
set { beforeText = value; }
}
public string EmailAfterText
{
get { return afterText; }
set { afterText = value; }
}
public string CaptchaErrorClass
{
get { return captchaErrorClass; }
set { captchaErrorClass = value; }
}
public bool CaptchaEnabled
{
get { return _CaptchaEnabled; }
set { _CaptchaEnabled = value; }
}
public bool EmailEnabled
{
get { return sendEmail; }
set { sendEmail = value; }
}
public string CaptchaErrorMessage
{
get { return captchaErrorMessage; }
set { captchaErrorMessage = value; }
}
/// <summary>
/// red,white,blackglass,clean
/// </summary>
public string CaptchaTheme
{
get { return captchaTheme; }
set { captchaTheme = value; }
}
public string CaptchaPrivateKey
{
get { return captchaPrivateKey; }
set { captchaPrivateKey = value; }
}
public string CaptchaPublicKey
{
get { return captchaPublicKey; }
set { captchaPublicKey = value; }
}
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
}
public override void OnSaved(FormDisplayEventArgs e)
{
//If captcha control is enabled we need to adda bit of code to redirect form properly
if (CaptchaEnabled && e.Redirect && !e.SendMail)
{
//Do Stuff
}
if(sendEmail)
{
//Send email
}
base.OnSaved(e);
}
public override void OnSaving(FormDisplayEventArgs e)
{
if (CaptchaEnabled)
{
//Validate and do stuff
}
base.OnSaving(e);
}
}
And then in my asp.net page that is using control, created by markup code, in the Page_Load() i try to assign some values to some properties and and the values aren't set properly, meaning that if i have set for isntance, the property EmailBeforeText = "somthing" this value will not be assigned..
protected void Page_Load(object sender, EventArgs e)
{
//2: Get the language of menuitem - Based on current culture setting (for by dropdownbox - change logic)
try
{
currentCulture = Thread.CurrentThread.CurrentCulture.ToString();
// Redirect if domain does not match rootnode.
DomainChecker.CheckURL(this.Request, this.Response, currentCulture);
if (footerArticle != null)
footerArticle.SourceMenuId = Digimaker.Config.Custom.Get("FooterID_" + currentCulture).ToString();
}
catch
{
currentCulture = "en-GB";
if( footerArticle != null )
footerArticle.SourceMenuId = Digimaker.Config.Custom.Get("FooterID_" + currentCulture).ToString();
}
Any ideas what i'm missing here?
Thanks a lot for your reading!
Regards,
byte_slave
short answer: use viewstate to persist your custom values!
Understanding ASP.NET ViewState whitepaper (see example with NavigateUrl)
edit: as reading the white-paper is obviously a really hard thing:
Each control is responsible for storing its own state, which is
accomplished by adding its changed state to its ViewState property.
The ViewState property is defined in the System.Web.UI.Control class,
meaning that all ASP.NET server controls have this property available.
(When talking about view state in general I'll use lower case letters
with a space between view and state; when discussing the ViewState
property, I'll use the correct casing and code-formatted text.)
If you examine the simple properties of any ASP.NET server control
you'll see that the properties read and write directly to the view
state. (You can view the decompiled source code for a .NET assembly by
using a tool like Reflector.) For example, consider the HyperLink Web
control's NavigateUrl property. The code for this property looks like
so:
public string NavigateUrl
{
get
{
string text = (string) ViewState["NavigateUrl"];
if (text != null)
return text;
else
return string.Empty;
}
set
{
ViewState["NavigateUrl"] = value;
}
}
As this code sample illustrates, whenever a control's property is
read, the control's ViewState is consulted. If there is not an entry
in the ViewState, then the default value for the property is returned.
When the property is assigned, the assigned value is written directly
to the ViewState.

interesting service behaviour in silverlight

I have a Silverlight project which takes some encrypted string thru its Service Reference: DataService (service which is done in an ASP.NET project).
The method from TransactionServices.cs to get the encrypted string is:
public void GetEncryptedString(string original)
{
DataService.DataServiceClient dataSvc = WebServiceHelper.Create();
dataSvc.GetEncryptedStringCompleted += new EventHandler<SpendAnalyzer.DataService.GetEncryptedStringCompletedEventArgs>(dataSvc_GetEncryptedStringCompleted);
dataSvc.GetEncryptedStringAsync(original);
}
On completing, put the result in encodedString var (which is initialized with an empty value):
void dataSvc_GetEncryptedStringCompleted(object sender, SpendAnalyzer.DataService.GetEncryptedStringCompletedEventArgs e)
{
if (e.Error == null)
{
try
{
if (e.Result == null) return;
this.encodedString = e.Result;
}
catch (Exception ex)
{
Logger.Error("TransactionService.cs: dataSvc_GetEncryptedStringCompleted: {0} - {1}",
ex.Message, ex.StackTrace);
MessageBox.Show(ex.ToString());
}
}
}
Now I want to get the encoded string from my MainPage.xaml like:
TransactionService ts = new TransactionService();
ts.GetEncryptedString(url);
Console.WriteLine(ts.encodedString);
I do not uderstand why ts.encodedString is empty. When I do the debug I see that it actually prints out empty and AFTER that it goes to the void dataSvc_GetEncryptedStringCompleted to take the result and fill it.
Can you point me what I've done wrong? Is there a way to wait for the encodedString to be fetched and only after that to continue?
Thanks a lot.
When you call the ts.GetEncryptedString(url); you just started async operation. And therefor the value you are accessing is will be set only in the callback method.
But you access it before the value is modified by the callback.
The solution which I am using will looks similar to folowing:
Redefine the GetEncryptedString method signature.
public void GetEncryptedString(string original, Action callback)
{
DataService.DataServiceClient dataSvc = WebServiceHelper.Create();
dataSvc.GetEncryptedStringCompleted += (o,e) =>
{
dataSvc_GetEncryptedStringCompleted(o,e);
callback();
}
dataSvc.GetEncryptedStringAsync(original);
}
Call it like this:
ts.GetEncryptedString(url, OtherLogicDependantOnResult);
where
OtherLogicDependantOnResult is
void OtherLogicDependantOnResult()
{
//... Code
}

Resources