Search Results

Search found 7294 results on 292 pages for 'parameters'.

Page 6/292 | < Previous Page | 2 3 4 5 6 7 8 9 10 11 12 13  | Next Page >

  • Validating parameters according to a fixed reference

    - by James P.
    The following method is for setting the transfer type of an FTP connection. Basically, I'd like to validate the character input (see comments). Is this going overboard? Is there a more elegant approach? How do you approach parameter validation in general? Any comments are welcome. public void setTransferType(Character typeCharacter, Character optionalSecondCharacter) throws NumberFormatException, IOException { // http://www.nsftools.com/tips/RawFTP.htm#TYPE // Syntax: TYPE type-character [second-type-character] // // Sets the type of file to be transferred. type-character can be any // of: // // * A - ASCII text // * E - EBCDIC text // * I - image (binary data) // * L - local format // // For A and E, the second-type-character specifies how the text should // be interpreted. It can be: // // * N - Non-print (not destined for printing). This is the default if // second-type-character is omitted. // * T - Telnet format control (<CR>, <FF>, etc.) // * C - ASA Carriage Control // // For L, the second-type-character specifies the number of bits per // byte on the local system, and may not be omitted. final Set<Character> acceptedTypeCharacters = new HashSet<Character>(Arrays.asList( new Character[] {'A','E','I','L'} )); final Set<Character> acceptedOptionalSecondCharacters = new HashSet<Character>(Arrays.asList( new Character[] {'N','T','C'} )); if( acceptedTypeCharacters.contains(typeCharacter) ) { if( new Character('A').equals( typeCharacter ) || new Character('E').equals( typeCharacter ) ){ if( acceptedOptionalSecondCharacters.contains(optionalSecondCharacter) ) { executeCommand("TYPE " + typeCharacter + " " + optionalSecondCharacter ); } } else { executeCommand("TYPE " + typeCharacter ); } } }

    Read the article

  • Pass parameters to Flash Main (Document) class

    - by loto
    In Flash CSn/AS3 you associate a Main class with a flash file which when loaded in the flash player "automatically creates an instance of the program's main class." I'd like to know how to pass arguments to the main class, since you don't write it yourself (you put its name in the Document textfield in the IDE).

    Read the article

  • Redeclaration of parameters

    - by Scott
    While looking through the Selenium source code I noticed the following in the PageFactory: public static <T> T initElements(WebDriver driver, Class<T> pageClassToProxy) { T page = instantiatePage(driver, pageClassToProxy); initElements(driver, page); return page; } public static void initElements(WebDriver driver, Object page) { final WebDriver driverRef = driver; initElements(new DefaultElementLocatorFactory(driverRef), page); } What is the benefit of having the following line? final WebDriver driverRef = driver; Wouldn't it have made sense to just make the parameter final, and then passing that along to the next method without declaring the new reference?

    Read the article

  • Insert not working

    - by user1642318
    I've searched evreywhere and tried all suggestions but still no luck when running the following code. Note that some code is commented out. Thats just me trying different things. SqlConnection connection = new SqlConnection("Data Source=URB900-PC\SQLEXPRESS;Initial Catalog=usersSQL;Integrated Security=True"); string password = PasswordTextBox.Text; string email = EmailTextBox.Text; string firstname = FirstNameTextBox.Text; string lastname = SurnameTextBox.Text; //command.Parameters.AddWithValue("@UserName", username); //command.Parameters.AddWithValue("@Password", password); //command.Parameters.AddWithValue("@Email", email); //command.Parameters.AddWithValue("@FirstName", firstname); //command.Parameters.AddWithValue("@LastName", lastname); command.Parameters.Add("@UserName", SqlDbType.VarChar); command.Parameters["@UserName"].Value = username; command.Parameters.Add("@Password", SqlDbType.VarChar); command.Parameters["@Password"].Value = password; command.Parameters.Add("@Email", SqlDbType.VarChar); command.Parameters["@Email"].Value = email; command.Parameters.Add("@FirstName", SqlDbType.VarChar); command.Parameters["@FirstName"].Value = firstname; command.Parameters.Add("@LasttName", SqlDbType.VarChar); command.Parameters["@LasttName"].Value = lastname; SqlCommand command2 = new SqlCommand("INSERT INTO users (UserName, Password, UserEmail, FirstName, LastName)" + "values (@UserName, @Password, @Email, @FirstName, @LastName)", connection); connection.Open(); command2.ExecuteNonQuery(); //command2.ExecuteScalar(); connection.Close(); When I run this, fill in the textboxes and hit the button I get...... Must declare the scalar variable "@UserName". Any help would be greatly appreciated. Thanks.

    Read the article

  • Two parameters in asp.net mvc route

    - by olst
    Hi. This is a modification to a question I've asked before on this forum. My controller action: public ActionResult SearchResults(string searchTerm, int page)... My view: <%= Html.PageLinks((int)ViewData["CurrentPage"], (int)ViewData["TotalPages"], i => Url.Action("SearchResults", new { page = i }))%>... The route entries: routes.MapRoute( null, "SearchResults", new { controller = "Search", action = "SearchResults", page = 1 } // Defaults ); routes.MapRoute( "Search", "SearchResults/Page{page}", new { controller = "Search", action = "SearchResults" }, new { page = @"\d+" } ); My goal is to have paging links for the search results. The problem is that when I click any page in the paging links, it gives me the search results of an empty serach term. How can I pass the search term parameter which is a string in addition to the page number parameter ? What should I put in the routing ?

    Read the article

  • How to create a bash function with variable parameters/arguments to grep several keywords/tags

    - by CornSmith
    I'm using the :!grep "tag1" filename | grep "tag2" filename | grep -n "tag3 or more" filename command in vim to search for my code snippets based on their tags (a simple comment at the top of a snippet) in one big file. I use snippets to remember tricky things. This is painful to write out each time. I'd like to make an alias, or function to do something like this: :!greptag tag1 tag2 ... tag39 And it should search the current doc and return the lines with all the tags on them. Vim is set to interactive shell mode so that it can parse my bashrc for aliases/functions. set shellcmdflag=-ic How can I construct a function that allows for variable arguments like this in bash?

    Read the article

  • Pass parameters to Windows Service to fire method

    - by Sam Youtsey
    Hi there, I'm attempting to build a Windows Service which will execute some method when a user clicks a button in a WinForms application. I'd like to be able to pass in a few strings when the user presses the GUI button which will have the service consume them and processes a specific method. What's the best way to do this? Thanks for help.

    Read the article

  • Passing parameters in VBA for Access

    - by Newbie
    In Access 2007 I have created a form with a textbox and a button. At the moment, when I press the button, I load a query with the textbox data passed as a parameter to the query criteria. I would like to change this so that all (manually input) options appear in a combobox (in place of the textbox). I would then like to pass the combobox text to a VBA module upon pressing the button. How do I do this? Similarly, I hope to output a different string from this module, and I hope to use this as the query criteria. How do I do this?

    Read the article

  • How to pass parameters dynamically in PHP?

    - by user198729
    I need to pass the $route to its inner function,but failed: function compilePath( $route ) { preg_replace( '$:([a-z]+)$i', 'pathOption' , $route['path'] ); function pathOption($matches) { global $route;//fail to get the $route } } I'm using php5.3,is there some feature that can help?

    Read the article

  • my output parameters are always null when i use BeginExecuteNonQuery

    - by CharlesO
    I have a stored procedure that returns a varchar(160) as an output parameter of a stored procedure. Everything works fine when i use ExecuteNonQuery, i always get back the expected value. However, once i switch to use BeginExecuteNonQuery, i get a null value for the output. I am using connString + "Asynchronous Processing=true;" in both cases. Sadly the BeginExecuteNonQuery is about 1.5 times faster in my case...but i really need the output parameter. Thanks!

    Read the article

  • Why isn't the new() generic constraint satisfied by a class with optional parameters in the construc

    - by Joshua Flanagan
    The following code fails to compile, producing a "Widget must be a non-abstract type with a public parameterless constructor" error. I would think that the compiler has all of the information it needs. Is this a bug? An oversight? Or is there some scenario where this would not be valid? public class Factory<T> where T : new() { public T Build() { return new T(); } } public class Widget { public Widget(string name = "foo") { Name = name; } public string Name { get; set; } } public class Program { public static void Main() { var widget = new Widget(); // this is valid var factory = new Factory<Widget>(); // compiler error } }

    Read the article

  • Is there a programming language that performs currying when named parameters are omitted?

    - by Adam Gent
    Many functional programming languages have support for curried parameters. To support currying functions the parameters to the function are essentially a tuple where the last parameter can be omitted making a new function requiring a smaller tuple. I'm thinking of designing a language that always uses records (aka named parameters) for function parameters. Thus simple math functions in my make believe language would be: add { left : num, right : num } = ... minus { left : num, right : num } = .. You can pass in any record to those functions so long as they have those two named parameters (they can have more just "left" and "right"). If they have only one of the named parameter it creates a new function: minus5 :: { left : num } -> num minus5 = minus { right : 5 } I borrow some of haskell's notation for above. Has any one seen a language that does this?

    Read the article

  • Best practice for setting Effect parameters in XNA

    - by hichaeretaqua
    I want to ask if there is a best practice for setting Effect parameters in XNA. Or in other words, what exactly happens when I call pass.Apply(). I can imagine multiple scenarios: Each time Apply is called, all effect parameters are transferred to the GPU and therefor it has no real influence how often I set a parameter. Each time Apply is called, only the parameters that got reset are transferred. So caching Set-operations that don't actually set a new value should be avoided. Each time Apply is called, only the parameters that got changed are transferred. So caching Set-operations is useless. This whole questions is bootless because no one of the mentions ways has any noteworthy impact on game performance. So the final question: Is it useful to implement some caching of set operation like: private Matrix _world; public Matrix World { get{ return _world; } set { if (value == world) return; _effect.Parameters["xWorld"].SetValue(value); _world = value; } } Thanking you in anticipation.

    Read the article

  • Best practice settings Effect parameters in XNA

    - by hichaeretaqua
    I want to ask if there is a best practice settings effect parameters in XNA. Or in other words, what exactly happens when I call pass.Apply(). I can imagine multiple scenarios: Each time Apply() is called, all effect parameters are transferred to the GPU and therefor it has no real influence how often I set a parameter. Each time Apply() is called, only the parameters that got reset are transferred. So caching Set-operations that don't actually set a new value should be avoided. Each time Apply() is called, only the parameters that got changed are transferred. So caching Set-operations is useless. This whole questions is bootless because no one of the mentions ways has any noteworthy impact on game performance. So the final question: Is it useful to implement some caching of Set-operation like: private Matrix _world; public Matrix World { get{ return _world;} set { if(value == world)return; _effect.Parameters["xWorld"].SetValue(value); _world = value; } Thanking you in anticipation

    Read the article

  • Avoid SQL Injection with Parameters

    - by simonsabin
    The best way to avoid SQL Injection is with parameters. With parameters you can’t get SQL Injection. You only get SQL Injection where you are building a SQL statement by concatenating your parameter values in with your SQL statement. Annoyingly many TSQL statements don’t take parameters, CREATE DATABASE for instance, or really annoyingly ALTER USER. In these situations you have to rely on using QUOTENAME or REPLACE to avoid SQL Injection. (Kimberly Tripp takes about this in her recent blog post Little...(read more)

    Read the article

  • SSRS optional parameters settings

    - by Natasa Gavrilovic
    Recently I had to create couple SQL Server Reports (SSRS) with optional parameters built in. It took me a while to refresh memory how this can be done. It was very simple to create reports and processes behind, but connecting these two were are little bit challenging – stored procedure was tested and worked fine, but when the report was passing optional parameters it didn’t returned expected results. After tweaking SQL stored procedures and reports parameter options, the following approach turn to be the winning one. 1) Defining report parameters: From Menu bar select ‘View’ and ‘Report Data’ Newly open window should have ‘Parameters’ folder display Right click on this folder and select ‘Add new parameter...’                             Default values need to be added from a query                 A query values need to include ‘’ (empty string) – as highlighted                   2) SQL stored procedure should have CASE statements inside WHERE and it was the only way that a report was getting correct results back.

    Read the article

  • ASP.NET Web API and Simple Value Parameters from POSTed data

    - by Rick Strahl
    In testing out various features of Web API I've found a few oddities in the way that the serialization is handled. These are probably not super common but they may throw you for a loop. Here's what I found. Simple Parameters from Xml or JSON Content Web API makes it very easy to create action methods that accept parameters that are automatically parsed from XML or JSON request bodies. For example, you can send a JavaScript JSON object to the server and Web API happily deserializes it for you. This works just fine:public string ReturnAlbumInfo(Album album) { return album.AlbumName + " (" + album.YearReleased.ToString() + ")"; } However, if you have methods that accept simple parameter types like strings, dates, number etc., those methods don't receive their parameters from XML or JSON body by default and you may end up with failures. Take the following two very simple methods:public string ReturnString(string message) { return message; } public HttpResponseMessage ReturnDateTime(DateTime time) { return Request.CreateResponse<DateTime>(HttpStatusCode.OK, time); } The first one accepts a string and if called with a JSON string from the client like this:var client = new HttpClient(); var result = client.PostAsJsonAsync<string>(http://rasxps/AspNetWebApi/albums/rpc/ReturnString, "Hello World").Result; which results in a trace like this: POST http://rasxps/AspNetWebApi/albums/rpc/ReturnString HTTP/1.1Content-Type: application/json; charset=utf-8Host: rasxpsContent-Length: 13Expect: 100-continueConnection: Keep-Alive "Hello World" produces… wait for it: null. Sending a date in the same fashion:var client = new HttpClient(); var result = client.PostAsJsonAsync<DateTime>(http://rasxps/AspNetWebApi/albums/rpc/ReturnDateTime, new DateTime(2012, 1, 1)).Result; results in this trace: POST http://rasxps/AspNetWebApi/albums/rpc/ReturnDateTime HTTP/1.1Content-Type: application/json; charset=utf-8Host: rasxpsContent-Length: 30Expect: 100-continueConnection: Keep-Alive "\/Date(1325412000000-1000)\/" (yes still the ugly MS AJAX date, yuk! This will supposedly change by RTM with Json.net used for client serialization) produces an error response: The parameters dictionary contains a null entry for parameter 'time' of non-nullable type 'System.DateTime' for method 'System.Net.Http.HttpResponseMessage ReturnDateTime(System.DateTime)' in 'AspNetWebApi.Controllers.AlbumApiController'. An optional parameter must be a reference type, a nullable type, or be declared as an optional parameter. Basically any simple parameters are not parsed properly resulting in null being sent to the method. For the string the call doesn't fail, but for the non-nullable date it produces an error because the method can't handle a null value. This behavior is a bit unexpected to say the least, but there's a simple solution to make this work using an explicit [FromBody] attribute:public string ReturnString([FromBody] string message) andpublic HttpResponseMessage ReturnDateTime([FromBody] DateTime time) which explicitly instructs Web API to read the value from the body. UrlEncoded Form Variable Parsing Another similar issue I ran into is with POST Form Variable binding. Web API can retrieve parameters from the QueryString and Route Values but it doesn't explicitly map parameters from POST values either. Taking our same ReturnString function from earlier and posting a message POST variable like this:var formVars = new Dictionary<string,string>(); formVars.Add("message", "Some Value"); var content = new FormUrlEncodedContent(formVars); var client = new HttpClient(); var result = client.PostAsync(http://rasxps/AspNetWebApi/albums/rpc/ReturnString, content).Result; which produces this trace: POST http://rasxps/AspNetWebApi/albums/rpc/ReturnString HTTP/1.1Content-Type: application/x-www-form-urlencodedHost: rasxpsContent-Length: 18Expect: 100-continue message=Some+Value When calling ReturnString:public string ReturnString(string message) { return message; } unfortunately it does not map the message value to the message parameter. This sort of mapping unfortunately is not available in Web API. Web API does support binding to form variables but only as part of model binding, which binds object properties to the POST variables. Sending the same message as in the previous example you can use the following code to pick up POST variable data:public string ReturnMessageModel(MessageModel model) { return model.Message; } public class MessageModel { public string Message { get; set; }} Note that the model is bound and the message form variable is mapped to the Message property as would other variables to properties if there were more. This works but it's not very dynamic. There's no real easy way to retrieve form variables (or query string values for that matter) in Web API's Request object as far as I can discern. Well only if you consider this easy:public string ReturnString() { var formData = Request.Content.ReadAsAsync<FormDataCollection>().Result; return formData.Get("message"); } Oddly FormDataCollection does not allow for indexers to work so you have to use the .Get() method which is rather odd. If you're running under IIS/Cassini you can always resort to the old and trusty HttpContext access for request data:public string ReturnString() { return HttpContext.Current.Request.Form["message"]; } which works fine and is easier. It's kind of a bummer that HttpRequestMessage doesn't expose some sort of raw Request object that has access to dynamic data - given that it's meant to serve as a generic REST/HTTP API that seems like a crucial missing piece. I don't see any way to read query string values either. To me personally HttpContext works, since I don't see myself using self-hosted code much.© Rick Strahl, West Wind Technologies, 2005-2012Posted in Web Api   Tweet !function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0];if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.src="//platform.twitter.com/widgets.js";fjs.parentNode.insertBefore(js,fjs);}}(document,"script","twitter-wjs"); (function() { var po = document.createElement('script'); po.type = 'text/javascript'; po.async = true; po.src = 'https://apis.google.com/js/plusone.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(po, s); })();

    Read the article

  • C# 4 Named Parameters for Overload Resolution

    - by Steve Michelotti
    C# 4 is getting a new feature called named parameters. Although this is a stand-alone feature, it is often used in conjunction with optional parameters. Last week when I was giving a presentation on C# 4, I got a question on a scenario regarding overload resolution that I had not considered before which yielded interesting results. Before I describe the scenario, a little background first. Named parameters is a well documented feature that works like this: suppose you have a method defined like this: 1: void DoWork(int num, string message = "Hello") 2: { 3: Console.WriteLine("Inside DoWork() - num: {0}, message: {1}", num, message); 4: } This enables you to call the method with any of these: 1: DoWork(21); 2: DoWork(num: 21); 3: DoWork(21, "abc"); 4: DoWork(num: 21, message: "abc"); and the corresponding results will be: Inside DoWork() - num: 21, message: Hello Inside DoWork() - num: 21, message: Hello Inside DoWork() - num: 21, message: abc Inside DoWork() - num: 21, message: abc This is all pretty straight forward and well-documented. What is slightly more interesting is how resolution is handled with method overloads. Suppose we had a second overload for DoWork() that looked like this: 1: void DoWork(object num) 2: { 3: Console.WriteLine("Inside second overload: " + num); 4: } The first rule applied for method overload resolution in this case is that it looks for the most strongly-type match first.  Hence, since the second overload has System.Object as the parameter rather than Int32, this second overload will never be called for any of the 4 method calls above.  But suppose the method overload looked like this: 1: void DoWork(int num) 2: { 3: Console.WriteLine("Inside second overload: " + num); 4: } In this case, both overloads have the first parameter as Int32 so they both fulfill the first rule equally.  In this case the overload with the optional parameters will be ignored if the parameters are not specified. Therefore, the same 4 method calls from above would result in: Inside second overload: 21 Inside second overload: 21 Inside DoWork() - num: 21, message: abc Inside DoWork() - num: 21, message: abc Even all this is pretty well documented. However, we can now consider the very interesting scenario I was presented with. The question was what happens if you change the parameter name in one of the overloads.  For example, what happens if you change the parameter *name* for the second overload like this: 1: void DoWork(int num2) 2: { 3: Console.WriteLine("Inside second overload: " + num2); 4: } In this case, the first 2 method calls will yield *different* results: 1: DoWork(21); 2: DoWork(num: 21); results in: Inside second overload: 21 Inside DoWork() - num: 21, message: Hello We know the first method call will go to the second overload because of normal method overload resolution rules which ignore the optional parameters.  But for the second call, even though all the same rules apply, the compiler will allow you to specify a named parameter which, in effect, overrides the typical rules and directs the call to the first overload. Keep in mind this would only work if the method overloads had different parameter names for the same types (which in itself is weird). But it is a situation I had not considered before and it is one in which you should be aware of the rules that the C# 4 compiler applies.

    Read the article

  • Retrieve input and output parameters for SQL stored procs and functions?

    - by Darth Continent
    For a given SQL stored proc or function, I'm trying to obtain its input and output parameters, where applicable, in a Winforms app I'm creating to browse objects and display their parameters and other attributes. So far I've discovered the SQL system function object_definition, which takes a given sysobjects.id and returns the text of that object; also discovered via search this post which describes extracting the parameters in the context of a app using the ADO.NET method DeriveParameters in conjunction with some caching for better performance; and for good measure found some helpful system stored procs from this earlier post on Hidden Features of SQL Server. I'm leaning towards implementing the DeriveParameters method in my C# app, since parsing the output of object_definition seems messy, and I haven't found a hidden feature in that post so far that would do the trick. Is DeriveParameters applicable to both functions and stored procs for purposes of retreiving their parameters, and if so, could someone please provide an example?

    Read the article

  • What is the best URL strategy to handle multiple search parameters and operators?

    - by Jon Winstanley
    Searching with mutltiple Parameters In my app I would like to allow the user to do complex searches based on several parameters, using a simple syntax similar to the GMail functionality when a user can search for "in:inbox is:unread" etc. However, GMail does a POST with this information and I would like the form to be a GET so that the information is in the URL of the search results page. Therefore I need the parameters to be formatted in the URL. Requirements: Keep the URL as clean as possible Avoid the use of invalid URL chars such as square brackets Allow lots of search functionality Have the ability to add more functions later. I know StackOverflow allows the user to search by multiple tags in this way: http://stackoverflow.com/questions/tagged/c+sql However, I'd like to also allow users to search with multiple additional parameters. Initial Design My design is currently to do use URLs such as these: http://example.com/search/tagged/c+sql/searchterm/transactions http://example.com/search/searchterm/transactions http://example.com/search/tagged/c+sql http://example.com/search/tagged/c+sql/not-tagged/java http://example.com/search/tagged/c+sql/created/yesterday http://example.com/search/created_by/user1234 I intend to parse the URL after the search parameter, then decide how to construct my search query. Has anyone seen URL parameters like this implemented well on a website? If so, which do it best?

    Read the article

  • Forward, redirect, forward!! How do I check parameters being sent?

    - by Arjun
    There's this form that I'm placing on a site. This form submits some parameters to a site which then sends some parameters using "GET" to another site, which then opens the third site. Now the first 2 sites pass so quickly that I can not see what parameters were passed using the URL. I just need a simple tool or hint or firefox addon or ANYTHING ELSE on how to track what parameters were sent to url1, url2 etc. There's got to be some tool for this, only I can't seem to find it! Argh!

    Read the article

  • Getting Query Parameters in Javascript

    - by PhubarBaz
    I find myself needing to get query parameters that are passed into a web app on the URL quite often. At first I wrote a function that creates an associative array (aka object) with all of the parameters as keys and returns it. But then I was looking at the revealing module pattern, a nice javascript design pattern designed to hide private functions, and came up with a way to do this without even calling a function. What I came up with was this nice little object that automatically initializes itself into the same associative array that the function call did previously. // Creates associative array (object) of query params var QueryParameters = (function() {     var result = {};     if (window.location.search)     {         // split up the query string and store in an associative array         var params = window.location.search.slice(1).split("&");         for (var i = 0; i < params.length; i++)         {             var tmp = params[i].split("=");             result[tmp[0]] = unescape(tmp[1]);         }     }     return result; }()); Now all you have to do to get the query parameters is just reference them from the QueryParameters object. There is no need to create a new object or call any function to initialize it. var debug = (QueryParameters.debug === "true"); or if (QueryParameters["debug"]) doSomeDebugging(); or loop through all of the parameters. for (var param in QueryParameters) var value = QueryParameters[param]; Hope you find this object useful.

    Read the article

  • Suggestion for setting web application parameters

    - by user40730
    I'm creating a web application on GWT. I'm using MVP pattern with activities and places. I have a xml config file containing some parameters to be used by the application. Content of this xml file is sent to the client using HttpRequest; I'm using a singleton class to hold the information from the xml file. Right now, the application is getting the data when the user starts the application in the home page, that is working well. Now, since I'm using activities and places, a user can bookmark a page and starts the application in any other page (Place). And here comes the problem: Since I'm using some of the information from the xml file to set some ui widgets, I have to check if the xml config file was read and the application already has the parameters (I do this by checking the singleton class). But the xml file is read by using an HttpRequest, so I got errors 'cause the application needs some parameters to initialize some ui widgets, but these parameters aren't ready on time. I was thinking on using an synchronous request to fix the problem, but it seems complicated and not recommendable to do that. So, I'd like to hear some other suggestions. Thanks.

    Read the article

  • Optional Parameters and Named Arguments in C# 4 (and a cool scenario w/ ASP.NET MVC 2)

    - by ScottGu
    [In addition to blogging, I am also now using Twitter for quick updates and to share links. Follow me at: twitter.com/scottgu] This is the seventeenth in a series of blog posts I’m doing on the upcoming VS 2010 and .NET 4 release. Today’s post covers two new language feature being added to C# 4.0 – optional parameters and named arguments – as well as a cool way you can take advantage of optional parameters (both in VB and C#) with ASP.NET MVC 2. Optional Parameters in C# 4.0 C# 4.0 now supports using optional parameters with methods, constructors, and indexers (note: VB has supported optional parameters for awhile). Parameters are optional when a default value is specified as part of a declaration.  For example, the method below takes two parameters – a “category” string parameter, and a “pageIndex” integer parameter.  The “pageIndex” parameter has a default value of 0, and as such is an optional parameter: When calling the above method we can explicitly pass two parameters to it: Or we can omit passing the second optional parameter – in which case the default value of 0 will be passed:   Note that VS 2010’s Intellisense indicates when a parameter is optional, as well as what its default value is when statement completion is displayed: Named Arguments and Optional Parameters in C# 4.0 C# 4.0 also now supports the concept of “named arguments”.  This allows you to explicitly name an argument you are passing to a method – instead of just identifying it by argument position.  For example, I could write the code below to explicitly identify the second argument passed to the GetProductsByCategory method by name (making its usage a little more explicit): Named arguments come in very useful when a method supports multiple optional parameters, and you want to specify which arguments you are passing.  For example, below we have a method DoSomething that takes two optional parameters: We could use named arguments to call the above method in any of the below ways: Because both parameters are optional, in cases where only one (or zero) parameters is specified then the default value for any non-specified arguments is passed. ASP.NET MVC 2 and Optional Parameters One nice usage scenario where we can now take advantage of the optional parameter support of VB and C# is with ASP.NET MVC 2’s input binding support to Action methods on Controller classes. For example, consider a scenario where we want to map URLs like “Products/Browse/Beverages” or “Products/Browse/Deserts” to a controller action method.  We could do this by writing a URL routing rule that maps the URLs to a method like so: We could then optionally use a “page” querystring value to indicate whether or not the results displayed by the Browse method should be paged – and if so which page of the results should be displayed.  For example: /Products/Browse/Beverages?page=2. With ASP.NET MVC 1 you would typically handle this scenario by adding a “page” parameter to the action method and make it a nullable int (which means it will be null if the “page” querystring value is not present).  You could then write code like below to convert the nullable int to an int – and assign it a default value if it was not present in the querystring: With ASP.NET MVC 2 you can now take advantage of the optional parameter support in VB and C# to express this behavior more concisely and clearly.  Simply declare the action method parameter as an optional parameter with a default value: C# VB If the “page” value is present in the querystring (e.g. /Products/Browse/Beverages?page=22) then it will be passed to the action method as an integer.  If the “page” value is not in the querystring (e.g. /Products/Browse/Beverages) then the default value of 0 will be passed to the action method.  This makes the code a little more concise and readable. Summary There are a bunch of great new language features coming to both C# and VB with VS 2010.  The above two features (optional parameters and named parameters) are but two of them.  I’ll blog about more in the weeks and months ahead. If you are looking for a good book that summarizes all the language features in C# (including C# 4.0), as well provides a nice summary of the core .NET class libraries, you might also want to check out the newly released C# 4.0 in a Nutshell book from O’Reilly: It does a very nice job of packing a lot of content in an easy to search and find samples format. Hope this helps, Scott

    Read the article

< Previous Page | 2 3 4 5 6 7 8 9 10 11 12 13  | Next Page >