View state or Hidden Field - asp.net

I have to store eight to ten values in variables which are available even after post back.
I tried using Hidden Field but value is lost on post back. I am now using View state , but it seems it is degrading performance.
I have ten View State fields. what should I use to avoid poor performance ?

You can store Dictionary in ViewState.
private Dictionary<string, string> MyValues
{
get
{
var value = ViewState["MyValues"] as Dictionary<string, string>;
return value ?? new Dictionary<string, string>();
}
set { ViewState["MyValues"] = value; }
}
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
var myValues = new Dictionary<string, string>
{
{"One", "1"}, {"Two", "2"}, {"Three", "3"}
};
MyValues = myValues;
}
else
{
string value1 = MyValues["One"];
string value2 = MyValues["Two"];
string value3 = MyValues["Three"];
}
}

Related

Pass values to a button from function

I have a function which is receiving parameters from another function and I have to pass these parameters to a button when it's execution get's complete !
async void CallCompanyApi(String CompanyGp, string CompanyId)
{
First.IsVisible = false;
Second.IsVisible = true;
// Next_Clicked(CompanyGp,CompanyId)
}
private void Next_Clicked(object sender, EventArgs e)
{
}
I have to pass these 2 parameters to that button !
you need to create class level variables to store these values
string _CompanyGp;
string _CompanyId;
async void CallCompanyApi(String CompanyGp, string CompanyId)
{
First.IsVisible = false;
Second.IsVisible = true;
// store the parameters in the class level variables
_CompanyGp = CompanyGp;
_CompanyId = CompanyId;
}
private void Next_Clicked(object sender, EventArgs e)
{
// you can now just reference _CompanyGp and _CompanyId
}
FYI, this is basic C# and really has nothing specific to do with Xamarin
Welcome to SO!
If CallCompanyApi and Next_Clicked located in different class, you can store them in Xamarin Forms by using Preferences.
using Xamarin.Essentials;
async void CallCompanyApi(String CompanyGp, string CompanyId)
{
First.IsVisible = false;
Second.IsVisible = true;
//Next_Clicked(CompanyGp,CompanyId)
Preferences.Set("CompanyGp", CompanyGp);
Preferences.Set("CompanyId", CompanyId);
}
Then in another class, click button will get them:
private void Next_Clicked(object sender, EventArgs e)
{
var CompanyGp = Preferences.Get("CompanyGp", "default_value");
var CompanyId = Preferences.Get("CompanyId", "default_value");
}
Else if they are in the same class, you can use the way as Jason's said.
============================Update=========================
You can set a default value if needed, such as follow:
var CompanyGp = Preferences.Get("CompanyGp", "Company_A");
var CompanyId = Preferences.Get("CompanyId", "1");
Defalut CompanyGp is Company_A, and default CompanyId is 1.

Label TextProperty CoerceValue delegate not called

I use Reflection to set the Label.TextProperty.CoerceValue to my custom delegate (TextProperty.CoerceValue are null by default)
but when Label text changed, the delegate are not called
the same strategy are apply/tried on Image.SourceProperty, Entry.TextProperty
all are called successful
is bug or Label.TextProperty by design will not call CoerceValue delegate?
thank you very much.
Xamarin.Forms 4.3.0.947036
var property = Label.TextProperty;
var coerceValue = property.GetType().GetProperty("CoerceValue", BindingFlags.NonPublic | BindingFlags.Instance);
oldDelegate = coerceValue?.GetValue(property) as BindableProperty.CoerceValueDelegate;
coerceValue?.SetValue(property, (bindable, value) => {
var modified = ModifyValue(value); // simply modify the value if required
return modified
});
If you want to call CoerceValue when Label.Text changed, I suggest you can use Bindable Properties to bind Label.TextPrperty.
public partial class Page9 : ContentPage
{
public static readonly BindableProperty labelvalueProperty = BindableProperty.Create("labelvalue", typeof(string), typeof(Page9), null , coerceValue: CoerceValue);
public string labelvalue
{
get { return (string)GetValue(labelvalueProperty); }
set { SetValue(labelvalueProperty, value); }
}
private static object CoerceValue(BindableObject bindable, object value)
{
string str = (string)value;
if(str=="cherry")
{
str = "hello world!";
}
return str;
}
public Page9 ()
{
InitializeComponent ();
label1.SetBinding(Label.TextProperty, "labelvalue");
labelvalue = "this is test";
BindingContext = this;
}
private void Btn1_Clicked(object sender, EventArgs e)
{
labelvalue = "cherry";
}
}
You can see the CoerceValue can be fired when Label.Text property changed.
I created a new Page Page1 in a Xamarin.Forms Project, with the following simple code in the code behind:
public Page1()
{
InitializeComponent();
}
protected override void OnAppearing()
{
Label l = new Label();
BindableProperty.CoerceValueDelegate d = (s, a) =>
{
string modified = "textY"; // simply modify the value if required
return modified;
};
var property = Label.TextProperty;
var coerceValue = property.GetType().GetProperty("CoerceValue", BindingFlags.NonPublic | BindingFlags.Instance);
var oldDelegate = coerceValue?.GetValue(property) as BindableProperty.CoerceValueDelegate;
coerceValue?.SetValue(property, d);
l.Text = "1"; // Text property is set to textY thanks to CoerceValueDelegate!
base.OnAppearing();
}
when i call l.Text = "1" the BindableProperty.CoerceValueDelegate i defined is correctly called, and l.Text is set to textY as expected.
#codetale, are you able to run this code on your side?

Passing parameters to remote SSRS report from ASP.NET MVC application

I have an ASP.NET MVC application that uses SSRS for reporting (using a web form and report viewer). I would like to pass two parameters dynamically to the remote report. My current implementation stores the parameters in session, which works fine on VS Development Server, but the variable is null on IIS, upon retrieval in the web form.
Here is the controller method that calls the view
public ActionResult ShowReport(string id)
{
var reportParameters = new Dictionary<string, string>();
reportParameters.Add("Param1", id);
reportParameters.Add("Param2", "user1");
Session["reportParameters"] = reportParameters;
return View("ReportName");
}
And here is how I attempt to retrieve the parameters from the web form
protected void Page_Load(object sender, EventArgs e)
{
var reportParameters = (Dictionary<string, string>)Session["reportParameters"];
foreach (var item in reportParameters)
{
ReportParameter rp = new ReportParameter(item.Key, item.Value);
ReportViewer1.ServerReport.SetParameters(rp);
}
}
Anyone know why Session["reportParameters"] is null?
Or is there some other way of passing these parameters?
You can do it too:
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
try
{
var js = new JavaScriptSerializer();
string reportPath= Request.QueryString["LocalReport"];
string parametersTemp = Request.QueryString["ParametersReport"];
List<ReportParameter> parameters = null;
if (parametrosTemp != "")
{
parameters = JsonConvert.DeserializeObject
<List<ReportParameter>>(parametrosTemp);
}
GenerateReport(reportPath, parameters );
}
catch (Exception ex) {
statusReport.Value = ex.Message;
}
}
}
private void GenerateReport(string reportPath, List<ReportParameter> reportParameters)
{
reportCurrent.ProcessingMode = ProcessingMode.Remote;
ServerReport serverReport = reportCurrent.ServerReport;
serverReport.ReportServerUrl =
new Uri(AppSettings.URLReportServer);
serverReport.ReportPath = reportPath;
serverReport.Refresh();
if (reportParameters != null)
{
reportCurrent.ServerReport.SetParameters(reportParameters);
}
}
Is the problem that Session["reportParameters"] is null or is it that you don't get any parameters added to your report? Because your code, as it stands, won't add parameters to your report even if you pass them across properly and so the report parameters will be null.
SetParameters takes IEnumerable<ReportParameter> (usually a List), not a ReportParameterobject. Your code should look more like this:
protected void Page_Load(object sender, EventArgs e)
{
var reportParameters = (Dictionary<string, string>)Session["reportParameters"];
List<ReportParameter> parameters = new List<ReportParameter>();
foreach (var item in reportParameters)
{
parameters.Add(new ReportParameter(item.Key, item.Value););
}
ReportViewer1.ServerReport.SetParameters(parameters);
}

Get a list of all active sessions in ASP.NET

I know what user is logged in with the following line of code:
Session["loggedInUserId"] = userId;
The question I have is how do I know what users are logged in so that other users can see what users are currently logged in.
In other words can I get all "loggedInUserId" sessions that are active?
I didn't try rangitatanz solution, but I used another method and it worked just fine for me.
private List<String> getOnlineUsers()
{
List<String> activeSessions = new List<String>();
object obj = typeof(HttpRuntime).GetProperty("CacheInternal", BindingFlags.NonPublic | BindingFlags.Static).GetValue(null, null);
object[] obj2 = (object[])obj.GetType().GetField("_caches", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(obj);
for (int i = 0; i < obj2.Length; i++)
{
Hashtable c2 = (Hashtable)obj2[i].GetType().GetField("_entries", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(obj2[i]);
foreach (DictionaryEntry entry in c2)
{
object o1 = entry.Value.GetType().GetProperty("Value", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(entry.Value, null);
if (o1.GetType().ToString() == "System.Web.SessionState.InProcSessionState")
{
SessionStateItemCollection sess = (SessionStateItemCollection)o1.GetType().GetField("_sessionItems", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(o1);
if (sess != null)
{
if (sess["loggedInUserId"] != null)
{
activeSessions.Add(sess["loggedInUserId"].ToString());
}
}
}
}
}
return activeSessions;
}
There is a solution listed in this page List all active ASP.NET Sessions
private static List<string> _sessionInfo;
private static readonly object padlock = new object();
public static List<string> Sessions
{
get
{
lock (padlock)
{
if (_sessionInfo == null)
{
_sessionInfo = new List<string>();
}
return _sessionInfo;
}
}
}
protected void Session_Start(object sender, EventArgs e)
{
Sessions.Add(Session.SessionID);
}
protected void Session_End(object sender, EventArgs e)
{
Sessions.Remove(Session.SessionID);
}
Basically it just tracks sessions into a List that you can use to find out information about. Can really store anything into that that you really want to - Usernames or whatever.
I don't htink there is anything at the ASP .net layer that does this already?
foreach (var item in Session.Contents)
{Response.Write(item + " : " + Session[(string)item] + "<br>");}

ASP.NET lisbox - Selected first item, always

I have a list box which is populated using a dictioanry. When I iterate throught the selected items using the following code, it always show only the first items as selected - even if the first item is not selected.
Have you ever encountered this scenario?
Could you please help on this?
This problem occurs when I use dictionary for binding. On the other hand a generic list works fine.
private void PopulateListBox2()
{
List<string> subjectList = new List<string>();
subjectList.Add("Maths");
subjectList.Add("Science");
ListBox1.DataSource = subjectList;
ListBox1.DataBind();
}
Even it will work fine, if the values are unique. But in my scenario, the values are same; only key varies. The following works
private void PopulateListBox5()
{
Dictionary<string, string> resultDictionary = new Dictionary<string, string>();
resultDictionary.Add("Maths", "Lijo1");
resultDictionary.Add("Science", "Lijo2");
ListBox1.DataValueField = "Value";
ListBox1.DataTextField = "Key";
ListBox1.DataSource = resultDictionary;
ListBox1.DataBind();
}
^^^^^^^^^^^^^^^^^^^
The following code has the problem.
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
PopulateListBox1();
ListBox1.SelectionMode = ListSelectionMode.Multiple;
}
}
private void PopulateListBox1()
{
Dictionary<string, string> resultDictionary = new Dictionary<string, string>();
resultDictionary.Add("Maths", "Lijo");
resultDictionary.Add("Science", "Lijo");
ListBox1.DataValueField = "Value";
ListBox1.DataTextField = "Key";
ListBox1.DataSource = resultDictionary;
ListBox1.DataBind();
}
protected void Button1_Click(object sender, EventArgs e)
{
MakeList1Items();
}
private void MakeList1Items()
{
string test = null;
foreach (ListItem item in ListBox1.Items)
{
if (item.Selected == true)
{
if(string.IsNullOrEmpty(test))
{
test=item.Text;
}
else
{
test = test +", " + item.Text;
}
}
}
Response.Write(test);
}
}
Thanks
Lijo
You have the DataValueField and DataTextField of the ListBox the wrong way around. I'm not sure why, but they must be like this:
ListBox1.DataValueField = "Key";
ListBox1.DataTextField = "Value";
So, in reality, you are best not using a Dictionary for for this kind of binding. Maybe try a List<KeyValuePair<string, string>> instead.

Resources