how to check string value and refresh the page in asp.net - asp.net

i have a static string in static class, its getting value from desktop application,
on asp.net i have to check that its null or have value, if it has value , i want to
show it on label (on aspx page) , i have put a backgroud worker in global.asax,
public static BackgroundWorker worker = new BackgroundWorker();
public static int ID = 0;
// public static List<Person> personList = new List<Person>();
public static string personList;
public static bool stopWorker = false;
void Application_Start(object sender, EventArgs e)
{
worker.DoWork += new DoWorkEventHandler(DoWork);
worker.WorkerReportsProgress = true;
worker.WorkerSupportsCancellation = true;
worker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(WorkerCompleted);
// Calling the DoWork Method Asynchronously
worker.RunWorkerAsync();
private static void DoWork(object sender, DoWorkEventArgs e)
{
//foreach (Person p in personList)
//{
personList = Class1.GetDataFromDesktop;
//}
}
its checking value time to time, but i am unable to show the response on label which is on aspx page
, what to do, is there any other process or i can do it using global.asax

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.

display next page asynchronously and then run its page load event

I have an airline site in which i am trying to display the fare from different API/Web service. But Firstly i want to display the search page--> Display processing --> binding data in the page from theses API/web service as they received.
but i am not able to display search page before the result processing.
What i have tried (code)-
public partial class asyncgridview : System.Web.UI.Page,ICallbackEventHandler
{
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsCallback)
{
ltCallback.Text = ClientScript.GetCallbackEventReference(this, "'bindgrid'", "EndGetData", "'asyncgrid'", false);
}
}
private string _Callback;
public string GetCallbackResult()
{
return _Callback;
}
public void RaiseCallbackEvent(string eventArgument)
{
DataTable table = fetchData();
gvAsync.DataSource = table;
gvAsync.DataBind();
using (System.IO.StringWriter sw = new System.IO.StringWriter())
{
gvAsync.RenderControl(new HtmlTextWriter(sw));
_Callback = sw.ToString();
}
}
}
regards
Avishek

Programming on com objects in asp.net

I have a com object from a windows platform application that is written by another language.
I can work with it using winform in C#.but when I want to use it in asp.net ,I should take it on sta threads , Otherwise I get this exception:
ActiveX control 'xxx' cannot be instantiated because the current
thread is not in a single-threaded apartment.
But I have a problem. I have to connect to a server by this com object and keep this connection for next requests (such as i did on winform).
is any way (such as static classes that dose not work here too) that this com object be public for all of the users that request a command.
I put some of my code:
public static class MyServer
{
public static string Error = "";
public static string Result = "";
private static MyComObject a = null;
private static bool IsConnected = false;
private static void Connect()
{
a = MyComObject;
a.CreateControl();
a.ReceivedData += new EventHandler(a_Received);
a.Err += new EventHandler(a_Err);
a.Connected += new EventHandler(a_Connected);
a.Disconnected += new EventHandler(a_Disconnected);
a.Connect(username , password);//connect to server and takes a long time
}
static void a_Disconnected(object sender, EventArgs e)
{
IsConnected = false;
}
static void a_Connected(object sender, EventArgs e)
{
IsConnected = true;
}
static void a_Err(object sender, EventArgs e)
{
Error += "Err Method = errCode : " + e.errCode.ToString() + " -- errMessage : " + e.errMessage + "\n";
}
static void a_Received(object sender, EventArgs e)
{
Result += "Connected Method = " + e.str + "\n";
}
public static void GetResult(string Command)
{
if (!IsConnected)
{
Connect();
}
a.Send(Command);
}
public static void DisConnect()
{
a.Disconnect();
a = null;
GC.Collect();
}
}

Simple way to calculate Response length in MVC4

I was trying to calculate the length of a HTTP Response.
Seems the stream doesn't want to play. (no read allowed. and the Content-Length doesn't seem set)
I was hoping to simply call some length property on the HttpContent response.
I have since googled and seen what looks to me like convoluted solutions around filters which I don't understand.
Is it possible to access the length (content itself is option extra )
If not I would appreciate a link to an example for 'mvc4/.net 4.5 filter' included
that I should work though till I do understand. :-)
public override void Init()
{
base.Init();
EndRequest += new EventHandler(EndRequestHandler);
}
public void EndRequestHandler(object sender, EventArgs e) {
var admService = new AdminServices();
admService.HTTPTrace(Context);
}
public void HTTPTrace(HttpContext httpContext) {
try {
var eventTrace = new MasterEventTrace();
eventTrace.RemoteAddress = req.UserHostAddress;
eventTrace.RequestLengthBytes = req.ContentLength;
// var targetMemoryStream = new MemoryStream();
// res.OutputStream.CopyTo(targetMemoryStream);
int len;
int.TryParse(res.Headers["Content-Length"], out len );
eventTrace.StatusCode = res.StatusCode;
eventTrace.ResponseLengthBytes = len; // <<<<<<< HOW to calculate this
EDIT: Based on Darin's response I got this working, Thank You Darin
I made a few tweaks to suit the situation, but otherwise as suggested.
It shows a little more from Global.asax.cs, and logging the Request and Response info as required.
//Global.asax.cs
public override void Init() {
base.Init();
BeginRequest += new EventHandler(BeginRequestHandler);
EndRequest += new EventHandler(EndRequestHandler);
}
public void EndRequestHandler(object sender, EventArgs e)
{
var adminService = new AdminServices();
var handler = Context.Response.Filter as ResponseStreamHandler;
adminService.HTTPTrace(Context, handler);
}
public void BeginRequestHandler(object sender, EventArgs e)
{
BootStrapUnauthentiated();
Context.Response.Filter = new ResponseStreamHandler(Context.Response.Filter);
}
public void HTTPTrace(HttpContext httpContext, ResponseStreamHandler responseStreamFilter)
{
try {
var _ILuwMaster = BosGlobal.BGA.ILuwMaster();
var req = httpContext.Request;
var res = httpContext.Response;
var eventTrace = new MasterEventTrace();
eventTrace.EventName = req.RequestType +":"+ req.Url.LocalPath;
eventTrace.EventDateTime = BosGlobal.BGA.Calendar.Now;
eventTrace.RemoteAddress = req.UserHostAddress;
eventTrace.RequestLengthBytes = req.ContentLength;
eventTrace.ResponseLengthBytes = responseStreamFilter.ResponseSize; //<<<<<<HERE
eventTrace.StatusCode = res.StatusCode;
// save trace entry in DB
_ILuwMaster.GetRepository<MasterEventTrace>().Add(eventTrace);
_ILuwMaster.Commit();
}
catch (Exception ex ) {} // DONT KILL Live traffic when logging errors occur
}
public class ResponseStreamHandler : MemoryStream {
private readonly Stream _responseStream;
public long ResponseSize { get; private set; }
public ResponseStreamHandler(Stream responseStream) {
this._responseStream = responseStream;
ResponseSize = 0;
}
public override void Write(byte[] buffer, int offset, int count) {
this.ResponseSize += count;
this._responseStream.Write(buffer, offset, count);
}
public override void Flush() {
base.Flush();
}
}
You could write a custom Response filter:
public class ResponseLengthCalculatingStream: MemoryStream
{
private readonly Stream responseStream;
private long responseSize = 0;
public ResponseLengthCalculatingStream(Stream responseStream)
{
this.responseStream = responseStream;
}
public override void Write(byte[] buffer, int offset, int count)
{
this.responseSize += count;
this.responseStream.Write(buffer, offset, count);
}
public override void Flush()
{
var responseSize = this.responseSize;
// Here you know the size of the response ...
base.Flush();
}
}
and register it in your Global.asax:
protected void Application_BeginRequest()
{
Context.Response.Filter = new ResponseLengthCalculatingStream(Context.Response.Filter);
}
And if you wanted to apply this filter only on particular controller actions you could write a custom action filter instead of applying it in the BeginRequest event in Global.asax:
public class ResponseLengthCapturingAttribute: ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
var response = filterContext.HttpContext.Response;
response.Filter = new ResponseLengthCalculatingStream(response.Filter);
}
}
and then all that's left is decorate the controller action with the corresponding action filter:
[ResponseLengthCapturing]
public ActionResult Index()
{
...
return View();
}

Open aspx Page after WCF Callback

I've the following problem:
I have to implemented a kind of a chat application. Therefore I use ASP.NET 4.5 and WCF. When I'm start click on the person I want to chat with, I call a wcf webservice. This webservice calls the wcf callback from the person I clicked on it. My problem is now, that I get the event called on the client side, but I am not able to open a new ChatWindow.
[CallbackBehavior(UseSynchronizationContext = false, ConcurrencyMode = ConcurrencyMode.Single)]
public class ChatContext : IChatClient, INotifyPropertyChanged
{
#region Events
public event EventHandler StartChat;
#endregion
public void FollowChatBegin(Person invitee)
{
StartChat(invitee, new EventArgs());
}
I have registered the StartChat Event in my main page:
public partial class MainPage: System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
// ...
Global.ChatContext.StartChat += ChatContextOnStartChat;
}
private void ChatContextOnStartChat(object sender, EventArgs eventArgs)
{
var person= (Person) sender;
string path = this.Request.Url.AbsoluteUri.Remove(this.Request.Url.AbsoluteUri.IndexOf(Request.Url.LocalPath, Request.Url.LocalPath.Length));
path += "/Controls/Chat/ChatWindow.aspx";
string parameters = "did=" + person.Id + "height=700px,width=800px,resizeable=yes,status=no";
path += parameters;
ScriptManager.RegisterStartupScript(this, this.GetType(), "openChartWindow", "window.open('" + path + "');", true);
this.upMain.Update();
}
}
ChatContextOnStartChat gives me the following problems:
this.Request is null
I cannot call my UpdatePanel.Update
I have no idea how I can simply open a pop up / dialog whatever... Can I just use a wrong pattern?

Resources