Search Results

Search found 11306 results on 453 pages for 'methods'.

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

  • Good practice to create extension methods that apply to System.Object?

    - by Christian
    Hello, I'm wondering whether I should create extension methods that apply on the object level or whether they should be located at a lower point in the class hierarchy. What I mean is something along the lines of: public static string SafeToString(this Object o) { if (o == null || o is System.DBNull) return ""; else { if (o is string) return (string)o; else return ""; } } public static int SafeToInt(this Object o) { if (o == null || o is System.DBNull) return 0; else { if (o.IsNumeric()) return Convert.ToInt32(o); else return 0; } } //same for double.. etc I wrote those methods since I have to deal a lot with database data (From the OleDbDataReader) that can be null (shouldn't, though) since the underlying database is unfortunately very liberal with columns that may be null. And to make my life a little easier, I came up with those extension methods. What I'd like to know is whether this is good style, acceptable style or bad style. I kinda have my worries about it since it kinda "pollutes" the Object-class. Thank you in advance & Best Regards :) Christian P.S. I didn't tag it as "subjective" intentionally.

    Read the article

  • master pages, form pages, form runat=server > all onclick methods on master page?

    - by b0x0rz
    the problem i have is that i have multiple nested master pages: level 1: global (header, footer, login, navigation, etc...) level 2: specific (search pages, account pages, etc...) level 3: the page itself now, since only one form can have runat=server, i put the form at global page (so i can handle things like login, feedback, etc...). now with this solution i'd have to also put the for example level 3 (see above) methods, such as search also on the level 1 master page, but this will lead to this page being heavy (for development) with code from all places, even those that are used on a single page only (change email form for example). is there any way to delegate such methods (for example: ChangeEMail) from level 1 (global masterpage) to level 3 (the single page itself). to be even more clear: i want to NOT have to have the method ChangeEMail on the global master page code behind, but would like to 'MOVE' it somehow to the only page that will actually use it. the reason why it currently has to be on the global master is that global master has form runat=server and there can be only one of those per aspx page. this way it will be easier (more logical) to structure the code. thnx (hope i explained it correctly) have searched but did not find any general info on handling this case, usualy the answer is: have all the methods on the master page, but i don't like it. so ANY way of moving it to the specific page would be awesome. thnx

    Read the article

  • Use properties or methods to expose business rules in C#?

    - by Val
    I'm writing a class to encapsulate some business rules, each of which is represented by a boolean value. The class will be used in processing an InfoPath form, so the rules get the current program state by looking up values in a global XML data structure using XPath operations. What's the best (most idiomatic) way to expose these rules to callers -- properties or public methods? Call using properties Rules rules = new Rules(); if ( rules.ProjectRequiresApproval ) { // get approval } else { // skip approval } Call using methods Rules rules = new Rules(); if ( rules.ProjectRequiresApproval() ) { // get approval } else { // skip approval } Rules class exposing rules as properties public class Rules() { private int _amount; private int threshold = 100; public Rules() { _amount = someExpensiveXpathOperation; } // rule property public bool ProjectRequiresApproval { get { return _amount < threshold } } } Rules class exposing rules as methods public class Rules() { private int _amount; private int threshold = 100; public Rules() { _amount = someExpensiveXpathOperation; } // rule method public bool ProjectRequiresApproval() { return _amount < threshold; } } What are the pros and cons of one over the other?

    Read the article

  • Do I have to implement Add/Delete methods in my NHibernate entities ?

    - by Lisa
    This is a sample from the Fluent NHibernate website: Compared to the Entitiy Framework I have ADD methods in my POCO in this code sample using NHibernate. With the EF I did context.Add or context.AddObject etc... the context had the methods to put one entity into the others entity collection! Do I really have to implement Add/Delete/Update methods (I do not mean the real database CRUD operations!) in a NHibernate entity ? public class Store { public virtual int Id { get; private set; } public virtual string Name { get; set; } public virtual IList<Product> Products { get; set; } public virtual IList<Employee> Staff { get; set; } public Store() { Products = new List<Product>(); Staff = new List<Employee>(); } public virtual void AddProduct(Product product) { product.StoresStockedIn.Add(this); Products.Add(product); } public virtual void AddEmployee(Employee employee) { employee.Store = this; Staff.Add(employee); } }

    Read the article

  • Passing multiple POST parameters to Web API Controller Methods

    - by Rick Strahl
    ASP.NET Web API introduces a new API for creating REST APIs and making AJAX callbacks to the server. This new API provides a host of new great functionality that unifies many of the features of many of the various AJAX/REST APIs that Microsoft created before it - ASP.NET AJAX, WCF REST specifically - and combines them into a whole more consistent API. Web API addresses many of the concerns that developers had with these older APIs, namely that it was very difficult to build consistent REST style resource APIs easily. While Web API provides many new features and makes many scenarios much easier, a lot of the focus has been on making it easier to build REST compliant APIs that are focused on resource based solutions and HTTP verbs. But  RPC style calls that are common with AJAX callbacks in Web applications, have gotten a lot less focus and there are a few scenarios that are not that obvious, especially if you're expecting Web API to provide functionality similar to ASP.NET AJAX style AJAX callbacks. RPC vs. 'Proper' REST RPC style HTTP calls mimic calling a method with parameters and returning a result. Rather than mapping explicit server side resources or 'nouns' RPC calls tend simply map a server side operation, passing in parameters and receiving a typed result where parameters and result values are marshaled over HTTP. Typically RPC calls - like SOAP calls - tend to always be POST operations rather than following HTTP conventions and using the GET/POST/PUT/DELETE etc. verbs to implicitly determine what operation needs to be fired. RPC might not be considered 'cool' anymore, but for typical private AJAX backend operations of a Web site I'd wager that a large percentage of use cases of Web API will fall towards RPC style calls rather than 'proper' REST style APIs. Web applications that have needs for things like live validation against data, filling data based on user inputs, handling small UI updates often don't lend themselves very well to limited HTTP verb usage. It might not be what the cool kids do, but I don't see RPC calls getting replaced by proper REST APIs any time soon.  Proper REST has its place - for 'real' API scenarios that manage and publish/share resources, but for more transactional operations RPC seems a better choice and much easier to implement than trying to shoehorn a boatload of endpoint methods into a few HTTP verbs. In any case Web API does a good job of providing both RPC abstraction as well as the HTTP Verb/REST abstraction. RPC works well out of the box, but there are some differences especially if you're coming from ASP.NET AJAX service or WCF Rest when it comes to multiple parameters. Action Routing for RPC Style Calls If you've looked at Web API demos you've probably seen a bunch of examples of how to create HTTP Verb based routing endpoints. Verb based routing essentially maps a controller and then uses HTTP verbs to map the methods that are called in response to HTTP requests. This works great for resource APIs but doesn't work so well when you have many operational methods in a single controller. HTTP Verb routing is limited to the few HTTP verbs available (plus separate method signatures) and - worse than that - you can't easily extend the controller with custom routes or action routing beyond that. Thankfully Web API also supports Action based routing which allows you create RPC style endpoints fairly easily:RouteTable.Routes.MapHttpRoute( name: "AlbumRpcApiAction", routeTemplate: "albums/{action}/{title}", defaults: new { title = RouteParameter.Optional, controller = "AlbumApi", action = "GetAblums" } ); This uses traditional MVC style {action} method routing which is different from the HTTP verb based routing you might have read a bunch about in conjunction with Web API. Action based routing like above lets you specify an end point method in a Web API controller either via the {action} parameter in the route string or via a default value for custom routes. Using routing you can pass multiple parameters either on the route itself or pass parameters on the query string, via ModelBinding or content value binding. For most common scenarios this actually works very well. As long as you are passing either a single complex type via a POST operation, or multiple simple types via query string or POST buffer, there's no issue. But if you need to pass multiple parameters as was easily done with WCF REST or ASP.NET AJAX things are not so obvious. Web API has no issue allowing for single parameter like this:[HttpPost] public string PostAlbum(Album album) { return String.Format("{0} {1:d}", album.AlbumName, album.Entered); } There are actually two ways to call this endpoint: albums/PostAlbum Using the Model Binder with plain POST values In this mechanism you're sending plain urlencoded POST values to the server which the ModelBinder then maps the parameter. Each property value is matched to each matching POST value. This works similar to the way that MVC's  ModelBinder works. Here's how you can POST using the ModelBinder and jQuery:$.ajax( { url: "albums/PostAlbum", type: "POST", data: { AlbumName: "Dirty Deeds", Entered: "5/1/2012" }, success: function (result) { alert(result); }, error: function (xhr, status, p3, p4) { var err = "Error " + " " + status + " " + p3; if (xhr.responseText && xhr.responseText[0] == "{") err = JSON.parse(xhr.responseText).message; alert(err); } }); Here's what the POST data looks like for this request: The model binder and it's straight form based POST mechanism is great for posting data directly from HTML pages to model objects. It avoids having to do manual conversions for many operations and is a great boon for AJAX callback requests. Using Web API JSON Formatter The other option is to post data using a JSON string. The process for this is similar except that you create a JavaScript object and serialize it to JSON first.album = { AlbumName: "PowerAge", Entered: new Date(1977,0,1) } $.ajax( { url: "albums/PostAlbum", type: "POST", contentType: "application/json", data: JSON.stringify(album), success: function (result) { alert(result); } }); Here the data is sent using a JSON object rather than form data and the data is JSON encoded over the wire. The trace reveals that the data is sent using plain JSON (Source above), which is a little more efficient since there's no UrlEncoding that occurs. BTW, notice that WebAPI automatically deals with the date. I provided the date as a plain string, rather than a JavaScript date value and the Formatter and ModelBinder both automatically map the date propertly to the Entered DateTime property of the Album object. Passing multiple Parameters to a Web API Controller Single parameters work fine in either of these RPC scenarios and that's to be expected. ModelBinding always works against a single object because it maps a model. But what happens when you want to pass multiple parameters? Consider an API Controller method that has a signature like the following:[HttpPost] public string PostAlbum(Album album, string userToken) Here I'm asking to pass two objects to an RPC method. Is that possible? This used to be fairly straight forward either with WCF REST and ASP.NET AJAX ASMX services, but as far as I can tell this is not directly possible using a POST operation with WebAPI. There a few workarounds that you can use to make this work: Use both POST *and* QueryString Parameters in Conjunction If you have both complex and simple parameters, you can pass simple parameters on the query string. The above would actually work with: /album/PostAlbum?userToken=sekkritt but that's not always possible. In this example it might not be a good idea to pass a user token on the query string though. It also won't work if you need to pass multiple complex objects, since query string values do not support complex type mapping. They only work with simple types. Use a single Object that wraps the two Parameters If you go by service based architecture guidelines every service method should always pass and return a single value only. The input should wrap potentially multiple input parameters and the output should convey status as well as provide the result value. You typically have a xxxRequest and a xxxResponse class that wraps the inputs and outputs. Here's what this method might look like:public PostAlbumResponse PostAlbum(PostAlbumRequest request) { var album = request.Album; var userToken = request.UserToken; return new PostAlbumResponse() { IsSuccess = true, Result = String.Format("{0} {1:d} {2}", album.AlbumName, album.Entered,userToken) }; } with these support types:public class PostAlbumRequest { public Album Album { get; set; } public User User { get; set; } public string UserToken { get; set; } } public class PostAlbumResponse { public string Result { get; set; } public bool IsSuccess { get; set; } public string ErrorMessage { get; set; } }   To call this method you now have to assemble these objects on the client and send it up as JSON:var album = { AlbumName: "PowerAge", Entered: "1/1/1977" } var user = { Name: "Rick" } var userToken = "sekkritt"; $.ajax( { url: "samples/PostAlbum", type: "POST", contentType: "application/json", data: JSON.stringify({ Album: album, User: user, UserToken: userToken }), success: function (result) { alert(result.Result); } }); I assemble the individual types first and then combine them in the data: property of the $.ajax() call into the actual object passed to the server, that mimics the structure of PostAlbumRequest server class that has Album, User and UserToken properties. This works well enough but it gets tedious if you have to create Request and Response types for each method signature. If you have common parameters that are always passed (like you always pass an album or usertoken) you might be able to abstract this to use a single object that gets reused for all methods, but this gets confusing too: Overload a single 'parameter' too much and it becomes a nightmare to decipher what your method actual can use. Use JObject to parse multiple Property Values out of an Object If you recall, ASP.NET AJAX and WCF REST used a 'wrapper' object to make default AJAX calls. Rather than directly calling a service you always passed an object which contained properties for each parameter: { parm1: Value, parm2: Value2 } WCF REST/ASP.NET AJAX would then parse this top level property values and map them to the parameters of the endpoint method. This automatic type wrapping functionality is no longer available directly in Web API, but since Web API now uses JSON.NET for it's JSON serializer you can actually simulate that behavior with a little extra code. You can use the JObject class to receive a dynamic JSON result and then using the dynamic cast of JObject to walk through the child objects and even parse them into strongly typed objects. Here's how to do this on the API Controller end:[HttpPost] public string PostAlbum(JObject jsonData) { dynamic json = jsonData; JObject jalbum = json.Album; JObject juser = json.User; string token = json.UserToken; var album = jalbum.ToObject<Album>(); var user = juser.ToObject<User>(); return String.Format("{0} {1} {2}", album.AlbumName, user.Name, token); } This is clearly not as nice as having the parameters passed directly, but it works to allow you to pass multiple parameters and access them using Web API. JObject is JSON.NET's generic object container which sports a nice dynamic interface that allows you to walk through the object's properties using standard 'dot' object syntax. All you have to do is cast the object to dynamic to get access to the property interface of the JSON type. Additionally JObject also allows you to parse JObject instances into strongly typed objects, which enables us here to retrieve the two objects passed as parameters from this jquery code:var album = { AlbumName: "PowerAge", Entered: "1/1/1977" } var user = { Name: "Rick" } var userToken = "sekkritt"; $.ajax( { url: "samples/PostAlbum", type: "POST", contentType: "application/json", data: JSON.stringify({ Album: album, User: user, UserToken: userToken }), success: function (result) { alert(result); } }); Summary ASP.NET Web API brings many new features and many advantages over the older Microsoft AJAX and REST APIs, but realize that some things like passing multiple strongly typed object parameters will work a bit differently. It's not insurmountable, but just knowing what options are available to simulate this behavior is good to know. Now let me say here that it's probably not a good practice to pass a bunch of parameters to an API call. Ideally APIs should be closely factored to accept single parameters or a single content parameter at least along with some identifier parameters that can be passed on the querystring. But saying that doesn't mean that occasionally you don't run into a situation where you have the need to pass several objects to the server and all three of the options I mentioned might have merit in different situations. For now I'm sure the question of how to pass multiple parameters will come up quite a bit from people migrating WCF REST or ASP.NET AJAX code to Web API. At least there are options available to make it work.© 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

  • How to deal with static utility classes when designing for testability

    - by Benedikt
    We are trying to design our system to be testable and in most parts developed using TDD. Currently we are trying to solve the following problem: In various places it is necessary for us to use static helper methods like ImageIO and URLEncoder (both standard Java API) and various other libraries that consist mostly of static methods (like the Apache Commons libraries). But it is extremely difficult to test those methods that use such static helper classes. I have several ideas for solving this problem: Use a mock framework that can mock static classes (like PowerMock). This may be the simplest solution but somehow feels like giving up. Create instantiable wrapper classes around all those static utilities so they can be injected into the classes that use them. This sounds like a relatively clean solution but I fear we'll end up creating an awful lot of those wrapper classes. Extract every call to these static helper classes into a function that can be overridden and test a subclass of the class I actually want to test. But I keep thinking that this just has to be a problem that many people have to face when doing TDD - so there must already be solutions for this problem. What is the best strategy to keep classes that use these static helpers testable?

    Read the article

  • Calling methods on Objects

    - by Mashael
    Let's say we have a class called 'Automobile' and we have an instance of that class called 'myCar'. I would like to ask why do we need to put the values that our methods return in a variable for the object? Why just don't we call the method? For example: Why should we write: string message = myCar.SpeedMessage(); Console.WriteLine(message); instead of: Console.WriteLine(myCar.SpeedMessage());

    Read the article

  • SQL SERVER – Quiz and Video – Introduction to Discovering XML Data Type Methods

    - by pinaldave
    This blog post is inspired from SQL Interoperability Joes 2 Pros: A Guide to Integrating SQL Server with XML, C#, and PowerShell – SQL Exam Prep Series 70-433 – Volume 5. [Amazon] | [Flipkart] | [Kindle] | [IndiaPlaza] This is follow up blog post of my earlier blog post on the same subject - SQL SERVER – Introduction to Discovering XML Data Type Methods – A Primer. In the article we discussed various basics terminology of the XML. The article further covers following important concepts of XML. What are XML Data Type Methods The query() Method The value() Method The exist() Method The modify() Method Above five are the most important concepts related to XML and SQL Server. There are many more things one has to learn but without beginners fundamentals one can’t learn the advanced  concepts. Let us have small quiz and check how many of you get the fundamentals right. Quiz 1.) Which method returns an XML fragment from the source XML? query( ) value( ) exist( ) modify( ) All of them Only query( ) and value( ) 2.) Which XML data type method returns a “1” if found and “0” if the specified XPath is not found in the source XML? query( ) value( ) exist( ) modify( ) All of them Only query( ) and value( ) 3.) Which XML data type method allows you to pick the data type of the value that is returned from the source XML? query( ) value( ) exist( ) modify( ) All of them Only query( ) and value( ) 4.) Which method will not work with a SQL SELECT statement? query( ) value( ) exist( ) modify( ) All of them Only query( ) and value( ) Now make sure that you write down all the answers on the piece of paper. Watch following video and read earlier article over here. If you want to change the answer you still have chance. Solution 1) 1 2) 3 3) 2 4) 4 Now compare let us check the answers and compare your answers to following answers. I am very confident you will get them correct. Available at USA: Amazon India: Flipkart | IndiaPlaza Volume: 1, 2, 3, 4, 5 Please leave your feedback in the comment area for the quiz and video. Did you know all the answers of the quiz? Reference: Pinal Dave (http://blog.sqlauthority.com) Filed under: Joes 2 Pros, PostADay, SQL, SQL Authority, SQL Query, SQL Server, SQL Tips and Tricks, T SQL, Technology

    Read the article

  • Helper methods StartOfMonth and StartOfNextMonth

    - by Michael Freidgeim
    There are couple methods recently added to My DateTimeHelper class     public static DateTime StartOfMonth(this DateTime dateValue)         {             return new DateTime(dateValue.Year,dateValue.Month,1,0,0,0);         }         public static DateTime StartOfNextMonth(this DateTime dateValue)         {             return StartOfMonth(dateValue).AddMonths(1);         }

    Read the article

  • Different Link Building Methods

    Link building plays a very important role in making a website popular. It is a process of creating inbound links to your page. Link building is something that you should not launch into without knowing enough about it. If you are creating back links organically, it's perfectly okay but do not go on creating dozens of links without considering standard link building methods.

    Read the article

  • Search Engine Placement Optimization - Methods and Practices That Work

    Proper utilization of search engine optimization is pertinent to the success of Internet related businesses. In order for SEO (search engine optimization) to be effective it must utilize methods and practices that have proven to be successful. The process involves knowing the proper keywords connected to using these keywords in order to provide a highest possible hit rate.

    Read the article

  • Do first-class methods exist?

    - by gdhoward
    Okay, I know first-class functions are cool, closures even better, etc. But is there any language with first-class methods? In my mind, I see a first-class method as an "object" that has both a function pointer and a pointer to a specific instance of the class/object, but the implementation doesn't matter. I just want to know if there is any language that uses them. And as a bonus, how were they implemented?

    Read the article

  • Best SEO Methods For Organic Traffic

    Search engine optimization is a complex and ever changing science on the internet. While certain things never seem to change about ranking high in the search engines, others simply never stop changing. These days, there are really only a handful of reliable methods for ranking high in the search engines, and it is something that you will see website designers and internet marketers raving about.

    Read the article

  • Alternate Methods of SEO

    We have had instances where all the known methods of search engine optimization have failed. You have a wonderful web site, very nice on page optimizations and thousands of important backlinks but all to no avail. Your web site gets little or no ranking. Hardly can it be seen among the first one thousand result search results.

    Read the article

  • Why does the Scala compiler disallow overloaded methods with default arguments?

    - by soc
    While there might be valid cases where such method overloadings could become ambiguous, why does the compiler disallow code which is neither ambiguous at compile time nor at run time? Example: // This fails: def foo(a: String)(b: Int = 42) = a + b def foo(a: Int) (b: Int = 42) = a + b // This fails, too. Even if there is no position in the argument list, // where the types are the same. def foo(a: Int) (b: Int = 42) = a + b def foo(a: String)(b: String = "Foo") = a + b // This is OK: def foo(a: String)(b: Int) = a + b def foo(a: Int) (b: Int = 42) = a + b // Even this is OK. def foo(a: Int)(b: Int) = a + b def foo(a: Int)(b: String = "Foo") = a + b val bar = foo(42)_ // This complains obviously ... Are there any reasons why these restrictions can't be loosened a bit? Especially when converting heavily overloaded Java code to Scala default arguments are a very important and it isn't nice to find out after replacing plenty of Java methods by one Scala methods that the spec/compiler imposes arbitrary restrictions.

    Read the article

  • Datamapper, defining your own object methods, how?

    - by Dublinclontarf
    So lets say I have a class like below class List include DataMapper::Resource property :id, Serial property :username, String def self.my_username return self[:username] end end list=List.create(:username=>,'jim') list.my_username When I run this it tells me that the method cannot be found, and on more investigation that you can only define class methods(not object methods) and that class methods don't have access to objects data. Is there any way to have these methods included as object methods and get access to object data? I'm using Ruby 1.8.6 and the latest version of datamapper.

    Read the article

  • Unit test helper methods?

    - by Aly
    Hi, I have classes which prviously had massive methods so i subdivided the work of this method into 'helper' methods. These helper methods are declared private to enforce encapsulation - however I want to unit test the big public methods, is it good to unit test the helper methods too as if one of them fail the public method that calls it will also fail - but this way we can identify why it failed. Also in order to test these using a mock object I would need to change their visibility from private to protected, is this desirable?

    Read the article

  • What's the meaning of the angle brackets on LINQ methods in Intellisense? (Contains<>, Count<>, Dis

    - by user312758
    They usually involve generics. But some methods with generics don't have them, and not all extension methods have them. They've just "been there" since day one, we've all seen them; but I realized I still don't know what they mean, and I can't find the answer anywhere. Now it's really bugging me. Google just turns up results that are about XML, etc. Is this officially documented anywhere? Thanks. EDIT: Well that's just great. Since I just created an account to make my first Stack Overflow post, to get an answer for this burning question; I'm not allowed to post my pretty Intellisense picture, or create a new tag "angle-brackets". I love Stack Overflow, but... what a welcome! Maybe my problem is that they aren't actually called "angle brackets"... ?? Anyway, I guess if you really want to see my beautiful screenshot you could manually go to: http://www.freeimagehosting.net/uploads/6a6c2f3268.png Bump me up please so I can include it in the post, thanks. ;)

    Read the article

  • How to queue and call actual methods (rather than immediately eval) in java?

    - by alleywayjack
    There are a list of tasks that are time sensitive (but "time" in this case is arbitrary to what another program tells me - it's more like "ticks" rather than time). However, I do NOT want said methods to evaluate immediately. I want one to execute after the other finished. I'm using a linked list for my queue, but I'm not really sure how/if I can access the actual methods in a class without evaluating them immediate. The code would look something like... LinkedList<Method> l = new LinkedList<Method>(); l.add( this.move(4) ); l.add( this.read() ); l.removeFirst().call(); //wait 80 ticks l.removeFirst().call(); move(4) would execute immediately, then 80 ticks later, I would remove it from the list and call this.read() which would then be executed. I'm assuming this has to do with the reflection classes, and I've poked around a bit, but I can't seem to get anything to work, or do what I want. If only I could use pointers...

    Read the article

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