I am making an iPhone app where I am using .NET webservice.
Let's say below is the URL I have.
http://www.myweb.com/wser.asmx/listOfStudents?class=12
Here I was getting list of students with below fields in it.
Name
Roll Number
Class
Now client asked to make arabic version. So we update the query to below.
http://www.myweb.com/wser.asmx/listOfStudents?class=12&appLang=ar
^^^^^^^^^^^^
For testing we update webservice on another server & checked and all is working fine.
Now while uploading app on App store, I noticed if I update actual webservice current app won't work as appLang variable is missing in current app that is there on app store.
If I don't update webservice & apple go in testing, the app will crash as it will throw error of missing parameter appLang.
So what I was thinking is,
I will upload new webservice, BUT appLang will be arabic BY-DEFAULT.
Like if I execute url http://www.myweb.com/wser.asmx/listOfStudents?class=12 with updated webservice (appLang added in webservice but not in url), it will not throw error of parameter missing appLang?
Is there any way to make default parameter?
while using GET isn't that pretty in this case (POST could be more suitable), you could do this :
//by specifying a messageName, you can do overloading with webmethods
[WebMethod (MessageName = "listOfStudentsDefault")]
[ScriptMethod(UseHttpGet=true)]
public string listOfStudents(int class, string appLang)
{
// code here...
}
[WebMethod (MessageName = "listOfStudents")]
[ScriptMethod(UseHttpGet=true)]
public string listOfStudents(int class)
{
return listOfStudents(class, "ar");
}
Related
I'm not sure of the best way to accomplish my goal. Looking for insight. I'm familiar with WebAPI services consumed through WPF and Silverlight but this is my first run at ASP and MVC.
I am building a site to verify contents of a shipment against an electronic manifest (EDI 856). I have a page that displays the shipping data and I need the users to scan each item barcode in the container. I would then like to pass that barcode to a service, verify the item belongs in that shipment and then update the page to show as much.
My plan was to have a single text box into which the user could scan/type the barcode and then submit that data to a WebAPI service which would verify the information and then probably use SignalR to send a message back to the page and update a grid with the item data.
If this is a decent way to go, I'm just not quite sure how to use ajax to call the WebAPI endpoint and provide the data I need.
I would advise against using SignalR in this situtation. What you need, judging from your description, is the most basic use case of submitting an ajax request and receiving a response.
You are not designing a system where you need the server to initiate communication with the browser or anything like that, where sockets (and SignalR as an abstraction over sockets with fallbacks to less suitable protocols) is a huge overkill.
Don't worry, your use case is rather simple.
It's a little out of scope to describe how to setup a WebApi project, how to configure routing, action names, etc. Simple google searches will surely provide ample quality tutorials on getting started.
I'll just try to explain what the general idea is, with some code samples, to get you thinking in the right direction.
You need to create an ApiController.
The simplest version of that Controller will probably look something like this:
public class ShipmentVerificationController : ApiController
{
//this is the response object you will be sending back to the client website
public class VerificationResult
{
public bool Valid;
}
public VerificationResult GetIsItemValid(string BarCode)
{
bool itemIsValid;
// Implement checks against the BarCode string here
itemIsValid = true;
return new VerificationResult { Valid = itemIsValid };
}
}
Note that the inner class represents the response you will be sending back. It should be properly filled out with additional info if needed and probably put into a separate .cs file in the "Models" folder or where ever you see fit.
I have declared it inside the controller for demonstration purposes only
Once you have a WebApi service deployed, it's really easy to send it data from your website and receive the feedback.
To simplify Ajax requests, jQuery is often used.
Once the user inputs the barcode into a textbox, you can hook up an event to check for return key being pressed (most barcode scanners send the return key command after they input the barcode data) and then write something along the lines of:
var barcode = $("#input-field").val();
$.getJSON( "<url_to_your_webapi_service>/api/ShipmentVerification/GetIsItemValid/" + barcode, function( data ) {
if (data.Valid) {
// great, highlight the item as valid
}
else {
//better indicate an error with the scanned item
}
});
Please note that for simplicity I have not included any error handling, url parameter encoding, and most importantly, zero authorization.
Authorization is very important if you deploy the web service to the open web but still do not want anyone to be able to call it.
You will have to research these topics yourself, but I hope I have presented you the core concepts and logic behind a simple service such as this, so you have a base to start with.
If you come up with specific problems and questions post a new question.
I actually found a more simple way to do this. I nixed the idea of using a WebAPI endpoint and just went with a normal controller. I used ajax to prevent the page from refreshing with the new view, since that view is actually just json data with my return values in it.
I am developing on Windows application in c# and I am using web server's web service in this Windows application.
The web service should be dynamic and I need to change it in the application.
I managed to do it by this code :
CallWebService.MyWS ws = new CallWebService.MyWS();
ws.Url = "new url";
This new url will be set as per client's web server url.
I am calling this web service (I mean web service functions) 20 to 25 times in my application.
Do I need to change this path everytime when I call it or for the first time will be ok ?
Use a fixed port number for your service and configure this url in your app/web.config file and use it in your code.
Create a helper class and use that. Make it configurable by using an app setting or better store in config table in database if you are using one.
If you are using WCF client, you can pass URL in client constructor. Otherwise create a partial class for your webservice to create that constructor.
public class MyWebServiceHelper
{
private string _url = null;
public MyWebServiceHelper()
{
this._url = GetWsUrlFromDbOrAppConfig();
}
public CallWebService.MyWS GetMyWebServiceProxy()
{
return new CallWebService.MyWS("WcfBindingConfig", _url);
}
}
I'm working on an ASP.Net C# application (my first!) that contains an HTTP Handler within it. My application works with several parameters that are passed in via the URL. My question(s) is as follows:
My applications entry point is via the HTTP Handler. When I enter my ProcessRequest method, I am assigning the values of the URL parameters to variables so that I may do something with the data.
Question: Is this safe, even if I am not setting the value to anything when I call the URL?
In my example: I call host/handler1.ashx instead of host/handler1.ashx?something=foo
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/plain";
string something = context.Request["something"];
context.Response.Write("Hello World: " + something);
}
When calling the above method using the plain URL with no parameters, it executes just fine, but the string something is just blank/null.
Additional questions:
What happens to the variable something in the case that I do not explicitly initialize it via the URL? I understand that it is null, but can this lead to problems?
Is it dangerous or not safe to call the plain URL (i.e. should I always call it with parameter values specified)?
What is the best way to call a "clean" ashx URL to start the application but not risk problems?
The application will do a series of subsequent GET redirects as it accumulates values and passes them back to the app via the query string.
Should I do a POST or GET upon initial call of the application?
Sorry for asking the same question multiple ways, but I'm a bit confused on the topic and this is my first time writing an app like this. Any patience and advice you could provide on how to safely handle and initialize parameters is greatly appreciated!
There is nothing wrong with omitting parameters to an endpoint. As the developer you are in charge of enforcing what the client is allowed send to you. If you expect a parameter and it's missing, throw an error (e.g. HttpException).
If you are creating or updating data (i.e. inserting or updating records in a database) the best method would be a POST or PUT.
Edit - Here is an example of how you can handle the input:
public void ProcessRequest(HttpContext context) {
//Maybe you require a value?
if (string.IsNullOrEmpty(context.Request["something"])) {
throw new HttpException(400, "You need to send a value!");
}
//Maybe you require a certain value?
if (context.Request["something"] != "beerIsGood") {
throw new HttpException(400, "You need to send the right value!");
}
}
You can't. The Internet is dangerous.
I'm working through the final issues of an application set to go live this week. I need help to either modify my code or explain to our hosters what they need to fix in the IIS/DNS configurations to make this code work as expected.
Here is the code:
public string BaseSiteUrl
{
get
{
var c = this.ControllerContext.RequestContext.HttpContext;
string baseUrl = c.Request.Url.Scheme + "://" + c.Request.Url.Authority
+ c.Request.ApplicationPath.TrimEnd('/') + '/';
return baseUrl;
}
}
I make a call to this in my Controller, to generate a url that gets persisted to a database.
It works fine when I run on my local machine. However, it does not work when it is run on the beta server.
Expected results on beta. On the beta server this is an application named dr405
https://beta.sc-pa.com/dr405/
The actual result on beta. (I changed the server/domain names to what you see in CAPS for security's sake)
http://SERVERNAME1.GROUP1.SUBGROUP.local/dr405/
I don't think you need the method you wrote. There is a UrlHelper class that adds extension methods. To get the base URL for your site you should be using the Content() method like this:
var baseUrl = Url.Content("~/");
In your example, it looks like the http://SERVERNAME1.GROUP1.SUBGROUP.local/dr405/ result is an internal host name. On your development machine the internal host matches your public facing one. Your hosting provider is unlikely to be able to modify this for you, especially if it's a shared hosting solution.
If you're behind a load balancer or similar, it might be worth checking server variables. In our case we do something like this:
string hostName = Request.Headers["x-forwarded-host"];
hostName = string.IsNullOrEmpty(hostName) ? Request.Url.Host : hostName;
This question I asked a while ago might be of interest:
Asp.net mvc 301 redirect from www.domain.com to domain.com
Due to time constraints, and the need to get this project out the door, I had to resort to hardcoding the main part of the url into the application. After I made the change I felt stupid for trying to make it dynamic in the first place. I mean how often should our domain name change?
I've made a little game in silverlight that records users scores whilst they play.
I decided it would be a lot better if I could implement a leaderboard, so I created a database in mySQL to store all the high scores along with names and dates. I have created some communications to the database in ASP.net. This works and I can simply insert and get data within the code.
It's now time to link the silverlight project with the ASP.net database communications, so I can send the users name and score as variables to my ASP.net code and then it will upload it to the database. That's all I need. Surely there must be an easy way of doing this, I just can't seem to find any ways when researching.
Thanks in advance,
Lloyd
At first you need add Generic Handler to your ASP.Net project.
public class Handler1 : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
string userName = context.Request["user"];
int score = int.Parse(context.Request["score"]);
//And store it in DB
}
}
After you need call this handler from SilverLight app:
string uri = HtmlPage.Document.DocumentUri.ToString();
// Remove the web page from the current URI to get the root URI.
string rootUri = uri.Remove(uri.LastIndexOf('/'),
uri.Length - uri.LastIndexOf('/'));
string diggUrl = String.Format(rootUri + "/" + "test.ashx?user={0}&score={1}", "testuser", "234");
// Initiate Async Network call to Digg
WebClient diggService = new WebClient();
diggService.DownloadStringAsync(new Uri(diggUrl));
here i used Uri Class to send parameter to asp.net, but you can send string format only.
// this code written on Silverlight Button Click Event.
Uri myURI = new Uri(HtmlPage.Document.DocumentUri,String.Format("Report.aspx?brcd={0}&acc={1}&user={2}", Brcd, Acc, User)); HtmlPage.Window.Navigate(myURI, "_blank");
below code is written on Asp.net page_load or page init event
Brcd = Request.QueryString["brcd"];// brcd value accept here.
acc= Request.QueryString["ACC"];`
user= Request.QueryString["User"];
in above code we accept the silverlight parameter in asp.net but in [] bracket put name as it is use in silverlight page because it case sensitive.
By ASP.NET, do you mean an ASP.NET Webforms app?
If so, an ASP.NET Webforms app is a method of building a UI. What you need is an API, for your Silverlight app to use programatically. For this purpose you may want to consider building an ASP.NET Webservice instead, which provides an API over HTTP.
What do you need its to send data to web server from a Silverlight application, right?
You can:
Call Javascript functions from Silverlight and, there, do a postback
Call web services with Silverlight, but make sure its in same server which your SL application came from, or you will face some XSS issues.
An easy way to do this is to have your Silverlight code create a REST URL by encoding the information into the query string, and invoking an .aspx page on the server. The page wouldn't need to return any markup; it would just handle the back-end stuff and return.
Alternatively, you could make a web service call from Silverlight to your back end.
I prefer the latter approach. It's a little more work the first time through, but it's also more general purpose and makes for generally better code in the long run.
Although technically you could use JavaScript, I wouldn't suggest it; why go backwards in tech if you don't have to?