Get SIM MSISDN & IMSI number in Windows Phone Application - windows-phone-8

Is it possible to get the SIM MSISDN & IMSI number in windows Phone app development?
I have gone through some of the Q/A but they all are asked a long time ago.

You could get SIM MSISDN & IMSI number in Windows Phone Application. Please notice that you should manually edit your application Package.appxmanifest as follows:
<Package xmlns="http://schemas.microsoft.com/appx/manifest/foundation/windows10"
xmlns:mp="http://schemas.microsoft.com/appx/2014/phone/manifest"
xmlns:uap="http://schemas.microsoft.com/appx/manifest/uap/windows10"
xmlns:rescap="http://schemas.microsoft.com/appx/manifest/foundation/windows10/restrictedcapabilities"
IgnorableNamespaces="uap mp rescap">
......
<Capabilities>
<rescap:Capability Name="cellularDeviceIdentity" />
</Capabilities>
The cellularDeviceIdentity capability allows apps to access cellular identification data.
Anyone may request access to these capabilities for store submission.
You could use MobileBroadbandModem class to get all CurrentDeviceInformation, and the following is core codes.
using Windows.Networking.NetworkOperators;
......
public IReadOnlyList<SimCard> GetSimCards()
{
var results = new List<SimCard>();
var modem = MobileBroadbandModem.GetDefault();
if (modem == null)
{
return results.AsReadOnly();
}
var account = modem.CurrentAccount;
if (account == null)
{
return results.AsReadOnly();
}
var simCard = new SimCard();
simCard.ICCID = account.CurrentDeviceInformation.SimIccId;
simCard.IMSI = account.CurrentDeviceInformation.SubscriberId;
simCard.MSISDN = modem.DeviceInformation.TelephoneNumbers;
simCard.MCC = ExtractMCC(simCard.IMSI);
simCard.MNC = ExtractMNC(simCard.IMSI);
simCard.MSID = ExtractMSID(simCard.IMSI);
results.Add(simCard);
return results.AsReadOnly();
}
I have uploaded code sample to git hub. Please check!

Related

How to search registered user on ejabberd server from client side using smack library?

I am using smack on the client-side. I tried to search registered users on the client-side because before creating a new user I want to know that the id is registered on server or not if not then create the user either log in the user but ejabberd server crashed with the error. Here are the crash logs of ejabberd server.
Failed to process iq:
#iq{
id = <<"Hh6AJ-28">>,type = set,lang = <<"en">>,
from =
#jid{
user = <<"admin">>,server = <<"faiqkhan-virtualbox">>,
resource = <<"92526029764259513741138">>,luser = <<"admin">>,
lserver = <<"faiqkhan-virtualbox">>,
lresource = <<"92526029764259513741138">>},
to =
#jid{
user = <<>>,server = <<"vjud.faiqkhan-virtualbox">>,resource = <<>>,
luser = <<>>,lserver = <<"vjud.faiqkhan-virtualbox">>,lresource = <<>>},
sub_els =
[#xmlel{
name = <<"query">>,
attrs = [{<<"xmlns">>,<<"jabber:iq:search">>}],
children =
[#xmlel{
name = <<"x">>,
attrs = [{<<"xmlns">>,<<"jabber:x:data">>},{<<"type">>,<<"submit">>}],
children =
[#xmlel{
name = <<"field">>,
attrs = [{<<"var">>,<<"user">>},{<<"type">>,<<"text-single">>}],
children =
[#xmlel{
name = <<"value">>,attrs = [],
children = [{xmlcdata,<<"wasiq#faiqkhan-virtualbox">>}]}]}]}]}],
meta = #{ip => {0,0,0,0,0,65535,49320,11092}}}
exception error: {module_not_loaded,mod_vcard_mnesia,
<<"faiqkhan-virtualbox">>}
in function gen_mod:get_module_opts/2 (src/gen_mod.erl, line 338)
in call from gen_mod:get_module_opt/3 (src/gen_mod.erl, line 318)
in call from mod_vcard_mnesia:filter_fields/3 (src/mod_vcard_mnesia.erl, line 200)
in call from mod_vcard_mnesia:search/4 (src/mod_vcard_mnesia.erl, line 78)
in call from mod_vcard:search_result/4 (src/mod_vcard.erl, line 479)
in call from mod_vcard:process_search/1 (src/mod_vcard.erl, line 264)
in call from gen_iq_handler:process_iq/3 (src/gen_iq_handler.erl, line 131)
in call from gen_iq_handler:process_iq/4 (src/gen_iq_handler.erl, line 109)
I used the following code to get a registered user from the client-side:
InetAddress address = InetAddress.getByName(HOST);
DomainBareJid serviceName = JidCreate.domainBareFrom("faiqkhan-VirtualBox"); XMPPTCPConnectionConfiguration.Builder builder = XMPPTCPConnectionConfiguration.builder();
builder.setPort(PORT);
builder.setSendPresence(true);
builder.setHostAddress(address);
builder.setServiceName(serviceName);
builder.setUsernameAndPassword("admin", "123456");
builder.setSecurityMode(ConnectionConfiguration.SecurityMode.disabled);
XMPPTCPConnection connection = new XMPPTCPConnection(builder.build());
try {
connection.connect();
connection.login("admin", "123456");
Logger.showError("21560-connection created to: " + connection.getHost());
Roster roster = Roster.getInstanceFor(connection);
Set<RosterEntry> entities = roster.getEntries();
UserSearchManager search = new UserSearchManager(connection);
DomainBareJid s = JidCreate.domainBareFrom("vjud.".concat("faiqkhan-VirtualBox"));
Form searchForm = search.getSearchForm(s);
Form answerForm = searchForm.createAnswerForm();
answerForm.setAnswer("user", "wasiq#faiqkhan-virtualbox");
ReportedData data = search.getSearchResults(answerForm, s);
if (data.getRows() != null) {
for (ReportedData.Row row : data.getRows()) {
for (CharSequence value : row.getValues("jid")) {
Log.i("Iteartor values......", " " + value);
}
}
}
} catch (SmackException | IOException | XMPPException | InterruptedException e) {
Logger.showError("21560-error on account creation: " + e.getMessage());
}
Server crashed on ReportedData data = search.getSearchResults(answerForm, s); line of code.
You found a bug in ejabberd:
It was already fixed in 2018 in
https://github.com/processone/ejabberd/commit/1be21126342d503205798605725ba5ceef9de42b
but the bug got reintroduced in 2019 in
https://github.com/processone/ejabberd/commit/a02cff0e780bb735531594c4ece81e8628f79782#diff-71f613241ed580c3e5dad2b4526503f2R12
and I've now applied a temporary fix in
https://github.com/processone/ejabberd/commit/92913389a51ddc564f11e0712b0d82fca8c9aecb
But even if that bug is fixed, the feature you want to use probably doesn't help: a user must set his vCard in order for his account to be provided in vJud search. In other words, vJUD searches in stored vCards, not in registered accounts. If I register an account but don't set a vCard, then vJUD will not find it.
before creating a new user I want to know that the id is registered on server or not
And why don't you simply attempt to register the account first?
On the other hand, if you would like to check in advance if an account is available for registration or not (like some web registration sites do, to allow the user modify the username until one is available), then I think XMPP doesn't provide that possibility for security reasons: it is not allowed to know if an account exists or not.
A solution for that would be to use the check_account ejabberd command
https://docs.ejabberd.im/developer/ejabberd-api/admin-api/#check-account
executing it with some frontend, like ejabberdctl, ReST or XMLRPC
https://docs.ejabberd.im/admin/guide/managing/#ejabberd-commands
$ ejabberdctl check_account user1 localhost
$ ejabberdctl check_account user6666 localhost
Error: false
~ 1

Whether SIM card is available or not in windows phone universal project

I'm creating winrt universal project for mobile and tablet.
I want to check:
In mobile application, I am sending a sms text to sms application like this.
var message = new ChatMessage();
message.Recipients.Add("9999");
message.Body = "R*" + voucherNo + "*" + accountNo + "*" + pin;
await ChatMessageManager.ShowComposeSmsMessageAsync(message);
I want to place a check above that whether user has inserted sim card or using mobile with out sim card. Well app is not crashing due to this so this is not a big issue if I couldn't place that check here (as I have already searched alot about it but got nothing so I'm assuming that it is not possible right not in winrt to check sim card availability), but a link of documentation/blog/SO question regarding this where it is mentioned that you can't check sim card availability would be helpful.
Thanks.
bool simAvailable = false;
var device = await ChatMessageManager.GetTransportsAsync();
if (device != null && device.Count > 0)
{
foreach (var item in device)
{
if (item.TransportFriendlyName != "No SIM")
{
simAvailable = true;
break;
}
}
}
Just enter this code and Simavailable will be true if phone hase sim card.

Windows phone 8.1 using Contact Picker to retrieve both email and phone number

I am using the following code to allow the user to select contacts:
ContactPicker ContactPicker = new ContactPicker();
ContactPicker.DesiredFieldsWithContactFieldType.Add(ContactFieldType.PhoneNumber);
var Contacts = await ContactPicker.PickContactsAsync();
if (Contacts.Count > 0)
{
foreach (Contact contact in Contacts)
{
string telephone = string.Empty;
string email = string.Empty;
if (contact.Phones.Count > 0)
{
telephone = contact.Phones[0].Number;
}
if (contact.Emails.Count > 0)
{
email = contact.Emails[0].Address;
}
PartyPerson person = new PartyPerson(DateTime.Now.ToString("PP_yyMMdd_hhmmss_ffff"), true, contact.DisplayName, 0, 0, 0, email, telephone);
AddPartyPerson(person);
}
}
ContactPicker = null;
However, I only get phone number, the object "contact" does not contain any email addresses even though they are present in the contact information.
One option is to switch:
ContactPicker.DesiredFieldsWithContactFieldType.Add(ContactFieldType.PhoneNumber);
with
ContactPicker.DesiredFieldsWithContactFieldType.Add(ContactFieldType.Email);
But then I don't get a phone number... I want to be able to retrieve all the information in one select.
Is there any way to select both information via one select?
(I also tried adding more than one entry to DesiredFieldsWithContactFieldType but then I get an exception...)
Best regards,
Keran
EDIT 07.08.2015:
Since the "ContactPicker.DesiredFieldsWithContactFieldType" can only accept one type of "ContactFieldType", the way I worked around this was first allow the user to get the contacts by ContactFieldType.PhoneNumber and then I programatically retrieve the email addressess of the selected contacts.
From the users point of view, this won't be a problem since everything will be visible correctly in the ContactPicker.PickContactsAsync, we just need to retrieve the missing email information manually in code-behind, which is easy since we know what contacts were selected by the user.
Try this:
ContactStore contactStore = await ContactManager.RequestStoreAsync(ContactStoreAccessType.AllContactsReadOnly);
ContactPicker contactPicker = new ContactPicker();
IList<Contact> pickedContacts = await contactPicker.PickContactsAsync();
int pickedCount = pickedContacts != null ? pickedContacts.Count : 0;
if (pickedCount > 0)
{
for (int i = 0; i < count; ++i)
{
Contact c = pickedContacts[i];
Contact realContact = await contactStore.GetContactByIdAsync(c.Id);
//...
}
}
So, you first need to get the "skeleton" of the contact, and then you can get the whole contact entity with all its properties from the ContactStore object.
It works for me on Windows 10 Mobile. There shouldn't be much difference from Windows 8.
Hope it helps.

How to insert Liferay blogs entry programmatically

I use Liferay 6.0.6 and i need to insert the blogs entry programmatically from my custom Portlet or scheduled job.
I found the class BlogsEntryLocalServiceUtil but don't know how to use it.
Thank you.
This is the solution:
Company company = CompanyLocalServiceUtil.getCompanyById(MY_COMPANY_ID);
Role adminRole = RoleLocalServiceUtil.getRole(company.getCompanyId(),"Administrator");
List<User> adminUsers = UserLocalServiceUtil.getRoleUsers(adminRole.getRoleId());
//GET USER ADMIN
User adminUser = null;
for (User user : adminUsers){
if (user.getEmailAddress().equals(MY_ADMIN_EMAIL)){
adminUser = user;
break;
}
}
if (adminUser!=null) {
long userID = adminUser.getUserId();
long groudID = adminUser.getGroupIds()[0];
PrincipalThreadLocal.setName(userID);
PermissionChecker permissionChecker=PermissionCheckerFactoryUtil.create(adminUser, true);
PermissionThreadLocal.setPermissionChecker(permissionChecker);
Calendar displayDate =CalendarFactoryUtil.getCalendar(TimeZone.getTimeZone(StringPool.UTC));
boolean allowPingbacks = true;
boolean allowTrackbacks = true;
int actionPublish = WorkflowConstants.ACTION_PUBLISH;
ServiceContext serviceContext = new ServiceContext();
serviceContext.setWorkflowAction(actionPublish);
serviceContext.setAssetCategoryIds(new long[]{category});
serviceContext.setCreateDate(displayDate.getTime());
serviceContext.getExpandoBridgeAttributes().put("key1", value1);
serviceContext.getExpandoBridgeAttributes().put("key2", value2);
serviceContext.setAddGuestPermissions(true);
serviceContext.setScopeGroupId(groudID);
//INSERT BLOGS ENTRY
BlogsEntryLocalServiceUtil.addEntry(userID, title, content, displayDate.get(Calendar.MONTH), displayDate.get(Calendar.DAY_OF_MONTH), displayDate.get(Calendar.YEAR), displayDate.get(Calendar.HOUR), displayDate.get(Calendar.MINUTE), allowPingbacks, allowTrackbacks, new String[]{}, serviceContext);
}
You have addEntry method available in the class you mentioned i.e. BlogsEntryLocalServiceUtil, just pass the required parameters and you will be able to create a blog entry.
but don't know how to use it.
For this, you can try to look into portal-impl folder of liferay source and find all the java sources available there to find how to implement them.

Windows Phone 8.1 live tile not updating daily

I'm having problems to get my Windows Phone 8.1 live tile update by itself daily (around 7am)
My project has 2 parts :
a Web API project hosted on Azure that provides the tile template in XML (that part works fine)
a Windows Phone 8.1 project with a single MainPage.xaml where I build 2 square/wide tiles
When I pin my app to the start screen from the app list, my tile (whether I choose the square or wide format) flips back and forth between my 2 brands of the day just fine.
The next morning at 7:15 am, the tile won't update with the 2 new brands :(
I noticed that if I tap the tile to launch the app and come back to the start screen, the tile has updated.
It also works if I unpin and repin the tile but in both cases, that's "cheating" :-/
I call my Azure website like this to get the tile templates of both brands :
http://example.azurewebsites.net/api/tiles/0 (BRAND1)
http://example.azurewebsites.net/api/tiles/1 (BRAND2)
The XML tile template looks like this (example):
<tile>
<visual>
<binding template="TileWide310x150ImageAndText01">
<image id="1" src="http://www.example.com/sales/BRAND1/visualWide.png"/>
<text id="1">Brand 1</text>
</binding>
<binding template="TileSquare150x150PeekImageAndText04">
<image id="1" src="http://www.example.com/sales/BRAND1/visualSquare.png"/>
<text id="1">Brand 1</text>
</binding>
</visual>
</tile>
The WP8.1 page contains this :
public MainPage()
{
this.InitializeComponent();
this.NavigationCacheMode = NavigationCacheMode.Required;
TileUpdateManager.CreateTileUpdaterForApplication().EnableNotificationQueue(true);
PeriodicUpdateRecurrence recurrence = PeriodicUpdateRecurrence.Daily;
Task<string> responseBody;
for (int i = 0; i < 2; i++)
{
using (var httpClient = new HttpClient())
{
httpClient.BaseAddress = new Uri("http://xxxxx.azurewebsites.net/api/tiles/" + i); //I hid the address here for discretion
HttpResponseMessage response = httpClient.GetAsync(httpClient.BaseAddress).Result;
string statusCode = response.StatusCode.ToString();
response.EnsureSuccessStatusCode();
responseBody = response.Content.ReadAsStringAsync();
}
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.LoadXml(responseBody.Result);
string srcWide, srcSquare, textWide, textSquare, templateWide, templateSquare;
XElement root = XElement.Parse(responseBody.Result);
IEnumerable<XElement> wideElement = root.Descendants("binding").Where(a => a.Attribute("template").Value.ToLower().Contains("wide"));
IEnumerable<XElement> squareElement = root.Descendants("binding").Where(a => a.Attribute("template").Value.ToLower().Contains("square"));
templateWide = wideElement.Attributes("template").SingleOrDefault().Value;
srcWide = wideElement.Descendants("image").Attributes("src").SingleOrDefault().Value;
textWide = wideElement.Descendants("text").SingleOrDefault().Value;
templateSquare = squareElement.Attributes("template").SingleOrDefault().Value;
srcSquare = wideElement.Descendants("image").Attributes("src").SingleOrDefault().Value;
textSquare = wideElement.Descendants("text").SingleOrDefault().Value;
XmlDocument wideTileXml = TileUpdateManager.GetTemplateContent(TileTemplateType.TileWide310x150ImageAndText01);
XmlNodeList wideTileTextAttributes = wideTileXml.GetElementsByTagName("text");
wideTileTextAttributes[0].InnerText = textWide;
XmlNodeList wideTileImageAttributes = wideTileXml.GetElementsByTagName("image");
((XmlElement)wideTileImageAttributes[0]).SetAttribute("src", srcWide);
((XmlElement)wideTileImageAttributes[0]).SetAttribute("alt", textWide);
XmlDocument squareTileXml = TileUpdateManager.GetTemplateContent(TileTemplateType.TileSquare150x150PeekImageAndText01);
XmlNodeList squareTileTextAttributes = squareTileXml.GetElementsByTagName("text");
squareTileTextAttributes[0].AppendChild(squareTileXml.CreateTextNode(textSquare));
XmlNodeList squareTileImageAttributes = squareTileXml.GetElementsByTagName("image");
((XmlElement)squareTileImageAttributes[0]).SetAttribute("src", srcSquare);
((XmlElement)squareTileImageAttributes[0]).SetAttribute("alt", textSquare);
IXmlNode node = wideTileXml.ImportNode(squareTileXml.GetElementsByTagName("binding").Item(0), true);
wideTileXml.GetElementsByTagName("visual").Item(0).AppendChild(node);
TileNotification tileNotification = new TileNotification(wideTileXml);
tileNotification.ExpirationTime = DateTimeOffset.UtcNow.AddDays(1).AddHours(7).AddMinutes(0);
TileUpdateManager.CreateTileUpdaterForApplication().Update(tileNotification);
}
List<Uri> urisToPoll = new List<Uri>(5);
urisToPoll.Add(new Uri("http://example.azurewebsites.net/api/tiles/0")); //fake url
urisToPoll.Add(new Uri("http://example.azurewebsites.net/api/tiles/1")); //fake url
//I want the tile to update its content every day at 7:15am
//(the Azure website supposedly returns new brands of the day at 7am)
DateTime dtTomorrow7 = DateTime.SpecifyKind(DateTime.Today.AddDays(1).AddHours(7).AddMinutes(15), DateTimeKind.Local);
DateTimeOffset dtoTomorrow7 = dtTomorrow7;
TileUpdateManager.CreateTileUpdaterForApplication().StartPeriodicUpdateBatch(urisToPoll, dtoTomorrow7, recurrence);
}
I'm not sure I'm using the StartPeriodicUpdateBatch method correctly.
In debug mode,I can see the DateTimeOffset value is Day+1 7:15am +2:00 which looks correct but the tile does not update.
I live in France that is UTC+2
Thanks for your suggestions.
Your dtTomorrow7 is incorrect. It should just be 7:15 AM. Then it will first do an update at 7:15 AM and subsequent updates occurring at the periodic interval thereafter(you set it to daily).
Example of start time where the last TimeSpan is offset from UTC:
DateTime tomorrow = DateTime.Today.AddDays(1);
var startTime = new DateTimeOffset(tomorrow.Year, tomorrow.Month, tomorrow.Day, 7, 15, 0, TimeSpan.FromHours(2));