Rectangle 27 95

Bugs found in all the custom javascript "natural string sort order" im...

I was really annoyed about this string natural sorting order so I took quite some time to investigate this issue. I hope this helps.

localeCompare() character support is badass, just use it. As pointed out by Shog9, the answer to your question is:

There are quite a bunch of custom implementations out there, trying to do string comparison more precisely called "natural string sort order"

When "playing" with these implementations, I always noticed some strange "natural sorting order" choice, or rather mistakes (or omissions in the best cases).

Typically, special characters (space, dash, ampersand, brackets, and so on) are not processed correctly.

You will then find them appearing mixed up in different places, typically that could be:

  • some will be between the uppercase 'Z' and the lowercase 'a'

When one would have expected special characters to all be "grouped" together in one place, except for the space special character maybe (which would always be the first character). That is, either all before numbers, or all between numbers and letters (lowercase & uppercase being "together" one after another), or all after letters.

My conclusion is that they all fail to provide a consistent order when I start adding barely unusual characters (ie. characters with diacritics or charcters such as dash, exclamation mark and so on).

Research on the custom implementations:

Natural Compare Lite
Natural Sort
Javascript Natural Sort
Alphanum
localeCompare()

Research on the browser-native implementations:

  • http://jsbin.com/beboroyifomu/2/edit?js,console - basic latin characters in string comparison : consistency check in string vs when a character is alone

So considering the current level of support provided by the javascript custom implementations I came across, we will probably never see anything getting any close to supporting all this characters & scripts (languages). Hence I would rather use the browsers' native localeCompare() method. Yes, it does have the downside of beeing non-consistent across browsers but basic testing shows it covers a much wider range of characters, allowing solid & meaningful sort orders.

Shog9
return item1.attr.localeCompare(item2.attr);

Thanks to Shog9's nice answer, which put me in the "right" direction I believe

How to sort strings in JavaScript - Stack Overflow

javascript string
Rectangle 27 16

You'll have to go with arrays or, if you require something that has a custom type, classes and objects.

Does PHP have structs or enums and if not what is the best implementat...

php enums typedef
Rectangle 27 16

You'll have to go with arrays or, if you require something that has a custom type, classes and objects.

Does PHP have structs or enums and if not what is the best implementat...

php enums typedef
Rectangle 27 141

How to draw a Bzier path in a custom view

It wasn't long ago that I didn't even know how to pronounce Bzier, let alone know how to use Bzier paths to make a custom shape. The following is what I have learned. It turns out that they aren't as scary as they seem at first.

These are the main steps:

  • Design the outline of the shape you want.
  • Divide the outline path into segments of lines, arcs, and curves.
  • Build that path programmatically.
  • Draw the path either in drawRect or using a CAShapeLayer.

You could do anything, but as an example I have chosen the shape below. It could be a popup key on a keyboard.

Look back at your shape design and break it down into simpler elements of lines (for straight lines), arcs (for circles and round corners), and curves (for anything else).

Here is what our example design would look like:

  • Orange dots are the control points for the curves
  • Green dots are the points between path segments
  • Dotted lines show the bounding rectangle
  • Dark blue numbers are the segments in the order that they will be added programmatically

We'll arbitrarily start in the bottom left corner and work clockwise. I'll use the grid in the image to get the x and y values for the points. I'll hardcode everything here, but of course you wouldn't do that in a real project.

The basic process is:

UIBezierPath
  • Choose a starting point on the path with moveToPoint
addLineToPoint
addArcWithCenter
addCurveToPoint
  • Close the path with closePath

Here is the code to make the path in the image above.

func createBezierPath() -> UIBezierPath {

    // create a new path
    let path = UIBezierPath()

    // starting point for the path (bottom left)
    path.move(to: CGPoint(x: 2, y: 26))

    // *********************
    // ***** Left side *****
    // *********************

    // segment 1: line
    path.addLine(to: CGPoint(x: 2, y: 15))

    // segment 2: curve
    path.addCurve(to: CGPoint(x: 0, y: 12), // ending point
        controlPoint1: CGPoint(x: 2, y: 14),
        controlPoint2: CGPoint(x: 0, y: 14))

    // segment 3: line
    path.addLine(to: CGPoint(x: 0, y: 2))

    // *********************
    // ****** Top side *****
    // *********************

    // segment 4: arc
    path.addArc(withCenter: CGPoint(x: 2, y: 2), // center point of circle
        radius: 2, // this will make it meet our path line
        startAngle: CGFloat(M_PI), //  radians = 180 degrees = straight left
        endAngle: CGFloat(3*M_PI_2), // 3/2 radians = 270 degrees = straight up
        clockwise: true) // startAngle to endAngle goes in a clockwise direction

    // segment 5: line
    path.addLine(to: CGPoint(x: 8, y: 0))

    // segment 6: arc
    path.addArc(withCenter: CGPoint(x: 8, y: 2),
                          radius: 2,
                          startAngle: CGFloat(3*M_PI_2), // straight up
        endAngle: CGFloat(0), // 0 radians = straight right
        clockwise: true)

    // *********************
    // ***** Right side ****
    // *********************

    // segment 7: line
    path.addLine(to: CGPoint(x: 10, y: 12))

    // segment 8: curve
    path.addCurve(to: CGPoint(x: 8, y: 15), // ending point
        controlPoint1: CGPoint(x: 10, y: 14),
        controlPoint2: CGPoint(x: 8, y: 14))

    // segment 9: line
    path.addLine(to: CGPoint(x: 8, y: 26))

    // *********************
    // **** Bottom side ****
    // *********************

    // segment 10: line
    path.close() // draws the final line to close the path

    return path
}

Note: Some of the above code can be reduced by adding a line and an arc in a single command (since the arc has an implied starting point). See here for more details.

We can draw the path either in a layer or in drawRect.

Method 1: Draw path in a layer

Our custom class looks like this. We add our Bezier path to a new CAShapeLayer when the view is initialized.

import UIKit
class MyCustomView: UIView {

    override init(frame: CGRect) {
        super.init(frame: frame)
        setup()
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        setup()
    }

    func setup() {

        // Create a CAShapeLayer
        let shapeLayer = CAShapeLayer()

        // The Bezier path that we made needs to be converted to 
        // a CGPath before it can be used on a layer.
        shapeLayer.path = createBezierPath().cgPath

        // apply other properties related to the path
        shapeLayer.strokeColor = UIColor.blue.cgColor
        shapeLayer.fillColor = UIColor.white.cgColor
        shapeLayer.lineWidth = 1.0
        shapeLayer.position = CGPoint(x: 10, y: 10)

        // add the new layer to our custom view
        self.layer.addSublayer(shapeLayer)
    }

    func createBezierPath() -> UIBezierPath {

        // see previous code for creating the Bezier path
    }
}

And creating our view in the View Controller like this

override func viewDidLoad() {
    super.viewDidLoad()

    // create a new UIView and add it to the view controller
    let myView = MyCustomView()
    myView.frame = CGRect(x: 100, y: 100, width: 50, height: 50)
    myView.backgroundColor = UIColor.yellow
    view.addSubview(myView)

}

Hmm, that's a little small because I hardcoded all the numbers in. I can scale the path size up, though, like this:

let path = createBezierPath()
let scale = CGAffineTransform(scaleX: 2, y: 2)
path.apply(scale)
shapeLayer.path = path.cgPath

Method 2: Draw path in draw

Using draw is slower than drawing to the layer, so this is not the recommended method if you don't need it.

Here is the revised code for our custom view:

import UIKit
class MyCustomView: UIView {

    override func draw(_ rect: CGRect) {

        // create path (see previous code)
        let path = createBezierPath()

        // fill
        let fillColor = UIColor.white
        fillColor.setFill()

        // stroke
        path.lineWidth = 1.0
        let strokeColor = UIColor.blue
        strokeColor.setStroke()

        // Move the path to a new location
        path.apply(CGAffineTransform(translationX: 10, y: 10))

        // fill and stroke the path (always do these last)
        path.fill()
        path.stroke()

    }

    func createBezierPath() -> UIBezierPath {

        // see previous code for creating the Bezier path
    }
}

which gives us the same result...

  • Thinking like a Bzier path (Everything I've ever read from this author is good and the inspiration for my example above came from here.)
  • Bezier Curves (how they are used in graphics applications)
  • Bezier Curves (good description of how the mathematical formulas are derived)

What if frame of the view changes? How can we resize the shape when an orientation change occurs?

@ozgur, There are at least two options. One would be to do a scale (and possibly translate) transform as I showed in my example above. Another option would be to recalculate the Bezier path based on the new frame. In the example above I hard coded all of the numbers into the Bezier path. However, when I have used Bezier paths in actual projects, I determine the Bezier values based on the frame size. When the frame (or more likely, bounds) changes I recalculate the Bezier path.

I chose the latter before. I recalculated the bezier path and updated the layer in question in layoutSubviews method but I am not sure if that is the right place to do it. Where would you update the path when the view's frame has changed?

@ozgur, layoutSubviews definitely sounds like the right place to do it. I would say if that is working then keep it there. Here is an example of where I used a Bezier path. (Scroll to the bottom.) For some reason I didn't put it in layoutSubviews but I don't remember why now. I should probably submit this to code review. I'm no expert. I just made the answer above to learn how to do Bezier paths myself.

@BohdanSavych, the draw method already belongs to the view, so you don't need to add it. It is a standard method defined by UIView for the purpose of drawing. We are just overriding it here so that we can do our own drawing on the view.

ios - Drawing UIBezierPath on code generated UIView - Stack Overflow

ios iphone objective-c uiview uibezierpath
Rectangle 27 141

How to draw a Bzier path in a custom view

It wasn't long ago that I didn't even know how to pronounce Bzier, let alone know how to use Bzier paths to make a custom shape. The following is what I have learned. It turns out that they aren't as scary as they seem at first.

These are the main steps:

  • Design the outline of the shape you want.
  • Divide the outline path into segments of lines, arcs, and curves.
  • Build that path programmatically.
  • Draw the path either in drawRect or using a CAShapeLayer.

You could do anything, but as an example I have chosen the shape below. It could be a popup key on a keyboard.

Look back at your shape design and break it down into simpler elements of lines (for straight lines), arcs (for circles and round corners), and curves (for anything else).

Here is what our example design would look like:

  • Orange dots are the control points for the curves
  • Green dots are the points between path segments
  • Dotted lines show the bounding rectangle
  • Dark blue numbers are the segments in the order that they will be added programmatically

We'll arbitrarily start in the bottom left corner and work clockwise. I'll use the grid in the image to get the x and y values for the points. I'll hardcode everything here, but of course you wouldn't do that in a real project.

The basic process is:

UIBezierPath
  • Choose a starting point on the path with moveToPoint
addLineToPoint
addArcWithCenter
addCurveToPoint
  • Close the path with closePath

Here is the code to make the path in the image above.

func createBezierPath() -> UIBezierPath {

    // create a new path
    let path = UIBezierPath()

    // starting point for the path (bottom left)
    path.move(to: CGPoint(x: 2, y: 26))

    // *********************
    // ***** Left side *****
    // *********************

    // segment 1: line
    path.addLine(to: CGPoint(x: 2, y: 15))

    // segment 2: curve
    path.addCurve(to: CGPoint(x: 0, y: 12), // ending point
        controlPoint1: CGPoint(x: 2, y: 14),
        controlPoint2: CGPoint(x: 0, y: 14))

    // segment 3: line
    path.addLine(to: CGPoint(x: 0, y: 2))

    // *********************
    // ****** Top side *****
    // *********************

    // segment 4: arc
    path.addArc(withCenter: CGPoint(x: 2, y: 2), // center point of circle
        radius: 2, // this will make it meet our path line
        startAngle: CGFloat(M_PI), //  radians = 180 degrees = straight left
        endAngle: CGFloat(3*M_PI_2), // 3/2 radians = 270 degrees = straight up
        clockwise: true) // startAngle to endAngle goes in a clockwise direction

    // segment 5: line
    path.addLine(to: CGPoint(x: 8, y: 0))

    // segment 6: arc
    path.addArc(withCenter: CGPoint(x: 8, y: 2),
                          radius: 2,
                          startAngle: CGFloat(3*M_PI_2), // straight up
        endAngle: CGFloat(0), // 0 radians = straight right
        clockwise: true)

    // *********************
    // ***** Right side ****
    // *********************

    // segment 7: line
    path.addLine(to: CGPoint(x: 10, y: 12))

    // segment 8: curve
    path.addCurve(to: CGPoint(x: 8, y: 15), // ending point
        controlPoint1: CGPoint(x: 10, y: 14),
        controlPoint2: CGPoint(x: 8, y: 14))

    // segment 9: line
    path.addLine(to: CGPoint(x: 8, y: 26))

    // *********************
    // **** Bottom side ****
    // *********************

    // segment 10: line
    path.close() // draws the final line to close the path

    return path
}

Note: Some of the above code can be reduced by adding a line and an arc in a single command (since the arc has an implied starting point). See here for more details.

We can draw the path either in a layer or in drawRect.

Method 1: Draw path in a layer

Our custom class looks like this. We add our Bezier path to a new CAShapeLayer when the view is initialized.

import UIKit
class MyCustomView: UIView {

    override init(frame: CGRect) {
        super.init(frame: frame)
        setup()
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        setup()
    }

    func setup() {

        // Create a CAShapeLayer
        let shapeLayer = CAShapeLayer()

        // The Bezier path that we made needs to be converted to 
        // a CGPath before it can be used on a layer.
        shapeLayer.path = createBezierPath().cgPath

        // apply other properties related to the path
        shapeLayer.strokeColor = UIColor.blue.cgColor
        shapeLayer.fillColor = UIColor.white.cgColor
        shapeLayer.lineWidth = 1.0
        shapeLayer.position = CGPoint(x: 10, y: 10)

        // add the new layer to our custom view
        self.layer.addSublayer(shapeLayer)
    }

    func createBezierPath() -> UIBezierPath {

        // see previous code for creating the Bezier path
    }
}

And creating our view in the View Controller like this

override func viewDidLoad() {
    super.viewDidLoad()

    // create a new UIView and add it to the view controller
    let myView = MyCustomView()
    myView.frame = CGRect(x: 100, y: 100, width: 50, height: 50)
    myView.backgroundColor = UIColor.yellow
    view.addSubview(myView)

}

Hmm, that's a little small because I hardcoded all the numbers in. I can scale the path size up, though, like this:

let path = createBezierPath()
let scale = CGAffineTransform(scaleX: 2, y: 2)
path.apply(scale)
shapeLayer.path = path.cgPath

Method 2: Draw path in draw

Using draw is slower than drawing to the layer, so this is not the recommended method if you don't need it.

Here is the revised code for our custom view:

import UIKit
class MyCustomView: UIView {

    override func draw(_ rect: CGRect) {

        // create path (see previous code)
        let path = createBezierPath()

        // fill
        let fillColor = UIColor.white
        fillColor.setFill()

        // stroke
        path.lineWidth = 1.0
        let strokeColor = UIColor.blue
        strokeColor.setStroke()

        // Move the path to a new location
        path.apply(CGAffineTransform(translationX: 10, y: 10))

        // fill and stroke the path (always do these last)
        path.fill()
        path.stroke()

    }

    func createBezierPath() -> UIBezierPath {

        // see previous code for creating the Bezier path
    }
}

which gives us the same result...

  • Thinking like a Bzier path (Everything I've ever read from this author is good and the inspiration for my example above came from here.)
  • Bezier Curves (how they are used in graphics applications)
  • Bezier Curves (good description of how the mathematical formulas are derived)

What if frame of the view changes? How can we resize the shape when an orientation change occurs?

@ozgur, There are at least two options. One would be to do a scale (and possibly translate) transform as I showed in my example above. Another option would be to recalculate the Bezier path based on the new frame. In the example above I hard coded all of the numbers into the Bezier path. However, when I have used Bezier paths in actual projects, I determine the Bezier values based on the frame size. When the frame (or more likely, bounds) changes I recalculate the Bezier path.

I chose the latter before. I recalculated the bezier path and updated the layer in question in layoutSubviews method but I am not sure if that is the right place to do it. Where would you update the path when the view's frame has changed?

@ozgur, layoutSubviews definitely sounds like the right place to do it. I would say if that is working then keep it there. Here is an example of where I used a Bezier path. (Scroll to the bottom.) For some reason I didn't put it in layoutSubviews but I don't remember why now. I should probably submit this to code review. I'm no expert. I just made the answer above to learn how to do Bezier paths myself.

@BohdanSavych, the draw method already belongs to the view, so you don't need to add it. It is a standard method defined by UIView for the purpose of drawing. We are just overriding it here so that we can do our own drawing on the view.

ios - Drawing UIBezierPath on code generated UIView - Stack Overflow

ios iphone objective-c uiview uibezierpath
Rectangle 27 84

I had this same issue and I resolve it by changing the UIButton type from "System" to "Custom". The blue background color does not show up in selected state when it is a "Custom" type.

Simple, but it removes the nice fade on touch. :(

This should be the accepted answer.

ios - How to remove UIButton selected background color? - Stack Overfl...

ios objective-c iphone uibutton uikit
Rectangle 27 129

Set up your service as a custom AngularJS Provider

Despite what the Accepted answer says, you actually CAN do what you were intending to do, but you need to set it up as a configurable provider, so that it's available as a service during the configuration phase.. First, change your Service to a provider as shown below. The key difference here is that after setting the value of defer, you set the defer.promise property to the promise object returned by $http.get:

app.provider('dbService', function dbServiceProvider() {

  //the provider recipe for services require you specify a $get function
  this.$get= ['dbhost',function dbServiceFactory(dbhost){
     // return the factory as a provider
     // that is available during the configuration phase
     return new DbService(dbhost);  
  }]

});

function DbService(dbhost){
    var status;

    this.setUrl = function(url){
        dbhost = url;
    }

    this.getData = function($http) {
        return $http.get(dbhost+'db.php/score/getData')
            .success(function(data){
                 // handle any special stuff here, I would suggest the following:
                 status = 'ok';
                 status.data = data;
             })
             .error(function(message){
                 status = 'error';
                 status.message = message;
             })
             .then(function(){
                 // now we return an object with data or information about error 
                 // for special handling inside your application configuration
                 return status;
             })
    }    
}

Now, you have a configurable custom Provider, you just need to inject it. Key difference here being the missing "Provider on your injectable".

app.config(function ($routeProvider) { 
    $routeProvider
        .when('/', {
            templateUrl: "partials/editor.html",
            controller: "AppCtrl",
            resolve: {
                dbData: function(DbService, $http) {
                     /*
                     *dbServiceProvider returns a dbService instance to your app whenever
                     * needed, and this instance is setup internally with a promise, 
                     * so you don't need to worry about $q and all that
                     */
                    return DbService('http://dbhost.com').getData();
                }
            }
        })
});
appCtrl
app.controller('appCtrl',function(dbData, DbService){
     $scope.dbData = dbData;

     // You can also create and use another instance of the dbService here...
     // to do whatever you programmed it to do, by adding functions inside the 
     // constructor DbService(), the following assumes you added 
     // a rmUser(userObj) function in the factory
     $scope.removeDbUser = function(user){
         DbService.rmUser(user);
     }

})

The following alternative is a similar approach, but allows definition to occur within the .config, encapsulating the service to within the specific module in the context of your app. Choose the method that right for you. Also see below for notes on a 3rd alternative and helpful links to help you get the hang of all these things

app.config(function($routeProvider, $provide) {
    $provide.service('dbService',function(){})
    //set up your service inside the module's config.

    $routeProvider
        .when('/', {
            templateUrl: "partials/editor.html",
            controller: "AppCtrl",
            resolve: {
                data: 
            }
        })
});
  • John Lindquist has an excellent 5 minute explanation and demonstration of this at egghead.io, and it's one of the free lessons! I basically modified his demonstration by making it $http specific in the context of this request
  • View the AngularJS Developer guide on Providers
factory
service
provider

The provider gives you a bit more configuration over the .service method, which makes it better as an application level provider, but you could also encapsulate this within the config object itself by injecting $provide into config like so:

It would really be useful if your codepen samples worked. For instance, $provide.service('dbService',function(){ doesn't have $http injected but uses it in its body. As it stands, I could not get your technique 2 to work. It's very frustrating that it is so hard to load config data from a remove file in an Angular program at startup.

@Alkaline I have learned a thing or two since this post. The answer is correct in theory but has 1 or 2 things (1 you pointed out) that should be fixed. Thanks for the comment. I'll review and update the answer. Deleted the codepen for the moment... never had a chance to finish it.

I think the information you provided here is incorrect. You can use a provider but during config phase you're not working with the result of the $get call. Instead you want to add methods on the provider instance and just return this when you call $get. In fact in your example you could just use a service... In a provider you also can't inject services like $http. And btw this //return the factory as a provider, that is available during the configuration phase is misleading/incorrect information

angularjs - Inject service in app.config - Stack Overflow

angularjs
Rectangle 27 23

You define the block as a custom type:

typedef void (^ButtonCompletionBlock)(int buttonIndex);

Then use it as an argument to a method:

+ (SomeButtonView*)buttonViewWithTitle:(NSString *)title 
                          cancelAction:(ButtonCompletionBlock)cancelBlock
                      completionAction:(ButtonCompletionBlock)completionBlock

When calling this in code it is just like any other block:

[SomeButtonView buttonViewWithTitle:@"Title"
                       cancelAction:^(int buttonIndex) {
                             NSLog(@"User cancelled");
                   } 
                     completionAction:^(int buttonIndex) {
                             NSLog(@"User tapped index %i", buttonIndex);
                   }];

If it comes time to trigger the block, simply call completionBlock() (where completionBlock is the name of your local copy of the block).

objective c - Custom completion block for my own method - Stack Overfl...

objective-c objective-c-blocks
Rectangle 27 286

Full implementation, with custom properties

MySerializableException
sealed
MyDerivedSerializableException

The main points about this implementation are summarized here:

must decorate each derived class with the [Serializable] attribute

SerializationException
[Serializable]
Exception
ISerializable
  • Provide a serialization constructor. This constructor should be private if your class is sealed, otherwise it should be protected to allow access to derived classes.
  • Override GetObjectData() and make sure you call through to base.GetObjectData(info, context) at the end, in order to let the base class save its own state.

MSTest unit tests for the three exception types defined above.

namespace SerializableExceptions
{
    using System;
    using System.Collections.Generic;
    using System.IO;
    using System.Runtime.Serialization.Formatters.Binary;
    using Microsoft.VisualStudio.TestTools.UnitTesting;

    [TestClass]
    public class UnitTests
    {
        private const string Message = "The widget has unavoidably blooped out.";
        private const string ResourceName = "Resource-A";
        private const string ValidationError1 = "You forgot to set the whizz bang flag.";
        private const string ValidationError2 = "Wally cannot operate in zero gravity.";
        private readonly List<string> validationErrors = new List<string>();
        private const string Username = "Barry";

        public UnitTests()
        {
            validationErrors.Add(ValidationError1);
            validationErrors.Add(ValidationError2);
        }

        [TestMethod]
        public void TestSerializableExceptionWithoutCustomProperties()
        {
            Exception ex =
                new SerializableExceptionWithoutCustomProperties(
                    "Message", new Exception("Inner exception."));

            // Save the full ToString() value, including the exception message and stack trace.
            string exceptionToString = ex.ToString();

            // Round-trip the exception: Serialize and de-serialize with a BinaryFormatter
            BinaryFormatter bf = new BinaryFormatter();
            using (MemoryStream ms = new MemoryStream())
            {
                // "Save" object state
                bf.Serialize(ms, ex);

                // Re-use the same stream for de-serialization
                ms.Seek(0, 0);

                // Replace the original exception with de-serialized one
                ex = (SerializableExceptionWithoutCustomProperties)bf.Deserialize(ms);
            }

            // Double-check that the exception message and stack trace (owned by the base Exception) are preserved
            Assert.AreEqual(exceptionToString, ex.ToString(), "ex.ToString()");
        }

        [TestMethod]
        public void TestSerializableExceptionWithCustomProperties()
        {
            SerializableExceptionWithCustomProperties ex = 
                new SerializableExceptionWithCustomProperties(Message, ResourceName, validationErrors);

            // Sanity check: Make sure custom properties are set before serialization
            Assert.AreEqual(Message, ex.Message, "Message");
            Assert.AreEqual(ResourceName, ex.ResourceName, "ex.ResourceName");
            Assert.AreEqual(2, ex.ValidationErrors.Count, "ex.ValidationErrors.Count");
            Assert.AreEqual(ValidationError1, ex.ValidationErrors[0], "ex.ValidationErrors[0]");
            Assert.AreEqual(ValidationError2, ex.ValidationErrors[1], "ex.ValidationErrors[1]");

            // Save the full ToString() value, including the exception message and stack trace.
            string exceptionToString = ex.ToString();

            // Round-trip the exception: Serialize and de-serialize with a BinaryFormatter
            BinaryFormatter bf = new BinaryFormatter();
            using (MemoryStream ms = new MemoryStream())
            {
                // "Save" object state
                bf.Serialize(ms, ex);

                // Re-use the same stream for de-serialization
                ms.Seek(0, 0);

                // Replace the original exception with de-serialized one
                ex = (SerializableExceptionWithCustomProperties)bf.Deserialize(ms);
            }

            // Make sure custom properties are preserved after serialization
            Assert.AreEqual(Message, ex.Message, "Message");
            Assert.AreEqual(ResourceName, ex.ResourceName, "ex.ResourceName");
            Assert.AreEqual(2, ex.ValidationErrors.Count, "ex.ValidationErrors.Count");
            Assert.AreEqual(ValidationError1, ex.ValidationErrors[0], "ex.ValidationErrors[0]");
            Assert.AreEqual(ValidationError2, ex.ValidationErrors[1], "ex.ValidationErrors[1]");

            // Double-check that the exception message and stack trace (owned by the base Exception) are preserved
            Assert.AreEqual(exceptionToString, ex.ToString(), "ex.ToString()");
        }

        [TestMethod]
        public void TestDerivedSerializableExceptionWithAdditionalCustomProperty()
        {
            DerivedSerializableExceptionWithAdditionalCustomProperty ex = 
                new DerivedSerializableExceptionWithAdditionalCustomProperty(Message, Username, ResourceName, validationErrors);

            // Sanity check: Make sure custom properties are set before serialization
            Assert.AreEqual(Message, ex.Message, "Message");
            Assert.AreEqual(ResourceName, ex.ResourceName, "ex.ResourceName");
            Assert.AreEqual(2, ex.ValidationErrors.Count, "ex.ValidationErrors.Count");
            Assert.AreEqual(ValidationError1, ex.ValidationErrors[0], "ex.ValidationErrors[0]");
            Assert.AreEqual(ValidationError2, ex.ValidationErrors[1], "ex.ValidationErrors[1]");
            Assert.AreEqual(Username, ex.Username);

            // Save the full ToString() value, including the exception message and stack trace.
            string exceptionToString = ex.ToString();

            // Round-trip the exception: Serialize and de-serialize with a BinaryFormatter
            BinaryFormatter bf = new BinaryFormatter();
            using (MemoryStream ms = new MemoryStream())
            {
                // "Save" object state
                bf.Serialize(ms, ex);

                // Re-use the same stream for de-serialization
                ms.Seek(0, 0);

                // Replace the original exception with de-serialized one
                ex = (DerivedSerializableExceptionWithAdditionalCustomProperty)bf.Deserialize(ms);
            }

            // Make sure custom properties are preserved after serialization
            Assert.AreEqual(Message, ex.Message, "Message");
            Assert.AreEqual(ResourceName, ex.ResourceName, "ex.ResourceName");
            Assert.AreEqual(2, ex.ValidationErrors.Count, "ex.ValidationErrors.Count");
            Assert.AreEqual(ValidationError1, ex.ValidationErrors[0], "ex.ValidationErrors[0]");
            Assert.AreEqual(ValidationError2, ex.ValidationErrors[1], "ex.ValidationErrors[1]");
            Assert.AreEqual(Username, ex.Username);

            // Double-check that the exception message and stack trace (owned by the base Exception) are preserved
            Assert.AreEqual(exceptionToString, ex.ToString(), "ex.ToString()");
        }
    }
}

+1: but if you're going to this much trouble, I'd go all the way and follow all the MS guidelines for implementing exceptions. One I can remember is to provide the standard construcors MyException(), MyException(string message) and MyException(string message, Exception innerException)

+10 if I could. That's a very useful answer.

Also - that the Framework Design Guideliness say that names for exceptions should end with "Exception". Something like MyExceptionAndHereIsaQualifyingAdverbialPhrase is disrecommended. msdn.microsoft.com/en-us/library/ms229064.aspx Someone once said, the code we provide here is often used as a pattern, so we should be careful to get it right.

Cheeso: The book "Framework Design Guidelines", in the section on Designing Custom Exceptions, states: "Do provide (at least) these common constructors on all exceptions." See here: blogs.msdn.com/kcwalina/archive/2006/07/05/657268.aspx Only the (SerializationInfo info, StreamingContext context) constructor is needed for serialisation correctness, the rest is provided to make this a good starting point for cut-and-paste. When you cut and paste, however, you will surely change the class names, therefore I don't think violating the exception naming convention is significant here...

What is the correct way to make a custom .NET Exception serializable? ...

.net exception serialization
Rectangle 27 9

Ah, I answered before you added the additional clarification. The short answer is, yes, just cast it as your custom type.

Borrowing from the code in the other question, and assuming that all your User Controls can be made to inherit from the same base class, you could do this.

Create a new class to act as the base control:

public class MyBaseControl : System.Web.UI.UserControl
{
    public string MyProperty 
    {
        get { return ViewState["MyProp"] as string; }
        set { ViewState["MyProp"] = value; }
    }
}

Then update your user controls to inherit from your base class instead of UserControl:

public partial class SampleControl2 : MyBaseControl
{
    ....

Then, in the place where you load the controls, change this:

UserControl uc = (UserControl)LoadControl(controlPath);
PlaceHolder1.Controls.Add(uc);
MyBaseControl uc = (MyBaseControl)LoadControl(controlPath);
uc.MyProperty = "foo";
PlaceHolder1.Controls.Add(uc);

I thought this only worked in web application projects and not web site projects. Is that still the case?

It should work, regardless. I've never had a problem with it.

c# - Set properties on dynamically added UserControl - Stack Overflow

c# .net asp.net user-controls .net-2.0
Rectangle 27 7

You define the block as a custom type:

typedef void (^ButtonCompletionBlock)(int buttonIndex);

Then use it as an argument to a method:

+ (SomeButtonView*)buttonViewWithTitle:(NSString *)title 
                      cancelAction:(ButtonCompletionBlock)cancelBlock
                  completionAction:(ButtonCompletionBlock)completionBlock

When calling this in code it is just like any other block:

[SomeButtonView buttonViewWithTitle:@"Title"
                   cancelAction:^(int buttonIndex) {
                         NSLog(@"User cancelled");
               } 
                 completionAction:^(int buttonIndex) {
                         NSLog(@"User tapped index %i", buttonIndex);
               }];

If it comes time to trigger the block, simply call completionBlock() (where completionBlock is the name of your local copy of the block

ios - How to write an Objective-C Completion Block - Stack Overflow

ios objective-c objective-c-blocks
Rectangle 27 5

  • even an instance of a custom type

Factories and Providers are most flexible out of the Service, Constant, Value in terms of what they bind to the injector. Hence Angular can detect the type of object/primitive that is bound to Service, Constant, Value hence friendlier since we know the type upfront (design/build time).

angularjs - What is the type friendly injection? - Stack Overflow

angularjs dependency-injection
Rectangle 27 3

The thing is path parameters come in String form. As per the specification, if we want the have a custom type be injected as a @PathParam, the custom class, should have one of three things:

  • A public static valueOf(String param) that returns the type
fromString(String param)
  • Or a public constructor that accepts a String
  • Another option implement a ParamConverter. You can see an example here.

If you don't own the class (it's a third-party class that you can't change) then your only option is to use the ParamConverter/ParamConverterProvider pair.

In either of these cases you'll want to construct the instance accordingly by parsing the String either in the constructor or in one of the above mentioned methods. After doing this, the custom type can be made a method parameter with the annotation.

The same holds true for other params, such as @FormParam, @HeaderParam, @QueryParam, etc.

java - How to use Custom type for @PathParam? - Stack Overflow

java web-services jersey jax-rs
Rectangle 27 504

All Services are singletons; they get instantiated once per app. They can be of any type, whether it be a primitive, object literal, function, or even an instance of a custom type.

The value, factory, service, constant, and provider methods are all providers. They teach the Injector how to instantiate the Services.

The most verbose, but also the most comprehensive one is a Provider recipe. The remaining four recipe types Value, Factory, Service and Constant are just syntactic sugar on top of a provider recipe.

  • The Value Recipe is the simplest case, where you instantiate the Service yourself and provide the instantiated value to the injector.
  • The Factory recipe gives the Injector a factory function that it calls when it needs to instantiate the service. When called, the factory function creates and returns the service instance. The dependencies of the Service are injected as the functions' arguments. So using this recipe adds the following abilities: Ability to use other services (have dependencies) Service initialization Delayed/lazy initialization
  • The Service recipe is almost the same as the Factory recipe, but here the Injector invokes a constructor with the new operator instead of a factory function.

You should use the Provider recipe only when you want to expose an API for application-wide configuration that must be made before the application starts. This is usually interesting only for reusable services whose behavior might need to vary slightly between applications.

  • The Constant recipe is just like the Value recipe except it allows you to define services that are available in the config phase. Sooner than services created using the Value recipe. Unlike Values, they cannot be decorated using decorator.

So service and factory are essentially the same? Using one of the other provides nothing other than alternative syntax?

This might be the best explanation. Sometimes examples are just distracting when you want the real meaning!

@Matt, yes, service is a concise way when you already have your own function which you want to expose as a service. From docs: myApp.factory('unicornLauncher', ["apiToken", function(apiToken) { return new UnicornLauncher(apiToken); }]); vs: myApp.service('unicornLauncher', ["apiToken", UnicornLauncher]);

@joshperry As a newbie, I've googled the difference between service and factory for a while. I do agree this is the best answer ever! I'd understand service as a service class (e.g. encoder/decoder class), which might have some private properties. And factory provides a set of stateless helper methods.

Yaa examples in other answers above fail to very clearly explain the core difference b/w services and providers which is what is injected at the time when these recipes are instantiated.

dependency injection - AngularJS: Service vs provider vs factory - Sta...

angularjs dependency-injection angularjs-service angularjs-factory angularjs-provider
Rectangle 27 504

All Services are singletons; they get instantiated once per app. They can be of any type, whether it be a primitive, object literal, function, or even an instance of a custom type.

The value, factory, service, constant, and provider methods are all providers. They teach the Injector how to instantiate the Services.

The most verbose, but also the most comprehensive one is a Provider recipe. The remaining four recipe types Value, Factory, Service and Constant are just syntactic sugar on top of a provider recipe.

  • The Value Recipe is the simplest case, where you instantiate the Service yourself and provide the instantiated value to the injector.
  • The Factory recipe gives the Injector a factory function that it calls when it needs to instantiate the service. When called, the factory function creates and returns the service instance. The dependencies of the Service are injected as the functions' arguments. So using this recipe adds the following abilities: Ability to use other services (have dependencies) Service initialization Delayed/lazy initialization
  • The Service recipe is almost the same as the Factory recipe, but here the Injector invokes a constructor with the new operator instead of a factory function.

You should use the Provider recipe only when you want to expose an API for application-wide configuration that must be made before the application starts. This is usually interesting only for reusable services whose behavior might need to vary slightly between applications.

  • The Constant recipe is just like the Value recipe except it allows you to define services that are available in the config phase. Sooner than services created using the Value recipe. Unlike Values, they cannot be decorated using decorator.

So service and factory are essentially the same? Using one of the other provides nothing other than alternative syntax?

This might be the best explanation. Sometimes examples are just distracting when you want the real meaning!

@Matt, yes, service is a concise way when you already have your own function which you want to expose as a service. From docs: myApp.factory('unicornLauncher', ["apiToken", function(apiToken) { return new UnicornLauncher(apiToken); }]); vs: myApp.service('unicornLauncher', ["apiToken", UnicornLauncher]);

@joshperry As a newbie, I've googled the difference between service and factory for a while. I do agree this is the best answer ever! I'd understand service as a service class (e.g. encoder/decoder class), which might have some private properties. And factory provides a set of stateless helper methods.

Yaa examples in other answers above fail to very clearly explain the core difference b/w services and providers which is what is injected at the time when these recipes are instantiated.

dependency injection - AngularJS: Service vs provider vs factory - Sta...

angularjs dependency-injection angularjs-service angularjs-factory angularjs-provider
Rectangle 27 504

All Services are singletons; they get instantiated once per app. They can be of any type, whether it be a primitive, object literal, function, or even an instance of a custom type.

The value, factory, service, constant, and provider methods are all providers. They teach the Injector how to instantiate the Services.

The most verbose, but also the most comprehensive one is a Provider recipe. The remaining four recipe types Value, Factory, Service and Constant are just syntactic sugar on top of a provider recipe.

  • The Value Recipe is the simplest case, where you instantiate the Service yourself and provide the instantiated value to the injector.
  • The Factory recipe gives the Injector a factory function that it calls when it needs to instantiate the service. When called, the factory function creates and returns the service instance. The dependencies of the Service are injected as the functions' arguments. So using this recipe adds the following abilities: Ability to use other services (have dependencies) Service initialization Delayed/lazy initialization
  • The Service recipe is almost the same as the Factory recipe, but here the Injector invokes a constructor with the new operator instead of a factory function.

You should use the Provider recipe only when you want to expose an API for application-wide configuration that must be made before the application starts. This is usually interesting only for reusable services whose behavior might need to vary slightly between applications.

  • The Constant recipe is just like the Value recipe except it allows you to define services that are available in the config phase. Sooner than services created using the Value recipe. Unlike Values, they cannot be decorated using decorator.

So service and factory are essentially the same? Using one of the other provides nothing other than alternative syntax?

This might be the best explanation. Sometimes examples are just distracting when you want the real meaning!

@Matt, yes, service is a concise way when you already have your own function which you want to expose as a service. From docs: myApp.factory('unicornLauncher', ["apiToken", function(apiToken) { return new UnicornLauncher(apiToken); }]); vs: myApp.service('unicornLauncher', ["apiToken", UnicornLauncher]);

@joshperry As a newbie, I've googled the difference between service and factory for a while. I do agree this is the best answer ever! I'd understand service as a service class (e.g. encoder/decoder class), which might have some private properties. And factory provides a set of stateless helper methods.

Yaa examples in other answers above fail to very clearly explain the core difference b/w services and providers which is what is injected at the time when these recipes are instantiated.

dependency injection - AngularJS: Service vs provider vs factory - Sta...

angularjs dependency-injection angularjs-service angularjs-factory angularjs-provider
Rectangle 27 504

All Services are singletons; they get instantiated once per app. They can be of any type, whether it be a primitive, object literal, function, or even an instance of a custom type.

The value, factory, service, constant, and provider methods are all providers. They teach the Injector how to instantiate the Services.

The most verbose, but also the most comprehensive one is a Provider recipe. The remaining four recipe types Value, Factory, Service and Constant are just syntactic sugar on top of a provider recipe.

  • The Value Recipe is the simplest case, where you instantiate the Service yourself and provide the instantiated value to the injector.
  • The Factory recipe gives the Injector a factory function that it calls when it needs to instantiate the service. When called, the factory function creates and returns the service instance. The dependencies of the Service are injected as the functions' arguments. So using this recipe adds the following abilities: Ability to use other services (have dependencies) Service initialization Delayed/lazy initialization
  • The Service recipe is almost the same as the Factory recipe, but here the Injector invokes a constructor with the new operator instead of a factory function.

You should use the Provider recipe only when you want to expose an API for application-wide configuration that must be made before the application starts. This is usually interesting only for reusable services whose behavior might need to vary slightly between applications.

  • The Constant recipe is just like the Value recipe except it allows you to define services that are available in the config phase. Sooner than services created using the Value recipe. Unlike Values, they cannot be decorated using decorator.

So service and factory are essentially the same? Using one of the other provides nothing other than alternative syntax?

@Matt, yes, service is a concise way when you already have your own function which you want to expose as a service. From docs: myApp.factory('unicornLauncher', ["apiToken", function(apiToken) { return new UnicornLauncher(apiToken); }]); vs: myApp.service('unicornLauncher', ["apiToken", UnicornLauncher]);

@joshperry As a newbie, I've googled the difference between service and factory for a while. I do agree this is the best answer ever! I'd understand service as a service class (e.g. encoder/decoder class), which might have some private properties. And factory provides a set of stateless helper methods.

Yaa examples in other answers above fail to very clearly explain the core difference b/w services and providers which is what is injected at the time when these recipes are instantiated.

dependency injection - AngularJS: Service vs provider vs factory - Sta...

angularjs dependency-injection angularjs-service angularjs-factory angularjs-provider
Rectangle 27 504

All Services are singletons; they get instantiated once per app. They can be of any type, whether it be a primitive, object literal, function, or even an instance of a custom type.

The value, factory, service, constant, and provider methods are all providers. They teach the Injector how to instantiate the Services.

The most verbose, but also the most comprehensive one is a Provider recipe. The remaining four recipe types Value, Factory, Service and Constant are just syntactic sugar on top of a provider recipe.

  • The Value Recipe is the simplest case, where you instantiate the Service yourself and provide the instantiated value to the injector.
  • The Factory recipe gives the Injector a factory function that it calls when it needs to instantiate the service. When called, the factory function creates and returns the service instance. The dependencies of the Service are injected as the functions' arguments. So using this recipe adds the following abilities: Ability to use other services (have dependencies) Service initialization Delayed/lazy initialization
  • The Service recipe is almost the same as the Factory recipe, but here the Injector invokes a constructor with the new operator instead of a factory function.

You should use the Provider recipe only when you want to expose an API for application-wide configuration that must be made before the application starts. This is usually interesting only for reusable services whose behavior might need to vary slightly between applications.

  • The Constant recipe is just like the Value recipe except it allows you to define services that are available in the config phase. Sooner than services created using the Value recipe. Unlike Values, they cannot be decorated using decorator.

So service and factory are essentially the same? Using one of the other provides nothing other than alternative syntax?

@Matt, yes, service is a concise way when you already have your own function which you want to expose as a service. From docs: myApp.factory('unicornLauncher', ["apiToken", function(apiToken) { return new UnicornLauncher(apiToken); }]); vs: myApp.service('unicornLauncher', ["apiToken", UnicornLauncher]);

@joshperry As a newbie, I've googled the difference between service and factory for a while. I do agree this is the best answer ever! I'd understand service as a service class (e.g. encoder/decoder class), which might have some private properties. And factory provides a set of stateless helper methods.

Yaa examples in other answers above fail to very clearly explain the core difference b/w services and providers which is what is injected at the time when these recipes are instantiated.

dependency injection - AngularJS: Service vs provider vs factory - Sta...

angularjs dependency-injection angularjs-service angularjs-factory angularjs-provider
Rectangle 27 503

All Services are singletons; they get instantiated once per app. They can be of any type, whether it be a primitive, object literal, function, or even an instance of a custom type.

The value, factory, service, constant, and provider methods are all providers. They teach the Injector how to instantiate the Services.

The most verbose, but also the most comprehensive one is a Provider recipe. The remaining four recipe types Value, Factory, Service and Constant are just syntactic sugar on top of a provider recipe.

  • The Value Recipe is the simplest case, where you instantiate the Service yourself and provide the instantiated value to the injector.
  • The Factory recipe gives the Injector a factory function that it calls when it needs to instantiate the service. When called, the factory function creates and returns the service instance. The dependencies of the Service are injected as the functions' arguments. So using this recipe adds the following abilities: Ability to use other services (have dependencies) Service initialization Delayed/lazy initialization
  • The Service recipe is almost the same as the Factory recipe, but here the Injector invokes a constructor with the new operator instead of a factory function.

You should use the Provider recipe only when you want to expose an API for application-wide configuration that must be made before the application starts. This is usually interesting only for reusable services whose behavior might need to vary slightly between applications.

  • The Constant recipe is just like the Value recipe except it allows you to define services that are available in the config phase. Sooner than services created using the Value recipe. Unlike Values, they cannot be decorated using decorator.

So service and factory are essentially the same? Using one of the other provides nothing other than alternative syntax?

@Matt, yes, service is a concise way when you already have your own function which you want to expose as a service. From docs: myApp.factory('unicornLauncher', ["apiToken", function(apiToken) { return new UnicornLauncher(apiToken); }]); vs: myApp.service('unicornLauncher', ["apiToken", UnicornLauncher]);

@joshperry As a newbie, I've googled the difference between service and factory for a while. I do agree this is the best answer ever! I'd understand service as a service class (e.g. encoder/decoder class), which might have some private properties. And factory provides a set of stateless helper methods.

Yaa examples in other answers above fail to very clearly explain the core difference b/w services and providers which is what is injected at the time when these recipes are instantiated.

dependency injection - AngularJS: Service vs provider vs factory - Sta...

angularjs dependency-injection angularjs-service angularjs-factory angularjs-provider
Rectangle 27 503

All Services are singletons; they get instantiated once per app. They can be of any type, whether it be a primitive, object literal, function, or even an instance of a custom type.

The value, factory, service, constant, and provider methods are all providers. They teach the Injector how to instantiate the Services.

The most verbose, but also the most comprehensive one is a Provider recipe. The remaining four recipe types Value, Factory, Service and Constant are just syntactic sugar on top of a provider recipe.

  • The Value Recipe is the simplest case, where you instantiate the Service yourself and provide the instantiated value to the injector.
  • The Factory recipe gives the Injector a factory function that it calls when it needs to instantiate the service. When called, the factory function creates and returns the service instance. The dependencies of the Service are injected as the functions' arguments. So using this recipe adds the following abilities: Ability to use other services (have dependencies) Service initialization Delayed/lazy initialization
  • The Service recipe is almost the same as the Factory recipe, but here the Injector invokes a constructor with the new operator instead of a factory function.

You should use the Provider recipe only when you want to expose an API for application-wide configuration that must be made before the application starts. This is usually interesting only for reusable services whose behavior might need to vary slightly between applications.

  • The Constant recipe is just like the Value recipe except it allows you to define services that are available in the config phase. Sooner than services created using the Value recipe. Unlike Values, they cannot be decorated using decorator.

So service and factory are essentially the same? Using one of the other provides nothing other than alternative syntax?

@Matt, yes, service is a concise way when you already have your own function which you want to expose as a service. From docs: myApp.factory('unicornLauncher', ["apiToken", function(apiToken) { return new UnicornLauncher(apiToken); }]); vs: myApp.service('unicornLauncher', ["apiToken", UnicornLauncher]);

@joshperry As a newbie, I've googled the difference between service and factory for a while. I do agree this is the best answer ever! I'd understand service as a service class (e.g. encoder/decoder class), which might have some private properties. And factory provides a set of stateless helper methods.

Yaa examples in other answers above fail to very clearly explain the core difference b/w services and providers which is what is injected at the time when these recipes are instantiated.

dependency injection - AngularJS: Service vs provider vs factory - Sta...

angularjs dependency-injection angularjs-service angularjs-factory angularjs-provider