Firing a server-side method via PageMethod - c#

I wrote a JavaScript function that fires when the user clicks OK in a RadConfirm dialog. This is supposed to trigger a JavaScript callback to the server to delete a record from the database. This may not be the best architecture (I can think of other ways to accomplish my goals) but I'm trying to struggle through this as a learning exercise. Below is the code I've written thus far. I think I've gotten most of it correct.
This Javascript function:
function confirmCallBackFn(arg) {
if (arg == true) {
PageMethods.RemovePackagePageMethod();
}
else {
}
}
Should invoke the following WebMethod on the server:
[WebMethod()]
public static void RemovePackagePageMethod(object sender, EventArgs e)
{
Inventory inv = new Inventory();
inv.RemovePackage();
}
Which in turn should execute the following method:
private void RemovePackage()
{
SBMData2.SBMDataContext db = new SBMData2.SBMDataContext();
var boxes = from p in db.Packages
where p.PackageID == Convert.ToInt32(RadGrid1.SelectedValues["PackageID"].ToString())
select p;
foreach (var box in boxes)
{
db.Packages.DeleteOnSubmit(box);
}
try
{
db.SubmitChanges();
RadGrid1.Rebind();
}
catch (Exception ex)
{
RadWindowManager1.RadAlert("System error deleting package", 200, 200, "exception", null);
}
}
Everything looks good to me and seems to be consistent with the posts I've read on this site and others about using PageMethod to fire code on the server. However, it's failing to execute the deletion in the final method (which I've tested in isolation). Can someone spot where I went wrong?

You are trying to use the RadGrid1 control in the RemovePackage method, but you are calling the method from a web method, so there is no instance of the Page class, and thus there is no RadGrid1 control.
You would have to send the id of the record that you want to delete from the client code to the web method, and from there along to the RemovePackage method.
Also, you can't rebind the RadGrid1 control to make the changes appear in the page. The web method call is not a page request, so there is no page response that can contain the updated grid. You would have to update the grid in the client code.

Try making the RemovePackage method Public (Friend may work too) instead of private and then try.

Related

How to pass data from one form to another form textbox in windows application?

I'm trying to pass a variable from one form to another form textbox. The 'variable' is a result of a calculation based on the user inputs.
Below is the code for the parent form(RuleInsertForm) where I'm calling the subform(Helpformula) to get the user inputs.
public partial class RuleInsertForm : Form
{
public string helpformulainputs;
}
private void RuleInsertForm_Load(object sender,EventArgs e)
{
if (helpformulainputs=="")
{
textBox_Inputs.Text = "";
}
else
{
textBox_Inputs.Text = helpformulainputs;
}
}
Below is the code for the subform(Helpformula) where i'm passing the result variable(formulainputs) to the parent form(RuleInsertForm).
public partial class HelpFormula : Form
{
public string formulainputs = string.Empty;
private void button_generateformula_Click(objectsender, EventArgs e)
{
using (RuleInsertForm insertform = new RuleInsertForm())
{
insertform.helpformulainputs = formulainputs;
this.Close();
insertform.Show();
}
}
}
Problem:
The values are getting passed to the text box but in the UI its not getting dispalyed.
so far I tried to push data back to parent form and then tried to display the data in the textbox where I failed.(I dont know where it went wrong suggest me if I can resolve the below one)
Now I need an alternative method to this for eg: instead of pushing the data back to parent form i need to make the variable available for all the forms trying to use the subform(formulainputs)
How can I acheive this process ? any suggestions are much appreciated.
The problem seems to be that insertForm.Show() does not block the execution of your button handler. Show opens the insertform as non-modal.
So after insertform is opened, the execution is continued in button_generateformula_Click and when you exit the using block, the insertform is disposed and therefore closed.
To solve this you may call insertForm.ShowDialog() instead.
For different ways of communicating between Forms look here or simply type communicate between forms into the SO search box.

Windows Phone ContactPicker won't await properly

Although this has been posted before on StackOverflow but i think none of those reflect my issue and none of those solutions work for me either. So i'm developing a Windows Phone app and my workflow is a bit like this:
App starts
ContactPicker opens up
User selects one or multiple contacts
Based on how many contacts he selected, that many PivotItems are added into the Pivot.
My code is as follows:
protected override void OnNavigatedTo(NavigationEventArgs e)
{
// TODO: Prepare page for display here.
// TODO: If your application contains multiple pages, ensure that you are
// handling the hardware Back button by registering for the
// Windows.Phone.UI.Input.HardwareButtons.BackPressed event.
// If you are using the NavigationHelper provided by some templates,
// this event is handled for you.
SelectContacts();
}
private async Task SelectContacts()
{
var picker = new ContactPicker();
picker.DesiredFieldsWithContactFieldType.Add(ContactFieldType.PhoneNumber);
ContactsList = (List<Contact>)await picker.PickContactsAsync();
DisplayContacts();
}
private void DisplayContacts()
{
if (ContactsList != null)
{
foreach (var item in ContactsList)
{
PivotItem pivotItem = new PivotItem();
pivotItem.Header = item.FirstName.ToString();
ContentRoot.Items.Add(pivotItem);
}
}
}
According to me, in SelectContacts() method, the app should wait at the await call and once it gets back the list of contacts, than it should execute the DisplayContacts() method but its not working. I've tried multiple other variations of this code and they aren't working either.
await the SelectContacts() method and add the DisplayContacts() method beneath it. Remove the DisplayContacts() method from SelectContacts()
await SelectContacts();
DisplayContacts();
I don't know the complete reason why but i figured it out that since i was making the PickContactsAsync() call in the OnNavigatedTo() event, that is why it wasn't working as expected. Once i moved the PickContactsAsync() call into the PageLoaded() event handler, it started working as usual.

Delay in event in code behind file

In my application I have a button to save some information. However, I would like to have a delay in the code before the last line is executed, so that the user could read the message that shows up before he gets redirected to the new page.
I know that doing this isn't at all an optimal way, but by some reasons (time, for example) I want to do it anyway.
So is it possible and if so, how could I do it?
Thanks in advance!
protected void SaveButton_Click(object sender, EventArgs e) {
// Lots of code not relevant for the problem here
Service service = new Service();
service.SaveMovie(movie);
successMessage.Visible = true;
happyMessage.Text = "The movie was successfully added, now add some genres!";
// Here I want a delay of 2 seconds before the next line is executed...
Response.Redirect(String.Format("~/Edit.aspx?id={0}", movie.MovieID), false);
}
You need to do this on the client side. One alternative is this:
Define a Javascript function in the page called redirect as so:
function redirect(url)
{
setTimeout(function(){window.location.href=url;} ,2000);
}
protected void SaveButton_Click(object sender, EventArgs e)
{
// Lots of code not relevant for the problem here
Service service = new Service();
service.SaveMovie(movie);
successMessage.Visible = true;
happyMessage.Text = "The movie was successfully added, now add some genres!";
// Here I want a delay of 2 seconds before the next line is executed...
ClientScript.RegisterStartupScript(this.GetType(),"somekey","redirect('"+String.Format("~/Edit.aspx?id={0}", movie.MovieID)+"');");
}
This will be easy if you are using Javascript. Use javascript will boost performance
Button_Click
{
string js ="<script type='text/javascript'>setTimeout(function()window.location.href="+String.Format("~/Edit.aspx?id={0}", movie.MovieID)+";} ,2000);</script>"
ScriptManager.RegisterStartupScript(Me.Page, GetType(Page), "js", js, False)
}
possible duplicate of
asp.net delay before response redirect

MediaElement - can't change sources from outside Silverlight

I'm making a Silverlight application and I'm using a MediaElement to play a video from the user's disk that I know the path of (say, "C:/foo.MOV"). I'd like a Javascript trigger from the browser to change the source of the MediaElement to another known file (eg "C:/bar.MOV"). I can make a button to do this in Silverlight, and I can have a Javascript trigger execute code inside the Silverlight app, but when I do, the MediaElement appears empty.
I've even tried having the Javascript call the btnLoadNewMediaTest_Click event, and while that event works fine called from user clicks on the button, it doesn't affect the media at all when called from outside the app.
Looking at the MediaElement in the debug, it seems that when it's called from the Javascript the MediaElement's Source appears as null and it seems to have made an empty copy.
I can confirm the Javascript is triggering the events in Silverlight, as it trips breakpoints in the Silverlight code.
I have managed to solve this: I created an EntryPoint class that is scriptable from JavaScript. When the JavaScript sendCommand is triggered, it puts a command and args into a queue held by the entry point. Every tick of a timer in the Silverlight app, the app checks the Count() of the queue and gets any commands and processes them.
From the Javascript, I call silverlightControl.Context.EntryPoint.setCommand("commandname", "args").
In the EntryPoint I have
[ScriptableMember()]
public string setCommand(string commandValue, string argsValue)
{
commands.Enqueue(commandValue);
args.Enqueue(argsValue);
commandWaitingFlag = true;
return Application.Current.HasElevatedPermissions.ToString();
}
In the Silverlight itself, I have a DispatcherTimer with an interval of 100ms. This has a tick event:
public void Each_Tick(object o, EventArgs e)
{
//Other code
if (entryPoint.commandWaitingFlag)
{
handleEntryPointCommands();
}
}
From inside handleEntryPointCommands I call a method of the entryPoint, getCommand():
public string[] getCommand() {
string commandOut = string.Empty;
string argsOut = string.Empty;
if (commands.Count > 0)
{
commandOut = commands.Dequeue();
argsOut = args.Dequeue();
if (commands.Count == 0)
{
commandWaitingFlag = false;
}
return new string[2] { commandOut, argsOut };
}
else
{
return new string[2];
}
}
and then can use the command I've gotten however I like. Hopefully that's more helpful with some code.

C# How can I update a form Control from foreign code

I'm trying to optimize my code to be called from both an UI-less commandline call or call it from the UI.
The problem is that I have is I have written the lets call It worker-code inside the Form-class.
Now I want to pull out that worker code into a separate class.
Lets make a small sample to make my needs clearer:
public partial class form1 :Form
{
void AddLogmessage(String msg)
{
// update an listview
ListViewItem item = new ListViewItem();
item.Text = msg;
// Add the item to the ListView
LogView.Items.Add(item);
}
// button on ui to start working
private void btnStartTestRun_Click(object sender, EventArgs e)
{
try
{
DoSomeWork();
}
catch(Exception ex)
{}
}
private void DoSomeWork()
{
// do some really generic hard work....
AddLogMessage("working");
// do some more generic long lasting hard work....
AddLogMessage("working goes on...");
// in case of an error throw Exception
}
Now I want to refcator the worker code to work outside the form class, but be able to report the things that happen to the UI (if there is one) or to call the workercode without UI and do other reportings to an different target (communicate with other library which reports the results to an server)
Something like this:
public void AutomaticTaskHandler()
{
string[] cmdline = Environment.GetCommandLineArgs();
Arguments args = new Arguments(cmdline);
if (args["automatic"] != null)
{
doSomeWork();
}
}
In this case I don't have to report the Messages to the UI, but send some other messages (NOT the same Messages!!) to an server.
So my question is how do I make this the best way not having to write the doSomeWork - code twice but be able to send only the messages which are in the current scene are needed?
I thought about Delegates and Events, but I'm not too familiar to this to make this work.
Any help will be appreciated.
Thanks Meister_Schnitzel
Basically, you would create an interface IMessageTarget with a method SendMessage. Your UI code would create an implementation of that interface that outputs the messages to the UI and your console code would create an implementation of that interface that sends the messages to a server. On calling the doWork method, you would supply an instance of IMessageTarget.

Categories