dimanche 28 juin 2015

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

When to use ?, !, None, or Lazy?

I just started learning Swift and recently found out about

1) "Normal" variables (for lack of a better name):

ex: var test1: String

2) "Optional" variables

ex: var test2: String?

3) "Implicitly Unwrapped Optionals"

ex: var test3: String!

4) Lazy variables

ex: lazy var test4: String

My understanding is this:

1) Use "Optional" variables (?) when the variable may or may not be initialized at points in the future starting from initialization

2) Use "Implicitly Unwrapped Optionals" (!) when the variable is guaranteed to be initialized

3) Optionals can be converted to Implicitly Unwrapped Optionals via "Forced Unwrapping"

ex: let possibleString: String? = "Hello" println(possibleString!)

4) Use Lazy variables when there is no need for something to be set until initialization (it seems these can be used with (?) or (!))

Therefore, my questions are:

1) When do I use option 1 - a variable without ? and without !

2) When do I use "lazy"

2.1) I read "lazy" is often used for singletons (http://ift.tt/1GINd7P) - why?

I have the most experience in Java and C++ terms, if that helps with my background for answering.

Xcode swift: global variable is empty

here is my code that did not work:

AppDelegate.swift

import UIKit

var systemLanguage = ""

func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
        // Override point for customization after application launch.

        // Systemsprache erkennen
        let systemLanguage = NSLocale.preferredLanguages()[0] as! String
        println("Device system language: \(systemLanguage)")

        return true
    }

settingsTableViewController.swift

override func viewDidLoad() {
        super.viewDidLoad()

        self.navigationController!.navigationBar.barStyle = UIBarStyle.Black
        self.navigationController!.navigationBar.tintColor = UIColor.whiteColor()

        if systemLanguage == "de" {

            self.title = "Einstellungen"

        } else {

            self.title = "Settings"

        }
        println("Device system language: \(systemLanguage)")

        self.tableView.backgroundColor = UIColor.darkGrayColor()

    }

When the app is starting the console says: Device system language: de

but when I change the view to settingsTableViewController the variable systemLanguage is empty. The console says: Device system language:

Why does it happen?

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.

Thank You.

How do I cancel my IOS application last update in app store, as I found some issue with it

How do I go back to my last app version, and cancel new update?

I have just release new version of my IOS application last week but I found some bug , which wasn't there in last version. So I want to cancel new version and stop it showing in app store in update section. How do I delete in iTune connect?? Is there any way of doing this please?

Glkit gl_points only one Point is big

I have to draw many Points an the get drawn as well but only one point is big(I see the other points but they are very small).

In my vertex shader i said :gl_pointsize = 25.0;

My Glkview:

- (void)glkView:(GLKView *)view drawInRect:(CGRect)rect{

glClearColor(0.65f, 0.65f, 0.65f, 1.0f);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

glBindVertexArrayOES(_vertexArray);

// Render the object with GLKit
[self.effect prepareToDraw];

glDrawArrays(GL_POINTS, 0, 36);



// Render the object again with ES2
glUseProgram(_program);

glUniformMatrix4fv(uniforms[UNIFORM_MODELVIEWPROJECTION_MATRIX], 1, 0, _modelViewProjectionMatrix.m);
glUniformMatrix3fv(uniforms[UNIFORM_NORMAL_MATRIX], 1, 0, _normalMatrix.m);

glDrawArrays(GL_POINTS, 0, 36);

Thanks in advance

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.

Error Domain=NSCocoaErrorDomain Code=134030

With an iOS app which has been working for about a year; thinking of an update, I recompiled it in the last version of Xcode (6.3.2). When trying to insert data in Core Data, I got this message in the debugging console:

Error: Error Domain=NSCocoaErrorDomain Code=134030 "The operation couldn't be completed. (Cocoa error 134030.) "

After looking on the net and finding nothing like a solution, and also making a few test with no conclusion. I decided to make this post.

Has any one had similar experience and found what was wrong?

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.

Default first letter uppercase in UIAlertController

Is there a way to default the first letter to uppercase when I display a UIAlertController?

var alertController = UIAlertController(title: i18nEnterPersonName, message: nil, preferredStyle: .Alert)
// initialization of alertController...
presentViewController(alertController, animated: true, completion: nil)

Realm query Object property field by it's property

I'm developing an application for iOS using swift and chose Realm as a database solution for it. I asked one question about Realm (Realm Question) and now I have another.

Suppose we have a schema like that:

class Person: Object {
    dynamic var id: String = NSUUID().UUIDString
    dynamic var name: String?
    dynamic var cars: Car?

class Car: Object {
    dynamic var name: String?

I have one class (Person) that contains any number of objects of another class (Car). Car that are "linked" with the Person has some properties in context of that Person (and they ca be different for same Car for different Persons or for two similar Cars for one Person). Using List<...>() we can not store such properties for each Item, am I right?

If we use Car only for one Person and only once we can create another class that includes only additional properties for Cars and links them with ID of Person plus ID of Car. But it does't work if we have two similar Cars with different additional properties.

So, how I see the solution. Have one table (class) stores ID of Person, ID of one Car and additional properties for this Car. For another Car for the same Person it has the same Person ID, Car ID (same or not) and another additional properties for this instance of a Car.

There is a problem (and a question that I mean). Having that structure I want to query all Cars from that table with their additional properties that have Person ID equals to some_id. How should I do this? Or maybe what another structure (maybe using List<...>) I should have to achieve such kind of behavior?

I hope I made the question clearer.

samedi 27 juin 2015

Giving a regular button a bar button identifier in swift

I want to get a button which isn't a bar button item to display the trash bin icon. Does anybody know how to do this programmatically?

UITapGestureRecognizer not working on iOS9

I have an application which uses UITapGestureRecognizers which seem to not work in iOS9 Beta 2.

They are successfully calling

- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch
{
  NSLog(@"shouldReceiveTouch");
  return YES;
}

but it doesn't hit any of the other UITapGesture delegate methods.

When I run the same application (from Xcode 7) on a device running on iOS 8, it works as expected.

Has anyone else hit this?

Here is how I initialise the UITapGestureRecognizer. TapGestureRecognizerSetup

Edit
If I create the UITapGestureRecognizer in code instead of in the ViewController xib it works fine, so there's something up with the xib parsing in iOS9 or something.

_tapGesture2 = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(onMainViewTap:)];
_tapGesture2.numberOfTapsRequired = 1;
_tapGesture2.delegate = self;
[self.view addGestureRecognizer:_tapGesture2];

Edit2
If I deleted the GestureRecognizer in the XIB and added it back in again using XCode 7, it also worked. When I did this, it added <pressTypeMask key="allowedPressTypes"/> into the xib under the UITapGestureRecognizer.

Adding UITextField above Keyboard

I found this link how to create tool bar above keyboard. But I don't use any textfield that I need to tap and show keyboard. My idea is press on "Leave comment" button and then keyboard with a text field will be appeared.

So in the link I've attached they seems use inputAccessoryView of text field you interact with. But in my case I don't have any text field.

So first of all I need to toggle keyboard without text field and then show keyboard with a textfield like a bar above keyboard. How can I make it?

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

Can't use information from DynamoDB scan

I am building a sign up/log in system in an iOS app using swift. I have a DynamoDB table set up, and I can send and load data from that table. However, I've run into a problem when I try to scan the table. I'm using the scan to check and make sure the emails, usernames, and passwords are original. The scan function works and brings all the data down, but when I try to use the data like when I say:

let results = task.result as! AWSDynamoDBPaginatedOutput

                for r in results.items{

                    if (self.emailTextField.text == r.userEmail){

                        self.emailMessageLabel.hidden = false
                        self.emailTextField.text = nil

                    }

the whole function gets confused. Because what it does is checks to see if emailTextField is equal to any of the results, and even if it is once, all of the other times it's not. So it will say that the emailMessageLabel.hidden is true as many times as emailTextField is not equal to anything, and false the one time that it is. So essentially the answer is both true and false, and I can't use that data. How do I fix this? I've been trying to fix it for days. I'll attach all the code that I've been trying to use.

Scan Function

func verifyAndActivateAccount(expression : AWSDynamoDBScanExpression) {
    self.emailMessageLabel.hidden = true
    self.nameMessageLabel.hidden = true
    self.passwordMessageLabel.hidden = true
    let tableRow = DDBTableRow()
    let dynamoDBObjectMapper = AWSDynamoDBObjectMapper.defaultDynamoDBObjectMapper()

    dynamoDBObjectMapper.scan(DDBTableRow.self, expression: expression) .continueWithExecutor(BFExecutor.mainThreadExecutor(),
        withBlock: { (task:BFTask!) -> AnyObject! in
            if (task.error == nil) {
                let results = task.result as! AWSDynamoDBPaginatedOutput

                for r in results.items{

                    if (self.emailTextField.text == r.userEmail){

                        self.emailMessageLabel.hidden = false


                    }
                    if (self.nameTextField.text == r.UserID) {

                        self.nameMessageLabel.hidden = false


                    }
                    if (self.passwordTextField.text == r.userPassword){

                        self.passwordMessageLabel.hidden = false


                    }



                }



            }else{

                self.giveSignUpAlert("Scan didn't work.")

            }

            return nil

    })

}

Button is Pressed

@IBAction func storeRegisterInfo(sender: UIButton) {
    let exp = AWSDynamoDBScanExpression()
    self.verifyAndActivateAccount(exp)
    //Check for original info
    let tableRow = DDBTableRow()
    tableRow?.UserID = self.nameTextField.text
    tableRow?.userEmail = self.emailTextField.text
    tableRow?.userPassword = self.passwordTextField.text

    let userEmail = emailTextField.text
    let userName = nameTextField.text
    let userPassword = passwordTextField.text
    let userConfirm = confirmTextField.text



    if userPassword != userConfirm {

        giveSignUpAlert("Your Passwords Don't Match!")

    }
    if (self.passwordTextField.text == self.confirmTextField.text) {
        if (userEmail.isEmpty || userName.isEmpty || userPassword.isEmpty || userConfirm.isEmpty){

            giveSignUpAlert("All Field Are Required")

        }else{

            self.insertDataIntoTable(tableRow)

        }

    }


}

WatchKit get data from closed App in iPhone

There are some applications (example Runtastic) where is possible from the Watch to activate some function of the companion App even if the App is not running in the iPhone (never opened or closed). How is possible to make the same with my Apps (get general data or settings)? I read some documents from Apple about app in background but I don't find nothing about App closed. Can someone help me? Thanks in advance

Custom user rating

I have never done anything like this so I am wondering if someone could give me some guidance. I allow users to log in through Facebook and I want to let them rate a (Yelp) business they have visited. How can I save their rating and combine this along with other users' ratings to create a custom rating for a business in Xcode? Thanks in advance

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 stored 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?

Icon-only Tab Bar in iOS [duplicate]

This question already has an answer here:

I want my tab bar to have icon only. However, when I set the tabbar label to "", it just shows no text in the place where the text originally should be, so it looks weird, like the following.

enter image description here

One can see that problem is the offset. I want the icon to be vertically aligned in the center, not like this in the above image. How to implement it?

PS: I'm using Swift.

saveAll() works but throws an error

I'm developing an app on iOS. I am updating my Users custom 'Rank' field based on their ordered 'Time01' field so they can be ordered on a scoreboard.

The code updates the 'Rank' fields but I get an error response.

This is my code...

Parse.Cloud.define("updateRanks", function(request, status) {
    var query = new Parse.Query(Parse.User);
    query.ascending('Time01');
    query.find({
        success: function(users) {
            for (var i = 0; i < users.length; i++) { 
                users[i].set("Rank", i + 1);
            }
            Parse.Object.saveAll(users, {
                    useMasterKey: true,
                    success: function(result) {
                            response.success();
                    },
                    error: function(error) {
                            response.error(error);
                    }
                });
        },
        error: function(error) {
            response.error(error);
        }
    });
});

And this is the error I get...

2015-06-28 15:34:46.276 Juggs[1188:166690] [Error]: ReferenceError: response is not defined
    at Parse.Object.saveAll.success (main.js:205:24)
    at Parse.js:2:7765
    at e (Parse.js:2:6545)
    at Parse.js:2:5994
    at Array.forEach (native)
    at Object.x.each.x.forEach [as _arrayEach] (Parse.js:1:664)
    at c.extend.resolve (Parse.js:2:5945)
    at e (Parse.js:2:6680)
    at Parse.js:2:5994
    at Array.forEach (native) (Code: 141, Version: 1.6.1)

I have called response.success() in the saveAll call so I'm wondering why I am getting this error? Any help would be much appreciated.

Create an animation when changing the path of a subLayer to another path

I have a UIView and its layer in which I added a CAShapeLayer as a subLayer with a path.

When I tap on a UIButton, I change the path of the subLayer with another path.

How can I animate this?

Is it possible to have an animation as soon as the path changes?

I tried to add:

let caAnimation = CABasicAnimation()
caAnimation.keyPath = "path"
caAnimation.duration = 2

shapeLayer.addAnimation(caAnimation, forKey: "path")

in the init(coder aDecoder: NSCoder) method of my UIView in order to have an animation when the path is changed in layoutSubviews() method but it doesn't work.

What did I do wrong?

Resume object path rather than restarting path, how?

So I've created a collision detector function, that restarts the player object path when a collision is detected. I'm trying to figure how to resume that path - start the path again from the point the player object hits. What method should I be looking for to achieve this?

UCWA multi-party conversation

May I question about UCWA multi-party conversation development?

I want to create a Multi-party IM conversation using the UCWA API's in iOS application. I was under an impression that I need to first create a peer to peer Conversation first, and then using the addParticipant API, I need to add another participant(s) to the existing conversation.And then I can conversation with all the participants.

The problem is that when arrived participant invitation from the other people, I accept the invitation, and can participate the convervastion.But when send a POST request on the sendMessage (UCWA) , I got the Http Status Code 409 Conflict Error.

The problem occured whent UCWA application to UCWA applcation. When UCWA application to MS Lync ,can communication without problem.

Any help appreciated.

Any advice about the step of multi-party IM Conversation?

Thanks in advance

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!

Hockey-SDK In-App Update feature?

I'm using Hockey-SDK in my app and a few of my testers have requested that I implement their In-App Update feature so they can be notified I guess when there is a new build available. I've never used this feature before, never used Hockey-SDK before, so I was wondering if anyone could point me to how to implement this.

I obviously did check their docs first, and found a section for this, although I found it almost too simple to understand correctly. To enable this feature when distributing via Ad-Hoc, but NOT enable it when it is uploaded to the App Store (how do they make that check by the way?), do I do this in my AppDelegate.m?

[[BITHockeyManager sharedHockeyManager] configureWithIdentifier:@"1ef7a1d2b1d0fd2b0a1f06d7355f6005"];
// Do some additional configuration if needed here
[[BITHockeyManager sharedHockeyManager] setDisableUpdateManager: NO];
[[BITHockeyManager sharedHockeyManager] startManager];
[[BITHockeyManager sharedHockeyManager].authenticator
 authenticateInstallation];

I guess I found it a bit confusing they'd use the wording setDisableUpdateManager:. Thank you for any help in advance!

AFNetworking 2.0 send multi images to server

I want to send 4 images to server using AFNetworking 2.0.

I have seen many examples to send one image, but do not understand how to send multiple images.

Does anyone know how to solve this problem?

Adding several pods increases iOS app launch time by 10+ seconds

I'm doing an iOS app project in Swift 1.2, using Cocoapods 0.37.2, Xcode 6.3.2. After adding around 8 pods in my project, app launch time greatly increases (around 10 seconds more) on device (iPhone 5). (Note: launch time means the time when you tap the app icon to open the app)

It is so slow iOS terminates it because it doesn't launch in time. The top of the crash log is as follows...

Application Specific Information: com.tryslowappswift failed to launch in time

Elapsed total CPU time (seconds): 27.720 (user 27.720, system 0.000), 68% CPU 
Elapsed application CPU time (seconds): 0.074, 0% CPU

Thread 0:
0   dyld                            0x1ff0f4c8 ImageLoaderMachOCompressed::rebase(ImageLoader::LinkContext const&) + 456
1   dyld                            0x1ff087be ImageLoader::recursiveRebase(ImageLoader::LinkContext const&) + 174
2   dyld                            0x1ff07dca ImageLoader::link(ImageLoader::LinkContext const&, bool, bool, bool, ImageLoader::RPathChain const&) + 186
3   dyld                            0x1ff012fc dyld::link(ImageLoader*, bool, bool, ImageLoader::RPathChain const&) + 204
4   dyld                            0x1ff022d6 dyld::_main(macho_header const*, unsigned long, int, char const**, char const**, char const**, unsigned long*) + 2362
5   dyld                            0x1fefe222 dyldbootstrap::start(macho_header const*, int, char const**, long, macho_header const*, unsigned long*) + 394
6   dyld                            0x1fefe03c _dyld_start + 60

No thread state (register information) available
...

You can test this by:

Note: I have created an example Swift project with all the pods setup in my github repo. You can just clone and run it on your device and see the delay for yourself.

  • Create a new blank project, nothing in the application:didFinishLaunchingWithOptions: method
  • Run the app on device and see the app launch very fast.
  • Stop. Now try adding a Podfile with about 8 pods (no matter big or small the pods are), do pod install.
  • Just for clarity, this is the Podfile I used...

Podfile

source 'http://ift.tt/1czpBWo'
platform :ios, '8.0'
use_frameworks! # required for Swift pods

pod 'Alamofire', '~> 1.2.1'
pod 'NPReachability', '~> 0.2.0'
pod 'ActionSheetPicker-3.0', '~> 1.6.1'
pod 'SDWebImage', '~> 3.7.2'
pod 'KVNProgress', '~> 2.2.1'
pod 'KeychainAccess'
pod 'JazzHands', '~> 0.2.1'
pod 'DGActivityIndicatorView'

  • Then run on device again. This time you will notice the 10+ seconds delay, even before application:didFinishLaunchingWithOptions: method is called. No import, no bridging header files, just install the pod into the project and it slows down the launch (-- rage guy meme !!! ---)

I suspect this has to do with Swift 1.2 so I tried on a Objective-C project, but I still experience the same delay. It seems to happen right after a normal pod installation, I have no idea how I can optimize or fix this. :(

Can't Make Out Image Resolution (PPI) Difference for IOS

I've been designing my images at 326 resolution for my iPhone app, but I just noticed that if I create a new image in photoshop at 10 x 10 at 326 resolution the amount of pixel is 20 x 20 and if I create a image in photoshop at 10 x 10 at 72 resolution the amount of pixels is still 20 x 20.

When both types are loaded to the app, they both display at the same size, so I wondering why would I design my images at 326 resolution when 72 produces the same result and at a smaller file size. Or am I missing something here.

Xcode playground takes way too long to run

I've been running Xcode with no issues, and all of a sudden playground sticks on Running Second, as seen in the image. Occasionally Xcode "stops" responding upon the launch of the project.

This takes forever and it's very hard to get a project going due to the time it takes to get start. Any ideas? I've spent hours trying to figure things out. I'm running Xcode 7 with Swift 2.0

Xcode playground takes way too long to run

I've been running Xcode with no issues, and all of a sudden playground sticks on Running Second, as seen in the image. Occasionally Xcode "stops" responding upon the launch of the project.

This takes forever and it's very hard to get a project going due to the time it takes to get start. Any ideas? I've spent hours trying to figure things out. I'm running Xcode 7 with Swift 2.0

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!

Making a UIBarButtonItem transparent in swift

How do I make a UIBarButtonItem's alpha be 0 in swift? I want it to fade in when a specific element appears on the screen. Does anybody know how to do this? Or any equally effective method would be great.

ReactiveCocoa takeUntil 2 possible signals ?

So I am trying to get the timer to stop upon a completed signal from my updated table and it appears not to be working.

I have gotten the signal to stop when the button is pressed the second time that works well.

However I tried to created a second signal to allow the scheduler to stop, and it does not appear to stop in both options 1 and 2 in the update table view.

Am I writing this correctly, is there a concept I am not understanding?

-(RACSignal*) startTimer {
    return [[[[RACSignal interval:1.0
            onScheduler:[RACScheduler mainThreadScheduler]]
             startWith:[NSDate date]]
             takeUntil:[self.start rac_signalForControlEvents:UIControlEventTouchUpInside]]
             takeUntil:self.completeSignal];
}

-(void) viewDidLoad {


    self.tableView.delegate = self;
    self.tableView.dataSource = self;

    RACSignal* pressedStart = [self.start rac_signalForControlEvents:UIControlEventTouchUpInside];

    @weakify(self);
    RACSignal* textChangeSignal = [[pressedStart map:^id(id value) {
        @strongify(self);
        return [self.start.titleLabel.text isEqualToString:@"Start"] ? @"Stop" : @"Start";
    }] startWith:@"Start"];

    [textChangeSignal subscribeNext:^(NSString* text) {
        @strongify(self);
        [self.start setTitle:text forState:UIControlStateNormal];
    }];


    static NSInteger t = 0;
    [[pressedStart flattenMap:^RACStream *(id value) {
        return [self startTimer];
    }] subscribeNext:^(id x) {
            t = t + 1;
            NSLog(@"%ld",t);
        [self updateTable];
    }];





}

-(void) updateTable {

    // option 1 Doesn't work
        [self.start    sendActionsForControlEvents:UIControlEventTouchUpInside];
// Option 2 doesn't work 
self.completeSignal = [RACSignal createSignal:^RACDisposable *(id<RACSubscriber> subscriber) {
        [subscriber sendCompleted];
        return nil;
    }];
    if ([self.excercises count] > 0 || self.excercises !=nil) {

    }else {
        // stop everything
        // using button signal
    }




}

Stored Data Are Lost After Migration

I've done light migration successfully but after updating the application the stored data are lost. I've gone these steps:

iPhone Core Data "Automatic Lightweight Migration"

Why does a panel always claim to have a child control on iOS?

I'm working on dynamically creating controls (TImageControl) inside of a panel. Part of it, I have a piece of code which clears out the old images first:

procedure TfrmImageView.Clear;
begin
  while sbImages.ControlsCount > 0 do
    sbImages.Controls[0].Free;
end;

This works perfectly on Windows. However, when I run it on an iPad, it gets stuck in a continuous loop, because for some reason ControlsCount is always 1. In fact, this happens even when I have never put any controls in there in the first place.

Why is this reporting always 1 control?

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 :)

iOS navigation controller without navigation bar

This is how I launched by main controller in my iOS app.

UIViewController *rootController = [[RootViewController alloc] init];
navigationController = [[UINavigationController alloc] initWithRootViewController:rootController];

self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
[self.window setRootViewController:navigationController];
[self.window makeKeyAndVisible];
return YES;

With this I am getting a blank bar at the top.

enter image description here

I want to use a navigation controller to control the flow of screens that users are able to reach by pressing back but I don't want a navigation bar. How can I change my code to get what I want?

How can we send message from iPhone to pager [duplicate]

This question already has an answer here:

Does anybody know if it's possible, and how, to programmatically send a SMS to Pager from the iPhone, with the official SDK / Cocoa Touch?

Thanks

Number of lines in UILabel in self-sizing tableview cell

I have a custom UITableViewCell subclass that is using self-sizing cells. The sizing of the cells is perfect and the label is being extended correctly. However, at run time I am trying to calculate the number of lines that the label will be extended to (I need to display the line numbers next to the label), and I am not able to achieve this. I have tried the following two methods and neither seem to be returning the correct number of lines that I am seeing when the app runs:

func lineCountForText(string: String, label: UILabel) -> Int {

        let font: UIFont = UIFont(name: "SourceCodePro-Regular", size: label.font.pointSize)!

        let rect = string.boundingRectWithSize(CGSizeMake(label.frame.width, CGFloat(MAXFLOAT)), options: NSStringDrawingOptions.UsesLineFragmentOrigin, attributes: [font : NSFontAttributeName], context: nil)

        return Int(ceil(rect.size.height/font.lineHeight))

    }

    func numberOfLinesForString(string: String, size: CGSize, font: UIFont) -> Int {
        let textStorage = NSTextStorage(string: string, attributes: [NSFontAttributeName: font])

        let textContainer = NSTextContainer(size: size)
        textContainer.lineBreakMode = .ByWordWrapping
        textContainer.maximumNumberOfLines = 0
        textContainer.lineFragmentPadding = 0

        let layoutManager = NSLayoutManager()
        layoutManager.textStorage = textStorage
        layoutManager.addTextContainer(textContainer)

        var numberOfLines = 0
        var index = 0
        var lineRange : NSRange = NSMakeRange(0, 0)
        for (; index < layoutManager.numberOfGlyphs; numberOfLines++) {
            layoutManager.lineFragmentRectForGlyphAtIndex(index, effectiveRange: &lineRange)
            index = NSMaxRange(lineRange)
        }

        return numberOfLines
    }

Am I not able to do this because it is a self-sizing cell?

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

PFQuery includeKey to give order

One of my fields for PFUser's is "ratingObject", a pointer to another class which has one column: "favouriteNumber". This keeps track of how many users follow this particular user. FavouriteNumber is just a number. I wanted to add this column directly to the PFUser row, however the app was crashing when I tried to increment this value from another user's account. Specifically when calling from user A:

userB.incrementKey("favouriteNumberInPFUser", byValue: 1)
userB.saveInBackground()

So I ended up creating this other class and adding a pointer to PFUser. However I need to perform a PFQuery taking into account this value. If it was in PFUser, no problem. But since it is in this other class, I can't really access it. I tried this:

var query2 = PFUser.query()
query2?.includeKey("ratingObject")
query2!.addDescendingOrder("ratingObject.favouriteNumber")

but it gives this error: [Error]: -ratingObject.favouriteNumber is not a valid order key (Code: 105, Version: 1.7.4)

Should I use Share Extension of Action Extension?

I've create a share extension for iOS that allows sharing files from safari, mail, drive, box & dropbox into my app. However I've discovered action extensions and now I'm thinking I might of been better off using them. Are share extensions meant to be for sharing to social networks etc? Should I be using an action extension for this use case?

AES Decryption in IOS not giving the exact result

Im trying to Decrypt my file in IOS. the file is encrypted with AES in C# application.

this is my IOS Decryption Method :

- (NSData *)AES128Operation:(CCOperation)operation key:(NSString *)key iv:(NSString *)iv
{
    NSLog(@"inside AES128Operation");
    char keyPtr[kCCKeySizeAES128 + 1];
    bzero(keyPtr, sizeof(keyPtr));
    [key getCString:keyPtr maxLength:sizeof(keyPtr) encoding:NSUTF8StringEncoding];

    char ivPtr[kCCBlockSizeAES128 + 1];
    bzero(ivPtr, sizeof(ivPtr));
    if (iv) {
        [iv getCString:ivPtr maxLength:sizeof(ivPtr) encoding:NSUTF8StringEncoding];
    }

    NSUInteger dataLength = [self length];
    size_t bufferSize = dataLength + kCCBlockSizeAES128;
    void *buffer = malloc(bufferSize);

    size_t numBytesEncrypted = 0;
    CCCryptorStatus cryptStatus = CCCrypt(operation,
                                          kCCAlgorithmAES128,
                                          kCCOptionPKCS7Padding | kCCOptionECBMode,
                                          keyPtr,
                                          kCCBlockSizeAES128,
                                          ivPtr,
                                          [self bytes],
                                          dataLength,
                                          buffer,
                                          bufferSize,
                                          &numBytesEncrypted);

    if (cryptStatus == kCCSuccess) {
         return [NSData dataWithBytes:buffer length:numBytesEncrypted];
    }
    free(buffer);
    return nil;
}

And the way im using it :

NSString *strKey = MyKey;
NSString *strIv = MyIV;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory , NSUserDomainMask, YES);
NSString *documentsDir = [paths objectAtIndex:0];
NSString *pathLocal_encrypted = [documentsDir stringByAppendingPathComponent:@"encrypted.file"];

NSData *data_encrpted = [[NSFileManager defaultManager] contentsAtPath:pathLocal_encrypted];

NSData *decryptedData = [data_encrpted AES128DecryptedDataWithKey:strKey iv:strIv];

IV is a 8 Byte Vector. The final decrypted file is unreadable or badly decrypted. i also tried Encrypt/Decrypt inside ios application with "AES128Operation" method on some test file and it works well but dont know why it cant decrypt the C# encrypted file.

The Decryption Works well in C# with this code (same file , Same iv , Same ,Key):

    static byte[] GetBytes(string str)
    {
        byte[] bytes = new byte[str.Length * sizeof(char)];
        System.Buffer.BlockCopy(str.ToCharArray(), 0, bytes, 0, bytes.Length);
        return bytes;
    }

    private static byte[] DecryptBytes(SymmetricAlgorithm alg, byte[] message)
    {
        if ((message == null) || (message.Length == 0))
        {
            return message;
        }
        using (var stream = new MemoryStream())
        {
            using (var decryptor = alg.CreateDecryptor())
            using (var encrypt = new CryptoStream(stream, decryptor, CryptoStreamMode.Write))
            {
                encrypt.Write(message, 0, message.Length);
                encrypt.FlushFinalBlock();
            }
            return stream.ToArray();
        }
    }
                path = openFileDialog1.FileName;
                byte[] encMessage = StreamFile(path);
                byte[] decMessage; 

                byte[] rkey = GetBytes(Mykey);
                byte[] riv = GetBytes(MyIv);
                using (var rijndael = new RijndaelManaged())
                {
                    rijndael.Key = rkey;
                    rijndael.IV = riv;
                    decMessage = DecryptBytes(rijndael, encMessage);
                }

due to answer suggestion ive tried this one to but still no hope :

    NSData *key = [NSData dataWithData:[strKey dataUsingEncoding:NSUTF8StringEncoding]];
    NSData *iv = [NSData dataWithData:[strIv dataUsingEncoding:NSUTF8StringEncoding]];
    NSData *decryptedData = [self doCipher:data_encrpted iv:iv key:key context:kCCDecrypt];

and the new function :

- (NSData *)doCipher:(NSData *)dataIn
                  iv:(NSData *)iv
                 key:(NSData *)symmetricKey
             context:(CCOperation)encryptOrDecrypt
{

    CCCryptorStatus ccStatus   = kCCSuccess;
    size_t          cryptBytes = 0;    // Number of bytes moved to buffer.
    NSMutableData  *dataOut    = [NSMutableData dataWithLength:dataIn.length + kCCBlockSizeAES128];

    ccStatus = CCCrypt( encryptOrDecrypt,
                       kCCAlgorithmAES128,
                       kCCOptionPKCS7Padding,
                       symmetricKey.bytes,
                       kCCKeySizeAES128,
                       iv.bytes,
                       dataIn.bytes,
                       dataIn.length,
                       dataOut.mutableBytes,
                       dataOut.length,
                       &cryptBytes);


        NSLog(@"CCCrypt status: %d", ccStatus);


    dataOut.length = cryptBytes;
    NSLog(@"CCCrypt ataOut.length: %d", dataOut.length);
    return dataOut;
}

this is the encryption\decryption setting inside C# :

   public RijndaelManaged GetRijndaelManaged(string secretKey, string iv)
    {
        var keyBytes = new byte[16];
        var secretKeyBytes = Encoding.UTF8.GetBytes(secretKey);
        Array.Copy(secretKeyBytes, keyBytes, Math.Min(keyBytes.Length, secretKeyBytes.Length));

        var ivBytes = new byte[16];
        var secretIvBytes = Encoding.UTF8.GetBytes(iv);
        Array.Copy(secretIvBytes, ivBytes, Math.Min(ivBytes.Length, secretIvBytes.Length));

        return new RijndaelManaged
        {
            Mode = CipherMode.CBC,
            Padding = PaddingMode.PKCS7,
            KeySize = 128,
            BlockSize = 128,
            Key = keyBytes,
            IV = ivBytes
        };
    }

    public byte[] Encrypt(byte[] plainBytes, RijndaelManaged rijndaelManaged)
    {
        return rijndaelManaged.CreateEncryptor()
            .TransformFinalBlock(plainBytes, 0, plainBytes.Length);
    }

    public byte[] Decrypt(byte[] encryptedData, RijndaelManaged rijndaelManaged)
    {
        return rijndaelManaged.CreateDecryptor()
            .TransformFinalBlock(encryptedData, 0, encryptedData.Length);
    }

specifying scene's background color in SceneKit

I'm trying to specify a background color (which is currently black) of a screen just before the scene appears. I searched documentation and this is what I found:

var background: SCNMaterialProperty { get }

A background to be rendered before the rest of the scene. (read-only) If the material property’s contents object is nil, SceneKit does not draw any background before drawing the rest of the scene. (If the scene is presented in an SCNView instance, the view’s background color is visible behind the contents of the scene.)

So I went and sent the contents to some color.

scene.background.contents = UIColor.redColor()

However, the moment before the scene renders, the screen(SCNView portion of it) is still black. What am I doing wrong? Perhaps the background property is not what I need? Also I'm not quite sure if a can drill further down some property which is only get(bacground is a getter), and than set some stuff like I did in code example. Thanks for answering

How would I optimize this search function?

I'm having a tough time thinking through how I can make my search function more optimal. So I have a situation where I load an array of objects from a SQLITE database. Essentially one element in the array has multiple properties that can be accessed. Inside one element of the array, you have properties like time and rooms. I want to make the search flexible without having the user to filter what they are searching for. What I don't like about my implementation is that I filter through both time and room, then I for loop the filtered arrays and add them to a general "searchArrayToDisplay." I think the for loop is wasteful. I was wondering if there is a way I can append the filtered elements to the general "searchArrayToDisplay" without having to for loop? The method below is generally fast, but I think there's a better way that I'm just not seeing. Hopefully I am clear. Thanks for any help!

let filteredTime = searchArray.filter { (time: ProductModel) -> Bool in
               if time.customText1 == nil {
                 return false
                  } else {
                  return  time.customText1.rangeOfString(searchString, options: NSStringCompareOptions.CaseInsensitiveSearch, range: nil, locale: nil) != nil

                }   
            }
            var m : ProductModel
            for m in filteredTime {

                searchArrayToDisplay.append(m)

            }

            let filteredRooms = searchArray.filter { (session: ProductModel) -> Bool in

                if session.roomName == nil {
                    return false
                } else {
                return session.roomName.rangeOfString(searchString, options: NSStringCompareOptions.CaseInsensitiveSearch, range: nil, locale: nil) != nil
                }   
            }
            for pm in filteredRooms {
                searchArrayToDisplay.append(pm)
            }

The real memory of iOS app will automatically reduce?

I used activity monitor to check the real mem of my app. when the app launched, the real mem reached about 100 mb. but after some time , the device went to sleep. Then I actived the device and reopened the app again, the real mem was only about 30 mb. so strange!

I know the real mem including both clean and dirty memory, the clean memory can be freed by system! but first, there isn't about 70 clean memory, and also the clean memory will be returned the App reopened.

so my question is If the real mem stat in activity monitor can be trusted?

Xcode 7 beta build fails when attempting to use Squeal

My Xcode (7 beta) build fails when trying to use Squeal's library. Its a brand new project with no additional code, and I followed the directions off of the Github page. However, Xcode still fails the build, and shows no errors as to why. Im severely confused. I even added the libraries for libsqlite3.tdb and libsqlite3.0.tbdand still fail. Should I try to create a dummy project in Xcode 6 and try it?

mercredi 6 mai 2015

What is the equivalence of getutcdate() in postgresql?

I migrate from SQL Server to PostgreSQL. How to translate the getutcdate function like:

Insert into mytable (mypk, toucheddate) values (99, getutcdate() )

how to perfom an update with group by?

I have concerns with an update statement. The primary key of my table is composed of the following columns:

ReferencePiece, NumeroPhase, AncienPoste,DateStrategie, DateCadence, NomProgramme, VersionProgramme.

Here is my procedure:

update S
set S.stock=T.Stock-T.NombrePiecesParAvion*T.CadenceProgramme
from SITUATIONS_Final_1 S inner join SITUATIONS_Final_1 T
on S.ReferencePiece=T.ReferencePiece and S.NumeroPhase=T.NumeroPhase and S.AncienPoste=T.AncienPoste
and T.DateDebProduction<S.DateDebProduction and T.stock = (select min(T.stock) from SITUATIONS_Final_1 T)
where  S.DateDebProduction=(select min(S.datedebproduction) as 'date1' 
from SITUATIONS_Final_1 S inner join SITUATIONS_Final_1 T
on S.ReferencePiece=T.ReferencePiece and S.NumeroPhase=T.NumeroPhase and S.AncienPoste=T.AncienPoste
where S.datedebproduction>T.DateDebProduction and T.stock = (select min(T.stock) from SITUATIONS_Final_1 T))

But actually, as there is no 'group by' on my update statement, It only takes into account the Min(stock) of all my references and do the update for the future dates.

I tried to do it as following but I'm sure it's much easier than that :

update S
set S.stock=T.Stock-T.NombrePiecesParAvion*T.CadenceProgramme
from SITUATIONS_Final_1 S inner join SITUATIONS_Final_1 T
on S.ReferencePiece=T.ReferencePiece and S.NumeroPhase=T.NumeroPhase and S.AncienPoste=T.AncienPoste
and T.DateDebProduction<S.DateDebProduction inner join (select referencepiece,NumeroPhase,AncienPoste,DateStrategie,
nomprogramme,versionprogramme, datedebproduction, min(stock) StockMini from SITUATIONS_Final_1 group by ReferencePiece,NumeroPhase,AncienPoste,DateStrategie,
nomprogramme,versionprogramme,DateDebProduction)
F on F.ReferencePiece=T.ReferencePiece and T.Stock=F.StockMini 
inner join (select referencepiece,NumeroPhase,AncienPoste,DateStrategie,
nomprogramme,versionprogramme, min(datedebproduction) datemini,stock
from SITUATIONS_Final_1 group by ReferencePiece,NumeroPhase,AncienPoste,DateStrategie,
nomprogramme,versionprogramme,DateDebProduction,stock) Z on F.ReferencePiece=Z.ReferencePiece
where T.DateDebProduction=Z.datemini and Z.datemini=F.DateDebProduction and Z.Stock=F.StockMini and T.ReferencePiece=Z.ReferencePiece and S.datedebproduction>T.DateDebProduction 
and T.stock=F.StockMini and S.ReferencePiece=T.ReferencePiece and T.ReferencePiece=F.ReferencePiece and F.numerophase=Z.numerophase
and T.numerophase=Z.numerophase and F.AncienPoste=Z.AncienPoste and T.AncienPoste=Z.AncienPoste and F.DateStrategie=Z.DateStrategie and T.DateStrategie =Z.DateStrategie
and F.nomprogramme=Z.nomprogramme and T.nomprogramme=Z.nomprogramme and F.versionprogramme=Z.versionprogramme and T.versionprogramme=Z.versionprogramme
and S.ReferencePiece=T.ReferencePiece and S.NumeroPhase=T.NumeroPhase and S.AncienPoste=T.AncienPoste and S.nomprogramme=T.nomprogramme 
and S.versionprogramme=T.versionprogramme and S.DateStrategie=T.datestrategie

But it doesn't perform well: It updates the same rows (the sames dates). I need this procedure to do something like that:

Referencepiece=RefA  DateDebProduction='02/05/2015'  Stock=4   NbrePieces=2   CadenceProgramme=1

For the same reference and the next date The stock should be= 4-2*1=2... Actually, this procedure is contained on another one. It launches it 5 times so that I can be sure that It will update all my rows. If you could help me finding a better way to update all rows without launching my procedure many times it would be great.

Here is a sample of data:

ReferencePiece  NumeroPhase AncienPoste DateStrategie   Charge  NomProgramme    VersionProgramme    CadenceProgramme    DateCadence DateDebProduction   NombrePiecesParAvion    Stock

RefA001     10      114179A     02/05/2015  0.000   Z540 A      BGR         29.000          01/03/2015  01/03/2015      1.000           23.000
RefA001     10      114179A     02/05/2015  0.000   Z540 A      BGR         25.000          01/04/2015  01/04/2015      1.000           NULL
RefA001     10      114179A     02/05/2015  0.000   Z540 A      BGR         19.000          01/05/2015  01/05/2015      1.000           NULL
RefA001     10      114179A     02/05/2015  0.000   Z540 A      BGR         25.000          01/06/2015  01/06/2015      1.000           NULL
RefXY001    10      1MR704      02/05/2015  0.220   X220        RM          2.000           01/05/2015  01/05/2015      2.000           12.000  
RefXY001    10      1MR704      02/05/2015  0.220   X220        RM          2.000           01/06/2015  01/06/2015      2.000           8.000   
RefXY001    10      1MR704      02/05/2015  0.220   X220        RM          2.000           01/07/2015  01/07/2015      2.000           NULL    
RefXY001    10      1MR704      02/05/2015  0.220   X220        RM          3.000           01/08/2015  01/08/2015      2.000           NULL    

As you can notice in this sample (where I've launched my procedure once), It updated the second row of the reference 'RefXY001' where stock=12-2*2=8, because 12<23. As I run this procedure, It will update only future dates of reference 'RefXY001' because the smallest stock is its.

Hibernate is generating wrong jointable

So I'm trying to lay a onetomany relationship between 2 tables in a different database, I have the following mapping:

    @OneToMany
    @JoinTable(
            name = "CountryEntityCountry",
            joinColumns = @JoinColumn(name = "countryEntityId"),
            inverseJoinColumns = @JoinColumn(name = "countryId")
    )
    @Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
    public Set<Country> getDestinationCountries() {
        return destinationCountries;
    }

countryEntityId points back to my own entity CountryEntity, countryId points to a table in another database. Obviously I'd want hibernate to generate a clustered primary key, this is the sql generated by hibernate in MS SQL server:

USE [dbNcrt]
GO

/****** Object:  Table [dbo].[CountryEntityCountry]    Script Date: 05/06/2015 08:51:44 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE TABLE [dbo].[CountryEntityCountry](
    [countryEntityId] [numeric](19, 0) NOT NULL,
    [countryId] [numeric](19, 0) NOT NULL,
PRIMARY KEY CLUSTERED 
(
    [countryEntityId] ASC,
    [countryId] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [FG_DATA],
UNIQUE NONCLUSTERED 
(
    [countryId] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_R

OW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [FG_DATA]
) ON [FG_DATA]

GO

ALTER TABLE [dbo].[CountryEntityCountry]  WITH CHECK ADD  CONSTRAINT [FK6DAE065D46A920C0] FOREIGN KEY([countryEntityId])
REFERENCES [dbo].[CountryEntity] ([id])
GO

ALTER TABLE [dbo].[CountryEntityCountry] CHECK CONSTRAINT [FK6DAE065D46A920C0]
GO

Now for some reason hibernate is adding a unique constraint to the key on the MANY side. I don't mind having hibernate generate a unique constraint, but I'd appreciate it if it could be on the correct side, not on the many side, obviously I will have rows like:

  • 1 245
  • 1 234
  • 2 245 -> Crash here already because of Hibernate's wrongfully generated unique constraint

Why is hibernate doing this? Is there something wrong with my mapping? I even tried adding explicitly unique=false to the countryId @JoinColumn, also tried adding the target entity explicitly, both of which hibernate seemed to have ignored.

Create random function that return DateTime in range : Invalid use of a side-effecting operator

Consider the SQL Server code :

CREATE FUNCTION dbo.CreateRandomDateTime ()
RETURNS DateTime
AS BEGIN
    DECLARE @DateFrom DATETime = '2012-01-01'
    DECLARE @DateTo DATeTime = '2012-06-30'
    DECLARE @DaysRandom Int= 0
    DECLARE @MillisRandom Int=0
    select @DaysRandom= DATEDIFF(day,@DateFrom,@DateTo)
    SELECT @DaysRandom = ROUND(((@DaysRandom -1) * RAND()), 0)

    --get random millis
    SELECT @MillisRandom = ROUND(((99999999) * RAND()), 0)

    SELECT @DateTo = DATEADD(day, @DaysRandom, @DateTo)
    SELECT @DateTo = DATEADD(MILLISECOND, @MillisRandom, @DateTo)
    RETURN @DateTo
END

I want to create a function that returns a random DateTime , but when I execute the code I get :

Msg 443, Level 16, State 1, Procedure CreateRandomDateTime, Line 9
Invalid use of a side-effecting operator 'rand' within a function.
Msg 443, Level 16, State 1, Procedure CreateRandomDateTime, Line 12
Invalid use of a side-effecting operator 'rand' within a function.
Msg 8116, Level 16, State 1, Procedure CreateRandomDateTime, Line 14
Argument data type datetime is invalid for argument 2 of dateadd function.
Msg 8116, Level 16, State 1, Procedure CreateRandomDateTime, Line 15
Argument data type datetime is invalid for argument 2 of dateadd function.

But when I run the code without the body function , I get a random datetime , so it seems that I did something wrong with the function .

Where did I go wrong ?

Create Surrogate Primary Key

Let's say I have table as follows:

FirstName   MiddleName  LastName    EmailAddress
John        Middle      Steward     some@thing.com
Alice       Wonder      Land        some@thing.com
Steve       Mac         Qwak        some@thing.com
Miss        Mon         Cherie      some@thing.com
Liz         Sea         Shell       some@thing.com

This is data source with employees. As you can see, there is no primary key. Is there any way how to enhance these data with some kind of surrogate primary key? Note this is data source. I assume it is not possible to create any primary key out of the data as any time one of the row / column change, this will also lead to change of the surrogate primary key. Correct? Or is there any way?

These data are meant to be loaded into DWH using SSIS. As there should be some Lookup transformation, I need to have primary key in the source data set.

mardi 5 mai 2015

How to create this complex Result using SQL

I have a sales amount table need to generate a report like this in sql server

QTY Amount  % Amount
5   5000    35%
10  10000   65%
15  15000   100%

The last row is total of all from top two rows.

35% is 5000/15000
67% is 10000/15000

How can i create a query for this ?

how to restrict sql database to be opened in other servers?

Currently i have a database that is attached to a named instance server with login credentials ,but at the same time if i attach the database to another server in other system ,the same gets opened.

How to deal with this?

Is there a way to restrict the database file to opened by others without valid credentials ?

Complex Sql Query for Sales Commison Calculation Multi Level

I'm trying to get employees report which shows their commission.

CREATE TABLE [dbo].[Employee] (
    [Id]               INT           NOT NULL,
    [firstname]        VARCHAR (100) NULL,
    [lastname]         VARCHAR (100) NULL,
    [promoterID]         INT           NULL,
    [titleID]         INT           NULL,   
    PRIMARY KEY CLUSTERED ([Id] ASC)
);

insert into employee(id,firstname,lastname,promoterid) values(1,'King1','Knight1',null,1)
insert into employee(id,firstname,lastname,promoterid) values(2,'King2','Knight2',1,2)
insert into employee(id,firstname,lastname,promoterid) values(3,'King3','Knight3',1,1)
insert into employee(id,firstname,lastname,promoterid) values(4,'King4','Knight4',2,3)
insert into employee(id,firstname,lastname,promoterid) values(5,'King5','Knight5',4,2)



CREATE TABLE [dbo].[sales_product] (
    [Id]               INT           IDENTITY (1, 1) NOT NULL,
    [customerid]         INT           NULL,
    [employeeid]          INT           NULL,
    [commision]        FLOAT (53)    NULL,
    PRIMARY KEY CLUSTERED ([Id] ASC)
);


insert into sales_product(id,customerid,employeeid,commision) values(1,2,5,100)
insert into sales_product(id,customerid,employeeid,commision) values(2,3,3,200)
insert into sales_product(id,customerid,employeeid,commision) values(3,5,2,100)
insert into sales_product(id,customerid,employeeid,commision) values(4,6,5,400)
insert into sales_product(id,customerid,employeeid,commision) values(5,7,1,500)

CREATE TABLE [dbo].[title] (
    [Id]          INT           NOT NULL,
    [title_code]  VARCHAR (200) NULL,
    [onA]         INT           NULL,
    [onEC]        INT           NULL,
    [onJSC]       INT           NULL,
    PRIMARY KEY CLUSTERED ([Id] ASC)
);

insert into title(id,title_code,<Dynamic Columns that gets created on adding new title whose name is "on" + title_code>) values(1,'A',20,30,10)
insert into title(id,title_code,<Dynamic Columns that gets created on adding new title whose name is "on" + title_code>) values(2,'EC',20,30,10)
insert into title(id,title_code,<Dynamic Columns that gets created on adding new title whose name is "on" + title_code>) values(3,'JSC',20,30,10)
insert into title(id,title_code,<Dynamic Columns that gets created on adding new title whose name is "on" + title_code>) values(4,'SSC',20,30,10,0)

Required Output:

firstname   lastname    totalcommison(employee commision + sum of (junior commsions*commision % based on title of, i.e if employee title_code is A than it will look for % on juniors title code ie onEC or JSC... which we get by getting juniors title code))

So far i'm able to get all the boses of employee in heirarchy

WITH EmployeeAncestor(id, firstname, promoterid) 
AS 
( 
  select id, firstname, promoter from employee WHERE id = 4

  union all 

  select m.id, m.firstname, m.promoterid 
  from EmployeeAncestor CTE,employeem 
  WHERE CTE.promoter = m.id 
 ) 
SELECT id, firstname, promoterid FROM EmployeeAncestor ORDER BY id ASC

I have following tables:

  1. sales_product - where i store employee sales and commission he gets

Column Names : salesid, employeeid, productid, commision

  1. Employee - this table stores employee detail, title id and promoter Id i.e, boss of the employee.

Column Names : employeeid, promoterid(employee id of manager), firstname, lastname, titleid

  1. title - where i store titles of the employee for example general manger, junior sales consultant etc and commission % on the different titles

For example

titleId     Title              CommisiononJuniorSalesCons     CommisiononSeniorSalesCons

 1.  General Manager                   10                          50  
 2. Junior Sales Cons                   0                           5

Now I want to create a SQL query and display it in a table where i get employee name and total commission he gets on his juniors. The commission will be calculated by multiplying the commission on product from sales_product table and % commission on employee sale from title and then we sum that commission and we get total commission earned by the employee.

How to create login for SQL Server with restricted permissions for an AD group?

I am trying to create a LOGIN to SQL Server using an Active Directory Group. This group should have the least amount of privileges required to perform their required tasks. The members of this group are users that monitor and operate a lot of the administrative tasks on the database but should not be allowed to view database content. They will need to be able to view the server state, perform traces, add databases to availability groups, restore databases and view metadata though. With below script the member of the group can view the server state etc. using a member that belongs to the group but I am not able to see metadata or add databases to availability groups. If I run the same script but create a LOGIN for a user instead of a group it works much better.

What am I missing in order to get this to work for a AD group instead of a user? The error that I get when logging in with user account belonging to the group is as follows:

Error: "The server principal "MACHINENAME\USERNAME" is not able to access the database "AdventureWorks2012" under the current security context. (Microsoft SQL Server, Error: 916)"

Script:

USE [master];
IF NOT EXISTS( SELECT *
                 FROM sys.server_principals
                 WHERE name = N'BUILTIN\Users' )
    BEGIN
        DECLARE @CreateError INT;
        CREATE LOGIN [BUILTIN\Users] FROM WINDOWS;
        SET @CreateError = @@ERROR;
        IF(@CreateError = 0)
            BEGIN EXEC master.dbo.sp_addsrvrolemember
                       @loginame = 'BUILTIN\Users',
                       @rolename = 'OperationRole';
            END;
        GRANT CONNECT SQL TO [BUILTIN\Users];
        USE [master];
        IF NOT EXISTS( SELECT *
                         FROM sys.database_principals
                         WHERE name = N'BUILTIN\Users' )
            CREATE USER [BUILTIN\Users] FOR LOGIN [BUILTIN\Users] WITH DEFAULT_SCHEMA = [dbo];
        IF NOT EXISTS( SELECT *
                         FROM sys.database_principals
                         WHERE name = N'OperationRole'
                           AND type = 'R' )
            BEGIN
                CREATE ROLE [OperationRole] AUTHORIZATION [dbo];
                GRANT EXECUTE ON [dbo].[CommandExecute] TO [OperationRole];
                GRANT VIEW DEFINITION ON [dbo].[CommandExecute] TO [OperationRole];
                GRANT EXECUTE ON [dbo].[DatabaseBackup] TO [OperationRole];
                GRANT VIEW DEFINITION ON [dbo].[DatabaseBackup] TO [OperationRole];
                GRANT EXECUTE ON [dbo].[DatabaseIntegrityCheck] TO [OperationRole];
                GRANT VIEW DEFINITION ON [dbo].[DatabaseIntegrityCheck] TO [OperationRole];
                GRANT EXECUTE ON [dbo].[DatabaseRestore] TO [OperationRole];
                GRANT VIEW DEFINITION ON [dbo].[DatabaseRestore] TO [OperationRole];
                GRANT EXECUTE ON [dbo].[GenerateRestoreScript] TO [OperationRole];
                GRANT VIEW DEFINITION ON [dbo].[GenerateRestoreScript] TO [OperationRole];
                GRANT EXECUTE ON [dbo].[sp_BlitzCache] TO [OperationRole];
                GRANT VIEW DEFINITION ON [dbo].[sp_BlitzCache] TO [OperationRole];
                GRANT EXECUTE ON [sys].[sp_readerrorlog] TO [OperationRole];
                GRANT EXECUTE ON [dbo].[sp_WhoIsActive] TO [OperationRole];
                GRANT VIEW DEFINITION ON [dbo].[sp_WhoIsActive] TO [OperationRole];
            END;
        IF EXISTS( SELECT *
                     FROM sys.database_principals
                     WHERE name = N'OperationRole'
                       AND type = 'R' ) EXEC sp_addrolemember
                                             N'OperationRole',
                                             N'BUILTIN\Users';
        USE [msdb];
        IF NOT EXISTS( SELECT *
                         FROM sys.database_principals
                         WHERE name = N'BUILTIN\Users' )
            CREATE USER [BUILTIN\Users] FOR LOGIN [BUILTIN\Users] WITH DEFAULT_SCHEMA = [dbo];
        IF NOT EXISTS( SELECT *
                         FROM sys.database_principals
                         WHERE name = N'SQLAgentUserRole'
                           AND type = 'R' )
            BEGIN
                CREATE ROLE [SQLAgentUserRole] AUTHORIZATION [dbo];
                GRANT EXECUTE ON [dbo].[sp_add_job] TO [SQLAgentUserRole];
                GRANT EXECUTE ON [dbo].[sp_add_jobschedule] TO [SQLAgentUserRole];
                GRANT EXECUTE ON [dbo].[sp_add_jobserver] TO [SQLAgentUserRole];
                GRANT EXECUTE ON [dbo].[sp_add_jobstep] TO [SQLAgentUserRole];
                GRANT EXECUTE ON [dbo].[sp_add_schedule] TO [SQLAgentUserRole];
                GRANT EXECUTE ON [dbo].[sp_addtask] TO [SQLAgentUserRole];
                GRANT EXECUTE ON [dbo].[sp_attach_schedule] TO [SQLAgentUserRole];
                GRANT EXECUTE ON [dbo].[sp_check_for_owned_jobs] TO [SQLAgentUserRole];
                GRANT EXECUTE ON [dbo].[sp_check_for_owned_jobsteps] TO [SQLAgentUserRole];
                GRANT EXECUTE ON [dbo].[sp_delete_job] TO [SQLAgentUserRole];
                GRANT EXECUTE ON [dbo].[sp_delete_jobschedule] TO [SQLAgentUserRole];
                GRANT EXECUTE ON [dbo].[sp_delete_jobserver] TO [SQLAgentUserRole];
                GRANT EXECUTE ON [dbo].[sp_delete_jobstep] TO [SQLAgentUserRole];
                GRANT EXECUTE ON [dbo].[sp_delete_jobsteplog] TO [SQLAgentUserRole];
                GRANT EXECUTE ON [dbo].[sp_delete_schedule] TO [SQLAgentUserRole];
                GRANT EXECUTE ON [dbo].[sp_detach_schedule] TO [SQLAgentUserRole];
                GRANT EXECUTE ON [dbo].[sp_droptask] TO [SQLAgentUserRole];
                GRANT EXECUTE ON [dbo].[sp_enum_sqlagent_subsystems] TO [SQLAgentUserRole];
                GRANT EXECUTE ON [dbo].[sp_get_job_alerts] TO [SQLAgentUserRole];
                GRANT EXECUTE ON [dbo].[sp_get_jobstep_db_username] TO [SQLAgentUserRole];
                GRANT EXECUTE ON [dbo].[sp_get_sqlagent_properties] TO [SQLAgentUserRole];
                GRANT EXECUTE ON [dbo].[sp_help_category] TO [SQLAgentUserRole];
                GRANT EXECUTE ON [dbo].[sp_help_job] TO [SQLAgentUserRole];
                GRANT EXECUTE ON [dbo].[sp_help_jobactivity] TO [SQLAgentUserRole];
                GRANT EXECUTE ON [dbo].[sp_help_jobcount] TO [SQLAgentUserRole];
                GRANT EXECUTE ON [dbo].[sp_help_jobhistory] TO [SQLAgentUserRole];
                GRANT EXECUTE ON [dbo].[sp_help_jobhistory_full] TO [SQLAgentUserRole];
                GRANT EXECUTE ON [dbo].[sp_help_jobhistory_sem] TO [SQLAgentUserRole];
                GRANT EXECUTE ON [dbo].[sp_help_jobhistory_summary] TO [SQLAgentUserRole];
                GRANT EXECUTE ON [dbo].[sp_help_jobs_in_schedule] TO [SQLAgentUserRole];
                GRANT EXECUTE ON [dbo].[sp_help_jobschedule] TO [SQLAgentUserRole];
                GRANT EXECUTE ON [dbo].[sp_help_jobserver] TO [SQLAgentUserRole];
                GRANT EXECUTE ON [dbo].[sp_help_jobstep] TO [SQLAgentUserRole];
                GRANT EXECUTE ON [dbo].[sp_help_jobsteplog] TO [SQLAgentUserRole];
                GRANT EXECUTE ON [dbo].[sp_help_operator] TO [SQLAgentUserRole];
                GRANT EXECUTE ON [dbo].[sp_help_proxy] TO [SQLAgentUserRole];
                GRANT EXECUTE ON [dbo].[sp_help_schedule] TO [SQLAgentUserRole];
                GRANT EXECUTE ON [dbo].[sp_maintplan_subplans_by_job] TO [SQLAgentUserRole];
                GRANT EXECUTE ON [dbo].[sp_notify_operator] TO [SQLAgentUserRole];
                GRANT EXECUTE ON [dbo].[sp_start_job] TO [SQLAgentUserRole];
                GRANT EXECUTE ON [dbo].[sp_stop_job] TO [SQLAgentUserRole];
                GRANT EXECUTE ON [dbo].[sp_uniquetaskname] TO [SQLAgentUserRole];
                GRANT EXECUTE ON [dbo].[sp_update_job] TO [SQLAgentUserRole];
                GRANT EXECUTE ON [dbo].[sp_update_jobschedule] TO [SQLAgentUserRole];
                GRANT EXECUTE ON [dbo].[sp_update_jobstep] TO [SQLAgentUserRole];
                GRANT EXECUTE ON [dbo].[sp_update_schedule] TO [SQLAgentUserRole];
                GRANT SELECT ON [dbo].[syscategories] TO [SQLAgentUserRole];
                GRANT SELECT ON [dbo].[sysjobs_view] TO [SQLAgentUserRole];
                GRANT SELECT ON [dbo].[sysschedules_localserver_view] TO [SQLAgentUserRole];
                ALTER AUTHORIZATION ON SCHEMA ::[SQLAgentUserRole] TO [SQLAgentUserRole];
            END;
        IF EXISTS( SELECT *
                     FROM sys.database_principals
                     WHERE name = N'SQLAgentUserRole'
                       AND type = 'R' ) EXEC sp_addrolemember
                                             N'SQLAgentUserRole',
                                             N'BUILTIN\Users';
        IF NOT EXISTS( SELECT *
                         FROM sys.database_principals
                         WHERE name = N'SQLAgentReaderRole'
                           AND type = 'R' )
            BEGIN
                CREATE ROLE [SQLAgentReaderRole] AUTHORIZATION [dbo];
                ALTER AUTHORIZATION ON SCHEMA ::[SQLAgentReaderRole] TO [SQLAgentReaderRole];
            END;
        IF EXISTS( SELECT *
                     FROM sys.database_principals
                     WHERE name = N'SQLAgentReaderRole'
                       AND type = 'R' ) EXEC sp_addrolemember
                                             N'SQLAgentReaderRole',
                                             N'BUILTIN\Users';
        IF NOT EXISTS( SELECT *
                         FROM sys.database_principals
                         WHERE name = N'SQLAgentOperatorRole'
                           AND type = 'R' )
            BEGIN
                CREATE ROLE [SQLAgentOperatorRole] AUTHORIZATION [dbo];
                GRANT EXECUTE ON [dbo].[sp_enum_login_for_proxy] TO [SQLAgentOperatorRole];
                GRANT EXECUTE ON [dbo].[sp_help_alert] TO [SQLAgentOperatorRole];
                GRANT EXECUTE ON [dbo].[sp_help_notification] TO [SQLAgentOperatorRole];
                GRANT EXECUTE ON [dbo].[sp_help_targetserver] TO [SQLAgentOperatorRole];
                GRANT EXECUTE ON [dbo].[sp_purge_jobhistory] TO [SQLAgentOperatorRole];
                GRANT SELECT ON [dbo].[sysalerts] TO [SQLAgentOperatorRole];
                GRANT SELECT ON [dbo].[sysalerts_performance_counters_view] TO [SQLAgentOperatorRole];
                GRANT SELECT ON [dbo].[sysnotifications] TO [SQLAgentOperatorRole];
                GRANT SELECT ON [dbo].[sysoperators] TO [SQLAgentOperatorRole];
                ALTER AUTHORIZATION ON SCHEMA ::[SQLAgentOperatorRole] TO [SQLAgentOperatorRole];
            END;
        IF EXISTS( SELECT *
                     FROM sys.database_principals
                     WHERE name = N'SQLAgentOperatorRole'
                       AND type = 'R' ) EXEC sp_addrolemember
                                             N'SQLAgentOperatorRole',
                                             N'BUILTIN\Users';
        IF EXISTS( SELECT *
                     FROM sys.database_principals
                     WHERE name = N'db_backupoperator'
                       AND type = 'R' ) EXEC sp_addrolemember
                                             N'db_backupoperator',
                                             N'BUILTIN\Users';
    END;
GO

ALTER SERVER ROLE dbcreator ADD MEMBER [BUILTIN\Users] ;
GO
GRANT ALTER ANY AVAILABILITY GROUP TO [BUILTIN\Users];
GO
GRANT ALTER ANY DATABASE TO [BUILTIN\Users];
GO
GRANT ALTER TRACE TO [BUILTIN\Users];
GO
GRANT CREATE ANY DATABASE TO [BUILTIN\Users];
GO
GRANT CREATE AVAILABILITY GROUP TO [BUILTIN\Users];
GO
GRANT VIEW ANY DEFINITION TO [BUILTIN\Users];
GO
GRANT VIEW SERVER STATE TO [BUILTIN\Users];
GO

I have realized that the reason why I am unable to view the metadata is because I the user does not exist in each database. So I would need to create that user for each database with no privileges in order to see the metadata. Unfortunately the following code is not working for me.

Could you help me get the below code working?

DECLARE @DB_Name varchar(100) 
DECLARE @Command nvarchar(200)
DECLARE database_cursor CURSOR FOR 
SELECT name 
FROM MASTER.sys.sysdatabases 
where dbid > 4

OPEN database_cursor

FETCH NEXT FROM database_cursor INTO @DB_Name

WHILE @@FETCH_STATUS = 0 
BEGIN 
     SELECT @Command = 'IF NOT EXISTS( SELECT * FROM sys.database_principals
                         WHERE name = N''BUILTIN\Users'')
                                    CREATE USER [BUILTIN\Users] FOR LOGIN [BUILTIN\Users] WITH DEFAULT_SCHEMA = [dbo]'
     EXEC sp_executesql @Command

     FETCH NEXT FROM database_cursor INTO @DB_Name 
END

CLOSE database_cursor 
DEALLOCATE database_cursor

Timeout Error in Stored Procedure in C#

i have this stored procedure to retreave data from database (dynamic query). and i am calling this stored procedure from c# codebehind, i am passsing two parameters from c# to this stored procedure.

alter procedure [dbo].[GetCompleteCPTDetails]
    @Practice_Short_Name varchar(50),
    @Uploaded_Date nvarchar(max)
as
begin
DECLARE @CPTtablename nvarchar(300)
DECLARE @vQuery NVARCHAR(max)
DECLARE @upldate nvarchar(100)
set @upldate = @Uploaded_Date
set @CPTtablename ='ACER_CLAIMS_MASTER_DETAIL_Hist_'+@Practice_Short_Name
SET @vQuery = 'select Practice_Short_Name,Service_Date_From,Carrier_Name,
   Location_Description,Patient_Number,Patient_First_Name,
   Patient_Last_Name,Voucher_Number,Procedure_Code,Service_Fees,
   Service_Payments,Service_Adjustments,Acer_Status,Acer_Allowed_Amount
   from ' +@CPTtablename+' 
   where Uploaded_Date =''' + @upldate + ''' 
   order by acer_status asc, Service_Date_From desc, Patient_First_Name asc'
EXEC (@vQuery)

end
GO

but when i am running this query it is giving me TimeOut error. but if i assign value to my parameters in SP and Run SP from query windows then it is showing correct data.

can any please explain me why it is giving timeout error if i am calling it from C# codebehind.

fatal error occurred while reading the input stream from the network

fatal error occurred while reading the input stream from the network. The session will be terminated. How important is this type of error? It's happens every 3:e day on production server. At the moment i looks that is has no bigger inpact on the server. It's virtual machin running Windows Server 2008 R2 Sp 1 with Microsoft SQL Server 2005 - 9.00.5000.00 (X64).

After reading kb942861, and reading other post

After checking TCP Chimney Offload is set to automatic?

Shall we stop the producton or is this type of error that the server is able to work without the suggested update of the server? I understand the error but need some more info about if we shall care?