Is there any working sample/example available to use Google People API for Android? - google-people-api

I looked into google people API on their official documentation page
https://developers.google.com/people/quickstart/java#step_4_run_the_sample
in spite of following all necessary steps API does not work.
I came across below example on GitHub which is not working as well. https://github.com/Suleiman19/People-API-App
also, I check google example
Credential credential = new AuthorizationCodeInstalledApp(
flow, new LocalServerReceiver()).authorize("user");
lang.NoClassDefFoundError: Failed resolution of: Ljava/awt/Desktop;

Below code is working. able to access people API
private static class GetUserInfoTask extends AsyncTask<String, Void, Void> {
private final Context context;
private ISignIn iSignIn;
private HttpTransport httpTransport = new NetHttpTransport();
private JacksonFactory jsonFactory = new JacksonFactory();
private String personEmail;
private String personLastName;
private String personFirstName;
private String image;
private String genderString;
private String aboutMeLocal;
private String phoneLocal;
private long birthdayLocal;
public GetUserInfoTask(Context context, ISignIn iSignIn) {
this.context = context;
this.iSignIn = iSignIn;
}
#Override
protected Void doInBackground(String... params) {
personEmail = params[0];
personLastName = params[1];
personFirstName = params[2];
image = params[3];
Person userProfile = null;
Collection<String> scopes = new ArrayList<>();
scopes.add(Scopes.PROFILE);
GoogleAccountCredential mCredential =
GoogleAccountCredential.usingOAuth2(context, scopes);
//mCredential.setSelectedAccount(new Account(personEmail, context.getString(R.string.account_type)));
mCredential.setSelectedAccountName(personEmail);
People service = new People.Builder(httpTransport, jsonFactory, mCredential)
.setApplicationName(context.getString(R.string.app_name)) // your app name
.build();
// Get info. on user
try {
userProfile = service.people().get("people/me").setRequestMaskIncludeField("person.biographies,person.birthdays,person.genders,person.phone_numbers").execute();
} catch (IOException e) {
FirebaseApp.initializeApp(context);
FirebaseCrash.report(e);
LogUtils.e(TAG, e.getMessage());
}
// Get whatever you want
if (userProfile != null) {
// Gender
List<Gender> genders = userProfile.getGenders();
if (genders != null && genders.size() > 0) {
Gender gender = genders.get(0);
if (gender != null) {
// save mGender
genderString = gender.getValue();
LogUtils.d(TAG, "mGender : " + gender.getValue());
}
}
// BirthDay
List<Birthday> birthdays = userProfile.getBirthdays();
if (birthdays != null && birthdays.size() > 0) {
Birthday birthday = birthdays.get(0);
if (birthday != null && birthday.getDate() != null && birthday.getDate().getYear() != null && birthday.getDate().getMonth() != null
&& birthday.getDate().getDay() != null) {
// save mBirthday
Calendar calendar = Calendar.getInstance();
calendar.set(birthday.getDate().getYear(), birthday.getDate().getMonth(), birthday.getDate().getDay());
birthdayLocal = calendar.getTime().getTime();
LogUtils.d(TAG, "mBirthday : " + birthday.toString());
}
}
// Phone Number
List<PhoneNumber> phoneNumbers = userProfile.getPhoneNumbers();
if (phoneNumbers != null && phoneNumbers.size() > 0) {
PhoneNumber phoneNumber = phoneNumbers.get(0);
if (phoneNumber != null) {
// save mPhoneNumber
phoneLocal = phoneNumber.getValue();
LogUtils.d(TAG, "mPhoneNumber : " + phoneNumber.getValue());
}
}
// biography (About me)
List<Biography> biographies = userProfile.getBiographies();
if (biographies != null && biographies.size() > 0) {
Biography biography = biographies.get(0);
if (biography != null) {
// save biography
aboutMeLocal = biography.getValue();
LogUtils.d(TAG, "biography : " + biography.getValue());
}
}
}
try{
ListConnectionsResponse response = service.people().connections()
.list("people/me")
// This line's really important! Here's why:
// http://stackoverflow.com/questions/35604406/retrieving-information-about-a-contact-with-google-people-api-java
.setRequestMaskIncludeField("person.names,person.emailAddresses,person.phoneNumbers,person.biographies")
.execute();
List<Person> connections = response.getConnections();
if(connections!=null && connections.size()>0){
for (Person person : connections) {
getPersonInfo(person);
}}
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
iSignIn.onSaveUserInformation(personEmail, personFirstName, personLastName, image, genderString, birthdayLocal, phoneLocal, aboutMeLocal);
}
}

Related

How to use Moq in unit test that calls another method in same EF Repository

In my project I am using Repository.
I'm trying to unit test a SAVE method and return the call value via the Get method.
I'm having a Repository Query mockup issue when calling through the Get method. Can you help me in this case?
I Have a Class:
public class ClientRoleBo
{
private readonly IRepositoryBase<ClientRole> _repository;
public ClientRoleBo(IRepositoryBase<ClientRole> repository)
{
_repository = repository;
}
public Task<ClientRoleResp?> Get(Guid clientGuid, Guid id)
{
return Task.FromResult(
_repository.Query(x => x.Guid == id && x.ClientGuid == clientGuid && !x.IsDeleted)
.Select(x => new ClientRoleResp
{
Code = x.Code,
Guid = x.Guid,
IsActive = x.IsActive,
Name = x.Name
}).FirstOrDefault()
);
}
public async Task<ClientRole> Save(Guid clientGuid, Guid? guid, ClientRoleReq req)
{
ClientRole? data = null;
var existItem = _repository.Query(x => x.Code == req.Code && x.ClientGuid == clientGuid).FirstOrDefault();
if (existItem != null)
throw new HttpResponseException(400, "Exist clientrole");
data = new()
{
Code = req.Code,
Name = req.Name,
IsActive = req.IsActive,
ModifiedDate = DateTime.Now,
CreatedDate = DateTime.Now,
ClientGuid = clientGuid
};
await _repository.AddAsync(data);
return (await Get(clientGuid, data!.Guid))!;
}
}
I have a issue when code call method "Save" return data of method "Get" same Repository
My Mock Repository:
public class TestClientRole{
public static IRepositoryBase<TEntiy> MockRepo<TEntiy>(TEntiy[] data, Expression<Func<TEntiy, bool>> returnExpression = null) where TEntiy : class
{
var mock = new Mock<IRepositoryBase<TEntiy>>();
mock.Setup(x => x.Query(
It.IsAny<Expression<Func<TEntiy, bool>>>()
)).Returns(returnExpression != null ? data.AsQueryable().Where(returnExpression).AsEnumerable() : data.AsEnumerable());
return mock.Object;
}
[Fact]
public void Save()
{
var clientRoles = new ClientRole[]
{
new ClientRole
{
Code = "123",
Name = "Role1",
Guid = Guid.NewGuid(),
},
new ClientRole
{
Code = "1234",
Name = "Role2",
Guid = Guid.NewGuid(),
}
};
var mockRepo = MockRepo<ClientRole>(clientRoles, x => x.Guid == clientRoles[0].Guid);
var svc = new ClientRoleBo(mockRepo);
var res = svc.Save(Guid.NewGuid, null, new ClientRoleReq { Code = "Role", Name = "Role" }).GetAwaiter().GetResult();
Assert.True(res.Guid == clientRoles[0].Guid);
}
}

How to get anonymous contact ID in Sitecore 9.1?

How to get anonymous contact ID using Sitecore API?
I'm using this code but can't find the contact ID in xconnect DB.
using (XConnectClient client = Sitecore.XConnect.Client.Configuration.SitecoreXConnectClientConfiguration.GetClient())
{
try
{
// var enumerator = client.Interactions.Where(x => x.DeviceProfile.Id == contactId).GetBatchEnumeratorSync(10);
Event ev = new Event(Guid.NewGuid(), DateTime.UtcNow) { Duration = new TimeSpan(20) };
var reference = new ContactReference(contactId);
Contact contact = client.Get<Contact>(reference, new ContactExpandOptions() { });
if (contact != null)
{
client.ExecuteRightToBeForgotten(contact);
client.Submit();
}
}
catch (XdbExecutionException ex)
{
// Manage exceptions
}
}
You can get it with the code new IdentifiedContactReference(Sitecore.Analytics.XConnect.DataAccess.Constants.IdentifierSource, Tracker.Current.Contact.ContactId.ToString("N")) This is the xDB identifier which is the identifier anonymous contacts get.
Here is the code I use _contactIdentificationRepository is in a Foundation repository. _contactIdentificationRepository.GetContactReference() will get the anonymous or identified contact reference.
Call xConnect
var contactReference = _contactIdentificationRepository.GetContactReference();
using (var client = SitecoreXConnectClientConfiguration.GetClient())
{
// we can have 1 to many facets
// PersonalInformation.DefaultFacetKey
// EmailAddressList.DefaultFacetKey
// Avatar.DefaultFacetKey
// PhoneNumberList.DefaultFacetKey
// AddressList.DefaultFacetKey
// plus custom ones
var facets = new List<string> { PersonalInformation.DefaultFacetKey };
// get the contact
var contact = client.Get(contactReference, new ContactExpandOptions(facets.ToArray()));
.....
}
_contactIdentificationRepository
private readonly ContactManager contactManager;
public ContactManager Manager => contactManager;
public ContactIdentificationRepository()
{
contactManager = Factory.CreateObject("tracking/contactManager", true) as ContactManager;
}
public IdentifiedContactReference GetContactReference()
{
// get the contact id from the current contact
var id = GetContactId();
// if the contact is new or has no identifiers
var anon = Tracker.Current.Contact.IsNew || Tracker.Current.Contact.Identifiers.Count == 0;
// if the user is anon, get the xD.Tracker identifier, else get the one we found
return anon
? new IdentifiedContactReference(Sitecore.Analytics.XConnect.DataAccess.Constants.IdentifierSource, Tracker.Current.Contact.ContactId.ToString("N"))
: new IdentifiedContactReference(id.Source, id.Identifier);
}
public Analytics.Model.Entities.ContactIdentifier GetContactId()
{
if (Tracker.Current?.Contact == null)
{
return null;
}
if (Tracker.Current.Contact.IsNew)
{
// write the contact to xConnect so we can work with it
this.SaveContact();
}
return Tracker.Current.Contact.Identifiers.FirstOrDefault();
}
public void SaveContact()
{
// we need the contract to be saved to xConnect. It is only in session now
Tracker.Current.Contact.ContactSaveMode = ContactSaveMode.AlwaysSave;
this.contactManager.SaveContactToCollectionDb(Tracker.Current.Contact);
}

Select default value OrderType selector by user login on SOOrder Screen

On SOOrder Screen: I have OrderType: C1,C2,CS,SO and C1->userRole A, C2->userRole B,CS & SO->userRole Administrator. I want to select the default Ordertype by userlogin, if userlogin= Admin so show the selector are CS & SO.
This is the my Code Editor: SOOrderEntry (Sales Orders):
protected void SOOrder_OrderType_FieldDefaulting(PXCache cache, PXFieldDefaultingEventArgs e)
{
PXResult<PX.SM.UsersInRoles> user = PXSelect<PX.SM.UsersInRoles,
Where<PX.SM.UsersInRoles.username, Equal<Current<AccessInfo.userName>>>>.Select(Base);
if(user != null)
{
PX.SM.UsersInRoles role = user;
if(role.Rolename == "Administrator")
e.NewValue = "CS";
else
if(role.Rolename == "A")
e.NewValue = "C1";
if(role.Rolename == "B")
e.NewValue = "C2";
}
}
My result is: when login us role Administrator, it showed all the order type.
You can try as below
public class CustomOrderTypeSelectorAttribute : PXCustomSelectorAttribute
{
public CustomOrderTypeSelectorAttribute()
: base(typeof(SOOrderType.orderType))
{
}
public IEnumerable GetRecords()
{
PXResult<PX.SM.UsersInRoles> user = PXSelect<PX.SM.UsersInRoles,
Where<PX.SM.UsersInRoles.username, Equal<Current<AccessInfo.userName>>>>.Select(Base);
if(user != null)
{
PXResult<SOOrderType> orderTypes = null;
if(roleName == "Administrator")
{
orderTypes = PXSelect<SOOrderType,
Where<SOOrderType.orderType, Equal<Required<SOOrderType.orderType>>,
Or<SOOrderType.orderType, Equal<Required<SOOrderType.orderType>>>>>.Select(Base, "CS", "SO");
}
else if(roleName == "A")
{
orderTypes = PXSelect<SOOrderType,
Where<SOOrderType.orderType, Equal<Required<SOOrderType.orderType>>>>.Select(Base, "C1");
}
else if(role.Rolename == "B")
{
orderTypes = PXSelect<SOOrderType,
Where<SOOrderType.orderType, Equal<Required<SOOrderType.orderType>>>>.Select(Base, "C2");
}
foreach (var item in orderTypes)
yield return item;
}
}
}
Then use cache attached to override OrderType property with custom select above

How to sync WebService operation in silverlight?

I am now on a project regarding controlling devices by using silverlight and web service(asmx page). The project flows like below:
pressing the button on the silverlight UI, it will send out a package by using socket to the middlewire. Then middlewire will accept the package and deconstructe it and return back another package to silverlight UI. I am using below code to load the button state, which will trigger database query:
private ButtonStateModel _buttonStateModel = new ButtonStateModel() { BtnOneImage = "Skins/images/flag/QU.png", BtnOneVisible = Visibility.Visible, BtnTwoVisible = Visibility.Collapsed };
public ButtonStateModel ButtonStateModel
{
get
{
ButtonStateModel btnState = null;
dataService.GetPR(BusEquipmentPermission.Control.RtuID, BusEquipmentPermission.Control.DevID, (result) =>
{
if (result != null && result.Count > 0)
{
var flag = result[0].PRFlag;
if (flag == 1)
{
btnState = new ButtonStateModel()
{
BtnOneImage = "Skins/images/flag/OP.png",
BtnOneVisible = Visibility.Visible,
BtnTwoImage = "Skins/images/flag/OFF.png",
BtnTwoVisible = Visibility.Visible
};
}
else if (flag == 2)
{
btnState = new ButtonStateModel()
{
BtnOneImage = "Skins/images/flag/OFF.png",
BtnOneVisible = Visibility.Visible,
BtnTwoImage = "Skins/images/flag/OR.png",
BtnTwoVisible = Visibility.Visible
};
}
}
});
return btnState;
}
set
{
if (value == _buttonStateModel)
{
return;
}
_buttonStateModel = value;
RaisePropertyChanged("ButtonStateModel");
}
}
Now the problem is, whenever I load the silverlight app, the button on the UI can't load its state correctly. I know the reason is because that the GetPR function is from webservice(asmx), it's very oddly that I can't do sync operation by using AutoResetEvent in silverlight generated client code:
public void GetPR(string rtuID, string devID, Action<List<BusControlPR>> action)
{
ServiceSoapClient proxy = new ServiceSoapClient();
proxy.GetPRAsync(rtuID, devID);
proxy.GetPRCompleted += (sender, args) =>
{
//I cannt do Sync Operation Here by using AutoResetEvent.
if (action != null)
action(args.Result.ToList());
};
}
I am using webservice (asmx page) instead of WCF ria service.
Above problem is what i meet, Anyone can give me some light?
The "GetPR" method is still running asynchronously, so the "ButtonStateModel" getter will return null immediately (the "completed" action will then have no effect). And, you do not want to use any kind of blocking inside your getters, as that will block the UI. Instead, you should put the "GetPR" in the initialization, and use the to set the "ButtonStateModel" property to the appropriate value:
public class TheViewModel
{
public ButtonStateModel ButtonStateModel
{
get
{
return _buttonStateModel;
}
set
{
if (value == _buttonStateModel)
{
return;
}
_buttonStateModel = value;
RaisePropertyChanged("ButtonStateModel");
}
}
public TheViewModel()
{
Initialize();
}
private void Initialize()
{
dataService.GetPR(BusEquipmentPermission.Control.RtuID, BusEquipmentPermission.Control.DevID, (result) =>
{
ButtonStateModel btnState = null;
if (result != null && result.Count > 0)
{
var flag = result[0].PRFlag;
if (flag == 1)
{
btnState = new ButtonStateModel()
{
BtnOneImage = "Skins/images/flag/OP.png",
BtnOneVisible = Visibility.Visible,
BtnTwoImage = "Skins/images/flag/OFF.png",
BtnTwoVisible = Visibility.Visible
};
}
else if (flag == 2)
{
btnState = new ButtonStateModel()
{
BtnOneImage = "Skins/images/flag/OFF.png",
BtnOneVisible = Visibility.Visible,
BtnTwoImage = "Skins/images/flag/OR.png",
BtnTwoVisible = Visibility.Visible
};
}
}
ButtonStateModel = btnState;
});
}
}

How to unit test unformatted method in mvc?

I have to unit test one of the very big and unformatted method in ASP.NET MVC 4.0.
Below is the code of action method :-
public ActionResult GetDetails(string ProdName, int ProdArea, int ProdAreaId= 0)
{
if (ProdAreaId == 0 && ProdArea == 1 && System.Web.HttpContext.Current.Session["ResponseProdAreaId"] != null)
{
ProdAreaId = (int)System.Web.HttpContext.Current.Session["ResponseProdAreaId"];
}
if (string.IsNullOrEmpty(ProdName))
{
if (System.Web.HttpContext.Current.Session["ProdName"] == null)
{
ProdName = Guid.NewGuid().ToString();
System.Web.HttpContext.Current.Session["ProdName"] = ProdName;
}
else
{
ProdName = System.Web.HttpContext.Current.Session["ProdName"].ToString();
}
}
else
{
ProdName = ProdName.Replace("___", " ");
}
List<StateDetail> stateList = ProductService.GetAllStates().Where(n => n.FKCountryID == (int)Countries.UnitedStates).ToList();
ProductAddressViewModel model = new ProductAddressViewModel
{
ProdArea = ProdArea,
FKProductID = CurrentProductId
};
model.States = stateList != null ? new SelectList(stateList, "StateID", "StateCode") : null;
if (System.Web.HttpContext.Current.Session[“ProdAddresses”] != null && ProdAreaId == 0 && ProdArea == 1)
{
List<ProductAddressDto> lstprodaddresses = (List<ProductAddressDto>)System.Web.HttpContext.Current.Session[“ProdAddresses”];
if (lstprodaddresses.Count > 0)
{
AddressDto addrDto = lstprodaddresses.First().Address;
//save address in DB
model.Address1 = addrDto.Address1;
model.Address2 = addrDto.Address2;
model.ProdArea = 1;
model.City = addrDto.City;
model.IsDefault = true;
model.ProdName = model.ProdName;
model.SelectedAddressTypeID = (int)AddressType.Street;
model.ZIPCode = addrDto.ZIPCode;
model.SelectedStateId = addrDto.FKStateID;
model.AddressTypes = GetAddressTypes();
}
}
else if (model.FKProductID > 0)
{
ToolDto tool = ToolService.GetToolDetails(model.FKProductID);
if (ProdAreaId > 0)
{
model.AddressTypes = GetAddressTypes();
ProductAddressDto prodaddr = tool.ToolAddresses.First(n => n.Tool_AddressID == ProdAreaId);
model.Address1 = prodaddr.Address.Address1;
model.Address2 = prodaddr.Address.Address2;
model.City = prodaddr.Address.City;
model.SelectedStateId = prodaddr.Address.FKStateID;
model.ZIPCode = prodaddr.Address.ZIPCode;
model.SelectedAddressTypeID = prodaddr.Address.FKAddressTypeID;
model.IsDefault = prodaddr.IsDefault;
model.FKAddressID = prodaddr.FKAddressID;
model.Tool_AddressID = prodaddr.Tool_AddressID;
model.FKProductID = prodaddr.FKProductID;
model.AddressTypes = GetAddressTypes();
}
else
{
//address types
List<int> excludeAddrTypes = new List<int>();
foreach (ProductAddressDto prodadrdto in tool.ToolAddresses)
{
if (prodadrdto.Tool_AddressID != ProdAreaId)
{
excludeAddrTypes.Add(prodadrdto.Address.FKAddressTypeID);
}
}
if (System.Web.HttpContext.Current.Session[“ProdAddresses”] != null)
{
excludeAddrTypes.Add((int)AddressType.Street);
}
var addrtypes = from AddressType e in Enum.GetValues(typeof(AddressType))
where !excludeAddrTypes.Contains((int)e)
select new { Id = (int)e, Name = e.ToString() };
model.AddressTypes = addrtypes.Select(x => new SelectListItem
{
Value = x.Id.ToString(),
Text = x.Name
});
if (tool.ToolAddresses.Count == 0)
{
model.IsDefault = (ProdArea == 1);
}
}
}
else
{
//filter out address types if responsed tool is there
if (System.Web.HttpContext.Current.Session[“ProdAddresses”] != null)
{
List<int> excludeAddrTypes = new List<int>();
excludeAddrTypes.Add((int)AddressType.Street);
var addrtypes = from AddressType e in Enum.GetValues(typeof(AddressType))
where !excludeAddrTypes.Contains((int)e)
select new { Id = (int)e, Name = e.ToString() };
model.AddressTypes = addrtypes.Select(x => new SelectListItem
{
Value = x.Id.ToString(),
Text = x.Name
});
}
else
{
model.AddressTypes = GetAddressTypes();
}
model.IsDefault = (ProdArea == 1);
}
model.ProdName = ProdName;
return PartialView("_AddUpdateAddress", model);
}
May be the method is not in correct format.But i have to do it's unit testing.I have do that in several different ways.But i am not sure about its correctness.
I want to know that how should we do unit test for such a big and unformatted method like this.
Can anyone help me out on this ?
Below is the piece of code of my unit testing method :-
[TestMethod]
public void GetDetailsTest_NotEmpty()
{
var ProdName = random.ToString();
var ProdArea = random.Next();
var ProdAreaId = 0;
var _toolServiceMock = new Mock<IToolService>();
var _lookupServiceMock = new Mock<ILookupService>();
var stateList = new List<StateDto> {
new StateDto() { StateID = random.Next(), StateCode = Guid.NewGuid().ToString(), Description = random.ToString(), FKCountryID = 1 },
new StateDto() { StateID = random.Next(), StateCode = Guid.NewGuid().ToString(), Description = random.ToString(), FKCountryID = random.Next() },
};
_lookupServiceMock.Setup(s => s.GetAllStates()).Returns(stateList); // .Returns(stateList);
//Arrange
CustomerDto cust = _toolService.LookupCustomers("", "").FirstOrDefault();
if (cust != null)
{
ToolDto tool = _toolService.GetToolDetails(cust.Tool.toolId);
if (tool.ToolAddresses.Count > 0 && tool.ToolAddresses.First().Address != null)
{
HttpContext.Current.Session["FKToolID"] = cust.FKToolID;
var controller = new ToolController(_toolServiceMock.Object);
PartialViewResult result = controller.SelectAddress(cust.Tool.Name, 1, tool.ToolAddresses.First().Tool_AddressID) as PartialViewResult;
var viewmodel = (ToolAddressViewModel)((ViewResultBase)(result)).Model;
if (viewmodel != null)
{
//Act
Assert.AreEqual(tool.ToolAddresses.First().Address.Address1, viewmodel.Address1);
Assert.AreEqual("_AddUpdateAddress", result.ViewName);
Assert.IsInstanceOfType(viewmodel, typeof(ToolAddressViewModel));
}
//Act
_lookupServiceMock.VerifyAll();
}
}
}
First of all, your method is a way too complicated and too long.
Make your actions short and with one responsability to respect SOLID principle (http://en.wikipedia.org/wiki/SOLID_(object-oriented_design)).
It will make your methods easier to test.
To help you with your problem, you can do something quick with your code :
Split your actions in internal virtual methods with one concern each (internal to be testable in you unit test project, virtual to be able to mock them).
Put the [assembly: InternalsVisibleTo("YourTestAssembly")] on your controller
In your unit test project, you will be able to test any of your internal methods separately.
Finally, to test your action, use a mocking framework (RhinoMock, Moq) to mock all your internal virtual methods and test the logic of your action (proxies generated by mocking framework will let you mock virtual methods).
It's the easiest way you can test your logic without breaking the existing application.
The inconvenient is that your logic is in internal methods wich let the whole assembly able to use it.