Ok I had one WebMethod in my web service which is working fine.
Then I wanted to add another one where I want to send whole object but when I trying to call this method from Windows Form its says method missing?
WebService code:
{
[WebMethod]
public int getNumber(int n)
{
return n * n * 100;
}
[WebMethod]
public string GetValues(string value)
{
return "OK";
}
}
Client code:
private void button1_Click_1(object sender, EventArgs e)
{
localhost.Service1 service2 = new localhost.Service1();
metadata detective = new metadata();
detective.CrimeID = txtCrimeID.Text;
detective.InvestigatorID = txtInvestID.Text;
detective.DataArtefactID = txtDataID.Text;
service2. **<== when I type here GetValues = "Menu.localhost.Service1 does not contain definition for GetValues"**
}
But if straight after "service2." i will start typing get, then method getNumber will be displayed as a possible choice. I dont uderstand Why one method is working fine but another one looks like not exist?
After modifying the webservice, the changes will not propogate to your winforms application until you update the reference to it. The available methods are stored in meta-data for the service when the reference is created.
Update your service reference.
Related
I have a webservice asmx written for Android and ios, communicate well with both of them, Methods that i used to return values in json format and example method is :
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public void Get_Rest_Distance(double startlat,double endlat,double startlng, double endlng)
{
double dist= GetDistance(startlat, endlat, startlng, endlng);
JavaScriptSerializer serializer = new JavaScriptSerializer();
HttpContext.Current.Response.Write(serializer.Serialize(dist));
}
the line: HttpContext.Current.Response.Write(serializer.Serialize(dist));
is used to give data to api call from android and ios,
Now want to call this method from my aspx page (Code Behind) and you noticed that return type of my function is void
I added reference of my webserivice and wrote some lines like:
localhost.RestData obj = new localhost.RestData();
string testdata= obj.Get_Rest_Distance(33.200526, 34.027379, -87.5441, -88.167831);
but getting error
Cannot implicitly convert type 'void' to 'string'
As i mentioned method is of return type void and now i want to get that data which HttpContext.Current.Response.Write(serializer.Serialize(dist)); statement returns or write.
Note:
Cannot use return in methods as service is live and both versions android and ios are working in production environment.
Please feel free to ask any question, i will provide more code if needed.
You can use Out Parameter which is something like this :
static void OutParameter(out int tmp)
{
ShowValue("OutParameter (pre): ");
tmp = 10;
ShowValue("OutParameter (post): ");
}
The thread is exactly what I need,
I have this:
WebService:
....
List<List<Int64>> whau = new List<List<Int64>>();
....
[WebMethod]
static setList(List<List<Int64>> list_web)
{
whau = list_web;
}
C#
public void func1 ()
{
List<List<Int64>> list = new List<List<Int64>>();
List<Int64> sublist = new List<Int64>();
sublist.Add(1);
sublist.Add(2);
list.Add(sublist);
service.setList(????);
}
But nothing works, I mean I've tried to send a List to the WebService, I used
sublist.ToArray()
and that works, but how to send the
List<List<>> var ?
Need really help !!
Edit :
I've already tried to do this :
service.setList(list);
and that works if the WebMethod is near the func1(), but of course the goal of WebService is not to be implemented in the same place that the Business Software...
Change your List<List<T>> to T[,] and see if it works.
Your code will look like
....
Int64[,] whau = new Int64[X,Y]; // I don't know the size of this.
....
[WebMethod]
static setList(Int64[,] list_web)
{
whau = list_web;
}
public void func1 ()
{
Int64[,] list = Int64[1, 2];
list[0, 1] = 1;
list[0, 2] = 2;
service.setList(list);
}
Remember that this is only an example. I don't know your actual code. This may cause compilation errors, but I think they will be easy to solve out.
Ok budies,
so what I ve done is simple finally,
I just send a list to the webservice,
and the webservice recieve that list and insert it to another list,
so is the WebService who creates the Nested List.
Thank you very much about your help you all !!
Regards !
FB
I'm currently working on a Windows Store app (for a school assignment), and I'm having trouble inserting data into my database which is stored in Azure. Whenever I attempt to insert data into the db, the MobileServiceInvalidOperationException gets thrown. My code is as follows:
In my model class
class Division
{
public string Id {get; set;}
[JsonProperty(PropertyName = "divisionTitle")]
public string DivisionTitle {get; set;}
}
And the relevant code in my MainPage.xaml.cs file
private MobileServiceCollection<Division, Division> divisionItems;
private IMobileServiceTable<Division> divisionTable = App.MobileService.GetTable<Division>();
private async void InsertDivision(Division divisionItem)
{
// This code inserts a new division Item into the database.
// When the operation completes and Mobile Services has
// assigned an Id, the item is added to the collection
try
{
await divisionTable.InsertAsync(divisionItem);
divisionItems.Add(divisionItem);
}
/////////////////////////////////////////////////////////
// The MessageDialog that pops up when this exception //
// gets thrown is: //
// //
// Internal Server Error (HTTP 500) //
////////////////////////////////////////////////////////
catch (MobileServiceInvalidOperationException e)
{
MessageDialog errormsg = new MessageDialog(e.Message,
string.Format("{0} (HTTP {1})",
e.Response.ReasonPhrase,
(int)e.Response.StatusCode));
var ignoreAsyncOpResult = errormsg.ShowAsync();
}
}
private void DivisionButtonSave_Click(object sender, RoutedEventArgs e)
{
var DivisionItem = new Division
{
DivisionTitle = DivisionInput.Text
};
InsertDivision(DivisionItem);
}
I also added a script in the management portal:
function insert(item, user, request) {
if (item.DivisionTitle.length > 15) {
request.respond(statusCodes.BAD_REQUEST, 'Division title must be under 15 characters');
}
else {
request.execute();
}
}
Before making the changes above, I was having no trouble communicating with Azure from within the app and wasn't having any problems inserting data. It's only after editing the script in Azure (the default insert method is simply the request.execute() statement), and since I added the InsertDivision method (I was previously entering data into the db directly from the event handler with the command await App.MobileService.GetTable<Division>().InsertAsync(DivisionItem);) that this problem has started to occur. I've tried a couple of different things and nothing has worked. After looking at my code does anything stick out? Thanks in advance to anyone who can help.
In the request sent to the service, the property DivisionTitle is sent with the first letter in lower case (since you defined it as such with the JsonProperty attribute):
{"divisionTitle":"the actual title"}
On your script, you're trying to access the property item.DivisionTitle (which doesn't exist, JavaScript is case-sensitive), and then access a property (length) of this undefined value. That will cause an error in your script. If you either change the script to use the actual JSON name (item.divisionTitle.length > 15) or change the JsonProperty declaration in the client to send the property with the first letter in upper case, it should work.
By the way, if you go to the "logs" tab in the portal, you should see some error which explains why you're getting the internal server error.
I created a new WPF project, and added a Awesomium 1.6.3 WebControl to it.
Then, I added this code to MainWindow.xaml.cs:
private void webControl1_Loaded(object sender, RoutedEventArgs e)
{
webControl1.LoadURL("https://www.google.com/");
}
private void webControl1_DomReady(object sender, EventArgs e)
{
var wc = new WebClient();
webControl1.ExecuteJavascript(jQuery);
webControl1.ExecuteJavascript(#"var __jq = jQuery.noConflict();");
webControl1.ExecuteJavascript(#"alert(__jq);");
using(var result = webControl1.ExecuteJavascriptWithResult(#"(function() { return 1; })();"))
{
MessageBox.Show(result.ToString());
}
//using (var result = webControl1.ExecuteJavascriptWithResult(#"(function() { return __jq('a'); })();"))
//{
// MessageBox.Show(result.ToString());
//}
}
And it alerts "1" and then "function (a,b){...}", which is out of order, now that I think about it, but whatever, that's another issue.
As soon as I uncomment the bottom code, it alerts "1" and then hangs. Why? How can I can some information about the links on a page? Or reliably pass some information back to C#? Or get access to the DOM with C#?
Edit: jQuery is just a string containing the jQuery 1.7 code.
Regarding why the following line hangs:
webControl1.ExecuteJavascriptWithResult(#"(function() { return __jq('a'); })();")
This is because ExecuteJavascriptWithResult can only return basic Javascript types (either a String, Number, Boolean, Array, or a user-created Object). You attempt to return a native DOM Element Object which cannot be mapped to one of these types and so the request fails.
An easy way to return complex objects would be to convert into a string using JSON.stringify(), then parse back out in your C# managed code.
For example:
JSValue rawToken = browser.ExecuteJavascriptWithResult(#"JSON.stringify(someTokenObjectHere);");
if (rawToken.IsString)
{
// For generic objects:
JObject payload = JObject.Parse(rawToken.ToString());
// For typed objects:
MyCustomTokenObject payload = JsonConvert.DeserializeObject<MyCustomTokenObject>(rawToken.ToString());
}
(It may be advantageous to include Newtonsoft.Json for the serialization stuff.)
What's a callback and how is it implemented in C#?
I just met you,
And this is crazy,
But here's my number (delegate),
So if something happens (event),
Call me, maybe (callback)?
In computer programming, a callback is executable code that is passed as an argument to other code.
—Wikipedia: Callback (computer science)
C# has delegates for that purpose. They are heavily used with events, as an event can automatically invoke a number of attached delegates (event handlers).
A callback is a function that will be called when a process is done executing a specific task.
The usage of a callback is usually in asynchronous logic.
To create a callback in C#, you need to store a function address inside a variable. This is achieved using a delegate or the new lambda semantic Func or Action.
public delegate void WorkCompletedCallBack(string result);
public void DoWork(WorkCompletedCallBack callback)
{
callback("Hello world");
}
public void Test()
{
WorkCompletedCallBack callback = TestCallBack; // Notice that I am referencing a method without its parameter
DoWork(callback);
}
public void TestCallBack(string result)
{
Console.WriteLine(result);
}
In today C#, this could be done using lambda like:
public void DoWork(Action<string> callback)
{
callback("Hello world");
}
public void Test()
{
DoWork((result) => Console.WriteLine(result));
DoWork(Console.WriteLine); // This also works
}
Definition
A callback is executable code that
is passed as an argument to other code.
Implementation
// Parent can Read
public class Parent
{
public string Read(){ /*reads here*/ };
}
// Child need Info
public class Child
{
private string information;
// declare a Delegate
delegate string GetInfo();
// use an instance of the declared Delegate
public GetInfo GetMeInformation;
public void ObtainInfo()
{
// Child will use the Parent capabilities via the Delegate
information = GetMeInformation();
}
}
Usage
Parent Peter = new Parent();
Child Johny = new Child();
// Tell Johny from where to obtain info
Johny.GetMeInformation = Peter.Read;
Johny.ObtainInfo(); // here Johny 'asks' Peter to read
Links
more details for C#.
A callback is a function pointer that you pass in to another function. The function you are calling will 'callback' (execute) the other function when it has completed.
Check out this link.
If you referring to ASP.Net callbacks:
In the default model for ASP.NET Web
pages, the user interacts with a page
and clicks a button or performs some
other action that results in a
postback. The page and its controls
are re-created, the page code runs on
the server, and a new version of the
page is rendered to the browser.
However, in some situations, it is
useful to run server code from the
client without performing a postback.
If the client script in the page is
maintaining some state information
(for example, local variable values),
posting the page and getting a new
copy of it destroys that state.
Additionally, page postbacks introduce
processing overhead that can decrease
performance and force the user to wait
for the page to be processed and
re-created.
To avoid losing client state and not
incur the processing overhead of a
server roundtrip, you can code an
ASP.NET Web page so that it can
perform client callbacks. In a client
callback, a client-script function
sends a request to an ASP.NET Web
page. The Web page runs a modified
version of its normal life cycle. The
page is initiated and its controls and
other members are created, and then a
specially marked method is invoked.
The method performs the processing
that you have coded and then returns a
value to the browser that can be read
by another client script function.
Throughout this process, the page is
live in the browser.
Source: http://msdn.microsoft.com/en-us/library/ms178208.aspx
If you are referring to callbacks in code:
Callbacks are often delegates to methods that are called when the specific operation has completed or performs a sub-action. You'll often find them in asynchronous operations. It is a programming principle that you can find in almost every coding language.
More info here: http://msdn.microsoft.com/en-us/library/ms173172.aspx
Dedication to LightStriker:
Sample Code:
class CallBackExample
{
public delegate void MyNumber();
public static void CallMeBack()
{
Console.WriteLine("He/She is calling you. Pick your phone!:)");
Console.Read();
}
public static void MetYourCrush(MyNumber number)
{
int j;
Console.WriteLine("is she/he interested 0/1?:");
var i = Console.ReadLine();
if (int.TryParse(i, out j))
{
var interested = (j == 0) ? false : true;
if (interested)//event
{
//call his/her number
number();
}
else
{
Console.WriteLine("Nothing happened! :(");
Console.Read();
}
}
}
static void Main(string[] args)
{
MyNumber number = Program.CallMeBack;
Console.WriteLine("You have just met your crush and given your number");
MetYourCrush(number);
Console.Read();
Console.Read();
}
}
Code Explanation:
I created the code to implement the funny explanation provided by LightStriker in the above one of the replies. We are passing delegate (number) to a method (MetYourCrush). If the Interested (event) occurs in the method (MetYourCrush) then it will call the delegate (number) which was holding the reference of CallMeBack method. So, the CallMeBack method will be called. Basically, we are passing delegate to call the callback method.
Please let me know if you have any questions.
Probably not the dictionary definition, but a callback usually refers to a function, which is external to a particular object, being stored and then called upon a specific event.
An example might be when a UI button is created, it stores a reference to a function which performs an action. The action is handled by a different part of the code but when the button is pressed, the callback is called and this invokes the action to perform.
C#, rather than use the term 'callback' uses 'events' and 'delegates' and you can find out more about delegates here.
callback work steps:
1) we have to implement ICallbackEventHandler Interface
2) Register the client script :
String cbReference = Page.ClientScript.GetCallbackEventReference(this, "arg", "ReceiveServerData", "context");
String callbackScript = "function UseCallBack(arg, context)" + "{ " + cbReference + ";}";
Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "UseCallBack", callbackScript, true);
1) from UI call Onclient click call javascript function for EX:- builpopup(p1,p2,p3...)
var finalfield= p1,p2,p3;
UseCallBack(finalfield, ""); data from the client passed to server side by using UseCallBack
2) public void RaiseCallbackEvent(string eventArgument) In eventArgument we get the passed data
//do some server side operation and passed to "callbackResult"
3) GetCallbackResult() // using this method data will be passed to client(ReceiveServerData() function) side
callbackResult
4) Get the data at client side:
ReceiveServerData(text) , in text server response , we wil get.
A callback is a function passed as an argument to another function. This technique allows a function to invoke the parameter function argument and even to pass a value back to the caller. A callback function can be designed to run before/after the function has finished and can pass a value.
It is a kind of construct where you call a long running function and ask him to call you back once it has finished with can return a parameter result to the caller.
It's like someone calls you in the middle of your work asking for status and you say "you know what give me 5 min and i will call you back" and at the end you call him to update. If you are a function the caller just added and passed another function that you invoked at the end. This can simpley be written in C# as:
public void VinodSrivastav(Action statusUpdate){
//i am still here working..working
//i have finished, calling you
statusUpdate();
}
//invokes
stackoverflow.VinodSrivastav((cam) => {
Console.Write("Is it finished");
});
The one simple example is the iterator function where the return will be multiple times, one can argue that we have yield for it:
public void IntreationLoop(int min, int max,Action<int> Callback)
{
for(int i = min;i<= max;i++)
Callback(i);
}
//call
IntreationLoop(5,50,(x) => { Console.Write(x); }); //will print 5-50 numbers
In the code above the function return type is void but it has an Action<int> callback which is called and sends each item from the loop to the caller.
The same thing can be done with if..else or try..catch block as:
public void TryCatch(Action tryFor,Action catchIt)
{
try{
tryFor();
}
catch(Exception ex)
{
Console.WriteLine($"[{ex.HResult}] {ex.Message}");
catchIt();
}
}
And call it as:
TryCatch(()=>{
int r = 44;
Console.WriteLine("Throwing Exception");
throw new Exception("something is wrong here");
}, ()=>{
Console.WriteLine("It was a mistake, will not try again");
});
In 2022 we have Func & Action doing the same, please see the demo code below which shows how this can be be used:
void Main()
{
var demo = new CallbackDemo();
demo.DoWork(()=> { Console.WriteLine("I have finished the work"); });
demo.DoWork((r)=> { Console.WriteLine($"I have finished the work here is the result {r}"); });
demo.DoWork(()=> { Console.WriteLine($"This is passed with func"); return 5;});
demo.DoWork((f)=> { Console.WriteLine($"This is passed with func and result is {f}"); return 10;});
}
// Define other methods and classes here
public class CallbackDemo
{
public void DoWork(Action actionNoParameter)
{
int a = 5;
int b = 10;
//i will do th maths and call you back
int result = a + b;
//callback
actionNoParameter(); //execute
Console.WriteLine($"[The Actual Result is {result}]");
}
public void DoWork(Action<int> actionWithParameter)
{
int a = 5;
int b = 10;
//i will do th maths and call you back
int result = a + b;
//callback
actionWithParameter(result); //execute
Console.WriteLine($"[The Actual Result is {result}]");
}
public void DoWork(Func<int> funcWithReturn)
{
int a = 5;
int b = 10;
//i will do th maths and call you back
int result = a + b;
//callback
int c = funcWithReturn(); //execute
result += c;
Console.WriteLine($"[The Actual Result is {result}]");
}
public void DoWork(Func<int,int> funcWithParameter)
{
int a = 5;
int b = 10;
//i will do th maths and call you back
int result = a + b;
//callback
result += funcWithParameter(result); //execute
Console.WriteLine($"[The Actual Result is {result}]");
}
}