iOS - app specific address book - ios6

I want to use the look/functionality of the Contacts app to display a list of company employees in my app. These employees should not be put into the address book of the phone user but be a standalone app specific list.
It seemed like ABPeoplePickerNavigationController is the way to go and that I can set the .addressBook property to an address book I create with ABAddressBookCreate() however when I run this on my phone it loads up all my contacts rather than just the one I have created as a test in my app. Employees I create are also saved to the central address book of the phone.
Is there a way to create a standalone address book not integrated with the central address book so I can use the ABPeoplePickerNavigationController? Facebook appear to have done something similar in their app when you look at your friends list.
I am hoping I don't have to build this from the ground up. There are a couple of similar questions around but nothing definitive.
ABAddressBookRef addressBook;
CFErrorRef error = NULL;
addressBook = ABAddressBookCreate();
ABRecordRef aRecord = ABPersonCreate();
CFErrorRef anError = NULL;
bool didSet;
didSet = ABRecordSetValue(aRecord, kABPersonFirstNameProperty, CFSTR("Andy"), &anError);
if (!didSet) {/* Handle error here. */}
didSet = ABRecordSetValue(aRecord, kABPersonLastNameProperty, CFSTR("Aardvark"), &anError);
if (!didSet) {/* Handle error here. */}
CFStringRef firstName, lastName;
firstName = ABRecordCopyValue(aRecord, kABPersonFirstNameProperty);
lastName = ABRecordCopyValue(aRecord, kABPersonLastNameProperty);
/* ... Do something with firstName and lastName. ... */
ABAddressBookAddRecord(addressBook, aRecord, &error);
CFRelease(aRecord);
CFRelease(firstName);
CFRelease(lastName);
ABAddressBookSave(addressBook, &error);
ABPeoplePickerNavigationController *picker =
[[ABPeoplePickerNavigationController alloc] init];
picker.addressBook = addressBook;
picker.peoplePickerDelegate = self;
[self presentModalViewController:picker animated:YES];
CFRelease(addressBook);

Related

Save the for-loop index for certain values to be used later

I'm trying to create two spreadsheets: one tracks student attendance at school, the other tracks their attendance at Track practice. The goal is to write a function, that I can set up as a button, that I can click that will automatically send emails to several people if the student is present at school but is absent for sports without getting excused.
Right now, the whole thing is working pretty well, but I have one issue. I have a column that will read "Good" or "Bad" depending on whether the student meets the above condition. The function turns these into an array. I would like to use the index of the "Bad"'s to find the necessary email addresses, which are stored at the same index point in another array that I make from the spreadsheet. I'm not sure how to save this index point and use it to reference the email addresses. Code below.
function sendEmailsMonday() {
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("TrackAttendance");
var dataRange = sheet.getRange("D2:D30");
var data = dataRange.getValues();// Gets array of "Good" and "Bad"
for (i in data) {
if(i = "Bad") {
var place = data.indexOf(i);
var dataRange2 = sheet.getRange("M2:M30");// Gets array of email addresses
var data2 = dataRange2.getValues();
var emailAddress = data2[place];
var message = "This is an automated email informing you that your child/advisee ____ was present at school today, but missed Track without being excused. Feel free to email Mr. # with any questions.";
var subject = "___ missed Track Practice";
MailApp.sendEmail(emailAddress, subject, message);
return;
}
}
}
So, the issue comes in with the index lines. If I get rid of
var place = data.indexOf(i);
and replace
var emailAddress = data[place];
with
var emailAddress = data[28];
or any other number, it will grab the email address and send it. But then it has nothing to do with the values in the other column.
Seems like this should be an easy fix but I'm bad at this.
Very late responding now. I think you are almost there.
Your IF statement should read:
if(i == "Bad") {
And then replace 'place' with i:
var emailAddress = data2[i];
It should work as expected now.

Apex - Retrieving Records from a type of Map<SObject, List<SObject>>

I am using a lead map where the first id represents an Account ID and the List resembles a list of leads linked to that account such as: Map<id, List<Id> > leadMap = new Map< id, List<id> >();
My question stands as following: Knowing a Lead's Id how do I get the related Account's Id from the map. My code looks something like this, The problems is on the commented out line.
for (Lead l : leads){
Lead newLead = new Lead(id=l.id);
if (l.Company != null) {
// newLead.Account__c = leadMap.keySet().get(l.id);
leads_to_update.add(newLead);
}
}
You could put all lead id and mapping company id in the trigger then get the company id
Map<string,string> LeadAccountMapping = new Map<string,string>();//key is Lead id ,Company id
for(Lead l:trigger.new)
{
LeadAccountMapping.put(l.id,l.Company);
}
//put the code you want to get the company id
string companyid= LeadAccountMapping.get(l.id);
Let me make sure I understand your problem.
Currently you have a map that uses the Account ID as the key to a value of a List of Lead IDs - So the map is -> List. Correct?
Your goal is to go from Lead ID to the Account ID.
If this is correct, then you are in a bad way, because your current structure requires a very slow, iterative search. The correct code would look like this (replace your commented line with this code):
for( ID actID : leadMap.keySet() ) {
for( ID leadID : leadMap.get( actId ) ) {
if( newLead.id == leadID ) {
newLead.Account__c = actId;
leads_to_update.add(newLead);
break;
}
}
}
I don't like this solution because it requires iterating over a Map and then over each of the lists in each of the values. It is slow.
If this isn't bulkified code, you could do a Select Query and get the Account__c value from the existing Lead by doing:
newLead.Account__c = [ SELECT Account__c FROM Lead WHERE Id = :l.id LIMIT 1];
However, this relies on your code not looping over this line and hitting a governor limit.
Or you could re-write your code soe that your Map is actually:
Map<ID, List<Leads>> leadMap = Map<ID, List<Leads>>();
Then in your query where you build the map you ensure that your Lead also includes the Account__c field.
Any of these options should work, it all depends on how this code snippet in being executed and where.
Good luck!

Unable to cast object of type [TweetSharp.TwitterUser]' to type 'TweetSharp.TwitterCursorList`1[TweetSharp.TwitterUser]'

hi i want to get follower list via tweetsharp but i have a exception this = Unable to cast object of type 'System.Collections.Generic.List1[TweetSharp.TwitterUser]' to type 'TweetSharp.TwitterCursorList1[TweetSharp.TwitterUser]'.
help me please HOW CAN I GET FOLLOWERLIST?
my code like this
string aranan = "anilsarii";
var AramaAyari = new SearchForUserOptions { Q = aranan, Count = 25 };
var users = ts.SearchForUser(AramaAyari); //Get list of users by query
//...
//var asd=ts.FollowList(new FollowListOptions{ OwnerId= 2603023494});
var followers = ts.ListFollowers(new ListFollowersOptions { Cursor = -1 });
while (followers.NextCursor != null)
{
followers = ts.ListFollowers(new ListFollowersOptions { followers.NextCursor });
}
You may just need to change this line;
followers = ts.ListFollowers(new ListFollowersOptions { followers.NextCursor });
to
followers = ts.ListFollowers(new ListFollowersOptions { Cursor = followers.NextCursor });
If that doesn't work, it's likely a problem in TweetSharp itself. TweetSharp has been abandoned by the original authors and is no longer maintained. As a result, there are a number of problems using it with the current Twitter API, due to changes on Twitter's end in the last few years. However there are several forks of TweetSharp that are current.
I tried your code with the one line modified above using TweetMoaSharp (a fork, available on Nuget, or on github here; https://github.com/Yortw/tweetmoasharp) and it worked fine.
Full disclosure: TweetMoaSharp is a fork primarily maintained by me. If you search Nuget for 'TweetSharp' you should find several others.

'Anonymous user' error after passing data with Angular to Rest

I am a beginner in Angular and Rest and I have a problem. I have a form in Django template and I want to pass data with Angular, receive it with Rest and process it. Angular knows to pass (post) the data by url to:
url(r'^api/nowyPacjent/$', CreateNewPatient.as_view(), name="api_tempPatient"),
The CreateNewPatient class looks like this:
class CreateNewPatient(generics.ListCreateAPIView):
model = TempPatient
queryset = TempPatient.objects.all()
serializer_class = CreateNewPatientSerializer
and the serializer looks like this:
class CreateNewPatientSerializer(serializers.Serializer):
name = serializers.CharField(max_length=30)
surname = serializers.CharField(max_length=70)
phone = serializers.CharField(max_length=15, required=False)
age = serializers.IntegerField(max_value=99, min_value=1, required=False)
company = serializers.PrimaryKeyRelatedField(many=False, queryset=Company.objects.all())
therapyStart = serializers.DateField(required=False)
def create(self, validated_data):
if 'therapyStart' in validated_data:
therapy_start = validated_data['therapyStart']
else:
therapy_start = datetime.date.today()
if 'age' in validated_data:
patient_age = validated_data['age']
else:
patient_age = 1;
if 'phone' in validated_data:
patient_phone = validated_data['phone']
else:
patient_phone = ''
newTempPatient = TempPatient(
name = validated_data['name'],
surname = validated_data['surname'],
company = validated_data['company'],
therapyStart = therapy_start,
age = patient_age,
phone = patient_phone
)
newTempPatient.save()
newPatient = Patient(
name=validated_data['name'],
surname=validated_data['surname'],
phone=patient_phone,
age=patient_age
)
newPatient.save()
user=None
request = self.context.get('request')
if request and hasattr(request,"user"):
user=request.user
newTherapyGroup = TherapyGroup.objects.create(
start = therapy_start,
patient = newPatient,
therapist = Therapist.objects.get(user = user),
company = validated_data['company']
)
newTherapyGroup.save()
return newTempPatient
Everything is fine - after submitting the template form the patient is created - until the code tries to get logged user from the request (just after the last if statement of the serializer). Then I receive the 'AnonymousUser' error and cannot create final model instance. I've tried to pass the data to the Django views and then use the Rest's serializer. However, the error occurred again. I've searched for the answer but nothing was helpful. Please, notice that I don't want to authenticate the logged user but to get data about him.
I think the problem is that Angular somehow loose information about CSRF token and log session and that is the reason of both errors (that is only my assumption).
Below is how Angular config looks like. NewPatientCtrl is responsible for mentioned form and model is one of the form element (and it works fine).
angular.module('pacjent', ['ngMessages', 'ui.bootstrap', 'datetime'])
.constant('companyListApi','http://localhost:8000/finanse/api/list/')
.constant('tempPatientApi','http://localhost:8000/pacjent/api/nowyPacjent/')
.factory('ModelUtils', ModelUtils)
.factory('newPatientFormApi',newPatientFormApi )
.factory('companyApi', companyApi)
.factory('mySharedService', mySharedService)
.controller('PacjentCtrl', PacjentCtrl)
.controller('NewPatientCtrl', NewPatientCtrl)
.controller('ModalInstanceCtrl', ModalInstanceCtrl)
.config(function($interpolateProvider, $httpProvider) {
$interpolateProvider.startSymbol('{[{');
$interpolateProvider.endSymbol('}]}');
$httpProvider.defaults.xsrfCookieName = 'csrftoken';
$httpProvider.defaults.xsrfHeaderName = 'X-CSRFToken';
})
The interesting thing is that this code works perfect on my colleague's system (Windows 7, Chrome) - the user data is gathered perfectly. However, I've tested it on three different systems (Windows 7 x64, Xubuntu 14.04, Ubuntu 14) and several browsers (Firefox, Chromium) on my PCs and the same error occurs.
Thank you a lot for any comments and advice. Sorry also for any non-professional statements.
it is because of this line:
user=request.user
# ...
therapist = Therapist.objects.get(user = user),
you are trying to get a therapist from your database with an Anynomous user in your ORM - it means a user who is not logged in.
you need is_authenticated() in your check:
if request and hasattr(request,"user") and request.user.is_authenticated():
user=request.user
newTherapyGroup = TherapyGroup.objects.create(
start = therapy_start,
patient = newPatient,
therapist = Therapist.objects.get(user=user),
company = validated_data['company']
)
newTherapyGroup.save()

Model won't update

Using cakephp:
I am trying to update customer information and the address the customer is linked to.
such that Customer.address_id = Address.id, and
Customer Model
$belongsTo = 'Address';
From the customers_controller
function profile($id = null)
{
if (empty($this->data['Customer']))
{
$this->Customer->id = $id;
$this->data = $this->Customer->read();
}
else
{
$this->Customer->id = $this->data['Customer']['id'];
$this->Customer->read();
$this->Customer->save($this->data['Customer']);
$this->Customer->Address->save($this->data['Address']);
}
}
Customer correctly updates, but Address always inserts a new row. How do I get this address to update?
first of all, take away lines 11 and 12. those serve no purpose. make sure your view contains form elements for Customer.id and Address.id. If you are just updating the Address you dont need line 13 either. The short answer is that Cakephp will insert row instead of update if the primary key is missing. In your case this means [Address][id].

Resources