dimanche 28 juin 2015

Cocoa Windows, not receiving events

For the last few days I've returned to an issue that I've been having for a while now. I've been trying to integrate Cocoa windows into my application, but the [NSApplication run] doesn't fit in with my programs model and getting the user inputs is more difficult than expected, As no event is received by the window.

I checked with XCode the value of _currentEvent and it's consistently nil which leads me to think that the window isn't capturing the events in the first place. I included a screenshot of the window while it's focused, although it doesn't appear to be active as the icons aren't coloured. I've also included the code for the window creation in Objective-C

Note: Calling [application run] does work and I receive inputs with an active looking window once called.

Source: http://ift.tt/1JrC01D

Variables:

Variables

Window:

Window

POST raw json code ios

i'm new to ios developing and i want to ask how can i post a raw json code to the server.

For Example: i want to send this JSON raw data to http://example.com/user

{ "user": 
                {   "username": "jkaaannyaad11",
                    "password": "secret123456",
                    "gender": "male",
                    "first_name": "assd",
                    "last_name": "ffsasd",
                    "birth_date": "can be null",
                    "phone_number": "12343234",
                                                                  "have_car":"1",
                                                                  "same_gender" :"0",
                                                                  "uid": "this is id for facebook , can be null"
                },
            "home": {
                    "longitude": "31.380301",
                    "latitude": "30.054272",
                    "name": "city"
                    },
            "work": {
                    "longitude": "30.068237",
                    "latitude": "31.024275",
                    "name": "village"
                    },
            "email": {
                    "email_type": "work",
                    "email": "hello.me@me.com"
                    }
            }

so how can i do it ?

Dearest Regards,

Slide Out Menu without a back Button

I use SWRevealViewController for my Slide Out Menu. I did actually the same like he did it here: https://www.youtube.com/watch?v=5SUV1YY2yxQ, but even I add a new ViewController and connect it with the segue "reveal view controller", start the app and click on the row to open the view controller, it will works, but I don't have a back Button. Why?

Can this dispatch_once singleton ever return nil?

Trying to find an issue we are experiencing intermittently, that seems to be occurring on devices with low memory conditions. The suspected cause is the NSDateFormatter singleton being nil.

Is there any possible situation where the singleton pattern below could return nil?

+ (NSDateFormatter *)dateFormatterUTC {

    static NSDateFormatter *formatter;
    static dispatch_once_t onceToken;

    dispatch_once(&onceToken, ^{
        formatter = [[NSDateFormatter alloc] init];
        formatter.dateFormat=@"yyyy-MM-dd HH:mm:ss ZZZ";
    });

    return formatter;
}

Dynamic replaceable uiviewcontroller in side a view with bottom static menu ios

How will achieve the above with a bottom static menu and replaceable uiviewcontrollers like fragments in android in the middle part?

iOS Push Notifications handle

Looking for a good practice regarding push notifications handle. currently in my app i'm handling the push notifications in the didFinishLaunchingWithOptions and in the didReceiveRemoteNotification delegates. I noticed that both handling logics are "firing" when i receive a push notifications when the app is "Dead". My remote notifications flag in Background Modes is ON in my app. Is there a good practice for handling this scenario ? why am i getting the push data in the didFinishLaunchingWithOptions(launchOptions) and didReceiveRemoteNotification is getting called too ? to my knowledge the didReceiveRemoteNotification is not spoused to get called when the app is "Dead".

After tableview reload cell not deleted

I have one UIView and inside one table view.After reload data visible cell remains and overlapping another cell in table view.I am using pull to refresh control and using reloadRowsAtIndexPaths.

[self.tableView beginUpdates];
[self.tableView reloadRowsAtIndexPaths:@[indexPath]withRowAnimation:UITableViewRowAnimationNone];
[self.tableView endUpdates];

If I put something like this :

 if(indexPath.row >5){

                                             [self.tableView beginUpdates];
                                             [self.tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
                                             [self.tableView endUpdates];
                                         }
                                         else {

                                             [self.tableView reloadData];


                                         }

In this scenario there is no overlapping but this is not best solution.

iOS/ObjC: "Fallback" tap gesture recognizer?

I have a UIViewController subclass whose view will generally contain some number of UIButtons and other interactive elements which may have one or more gesture recognizes attached to them.

What I'm trying to do is provide some visual feedback in the event that the user taps on a part of the screen that is not interactive. In other words: when the user taps the screen anywhere, if and only if no other control in the view responds to the touch event (including if it's, say, the start of a drag), then I want to fire off a method based on the location of the tap.

Is there a straightforward way to do this that would not require my attaching any additional logic to the interactive elements in the view, or that would at least allow me to attach such logic automatically by traversing the view hierarchy?

It takes long time to fetch images (Objective-C)

I am a beginner ios developer and i want to create a photo album app. I find some codes from internet and try to learn from there. In the app, when i click an album, it takes so much time for the album's collectionview of images to load. To fetch the images, my code is in ViewWillAppear. Can you help me optimize this code for better performance. If there is more than 10-15 images, this takes so long to load. Thanks in advance and sorry if my English is bad.

-(void)viewWillAppear:(BOOL)animated
{
    // Call to the super classes implementation of viewWillAppear
    [super viewWillAppear:YES];
    /* The Photos are stored in Core Data as an NSSet. */
    NSSet *unorderedPhotos = self.album.photos;
    /* To organize them we use a NSSort descriptor to arrange the photos by date. */
    NSSortDescriptor *dateDescriptor = [NSSortDescriptor sortDescriptorWithKey:@"date" ascending:YES];
    NSArray *sortedPhotos = [unorderedPhotos sortedArrayUsingDescriptors:@[dateDescriptor]];
    self.photos = [sortedPhotos mutableCopy];

    /* Now that the photos are arranged we reload our CollectionView. */
    [self.collectionView reloadData];

}

Objective C: when valueForKey is an instance with properties

i am trying to extract a property of an instance of a class that is a property of another class! easier shown by example...

// Person is a class with properties: name and age
Person *person = [[Person alloc] init];
[person setName:@"Alex"];

// Age is a class with properties value (i.e. 100) and unit (i.e. year)
Age *age = [[Age alloc] init];
[age setValue:@100];
[person setAge:age];

NSMutableArray *people = [[NSMutableArray alloc] init];
[people addObject:person];

for (id person in people) {

how can i extract the value property of the age instance associated to the person?

    //[person valueForKey:@"age.value")];

i expect to get @100 - i get 'NSInvalidArgumentException'

this gives me the instance of Age - but i would rather have the value property.

    //[person valueForKey:@"age")];
}

is this possible? any help is much appreciated.

Add Object to NSMutableArray even it is check marked

I try to add the cell.textlabel.text to an NSMutableArray even it is check marked. I do this with following code:

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{

    UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];

    if (cell.accessoryType == UITableViewCellAccessoryCheckmark) {
        cell.accessoryType = UITableViewCellAccessoryNone;
    }
    else{
        cell.accessoryType = UITableViewCellAccessoryCheckmark;

        self.selectedDays = [[NSMutableArray alloc] init];
        [self.selectedDays addObject:cell.textLabel.text];

        NSLog(@"%@", self.selectedDays);

    }
}

But it does not add, but replace.

    2015-06-28 xx:xx:xx xxxx - xxxx[xxx:xxx] (
    Monday
    )
    2015-06-28 xx:xx:xx xxxx - xxxx[xxx:xxx] (
    Tuesday
    )
    2015-06-28 xx:xx:xx xxxx - xxxx[xxx:xxx] (
    Wednesday
    )

How to push UIViewController from AppDelgate

I am building an iOS Application where there are 4 screen as - verify phone number,fb login, set your profile and home. Now what I need is that if a user have set her profile info and after clicking on next if he close the app. On the restarting of the app it should directly get navigated to the home screen and there should not be repetition of all the 3 screens again.

What happens is, the screen 1 ( verify phone no ) is shown for a short period of time and then home screen appears. I want home screen to appear immediately after the splash screen when I reopen the app.

I am using below code.

UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
    UINavigationController *mvc = [storyboard instantiateViewControllerWithIdentifier:@"Home"];
    [self.window.rootViewController presentViewController:mvc animated:YES completion:nil];

importing swift framework into a objective-c project

I am importing swift framework into objective-c project like this:

@import MyFramework;

The problem is that only some of the classes are recognized by the class i am importing the framework.

The class which is recognized:

public class RecognizedClass:UIViewController, WKNavigationDelegate, WKScriptMessageHandle 
 { ... } 

The class which is not:

public class VeediUtils
{ ... } 

They are both public so why the first is recognized in the workspace and the other not?

Also i see in the header file MyFramework-Swift.h that a class

@interface RecognizedClass : UIViewController <WKNavigationDelegate, WKScriptMessageHandler>

Appear while the other dont

Why is that?

Also to point that this same procedure work when i am importing swift framework to swift project

Disable horizontal shift of webview content

I have the following code:

[myWebView.scrollView.panGestureRecognizer requireGestureRecognizerToFail:swipe];
[myWebView.scrollView.panGestureRecognizer requireGestureRecognizerToFail:swipe2];

which disables mywebview to scroll horizontaly. Instead it should perform an other method after swiping. It works with iOS 8+ but in iOS 7.1 the content of the webview still gets "scrolled" horizontally. I´ve attached a screenshot to illustrate my problem. I don´t want the gray area on the right to happen:

http://ift.tt/1ID2E1V

As you can see not the whole content is shiftet to the left. How can I prevent this "inner" horizontal shift and perform instead a method while swiping to the left? Thx.

Is it possible to use the location indicator outside MKMapView?

Does anyone know if it's possible to use the little blue dot outside the context of an MKMapView (and if so how)?

I've seen it done in a few other apps, however I don't know whether they've just tried to manually recreate it or whether the component is available. I tried searching online, but I don't actually know the name of the component which is making it very challenging.

enter image description here

How to debug uncaught NSRange exception in Xcode?

I am getting the following exception. How can I find from looking at this as to where I am having a problem with my NSArray

*** Terminating app due to uncaught exception 'NSRangeException', reason:

'*** -[__NSArrayI objectAtIndex:]: index 1 beyond bounds [0 .. 0]'
*** First throw call stack:
(
    0   CoreFoundation                      0x0000000109ba4a75 __exceptionPreprocess + 165
    1   libobjc.A.dylib                     0x000000010983dbb7 objc_exception_throw + 45
    2   CoreFoundation                      0x0000000109a9c97e -[__NSArrayI objectAtIndex:] + 190
    3   UIKit                               0x00000001076bd506 -[UITableViewDataSource tableView:heightForRowAtIndexPath:] + 109
    4   UIKit                               0x00000001073f0afb __66-[UISectionRowData refreshWithSection:tableView:tableViewRowData:]_block_invoke + 302
    5   UIKit                               0x00000001073f018e -[UISectionRowData refreshWithSection:tableView:tableViewRowData:] + 4125
    6   UIKit                               0x00000001073f250b -[UITableViewRowData _ensureSectionOffsetIsValidForSection:] + 131
    7   UIKit                               0x00000001073f56f5 -[UITableViewRowData rectForFooterInSection:heightCanBeGuessed:] + 352
    8   UIKit                               0x00000001073f57ca -[UITableViewRowData heightForTable] + 56
    9   UIKit                               0x000000010724e553 -[UITableView _adjustExtraSeparators] + 216
    10  UIKit                               0x00000001072637b2 -[UITableView layoutSubviews] + 251
    11  UIKit                               0x00000001071f01c3 -[UIView(CALayerDelegate) layoutSublayersOfLayer:] + 521
    12  QuartzCore                          0x0000000108ad1c58 -[CALayer layoutSublayers] + 150
    13  QuartzCore                          0x0000000108ac687e _ZN2CA5Layer16layout_if_neededEPNS_11TransactionE + 380
    14  QuartzCore                          0x0000000108ac66ee _ZN2CA5Layer28layout_and_display_if_neededEPNS_11TransactionE + 24
    15  QuartzCore                          0x0000000108a3436e _ZN2CA7Context18commit_transactionEPNS_11TransactionE + 242
    16  QuartzCore                          0x0000000108a35482 _ZN2CA11Transaction6commitEv + 390
    17  QuartzCore                          0x0000000108a35aed _ZN2CA11Transaction17observer_callbackEP19__CFRunLoopObservermPv + 89
    18  CoreFoundation                      0x0000000109ad9507 __CFRUNLOOP_IS_CALLING_OUT_TO_AN_OBSERVER_CALLBACK_FUNCTION__ + 23
    19  CoreFoundation                      0x0000000109ad9460 __CFRunLoopDoObservers + 368
    20  CoreFoundation                      0x0000000109acf293 __CFRunLoopRun + 1123
    21  CoreFoundation                      0x0000000109acebc6 CFRunLoopRunSpecific + 470
    22  GraphicsServices                    0x000000010a460a58 GSEventRunModal + 161
    23  UIKit                               0x0000000107176580 UIApplicationMain + 1282
    24  APP_NAME                            0x0000000106d0dfc3 main + 115
    25  libdyld.dylib                       0x000000010aa68145 start + 1
    26  ???                                 0x0000000000000001 0x0 + 1
)
libc++abi.dylib: terminating with uncaught exception of type NSException

Objective-C dot accessor behaves differently with implicit getter

Can one of you kind people please help me to understand why I get '(null)' for the second line in the output but not the fourth? Many thanks in advance

MyClass.h

@interface MyClass : NSObject
@property (readonly) NSString *foo;
@property (getter=getBar, readonly) NSString *bar;
@end

main.m

@implementation MyClass
- (NSString *)getFoo { return @"foo"; }
- (NSString *)getBar { return @"bar"; }
@end

int main(int argc, const char * argv[]) {
    @autoreleasepool {     
        MyClass *myClassInstance = [MyClass new];

        NSLog(@"%@", myClassInstance.getFoo);
        NSLog(@"%@", myClassInstance.foo);

        NSLog(@"%@", myClassInstance.getBar);
        NSLog(@"%@", myClassInstance.bar);
    }
    return 0;

output

foo
(null)
bar
bar

Send a busy signal when the app is in another call

I am using twilio iOS SDK. Is it possible to send a busy signal from the app if it is in another call?

Query PFRelation of blocked users

I'm trying to query the 'friend' relation while excluding any friends that have blocked the user (which is stored as a relation<_user>) on the friends user with a relation to the user they are blocking (potentially the user checking their friends). I tried querying like below, but it isn't excluding the record like I would think:

[SVProgressHUD showWithStatus:@"Loading ..."];

[friends removeAllObjects];

PFRelation *friendRelation = [[PFUser currentUser] objectForKey:@"friendsRelation"];
if (friendRelation)
{
PFQuery *friendsQuery = [friendRelation query];
    [friendsQuery orderByAscending:@"firstname"];
    [friendsQuery whereKey:@"disabled" notEqualTo:[NSNumber numberWithBool:YES]];
    [friendsQuery whereKey:@"Blocked" notEqualTo:[PFUser currentUser]];
[friendsQuery findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error)
 {
     if (!error)
     {
         friends = [objects mutableCopy];
         [self.myTableView reloadData];
         [SVProgressHUD dismiss];
     }
     else
     {
         [SVProgressHUD showErrorWithStatus:@"Loading failed. Please try again."];
     }
 }];
}
else
{
    [SVProgressHUD dismiss];
}

Is there a way to accomplish what I am trying to do?

is it able to override NSObject init method to add every object into a single NSMutableArray?

I have a singleton object obj1, having a NSMutableArray member called Objects

and i added a category called NSObject (Register)

@implementation NSObject (Register)
-(id)init
{
    [[obj1 defaultObject] addObjectToView:self];
    return self;
}
@end

the addObjectToView method just simply add the object to the array

-(void)addObjectToView:(id)object
{
    [object retain];
    [Objects addObject:object];
}

(Object is a NSMutableArray)

the problem is, when i tried to test it, i did

NSWindow *window = [[NSWindow alloc] init];

and then i got 505 scary objects in the array,

(sorry, unable to post image) http://ift.tt/1QWWq6G

did i do anything wrong?

BTW, it is possible to manage the relationship of all objects and send isolate objects dealloc message to implement a garbage collector in Objective-C ?

Parse object containing array elements

I have a Parse object called Recipes and a column called ingredients, which is an array. I want to query my object list and retrieve a recipe based on some ingredients that I select.

If I use the whereKey:containsAllObjectsInArray: message on the query object, I will get recipes with more ingredients. Also, whereKey:containedIn: does not solve my problem. The retrieved objects should have an array of ingredients containing all my selected ingredients or only some of them. It should never have more ingredients than those I've selected.

Any ideas?

call class method within a framework

In objective-c how can i call class method inside a framework?

This is the method declaration:

public class func setGameLevel(level:Int)
{
    current_level = level
}

That is the class declaration (of the framework class):

public class MyClass
{

I imported the framework, now how can i call the method setGameLevel of the MyClass method?

In swift its called using:

MyClass.setGameLevel(1)

EXC_BAD_ACCESS tapping uisearchbar three times

I am trying to implement a search bar in a UICollectionView as a UICollectionViewReusableView

This way I am not using a UISearchController but I am changing the datasource of the collectionview

In my custom layout I am adding the searchbar this way:

override func prepareLayout() {
    super.prepareLayout()
    var searchBarAttributes = UICollectionViewLayoutAttributes(forSupplementaryViewOfKind: TeacherSearchbarIdentifier, withIndexPath: NSIndexPath(forItem: 0, inSection: 0))
    searchBarAttributes.frame = CGRectMake(0, 0, collectionViewContentSize().width, 44)
    searchBarAttributes.zIndex = 100
    miscAttributes.append(searchBarAttributes)
}

override func layoutAttributesForElementsInRect(rect: CGRect) -> [AnyObject]? {
    var attributes = [UICollectionViewLayoutAttributes]()
    for (idx, attr) in enumerate(miscAttributes) {
        if CGRectIntersection(rect, attr.frame) != CGRectNull {
            attributes.append(attr)
        }
    }

    return attributes
}

I am setting the delegate like this:

func collectionView(collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, atIndexPath indexPath: NSIndexPath) -> UICollectionReusableView {
    var view = collectionView.dequeueReusableSupplementaryViewOfKind(kind, withReuseIdentifier: kind, forIndexPath: indexPath) as! UICollectionReusableView
    if kind == TeacherSearchbarIdentifier {
        controller.searchBar = (view as! TeacherSearchView).searchBar
        return view
    }
}

The variable controller is the UICollectionViewController which implements the UISearchBarDelegate Protocol

The delegate is set in didSet of the searchBar variable. These are my delegates:

override func scrollViewDidScroll(scrollView: UIScrollView) {
    self.view.endEditing(true)
}

func searchBarShouldBeginEditing(searchBar: UISearchBar) -> Bool {
    searchBar.setShowsCancelButton(true, animated: true)
    return true
}

func searchBarShouldEndEditing(searchBar: UISearchBar) -> Bool {
    searchBar.setShowsCancelButton(false, animated: true)
    searchBar.resignFirstResponder()
    return true
}

func searchBarCancelButtonClicked(searchBar: UISearchBar) {
    searchBar.setShowsCancelButton(false, animated: true)
    searchBar.resignFirstResponder()
}

Now my problem!

When I am tapping on the search bar, the keyboard appears. If I press the cancel button or scroll, it dissappears. Just as I want it to. This also works a second time.

BUT!

If I do this a third time, I get a EXC_BAD_ACCESS:

EXC_BAD_ACCESS (code=1, address=0x14ac0beb8)

I tried turning on Enabling Zombie Objects, but no information was provided. I also tried profiling for Zombie Objects, it just crashes without any noticeable information.

Please help me on how I can resolve this error, or give me further debugging instructions.

Displaying NSMutable array using User Defaults

I am working on an app that has a mutable array of custom object ToDoItem(kind of morphed the dev example into my own app, will change later). I know its not the best way to do it, but I am using the user defaults to save it. Now, in the commented out code at the top, simply calling "addObject" loads the info into the table view. I don't know the intricacies of how this works, can somebody please explain why nothing is loading to the table view when I load it from user defaults? I am a beginner, so please explain thoroughly. Thank you for any help!

@interface ToDoListTableViewController ()
@property NSMutableArray *toDoItems;

@end

@implementation ToDoListTableViewController
- (void)loadInitialData1 {

   /*
ToDoItem *item1 = [[ToDoItem alloc] init];
item1.location = @"BDK";
item1.total = [[NSNumber alloc] initWithFloat:15.0];
item1.tip = [[NSNumber alloc] initWithFloat:5.567];
item1.percentage = [[NSNumber alloc] initWithFloat:33.0];
[self.toDoItems addObject:item1];
ToDoItem *item2 = [[ToDoItem alloc] init];
item2.location = @"Emrick";
item2.total = [[NSNumber alloc] initWithFloat:10.0];
item2.tip = [[NSNumber alloc] initWithFloat:2.0];
item2.percentage = [[NSNumber alloc] initWithFloat:20.0];
[self.toDoItems addObject:item2];
ToDoItem *item3 = [[ToDoItem alloc] init];
item3.location = @"PPM";
item3.total = [[NSNumber alloc] initWithFloat:20.0];
item3.tip = [[NSNumber alloc] initWithFloat:20.0];
item3.percentage = [[NSNumber alloc] initWithFloat:100.0];
[self.toDoItems addObject:item3];
*/


self.toDoItems = [[[NSUserDefaults standardUserDefaults]objectForKey:@"key"]mutableCopy];

}

- (IBAction)unwindToList:(UIStoryboardSegue *)segue {
AddToDoItemViewController *source = [segue sourceViewController];
ToDoItem *item = source.toDoItem;
if (item != nil) {

    [self.toDoItems addObject:item];
    [self.tableView reloadData];

    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];

    [defaults setObject:self.toDoItems forKey:@"key"];

    [defaults synchronize];

    NSLog(@"Data saved");

    }
}

MySQL server and iOS

I run a site write now with a quite big MySQL database. Now, I want to create an app. I will need to use obviously a database de to the fact my data are already there.

Thus,

1) Should I keep using the MySQL server and my iOS app will connect to this MySQL serve for getting data?

2) is there any problem if I use the MySQL server ? Security issues maybe?

3) if I have to change the MySQL server, what database infrastructure I need to build and work with?

I am totally newbie on iOS apps. And now I planning to face any issues my iOS app will have.

Google map cocoa pods integration issue

Hi I am integrating google maps with cocoa pods. I have done the integration but when i an running the project I Am getting following issue

ld: warning: Auto-Linking supplied '/Users/SANDY/Robert/Office/ProjectName/Pods/GoogleMaps/Frameworks/GoogleMaps.framework/GoogleMaps', framework linker option at /Users/SANDY/Robert/Office/ProjectName/Pods/GoogleMaps/Frameworks/GoogleMaps.framework/GoogleMaps is not a dylib
Undefined symbols for architecture i386:
  "_OBJC_CLASS_$_GMSCameraPosition", referenced from:
      objc-class-ref in EzTripInfoViewController.o
      objc-class-ref in TrackOrderViewController.o
      objc-class-ref in DriverInfoViewController.o
      objc-class-ref in DashboardViewController.o
  "_OBJC_CLASS_$_GMSCameraUpdate", referenced from:
      objc-class-ref in EzTripInfoViewController.o
      objc-class-ref in TrackOrderViewController.o
      objc-class-ref in DriverInfoViewController.o
      objc-class-ref in DashboardViewController.o
  "_OBJC_CLASS_$_GMSCoordinateBounds", referenced from:
      objc-class-ref in EzTripInfoViewController.o
      objc-class-ref in TrackOrderViewController.o
      objc-class-ref in DriverInfoViewController.o
      objc-class-ref in DashboardViewController.o
  "_OBJC_CLASS_$_GMSMapView", referenced from:
      objc-class-ref in EzTripInfoViewController.o
      objc-class-ref in TrackOrderViewController.o
      objc-class-ref in DriverInfoViewController.o
      objc-class-ref in DashboardViewController.o
  "_OBJC_CLASS_$_GMSMarker", referenced from:
      objc-class-ref in EzTripInfoViewController.o
      objc-class-ref in TrackOrderViewController.o
      objc-class-ref in DriverInfoViewController.o
      objc-class-ref in DashboardViewController.o
  "_OBJC_CLASS_$_GMSPath", referenced from:
      objc-class-ref in EzTripInfoViewController.o
      objc-class-ref in TrackOrderViewController.o
      objc-class-ref in DriverInfoViewController.o
      objc-class-ref in DashboardViewController.o
  "_OBJC_CLASS_$_GMSPolyline", referenced from:
      objc-class-ref in EzTripInfoViewController.o
      objc-class-ref in TrackOrderViewController.o
      objc-class-ref in DriverInfoViewController.o
      objc-class-ref in DashboardViewController.o
  "_OBJC_CLASS_$_GMSServices", referenced from:
      objc-class-ref in EzAppDelegate.o
ld: symbol(s) not found for architecture i386
clang: error: linker command failed with exit code 1 (use -v to see invocation)

Thanks for help in advance.

How to wake iphone on applewatch programmaticlly

So my scenario is control iphone music player on applewatch. Just like what the applewatch music glance would do. The project is gonna be iphone app, watch app, and watch extension. however, I want it to be able to work even thou my iphone app is not active. I know when iphone app is active, I could use wcsession and sendMessage to control the music on iphone. However, when the iphone app is not active. I don't know what I should do to get the work done. Any ideas?

One more thing, I am newbie to objective-c and ios, therefore, I don't understand how iphone app works when it is not active. Does it need to be active first do those job, or it is never really inactive so it could still do work, if anyone could tell me about that would be great as well.

simple CoverFlow example in objective C

can you please provide me with a simple coverflow sample code, I am trying to find some, but all examples are complex and contain unwanted details.

How to show ProgressBar With AFNetworking AFHTTPRequestOperationManager

I am trying to show the Progress Bar as I download a JSON from a url. The JSON is downloading correctly but I am not sure how to show the Progress Bar. I have tried using UIProgressView but it does not display on the screen. Any suggestions would be appreciated.

CGFloat width = [UIScreen mainScreen].bounds.size.width;
CGFloat height = [UIScreen mainScreen].bounds.size.height;

CGRect rect = CGRectMake(width/2, height/2, width/5, height/5);
UIProgressView *myProgressView = [[UIProgressView alloc]initWithFrame:rect];
myProgressView.progressViewStyle = UIProgressViewStyleBar;
[self.view addSubview:myProgressView];

AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];    
[manager GET:@"https:urlWithJson" parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
      [operation setDownloadProgressBlock:^(NSUInteger bytesRead, long long totalBytesRead, long long totalBytesExpectedToRead)
       {
           myProgressView.progress = (float)totalBytesRead / totalBytesExpectedToRead;
       }];
      [operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
          NSLog(@"operation Completed");
      } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
          NSLog(@"ERROR");
      }];

      [operation start];
  } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
      NSLog(@"timeout Error: %@", error);
  }];

Creating a Bridging Header

I am creating a Bridging Header manually since it doesn't let me do it automatically. I created the a header file called "AppName-Bridging-Header.h. The problem is that I can not set it as the project’s Bridging header, which can be normally done through the project’s build settings. I do not have the Objective-C Bridging file section under Swift Compiler -Code generation. I only have Optimization level. Thank you.

Importing swift written framework to project written in objective-c

I wrote a cocoa touch framework in swift code

Test.framework

In this framework i can see files Test.h and test-Swift.h

I am now trying to import it to an objective c project.

Put the file in the project folder and in build phases i added the framework to "Link Binary With Libraries" and "Copy Bundle Resources"

Now i am not sure about ho to do it but when i try to import the fraqmework in the ViewController.m class like this:

#import "Test-Swift.h"

It gives me file not found error

BTW when creating new Swift project and doing the same it works

IOS optimization using time profiler and Core Animation

So I have an app, in which I use custom UIView. There are other UIView, which are subviews of that view. All of them have pan gesture recognizers, so that the user can pan them in the specific fashion. When I test my app using one such view all is well and good, it is all smooth and fps is around 55-60. However, when I add the second one(somewhat smaller then the first one, and kinda inside first one, but not as a subview). The FPS of the outer views drops to 20-30, while the inner one(which is smaller) works in 60 fps. This two views are ABSOLUTELY independent, meaning that interacting with one doesn't affect the other one. In addition to that, I checked running time on the interval of one second, the results are the following: For 1 view: 153ms For 2 views 145ms For 3 views 150ms

The calculations that are performed on each view are ABSOLUTELY identical in complexity. Why does one work smoothly, but when I add the second one it starts to lag, while the execution time stays the same ? I would appreciate if somebody could hint me at how I should debug it.

The most consuming operation according to the Time Profiler is repositioning one of the views:

view.center = newCenter

I simply can't understand why FPS drops 2-3 times, while the running time stays the same. What should I look for ?

UPDATE:

So I found the source of the problem, when one view is inside the frame of the other the whole thing is being constantly redrawn, even though no changes were made to the layout of the inner view. So when I positioned a few of them in different parts of the screen everything was fine, but when I put one "inside" the other things get messed up. Inner one works quickly, while the outer one lags. "Flash updated regions" flag in core animation show that when I interact with outer view, inner view gets updated as well. Any suggestions on what I might need to do, because I need that layout when they are one inside each other. So how can I prevent(lock) other view from redrawing ?

Thank You.

Passing Facebook login information to the second view

This is a 2 part question.

1.) Once the user login to the application i want to navigate to DashboardViewController. However, i am ending up with a warning.

Warning: Attempt to present on whose view is not in the window hierarchy!

How to solve this?

2.) I want to pass (id<FBGraphUser>)user to the DashboardViewController, How can i achieve this?

The code is as follows:

-(void)viewWillAppear:(BOOL)animated{
    //[self toggleHiddenState:YES];
    self.lblLoginStatus.text = @"";

    self.loginButton.delegate = self;
    self.loginButton.readPermissions = @[@"public_profile", @"email"];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


#pragma mark - Private method implementation

-(void)toggleHiddenState:(BOOL)shouldHide{
    self.lblUsername.hidden = shouldHide;
    self.lblEmail.hidden = shouldHide;
    self.profilePicture.hidden = shouldHide;
}


#pragma mark - FBLoginView Delegate method implementation

-(void)loginViewShowingLoggedInUser:(FBLoginView *)loginView{



    self.lblLoginStatus.text = @"You are logged in.";

    [self toggleHiddenState:NO];
}



-(void)loginViewFetchedUserInfo:(FBLoginView *)loginView user:(id<FBGraphUser>)user{
    NSLog(@"%@", user);
    self.profilePicture.profileID = user.objectID;
    self.lblUsername.text = user.name;
    self.lblEmail.text = [user objectForKey:@"email"];
//

    [self performSelector:@selector(displayDashboard) withObject:nil afterDelay:0.5];

}

-(void)displayDashboard{
    DashboardViewController *vc = [self.storyboard instantiateViewControllerWithIdentifier:@"DashboardSegue"];

    [[[[[UIApplication sharedApplication] delegate] window] rootViewController] presentViewController:vc animated:YES completion:nil];
}




-(void)loginViewShowingLoggedOutUser:(FBLoginView *)loginView{
    self.lblLoginStatus.text = @"You are logged out";

    [self toggleHiddenState:YES];
}


-(void)loginView:(FBLoginView *)loginView handleError:(NSError *)error{
    NSLog(@"OKKKKK %@ ", [error localizedDescription]);

}


@end

Create forget password functionality using AWS EC2

I'm currently thinking of the process on how to create a "Forget Password" functionality for my app. I have not use AWS EC2 service before so I want to know how can I go about doing it or is there a sample tutorial for me to look at?

Thanks!

Is there a perfect way to use iOS Framework template instead of static library now?

Since iOS8 and Xcode6 has release for a year, I have still cannot find a canonical tutorial for using Framwork template (iOS Universal Framework Mk 8) to develope a static library.

enter image description here

Even though the most popular Repo I think, kstenerud/iOS-Universal-Framework, has shut down when iOS8 Framework release.

enter image description here


However, when I try to develope a Static Framework I got ton of issues to resolve:

  1. I still have to do lipo for x86_64, i386, arm64, amrv7;
  2. remove Code signature from Framework;
  3. Build a resource bundle and import it to app project independent;
  4. Framework Info.plist and modules seem useless;
  5. Still a little worried if Apple will refuse my app since use a Static Framework.

Is there a good tutorial for building and using Static Framework? Any help will be appreciated! Thx.

I get error when I add a UITableView

I have a static UITableView, and in one of the cells, I have a dynamic UITableView. Here is the code I used:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell;

    if (self.tableView == tableView) {
        cell = [tableView cellForRowAtIndexPath:indexPath];
    }
    else {
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];
        [cell.textLabel setText:self.tagsArray [indexPath.row]];
    }
    return cell;
}

When I run the app, it crashes with the following error:

Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'UITableView dataSource must return a cell from tableView:cellForRowAtIndexPath:'
*** First throw call stack:
(
    0   CoreFoundation                      0x0000000106efbc65 __exceptionPreprocess + 165
    1   libobjc.A.dylib                     0x0000000106b94bb7 objc_exception_throw + 45
    2   CoreFoundation                      0x0000000106efbaca +[NSException raise:format:arguments:] + 106
    3   Foundation                          0x00000001067a998f -[NSAssertionHandler handleFailureInMethod:object:file:lineNumber:description:] + 195
    4   UIKit                               0x000000010762fa83 -[UITableView _configureCellForDisplay:forIndexPath:] + 128
    5   UIKit                               0x0000000107637a41 -[UITableView _createPreparedCellForGlobalRow:withIndexPath:willDisplay:] + 533
    6   UIKit                               0x0000000107616248 -[UITableView _updateVisibleCellsNow:isRecursive:] + 2853
    7   UIKit                               0x000000010762c8a9 -[UITableView layoutSubviews] + 210
    8   UIKit                               0x00000001075b6a2b -[UIView(CALayerDelegate) layoutSublayersOfLayer:] + 536
    9   QuartzCore                          0x0000000106588ec2 -[CALayer layoutSublayers] + 146
    10  QuartzCore                          0x000000010657d6d6 _ZN2CA5Layer16layout_if_neededEPNS_11TransactionE + 380
    11  QuartzCore                          0x000000010657d546 _ZN2CA5Layer28layout_and_display_if_neededEPNS_11TransactionE + 24
    12  QuartzCore                          0x00000001064e9886 _ZN2CA7Context18commit_transactionEPNS_11TransactionE + 242
    13  QuartzCore                          0x00000001064eaa3a _ZN2CA11Transaction6commitEv + 462
    14  QuartzCore                          0x00000001064eb0eb _ZN2CA11Transaction17observer_callbackEP19__CFRunLoopObservermPv + 89
    15  CoreFoundation                      0x0000000106e2eca7 __CFRUNLOOP_IS_CALLING_OUT_TO_AN_OBSERVER_CALLBACK_FUNCTION__ + 23
    16  CoreFoundation                      0x0000000106e2ec00 __CFRunLoopDoObservers + 368
    17  CoreFoundation                      0x0000000106e24a33 __CFRunLoopRun + 1123
    18  CoreFoundation                      0x0000000106e24366 CFRunLoopRunSpecific + 470
    19  GraphicsServices                    0x000000010ad61a3e GSEventRunModal + 161
    20  UIKit                               0x0000000107536900 UIApplicationMain + 1282
    21  myBudget                            0x000000010611fe5f main + 111
    22  libdyld.dylib                       0x0000000108952145 start + 1
)
libc++abi.dylib: terminating with uncaught exception of type NSException

Why do I get this error, and what can I do to fix it?

How to retrieve part of JSON file?

it's possible by using IF to retrieve some parts of JSON not all of it in Objective-C. like i want to retrieve just those data when Gender equals Male

[
  {
    "name":"A",
    "gender":"Male",
    "age":20
  },
  {
    "name":"B",
    "gender":"Female",
    "age":12
  },
 {
    "name":"C",
    "gender":"Male",
    "age":20
  }
]

any idea would be appreciated.

samedi 27 juin 2015

Changing the status bar color on UISearchController

I'm trying to change iOS 8 search bar status bar color but I tried the UIStatusBarStyleLightContent with no luck anyone knows a better way? Example of how it looks right now

Get the number of lines in UILabel iOS8

I'm seeing lots of deprecated answers for this question:

How do I calculate the number of lines in use in a UILabel based of its set text?

I know that I need to set the UILabel to have bounds that resize with word wrapping. In this way, I could detect the height of my UILabel and adjust an NSLayoutConstraint for the height of my UITableViewCell. Basically my problem plain and simple is:

How can I determine my UILabel's number of lines in use(based of descriptionLabel.text) or height in order to resize My UITableView's UITableViewCells which contain my UILabel.

Currently I have used this code:

descriptionLabel = [[UILabel alloc] initWithFrame:CGRectMake(30, 30, 270, 65)];
descriptionLabel.textColor = [UIColor blackColor];
descriptionLabel.numberOfLines = 0;
descriptionLabel.adjustsFontSizeToFitWidth = YES;

What is the point of a nil AutoreleasingUnsafeMutablePointer in a Swift closure?

I was reading the different ways to parse REST API calls in Swift and came across the following:

var url : String = "http://ift.tt/1tENtnZ"
var request : NSMutableURLRequest = NSMutableURLRequest()
request.URL = NSURL(string: url)
request.HTTPMethod = "GET"

NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue(), completionHandler:{ (response:NSURLResponse!, data: NSData!, error: NSError!) -> Void in
    var error: AutoreleasingUnsafeMutablePointer<NSError?> = nil
    let jsonResult: NSDictionary! = NSJSONSerialization.JSONObjectWithData(data, options:NSJSONReadingOptions.MutableContainers, error: error) as? NSDictionary

    if (jsonResult != nil) {
        // process jsonResult
    } else {
       // couldn't load JSON, look at error
    }


})

The one line that makes no sense to me is var error: AutoreleasingUnsafeMutablePointer<NSError?> = nil. We already captured our NSError parameter and stored it in a variable called error, and now we're overwriting that and making it nil in our first line in the closure? Or if somehow Swift then performs a downcast of the error from type NSError! to AutoreleasingUnsafeMutablePointer<NSError?>, then can someone explain how that happens?

Thanks!

UITextInputCurrentInputModeDidChangeNotification return nill in ios 8.3

I want to detect current input mode of keyboard, and change text direction with respect to it (rtl if arabic, and ltr if english) in viewDidLoad:

- (void)viewDidLoad {
[super viewDidLoad];

[[NSNotificationCenter defaultCenter] addObserver:self
                                         selector:@selector(changeInputMode:)
                                             name:UITextInputCurrentInputModeDidChangeNotification object:nil];

} and in changeInputMode:

-(void)changeInputMode:(NSNotification *)notification
{
    UITextInputMode *thisInputMode = [notification object];

    NSLog(@"inputMethod=%@",thisInputMode);
}

but thisInputMode is nill! if I use this code instead:

    NSString *inputMethod = [[UITextInputMode currentInputMode] primaryLanguage];
    NSLog(@"inputMethod=%@",inputMethod);

it works fine and detects current password, but currentInputMode is deprecated. why [notification object] returns nill?

Add lines on ImageView IOS (objective c)

enter image description here

I need some help to get this thing working..

Basically on button click, I have to add a line of fixed width with circle end points on the ImageView. User can add upto 5 lines. If I click on any circle (red dot) end point of line, it should allow to resize the line. Point can be dragged to any position on screen and line has to be straight. At the end, i should be able to calculate the length of each line. I just spent a lot of time on this and referring other similar answers. But so far, no luck.. Any reference code or links is greatly appreciated. Thanks!

IOS resize or reposition line on touching end points (Objective c)

I am trying to resize the line, by touching the red circle points. Let's say, I want to move this line above lips in the image below, How can i achieve this. The line is not moving from the position. I have just started up with this thing and can't find much relevant resources to accomplish this. Trying the best...Please guide me in the right direction. Below is my code and reference image.

Objective c code:

- (void)viewDidLoad
{
    [super viewDidLoad];
    UIBezierPath *path = [UIBezierPath bezierPathWithArcCenter:CGPointMake(100, 100) radius:10 startAngle:0 endAngle:6.2831853 clockwise:TRUE];

    //Add second circle
    [path moveToPoint:CGPointMake(100.0, 100.0)];
    [path addLineToPoint:CGPointMake(200, 200)];
    [path moveToPoint:CGPointMake(200, 200)];

    [path addArcWithCenter:CGPointMake(200, 200) radius:10 startAngle:0 endAngle:6.2831853 clockwise:TRUE];


    [path closePath];
    [[UIColor redColor] setStroke];
    [[UIColor redColor] setFill];
    [path stroke];
    [path fill];

    CAShapeLayer *shapeLayer = [CAShapeLayer layer];
    shapeLayer.path = [path CGPath];
    shapeLayer.strokeColor = [[UIColor blueColor] CGColor];
    shapeLayer.lineWidth = 2.0;
    shapeLayer.fillColor = [[UIColor redColor] CGColor];

    [self.view.layer addSublayer:shapeLayer];

}

enter image description here

I will add multiple lines like this and my ultimate aim is to move individual line at any position in the image and get measurement of that area using line size.

EDIT: The scenario is, at any given time there will be some flexible lines available on the screen. Lets's say by clicking button, one more new line will be added to screen. The user can just drag any end point to resize the line in any direction. I can't get this thing working correctly.. no luck.

Here is my gist file link, http://ift.tt/1dp9Hm0 It basically adds a UIView to create a line on image. The code in gist allows me to resize the line height by moving touch points up and down but doesn't allow me to rotate the angle of line and adding text in the centre. THANKS

Thanks!

How to get all the classes of an application specified with identifier in iOS?

I want to get all the classes of a specified application (maybe any other apps, not only the app itself), I can get the NSBundle of that application with it's identifier, but how can I get the classes with the NSBundle, or can I get the classes directly with the application's identifier? We assume it could be a jailbroken environment.I tryied objc_copyClassNamesForImage but failed, does any one have ideas? Any help will be appreciated!

NSBundle * bundle = [NSBundle bundleWithIdentifier:appIdentifier];
NSString * bundlePath = [bundle bundlePath];
NSLog(@"%@", bundlePath);

unsigned int count;
const char **classes;

classes = objc_copyClassNamesForImage([bundlePath UTF8String], &count);

for (int i = 0; i< sizeof(classes)/sizeof(classes[0]); i++){
    NSLog(@"class name: %s", classes[i]);
}

IOS line measurement on picture

I need some help to get started on drawing lines with circle at ends, and measure its length. I am able to draw the line but can't make it moving,having spent hours decided to post on SO.

So please see below image and guide me to get started. Any sample or tutorial using objective c will help.

enter image description here

Thanks :)

Parse Relation [Error]: can't add a non-pointer to a relation (Code: 111, Version: 1.7.5)

I have a jobs app that enables users to view jobs. Jobs is a class in my Parse backend. I want to create a Favorites tab where user can mark certain jobs.

I've created a Relations Column in my User Class referring it to my Jobs class.

However, I have ran into this when the user taps to make the job a favorite: [Error]: can't add a non-pointer to a relation (Code: 111, Version: 1.7.5)

I feel like my PFRelation coding is spot on. I've researched this error but cannot seem to find any subject that relates to my problem. I must be making a mistake somewhere but

@interface JobDetailViewController ()

@end

@implementation JobDetailViewController

@synthesize jobPhoto;
@synthesize RotationLabel;
@synthesize QualificationsTextView;
@synthesize Job_DescriptionTextView;
@synthesize TypeLabel;
@synthesize LocationLabel;
@synthesize ClearanceLabel;
@synthesize PositionLabel;
@synthesize job;
@synthesize POC;
@synthesize Email;
@synthesize Phone;
@synthesize Apply;



- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];

    [_Scroller setScrollEnabled:YES];
    [_Scroller setContentSize:CGSizeMake(320, 2200)];

    [self dismissKeyboard];
    self.PositionLabel.text = job.position;
    self.RotationLabel.text = job.rotation;
    self.LocationLabel.text = job.location;
    self.TypeLabel.text = job.type;
    self.ClearanceLabel.text = job.clearance;
    jobPhoto.file = (PFFile *)job.imageFile;
    [jobPhoto loadInBackground];

    NSMutableString *pocText = [NSMutableString string];
    for (NSString* poc in job.poc) {
        [pocText appendFormat:@"%@\n", poc];
    }
    self.POC.text = pocText;

    NSMutableString *emailText = [NSMutableString string];
    for (NSString* email in job.email) {
        [emailText appendFormat:@"%@\n", email];
    }
    self.Email.text = emailText;


    NSMutableString *phoneText = [NSMutableString string];
    for (NSString* phone in job.phone) {
        [phoneText appendFormat:@"%@\n", phone];
    }
    self.Phone.text = phoneText;

    NSMutableString *applyText = [NSMutableString string];
    for (NSString* apply in job.apply) {
        [applyText appendFormat:@"%@\n", apply];
    }
    self.Apply.text = applyText;

    NSMutableString *qualificationsText = [NSMutableString string];
    for (NSString* qualifications in job.qualifications) {
        [qualificationsText appendFormat:@"%@\n", qualifications];
    }
        self.QualificationsTextView.text = qualificationsText;

    NSMutableString *job_descriptionText = [NSMutableString string];
    for (NSString* job_description in job.job_description) {
        [job_descriptionText appendFormat:@"%@\n", job_description];
    }
    self.Job_DescriptionTextView.text = job_descriptionText;
}



- (IBAction)favoriteButtonAction:(id)sender {
    PFObject *jobs = [PFObject objectWithClassName:@"Jobs"];
    PFUser *user = [PFUser currentUser];
    PFRelation *relation = [user relationForKey:@"Favorites"];
    [relation addObject:jobs];

    [user saveInBackground];



}


- (void)viewDidUnload
{
    [self setJobPhoto:nil];
    [self setPositionLabel:nil];
    [self setRotationLabel:nil];
    [self setLocationLabel:nil];
    [self setTypeLabel:nil];
    [self setQualificationsTextView:nil];
    [self setJob_DescriptionTextView:nil];
    [self setPOC: nil];
    [self setPhone:nil];
    [self setEmail:nil];
    [self setApply:nil];
    [self dismissKeyboard];

    [super viewDidUnload];
    // Release any retained subviews of the main view.
}

-(void) dismissKeyboard {
    [Email resignFirstResponder];
    [POC resignFirstResponder];
    [Phone resignFirstResponder];
    [Job_DescriptionTextView resignFirstResponder];
    [QualificationsTextView resignFirstResponder];
}

- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField
{
 return NO;
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

- (void) favoriteSuccess {
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Success!" message:@"Added job to Favorites!" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
    [alert show];
}


- (void) favoriteFailed {
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Ooooops!" message:@"Error occurred while adding to Favorites!" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
    [alert show];
}



@end

JobListViewController that populates the jobs prior to the JobDetailViewController:

#import "JobDetailViewController.h"
#import "JobListViewController.h"
#import "Job.h"
#import "SearchedResultCell.h"
#import <Parse/Parse.h>



@interface JobListViewController () <UISearchDisplayDelegate, UISearchBarDelegate> {

}

@property (nonatomic, weak) IBOutlet UISearchBar *searchedBar;
@property (nonatomic, strong) NSString *mainTitle;
@property (nonatomic, strong) NSString *subTitle;
@property (nonatomic, assign) BOOL canSearch;

@end

    @interface JobListViewController ()

    @end

    @implementation JobListViewController
    {}
    @synthesize searchedBar;
    @synthesize mainTitle;
    @synthesize subTitle;
    @synthesize canSearch;


    - (id)initWithCoder:(NSCoder *)aCoder
    {
        self = [super initWithCoder:aCoder];
        if (self) {
            // Custom the table

            // The className to query on
            self.parseClassName = @"Jobs";

            // The key of the PFObject to display in the label of the default cell style
            self.textKey = @"Position";

            // Whether the built-in pull-to-refresh is enabled
            self.pullToRefreshEnabled = YES;

            // Whether the built-in pagination is enabled
            self.paginationEnabled = YES;

            // The number of objects to show per page
            self.objectsPerPage = 20;
        }
        return self;
    }

    - (void)viewDidLoad
    {
        [super viewDidLoad];



    }

    - (void)viewWillAppear:(BOOL)animated {
        [super viewWillAppear:animated];

        self.canSearch = 0;

    }

    - (void)viewDidAppear:(BOOL)animated {
        [super viewDidAppear:animated];
    }

    - (void)viewWillDisappear:(BOOL)animated {
        [super viewWillDisappear:animated];
    }

    - (void)viewDidDisappear:(BOOL)animated {
        [super viewDidDisappear:animated];
    }

    - (void)viewDidUnload
    {
        [super viewDidUnload];
        // Release any retained subviews of the main view.
    }

    - (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
    {
        return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
    }

    - (void)objectsWillLoad {
        [super objectsWillLoad];

        // This method is called before a PFQuery is fired to get more objects
    }


    - (PFQuery *)queryForTable
    {
        PFQuery *query1 = [PFQuery queryWithClassName:@"Jobs"];
        NSString *searchThis = [searchedBar.text capitalizedString];
        [query1 whereKey:@"Position" containsString:searchThis];
        PFQuery *query2 = [PFQuery queryWithClassName:@"Jobs"];
        [query2 whereKey:@"Type" containsString:searchThis];
        PFQuery *query = [PFQuery orQueryWithSubqueries:@[query1,query2]];
            [query orderByDescending:@"createdAt"];

        if (self.pullToRefreshEnabled) {
            query.cachePolicy = kPFCachePolicyNetworkOnly;
        }

        // If no objects are loaded in memory, we look to the cache first to fill the table
        // and then subsequently do a query against the network.

        return query;
    }







    - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath object: (PFObject *)object
    {
        static NSString *simpleTableIdentifier = @"JobCell";
            static NSString *pimpleTableIdentifier = @"JobCell";

        UITableViewCell *cell = [self.tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier];

        if (cell == nil) {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:simpleTableIdentifier];

        SearchedResultCell *bell = [self.tableView dequeueReusableCellWithIdentifier:pimpleTableIdentifier];

        if (bell == nil) {
            bell = [[SearchedResultCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:pimpleTableIdentifier];

            }

            [self configureSearchResult:bell atIndexPath:indexPath object:object];


        }

        // Configure the cell
        PFFile *thumbnail = [object objectForKey:@"imageFile"];
        PFImageView *thumbnailImageView = (PFImageView*)[cell viewWithTag:100];
        thumbnailImageView.image = [UIImage imageNamed:@"AppIcon.png"];
        thumbnailImageView.file = thumbnail;
        [thumbnailImageView loadInBackground];

        UILabel *positionLabel = (UILabel*) [cell viewWithTag:101];
        positionLabel.text = [object objectForKey:@"Position"];
        UILabel *rotationLabel = (UILabel*) [cell viewWithTag:102];
        rotationLabel.text = [object objectForKey:@"Rotation"];
        UILabel *locationLabel = (UILabel*) [cell viewWithTag:103];
        locationLabel.text = [object objectForKey:@"Location"];
        UILabel *typeLabel = (UILabel*) [cell viewWithTag:104];
        typeLabel.text = [object objectForKey:@"Type"];


    return cell;
    }


    - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
        if ([segue.identifier isEqualToString:@"showJobDetail"]) {
            NSIndexPath *indexPath = [self.tableView indexPathForSelectedRow];

            Job *job = [[Job alloc] init];

            JobDetailViewController *destViewController = segue.destinationViewController;

            PFObject *object = [self.objects objectAtIndex:indexPath.row];
            job.position = [object objectForKey:@"Position"];
            job.poc = [object objectForKey:@"POC"];
            job.email = [object objectForKey:@"Email"];
            job.phone = [object objectForKey:@"Phone"];
            job.apply = [object objectForKey:@"Apply"];
            job.imageFile = [object objectForKey:@"imageFile"];
            job.rotation = [object objectForKey:@"Rotation"];
            job.location = [object objectForKey:@"Location"];
              job.type = [object objectForKey:@"Type"];
            job.clearance = [object objectForKey:@"Clearance"];
            job.job_description = [object objectForKey:@"Job_Description"];
            job.qualifications = [object objectForKey:@"Qualifications"];
            destViewController.job = job;

        }

    }

    - (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
    {

        [self clear];

        self.canSearch = 1;

        [self.searchedBar resignFirstResponder];

        [self queryForTable];
        [self loadObjects];

    }



    - (void)configureSearchResult:(SearchedResultCell *)cell atIndexPath:(NSIndexPath *)indexPath object:(PFObject *)object
    {
        mainTitle = [object objectForKey:@"Position"];
        cell.mainTitle.text = mainTitle;

        subTitle = [object objectForKey:@"Type"];
        cell.detail.text = subTitle;

         // Implement this if you want to Show image
         cell.showImage.image = [UIImage imageNamed:@"AppIcon.png"];

         PFFile *imageFile = [object objectForKey:@"imageFile"];

         if (imageFile) {
         cell.showImage.file = imageFile;
         [cell.showImage loadInBackground];
         }
    }


    #pragma mark - UITableViewDelegate

    - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
    {



        [tableView deselectRowAtIndexPath:indexPath animated:YES];

        [searchedBar resignFirstResponder];

        if ([self.objects count] == indexPath.row) {
            [self loadNextPage];
        } else {
            PFObject *photo = [self.objects objectAtIndex:indexPath.row];
            NSLog(@"%@", photo);

            // Do something you want after selected the cell
        }
    }



    #pragma mark - UIScrollViewDelegate


    - (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
        [self.searchedBar resignFirstResponder];
    }

    - (void)searchBarCancelButtonClicked:(UISearchBar *) searchBar {
        [self.searchedBar resignFirstResponder];
        [self queryForTable];
        [self loadObjects];

    }







    @end

Update image of UIImageView in NSmutableArray?

I have:

Class Piece inherit UIImageView;

- (void)setJumpAt:(int)frame {
NSMutableArray *ret = [SkinConstants BallSelected];
NSString *name = [NSString stringWithFormat:@"balls-%d-%d", color - 1, [[ret objectAtIndex:frame] intValue]];
UIImage *a = [UIImage imageNamed:name];
NSLog(@"%d setJumpAt: %@", self.tag ,name);
[self performSelectorOnMainThread:@selector(setImage:) withObject:a waitUntilDone:NO];
[self  setNeedsDisplay];
[self setNeedsLayout];}

Class Player contain NSMutableArray of Piece;

Class JumpThread contain NSTimer use to set image of Piece;

- (void) timer_Tick{
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_async(queue, ^{
        [piece setJumpAt:frame++];
        [piece setNeedsDisplay];
        if (frame == len)
            frame = 0;
    dispatch_async(dispatch_get_main_queue(), ^{
    });
});}

I run code normal, but image of Piece not change in mainview, Sorry, I'm not so good at English.

Create a Url shortcut in Xcode using Objective c

In my app users can upload images to my website and they can share the link. What I need to do is to create a link shortcut.

For example I have this link: (http://ift.tt/1dpVk0W)

i need to change the link to (for example): wedv.ghfi

is it possible to do it?

Thanks

Can cocos-2dx play a song from the phone's library?

I'm using an MPMusicPlayerController to access and play music in an objective C file, but I need to play it in my C++ file using SimpleAudioEngine. Is it possible to select an item with MPMusicPlayerController and use its URL(ipod-library://item/item.m4a?id=456458322781804615) to play the music?

Deterministic shuffle in Objective C

This code in Java is the implementation of Knuth's shuffle, but a deterministic one, controllable by the seed to the random number generator.

public String shuffleString(String data, long shuffleSeed) {
    if(shuffleSeed!=0) {
        Random rnd = new Random(shuffleSeed);
        StringBuilder sb = new StringBuilder(data);
        int n = data.length();
        while(n>1) {
            int k = rnd.nextInt(n--);
            char t = sb.charAt(n);
            sb.setCharAt(n, sb.charAt(k));
            sb.setCharAt(k, t);
        }
        return sb.toString();
    }
    else {
        return data;
    }
}

How can I implement a deterministic shuffle in Objective C that outputs the same shuffle order given the same seed? I am using srandom(_shuffleSeed); and random()%(n--) knowing that arc4_random is better but that cannot be seeded.

- (NSString*) shuffleString:(NSString*) data withShuffleSeed:(int) shuffleSeed {
    if(shuffleSeed!=0) {
        srandom(_shuffleSeed);
        NSMutableString *result = [[NSMutableString alloc] initWithString:data];
        unsigned long n = data.length;
        while(n>1) {
            unsigned long k = random()%(n--);
            unichar t = [result characterAtIndex:n];
            NSRange r1 = {n,1};
            [result replaceCharactersInRange:r1 withString:[NSString stringWithFormat:@"%c", [result characterAtIndex:k]]];
            NSRange r2 = {k,1};
            [result replaceCharactersInRange:r2 withString:[NSString stringWithFormat:@"%c", t]];
        }
        return result;
    }
    else {
        return data;
    }
}

Currently, the two shuffle methods do not generate the same result for the same input parameters. I am sure I am missing something!

mercredi 6 mai 2015

How to make Transparent Web-browser control

I have a system windows forms where i show the web browser control over the media-player control as shown in image below, enter image description here

I want to make Transparent web browser control. I have try many things but i am not able to make transparency over web browser control, i have try :

this.SetStyle(ControlStyles.SupportsTransparentBackColor, true);
            this.BackColor = Color.FromArgb(0, 0, 0, 0);
            this.TransparencyKey = Color.Red;
            this.BackColor = Color.Magenta;
            this.TransparencyKey = Color.Magenta;*/
            SetStyle(ControlStyles.SupportsTransparentBackColor, true);
            this.BackColor = Color.Transparent; 

My code is :

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.DirectX.AudioVideoPlayback;
using System.Windows.Forms;

namespace Windows_Video
{
    public partial class Form1 : Form
    {
        Video vdo;

        public string mode = "play";
        public string PlayingPosition, Duration;

        public Form1()
        {

            InitializeComponent();
          //  VolumeTrackBar.Value = 4;

        }
        private void Form1_Load(object sender, EventArgs e)
        {
            OpenFileDialog openFileDialog1 = new OpenFileDialog();
            if (openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                this.textBox1.Text = openFileDialog1.FileName;
            }
            axWindowsMediaPlayer1.URL = textBox1.Text;
            axWindowsMediaPlayer1.Ctlcontrols.play();

        }
    private void button1_Click(object sender, EventArgs e)
        {
         /*   OpenFileDialog openFileDialog1 = new OpenFileDialog();
            if (openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                this.textBox1.Text = openFileDialog1.FileName;
            }*/
        }    

        private void button2_Click(object sender, EventArgs e)
        {

        //    axWindowsMediaPlayer1.URL = textBox1.Text;
         //   axWindowsMediaPlayer1.Ctlcontrols.play();
        }

        private void button3_Click(object sender, EventArgs e)
        {

        }

        private void textBox1_TextChanged(object sender, EventArgs e)
        {

        }

        private void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
        {
            //this.BackColor = System.Drawing.Color.Transparent;
            this.SetStyle(ControlStyles.SupportsTransparentBackColor, true);
            this.BackColor = Color.Transparent;
        } 
    }    
}

How to run aspx.cs page load event parallel from asp.net mvc functionality

I'm working on a project which is built in asp.net MVC and is using an aspx/aspx.cs page in order to implement ReportViewer Control. But the thing happening is when i try to view the report the other functionality seems to be on hold until the page is loaded completely. So i'm thinking how can i run it parallel to my asp.net mvc functionality so that both works synchronously. Do i need to use multi-threading here? Please help i'm stuck here.

convert json to object by mapping key as field of class and #text as value of that field

Although there are tons of links to convert json to object but here the requirement is bit different.

I have this xml -

{
  "structure": {
    "-type": "DivideByZeroException",
    "property": [
      {
        "-key": "Message",
        "#text": "Attempted to divide by zero."
      },
      { "-key": "Data" },
      { "-key": "InnerException" },
      {
        "-key": "TargetSite",
        "#text": "Void btnWriteError_Click(System.Object, System.Windows.RoutedEventArgs)"
      },
      {
        "-key": "StackTrace",
        "#text": "   at WpfApplication1.MainWindow.btnWriteError_Click(Object sender, RoutedEventArgs e) in c:\\Users\\Anil.Purswani\\Desktop\\WPF_Application\\WpfApplication1\\MainWindow.xaml.cs:line 169"
      },
      { "-key": "HelpLink" },
      {
        "-key": "Source",
        "#text": "WpfApplication1"
      },
      {
        "-key": "HResult",
        "#text": "-2147352558"
      }
    ]
  }
}

and would like to convert it into -

Class ModelError
{
   string Message;
   Exception InnerException;
   string TargetSite;
   string StackTrace;
   string HelpLink;
   string Source;
   string HResult;
}

So the final object should contain like this -

modelerrorobj.Message =  "Attempted to divide by zero."
modelerrorobj.Data = null;
modelerrorobj.InnerException = null;
modelerrorobj.Targetsite = "Void btnWriteError_Click(System.Object, System.Windows.RoutedEventArgs)";
modelerrorobj.StackTrace = "   at WpfApplication1.MainWindow.btnWriteError_Click(Object sender, RoutedEventArgs e) in c:\\Users\\Anil.Purswani\\Desktop\\WPF_Application\\WpfApplication1\\MainWindow.xaml.cs:line 169"

So basically, "-key" value i.e. "Message", "Data", "StackTrace" is the field in class ModelError and "#text" is the value of that corresponding field.

for e.g.

      {
        "-key": "Message",
        "#text": "Attempted to divide by zero."
      },

in above, "Message" is the field and "Attempted to divide by zero." is the value of that field.

Please note I have Json but how to convert it in ModelError?

The security of dll files in a Client/Server application in .net

I'm going to write a Client/Server application. There are some ambiguous concepts in this that I was not able to get answer to after many hours of searching.

As we all know one of the major caveats of the .Net framework is that the DLL files can be decompiled and reverse-engineered on the client's machine.

Now my question is can I put some of the DLL files required by the Client on the Server?

And if true, will it be completely secure or it will still be open to getting reverse-engineered/decompiled by crackers?

Access denied when downloading CloudBlockBlob

I would like to download a blob from my Azure stockage to the virtual machine which host my cloud service. The problem is, it seems that every disks/folders in that machine is restricted. I got an access denied error to the directory where I want to put the blob. I use blob.downloadToStream method.

That's why I've taken my virtual machine on remote desktop and have set a directory in a disk with fullcontrol/read/write rights to "Everyone". It did not solve the problem.

Next, I've put "Runtime executionContext="elevated" " to my csdef file. Same problem.

Now my idea is, if possible, to put admin rights to the service which host my worker : WaWorkerHost (I think), but I didn't find it in the service list of my virtual machine.

My question is, how to solve this access problem ? Is my idea correct ?

How to get Ip address of a machine by passing the mac address in .Net [duplicate]

This question is an exact duplicate of:

I know the mac address of a machine. By using the mac address I need to get the IP address of the machine. How is it possible in .NET?

Lucene retrieve Values based on conditional of two fields

I've been trying to get Lucene.NET to respect a given condition which requires an evaluation of the index document fields.

I have a database table which stores "Experiences". For each experience there are two field/columns which tell is the row/ExperienceId is current (IsCurrent flag) as well as a StartDate and an EndDate.

Now, when implementing a "search engine" on the platform I need to have an option which, once checked (it's a checkbox) should retrieve only the those where IsCurrent is 1 or, otherwise, the one where the EndDate is the closest to the current date, i.e, EndDate is the highest. All this should be done for each PersonId (a foreing key in my Experiences table)

The thing is, I don't know how to tell Lucene that it should repect these conditions, that is, give me the ones with IsCurrent = 1 or the ones where IsCurrent = 0 but the EndDate is the maximum for each PersonId.

I looked into MultiTermQueries but couldn't make any sense of it.

I was trying the code bellow but I don't think this is working because the results make no sense (and I know the problem lies between the chair and the keyboard).

if (isCurrent)
{
    BooleanQuery queryIsCurrent = new BooleanQuery();
    queryIsCurrent.Add(new TermQuery(new Term("IsCurrent", "1")), BooleanClause.Occur.SHOULD);
    booleanQuery.Add(queryIsCurrent, BooleanClause.Occur.SHOULD);
    //Should I be using SHOULD here?? ^^


    //Should I be using this code for the date at all? I don't think so..
    TermRangeQuery termRangeQuery = null;
    termRangeQuery = new TermRangeQuery("EndDate", null, DateTime.Now.ToString(), true, true);
    booleanQuery.Add(termRangeQuery, BooleanClause.Occur.MUST);
}

linq query conditions by database and a list contents

I want to retrieve all tickets whose badge number is present in the list

i have a listA

public class LigneXls

     {
         public string sup { get; set; }
         public string tiers { get; set; }
        p ublic string badge { get; set; }
   }

i have a method :

            try
            {
                   List<DataObjects.LigneXls> listeLigneXls)
                   var listeTickets = from ti in _AGAPEntitie5.TICKETS
                             join ch in _AGAPEntitie5.CHAUFFEURS on ti.ID_CHAUFFEUR equals ch.ID_CHAUFFEUR
                             join tour in _AGAPEntitie5.TOURNEES on ch.ID_CHAUFFEUR equals tour.ID_CHAUFFEUR
                             join tour2 in _AGAPEntitie5.TOURNEES on ti.ID_TOURNEE equals tour2.ID_TOURNEE
                             join chb in _AGAPEntitie5.CHAUFFEUR_BADGE on ch.ID_CHAUFFEUR equals chb.ID_CHAUFFEUR
                             where chb.NUM_BADGE.Contains(listeLigneXls.Select(lgn => lgn.badge).ToString())
                             _AGAPEntitie5.CHAUFFEUR_BADGE.Where(p=>p..Any(x=>))
                             //where listeLigneXls.Any(s=>chb.NUM_BADGE.Contains(s.badge))
                             select new AGAP4.DataObjects.Ticket
                              {
                                  id = ti.ID_TICKET,
                                  poids_entrant = ti.POIDS_ENTRANT,
                                  poids_sortant = ti.POIDS_SORTANT,
                                  poids_net = ti.POIDS_Net,
                                  id_tournee = ti.ID_TOURNEE,
                                  id_chauffeur = ti.ID_CHAUFFEUR
                              };
                   lines_tickets = listeTickets.ToList();
                   return lines_tickets;
            }

i try this condition but it doesn't work,

try {

                    where chb.NUM_BADGE.Contains(listeLigneXls.Select(lgn =>lgn.badge).ToString())
                    //where listeLigneXls.Any(s=>chb.NUM_BADGE.Contains(s.badge))
                }

doesn't recognize tostring for the first and doesn't recognize the list

Any idea how solve my problem?

PayPal .Net Invoice API multiple Accounts

I cant add multiple PayPal-Merchant-Accounts to my C# PayPal-API. I found this solution, but i get an error by name id field: Is it possible to have multiple seller PayPal accounts a la eBay? (ASP.NET MVC 5) Is it possible to send the API login details by the Paypal-Object?

How to integrate any weather widget in lockscreen apps in WP 8.1?

I have developed a lockscreen app for window phone 8/8.1, that's released in the windows store, but lot of my friends suggested that I should integrate the weather widgets with customize options like location, refresh interval, etc in the app.

I searched a lot in the internet, I googled a lot, but believe me there seems to be nothing is provided to integrate weather widgets in lockscreen. Is there any way? Or is this something not allowed in WP 8.1?

In windows Phone to work with lockscreen apps, developer have to work with Backgroundtask agent, I know and I did that, but how to access the open area left in the lockscreen?

Any sample code, links or even a guide would do, please help. Please guide me, a novice app developer.

MeasureCharacterRanges, Region and IDisposable

Graphics.MeasureCharacterRanges returns an array of Region. Region implements IDisposable. Is it my responsibility as a caller to dispose each of them?

Neither the documentation nor the samples mentions this, which leads me to suspect that it is not necessary, although I fail to see why I would get away with it. At the same time, some other GDI+ objects are very bad to dispose (SystemFont, SystemBrush, SystemPen, etc...)

(I'm about to use this on a heavy loaded web service, where I recently tracked down a memory leak because someone had failed to dispose a bitmap.)

Nuget - unable to resolve package that could previously be resolved

We have a nuget server set up and are using Jenkins for CI integration. For the past two months everything has been working perfectly, however today we got the following error after update one of our Nuget packages:

Jenkins\Trunk\trunk\Solution.sln" (default target) (1) -> "F:\Jenkins\Trunk\trunk\Ioc\TPI.csproj" (default target) (44) -> F:\Jenkins\Trunk\trunk.nuget\NuGet.targets(100,9): error : Unable to find version '1.0.3.2' of package 'Solution.Extensions'. [F:\Jenkins\Trunk\trunk\Ioc\TPI.csproj]

I checked our nuget server and the package is definitely there. Previous versions have resolved fine, however this latest update and publish of our package seems to have inexplicably broken something. It was a simple update to the nuget package, just a single method being added with no dependencies created and the tried and tested publish procedure followed.

Any ideas why MS Build might suddenly be unable to resolve a Nuget dependency? All suggestions welcome.

Thanks

Performance difference in empty array initialization

Recently, I've been working in performance/memory optimization and have stucked in the empty array initialization which uses generic method to initialize empty array:

Code implementation of generic empty array class:

    public static class EmptyArray<T>
    {
        public static readonly T[] Instance;

        static EmptyArray()
        {
            Instance = new T[0];
        }
    }

So, whenever creating empty array of any type,it has been called as like:

var emptyStringArray = EmptyArray<string>.Instance;

Such empty array declaration has been done in many places of codebase. I am confused how would it be differs in performance while using :

var emptyStringArray = new string[0];

I've asked to above code author and he has replied me :

Basically, all empty arrays are readonly, and are equal to one another, which means that you can use the same instance (which will be created lazily on demand during run-time)… That should reduce the total number of allocations, reduce memory usage and GC pressure, and should result in some improvement

Still, I am not able to understand how would EmptyArray Instance boost the performance in array declaration.

How to get a control to fill its container up to its maximum size, then center align

I have a Windows Forms application consisting of a control within a window. I'd like the width of the control to fill the width of the form up to its MaximumSize.Width, at which point it centers itself within the window. Is there a way I can do this without code behind, if possible?

Notification to Application from a crashing windows service

I have a .Net application which manages a number of long running services. Some of the services occasionally crash with the dreaded

Fatal Execution Engine Error

due (I believe) to badly written unmanaged class libraries.

I'd like to know is there a way for the service manager app to receive a notification somehow that the service has crashed and stopped?

I know I can check the list of services to see are they all there regularly but I'd like to know if there is a better way to do it.

IWindsorInstaller Exclude assemblies

I can't exclude some assemblies in install process.

I try this :

 public class InternationnalisationInstaller : IWindsorInstaller
{
    public void Install(Castle.Windsor.IWindsorContainer container, Castle.MicroKernel.SubSystems.Configuration.IConfigurationStore store)
    {
        string path = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)
        var filter = new AssemblyFilter(path)
                .FilterByAssembly(a => !a.IsDynamic
                    && !a.FullName.Contains("Microsoft"));

        container.Register(Classes.FromAssemblyInDirectory(filter)
            .BasedOn<ITraductionProvider>()               
            .WithService.AllInterfaces());
    }
}

in dev no problem, but in production :

Impossible de charger le fichier ou l'assembly 'Microsoft.VisualStudio.Shell.Immutable.10.0, Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' ou une de ses dépendances. Le fichier spécifié est introuvable. à System.Reflection.RuntimeAssembly.GetExportedTypes(RuntimeAssembly assembly, ObjectHandleOnStack retTypes) à System.Reflection.RuntimeAssembly.GetExportedTypes() à Castle.Core.Internal.ReflectionUtil.GetAvailableTypes(Assembly assembly, Boolean includeNonExported) à Castle.Core.Internal.ReflectionUtil.GetAvailableTypesOrdered(Assembly assembly, Boolean includeNonExported) à Castle.MicroKernel.Registration.FromAssemblyDescriptor.b__0(Assembly a) à System.Linq.Enumerable.d__14 2.MoveNext() à Castle.MicroKernel.Registration.FromDescriptor.Castle.MicroKernel.Registration.IRegistration.Register(IKernelInternal kernel) à Castle.MicroKernel.Registration.BasedOnDescriptor.Castle.MicroKernel.Registration.IRegistration.Register(IKernelInternal kernel) à Castle.MicroKernel.DefaultKernel.Register(IRegistration[] registrations) à Castle.Windsor.WindsorContainer.Register(IRegistration[] registrations) à Internationnalisation.InternationnalisationInstaller.Install(IWindsorContainer container, IConfigurationStore store)

this assembly is used to tag class for VSIX registration. Can you help me ? Thanks

404 after changing routes in ASP NET MVC application

I had working routes on my app that looked like this:

            routes.MapRoute(
            name: "Category",
            url: "{name}-c{categoryId}",
            defaults: new { controller = "Products", action = "Index", name = "ErrorName" },
            namespaces: new[] { "B2B.Controllers" });

        routes.MapRoute(
            name: "InfoPage",
            url: "{name}-i{id}",
            defaults: new { controller = "InfoPages", action = "Details", name = "ErrorName" },
            namespaces: new[] { "B2B.Controllers" });

I've changed the dash (-) to the hash (#) because spaces are changed in url to dashes.

 url: "{name}#c{categoryId}",
 url: "{name}#i{id}",

Now I've this same routes with only this one char changed and I get 404 on urls like this:

siteadess:1234/1.0.1-Podstawowa%23c4

I've also tried to change hash to under score and it didn't worked either.

How to add view to a PRISM TabControl region WITHOUT making it selected?

We have a WPF application using PRISM, with a region of type TabControl.

    <TabControl prism:RegionManager.RegionName="{x:Static inf:RegionNames.ContentRegion}">
        <TabControl.ItemContainerStyle>
            <Style TargetType="{x:Type TabItem}">
                <Setter Property="Header" Value="{Binding TabName}" />
            </Style>
        </TabControl.ItemContainerStyle>
    </TabControl>

And we are registering views with

_regionManager.RegisterViewWithRegion(RegionNames.ContentRegion, typeof(ContentView));

Problem is, this way the registered tab automatically gets selected. Is there a way to add a view as tab but NOT select it??

Experience bad performance IIS 8 200 applications

We are developing an application which is almost ready for launch. We have the vision to host around 200 applications on one server. So we did a loadtest.

When I test with one application and 200 users, no problem at all and seems to work very quick. But the test when having 200 applications and each application one user works very bad. All applications are in one AppPool

We did some optimalisations like:

  • minified the css/javascript
  • put extra mem (2GB for 200 users and one application, no problem, 200 applications was problem, after that we upgraded to 12GB memory but performance keep bad)
  • Set the setting in IIS to release memory when application is not used anymore of idle for a time of 30 min.
  • We used interning of .NET

We will do:

  • Move static files outside the SSL so can be cached

Do anyone have experience with this (in my opinion small set of applications) set of applications? I expected IIS would use his memory better.

How do I make sure the NotifyIcon closes with my app?

This question is in response to many apps that I must use on a daily basis which all seem to have one thing in common that really gets on my nerves. And so, here I am, providing you with a solution you can implement!

How do I make sure my NotifyIcon is removed from the Notification Area when my app closes?

How to bind image and text together in the same column

I want to bind the image and text together in the same column. I managed to bind the text part but failed to bind the image part. This is what I've done so far:

<ListView.View>
  <GridView>
    <GridViewColumn x:Name="TimeColumn" Header="Time" Width="80">
      <GridViewColumn.CellTemplate>
        <DataTemplate>
          <TextBlock>
            <TextBlock.Text>
              <MultiBinding>
                <!--<PUT IMAGE>-->
                <Binding Path="Time"/>
              </MultiBinding>
            </TextBlock.Text>
          </TextBlock>
        </DataTemplate>
      </GridViewColumn.CellTemplate>
    </GridViewColumn>
  </GridView>
</ListView.View>

This is my expected result:

enter image description here

Any suggestion?

restsharp addparameter json For POST not work

I 'm very reading on stack overflow. But it's not work! I'm use RestSharp on REst webservice. I want to sent JSON Format to webservice.

my json fotmat, I'm sent on POSTMAN app in google chrome. It's work! :

{
"boss":[{
    "cus":"454",
    "date":"July 23,2015",
    "mangpo":"9.1",
    "namo":"rattatrayaya"
},{
    "cus":"872",
    "date":"Feb 23,2015",
    "mangpo":"9.1",
    "namo":"nama Arya Vlokita"
}]

}

in this code:

 string url = "http://ShiVamSaRaNum/Uma/index.php/create_sudo/Saranung";
        var client = new RestClient(url);
        var request = new RestRequest(Method.POST);
       request.RequestFormat = DataFormat.Json;
       request.AddBody(
           new{
               cus = "454",
               date = "July 23,2015",
               mangpo = "9.1",
               namo = "rattatrayaya"
                });
       RestResponse response = client.Execute(request);
       var content = response.Content;
       Console.WriteLine(content.ToString());
       Console.ReadLine();

- some one ask: request.AddParameter("application/json", json, ParameterType.RequestBody); - some one ask: request.AddObject(jsonObject) and some one ask: request.Addbody(jsonObject)

Now I'm very confused! Help me now!

P.S. if you can please revise write full my coding with me. and ask me add namespace to use. I'm add references RESTSHARP completely. P.S.1 I'm novice on c# and .net, help me now! Jesus Love You

Fill SERFF template XLSM File using C# EPPLUS library?

How to fill the SERFF template containing MACROS using EPPLUS Library. When i tried to edit template using this code the SERFF template crashes here is code i am using for editing and exporting template we can get SERFF template from here http://ift.tt/1ADYeVq

FileInfo newFile = new FileInfo(@"D:\FFM Sharred\SERFF-PlansBenefits.xlsm");

ExcelPackage pck = new ExcelPackage(newFile);

var ws = pck.Workbook.Worksheets.First();

ws.SetValue("B2", "33333");

Response.BinaryWrite(pck.GetAsByteArray());
Response.ContentType = "application/vnd.ms-excel.sheet.macroEnabled.12";           
Response.AddHeader("content-disposition", "attachment;  filename=Sample4.xlsm"); 

ATL project can't find referenced dll from the same solution

I have two projects in my solution. First one is an ATL project (created using this guide: http://ift.tt/1brstZ6 ). Second one is a CLR Class Library project (as per this: http://ift.tt/1GOkhe5 ).

Now the problem is that when I use this COM object in an other program, it crashes. When I attach a debugger to the process, it throws a System.IO.FileNotFoundException: Could not load file or assembly 'CLRClassLibrary, Version=1.0.5604.15598, Culture=neutral, PublicKeyToken=null' or one of its dependencies. The system cannot find the file specified.

When I build a Release, the program doesn't crash, but simply tells me that method was not found.

I checked both Debug and Release folders and they contain CLRClassLibrary.dll. TargetedNetFramework version 4.5

VC++ JSON parsing and unescaping

In my VC++ project, I have a server response that looks like this that gets assigned to a System::String:

{
    "someValue": "1",
    "someObject": {
        "content": "<div id=\"someContent\">text<\/div>"
    }
}

The true JSON object is a little more complex, but the above demonstrates that the JSON object has some values containing HTML. The response also contains escaped characters.

As I'm using .NET, I'd like to know the best option to:

  1. Read the JSON object
  2. Convert the HTML string to unescaped HTML that can be read with my HTML parser

My previous approach to unescaping the HTML in these types of responses was to use the .NET method Replace.

Is Task.Run or Task.Factory.StartNew a bad practice for windows phone or any other client platform?

I have WP 8.1 app that using web service a lot, and I want to keep it as much responsive as possible. From iOS dev expierense - there is one strict rule: "Do not do in UI thread any complex calculations! Doesnt matter how you will reach this: with blocks or with GCD".

Problem that not all API has async versions, e.g. JSON.NET, SQLite or any own complex algorithm in the app. I have read a lot of articles that are defining Task.Run and Task.Factory.StartNew as bad practice + this.

So, is it good to write code like this? Will it cause some cpu overloading/battery drain or some another performance issues? And if not - what is the right way to make complex operations async(background thread)?

 protected async Task<T> GetDataAsync<T>(string uriString, CancellationToken cancellationToken = default(CancellationToken))
    {
        var uriToLoad = new Uri(uriString);
        using (var httpClient = new HttpClient())
        {
            var data = await httpClient.GetAsync(uriToLoad, cancellationToken).ConfigureAwait(false);
            data.EnsureSuccessStatusCode();
            cancellationToken.ThrowIfCancellationRequested();

            var dataString = await data.Content.ReadAsStringAsync();
            cancellationToken.ThrowIfCancellationRequested();

            // async wrapped call to sync API
            var result = await Task.Factory.StartNew(() => JsonConvert.DeserializeObject<T>(dataString), cancellationToken).ConfigureAwait(false);
            cancellationToken.ThrowIfCancellationRequested();

            return result;
        }
    }

Record execution of .Net program in order to debug through it at a later point in time

I have an intergration test and during the execution quite a lot of data originates due to the behaviour of the system under test. Depending on the test run result this data is valuable or not. I therefore have the problem that I must find some "structure" (for every test this would be some other structure I have to come up with because there are many different tests with different data) to store the data in because I might need it - mostly in a later point in time - in order to look it up again.

For me the best (yet I assume quite heavy-weighted in terms of disk usage) solution would be to record the execution (serializing the generated data over time) and have a possibility to "virtually" step through the run any time afterwards.

Is there a tool or a concept with which I can accomplish this or is there some crutial part I'm missing or mistaken about? Looking forward to your input.

mardi 5 mai 2015

Motorola Scanner SDK BarcodeEvent returns Cradle's ID

I have two LI4278 barcode scanners. I want each scanner to beep when one of it reads a barcode that is not in the database. To do this I use BarcodeEvent of the SDK. But the event gives me the id of the cradles not the scanner. Becouse of this i can not beep the scanner. How can i get the id of scanner?

Here is my code;

    private void Form1_Load(object sender, EventArgs e)
    {
            cCoreScannerClass = new CCoreScannerClass();


            //Call Open API
            short[] scannerTypes = new short[1];//Scanner Types you are interested in
            scannerTypes[0] = 1; // 1 for all scanner types
            short numberOfScannerTypes = 1; // Size of the scannerTypes array
            int status; // Extended API return code
            cCoreScannerClass.Open(0, scannerTypes, numberOfScannerTypes, out status);
            // Subscribe for barcode events in cCoreScannerClass
            cCoreScannerClass.BarcodeEvent += new _ICoreScannerEvents_BarcodeEventEventHandler(OnBarcodeEvent);
            // Let's subscribe for events
            int opcode = 1001; // Method for Subscribe events
            string outXML; // XML Output
            string inXML = "<inArgs>" +
            "<cmdArgs>" +
            "<arg-int>1</arg-int>" + // Number of events you want to subscribe
            "<arg-int>1</arg-int>" + // Comma separated event IDs
            "</cmdArgs>" +
            "</inArgs>";
            cCoreScannerClass.ExecCommand(opcode, ref inXML, out outXML, out status);
            short numberOfScanners = 2;
            int[] sfScannerIDList = new int[255];
            cCoreScannerClass.GetScanners(out numberOfScanners, sfScannerIDList, out outXML, out status);

    }

    void OnBarcodeEvent(short eventType, ref string pscanData)
    {
        string barcode = pscanData;
    }

Custom attributes in c# for data types

I am thinking about making a custom attribute so that when we are using multiple data readers [SqldataReader] on different objects/tables, we could use the attribute to get the type of the property, and the "columnName" of the property. This way, we could then have a method that takes the data reader as a param, and from there could reflect the attributes to read in the columns. An example of what is currently being done is below, and then an example of what I am trying to accomplish. The problem I am having, is how to manage how to tell it what the (Type) is.

 private static App GetAppInfo(SqlDataReader dr)
    {
        App app = new App();

        app.ID = MCCDBUtility.GetDBValueInt(dr, "APPLICATION_ID");
        app.Name = MCCDBUtility.GetDBValueString(dr, "APPNAME");
        app.Desc = MCCDBUtility.GetDBValueString(dr, "APPDESCRIPTION");
        app.Version = MCCDBUtility.GetDBValueString(dr, "APP_VERSION");
        app.Type = MCCDBUtility.GetDBValueString(dr, "APPLICATIONTYPEID");
        app.AreaName = MCCDBUtility.GetDBValueString(dr, "AREANAME");

        return app;
    }

What I am thinking though, so if I had a class for example like so:

[DataReaderHelper("MethodNameToGetType", "ColumnName")]
public string APPNAME {get;set;}

How could I go about this?

C# .net / mono cross-platform differences?

I've been searching for a while now trying to find an answer for this, basically if I create a visual studio app using .net c# and I want to port it to mac / linux,

  1. Will there be and code I'll have to move around/change when switching to mono?

  2. What things should I avoid doing while developing to make it easier to port later?

  3. Is system.windows.forms usable in mono? Should I just use GTK#? Does it matter?

Fastest way to memoize expression

I have a function, that transform input Expression to output BlockExpression. So I write this code:

    private static readonly Dictionary<Expression, BlockExpression> MemberMemoizeDictionary = new Dictionary<Expression, BlockExpression>(); 
    private static BlockExpression CreateBody<TProperty>(CustomComparer<T> comparer, Expression<Func<T, TProperty>> member, bool createLabel)
        where TProperty : IComparable<TProperty>, IComparable
    {
        BlockExpression expression;
        if (MemberMemoizeDictionary.TryGetValue(member, out expression))
        {
            return expression;
        }

        MemberExpression memberExpression = (MemberExpression) (member.Body is MemberExpression ? member.Body : ((UnaryExpression)member.Body).Operand);
        BlockExpression result = comparer.CreateCompareTo<TProperty>(memberExpression, createLabel);
        MemberMemoizeDictionary[member] = result;
        return result;
    }

but it's not working.

I was thinking that Expressions are immutable, so I can use them as dictionary keys, but I see it's not true.

What is easiest and fastest way to solve this problem? It's always a single member-expression, with a possible convert due to boxing of value-type properties.