Debug Microsoft.AspNet.Identity.Core pdb - debugging

I try to implement register base on Microsoft.AspNet.Identity.Core.
package.config :
<?xml version="1.0" encoding="utf-8"?>
<packages>
<package id="EntityFramework" version="6.1.3" targetFramework="net451" />
<package id="Microsoft.AspNet.Identity.Core" version="2.2.1" targetFramework="net451" />
<package id="Microsoft.AspNet.Identity.EntityFramework" version="2.2.1" targetFramework="net451" />
<package id="Microsoft.AspNet.Identity.Owin" version="2.2.1" targetFramework="net451" />
<package id="Microsoft.Owin" version="3.0.1" targetFramework="net451" />
<package id="Microsoft.Owin.Security" version="3.0.1" targetFramework="net451" />
<package id="Microsoft.Owin.Security.Cookies" version="3.0.1" targetFramework="net451" />
<package id="Microsoft.Owin.Security.OAuth" version="3.0.1" targetFramework="net451" />
<package id="Newtonsoft.Json" version="7.0.1" targetFramework="net451" />
<package id="Owin" version="1.0" targetFramework="net451" />
</packages>
My unit test class:
public class register_test
{
Mock<IUserStore<ApplicationUser>> _userStore;
IRegisterService _registerService;
Mock<ApplicationUserManager> _userManagerMock;
IDataProtectionProvider _dataProvider;
public register_test()
{
_dataProvider = new DpapiDataProtectionProvider("paracours");
_userStore = new Mock<IUserStore<ApplicationUser>>();
_userManagerMock = new Mock<ApplicationUserManager>(_userStore.Object, _dataProvider);
_registerService = new RegisterService(_userManagerMock.Object);
}
[Fact]
public async Task register_sucess()
{
ApplicationUser user = new ApplicationUser() { Email = "user1#test.fr", UserName = "user1#test.fr" };
_userManagerMock.Setup(u => u.CreateAsync(It.IsAny<ApplicationUser>(), It.IsAny<string>()))
.ReturnsAsync(IdentityResult.Success)
.Callback(() => user.Id = "0f8fad5b-d9cb-469f-a165-70867728950e");
var result = await _registerService.RegisterAsync(user);
_userManagerMock.Verify(x =>
x.CreateAsync(
It.Is<ApplicationUser>(u => u.Email == "user1#test.fr"),
It.Is<string>(pass => pass == "P#ssword1")));
Assert.NotNull(result);
Assert.Equal(user.Id, "0f8fad5b-d9cb-469f-a165-70867728950e");
}
[Fact]
public void email_token_generation_success()
{
_userManagerMock.Setup(u => u.FindByIdAsync(It.IsAny<string>()))
.ReturnsAsync(new ApplicationUser() { Email = "user1#test.fr", UserName = "user1#test.fr", EmailConfirmed = false });
var result = _registerService.EmailToken("0f8fad5b-d9cb-469f-a165-70867728950e");
Assert.NotNull(result);
}
}
My service :
public class RegisterService : IRegisterService
{
private readonly ApplicationUserManager _userManager;
public RegisterService() { }
public RegisterService(ApplicationUserManager userManager)
{
_userManager = userManager;
}
public virtual async Task<IdentityResult> RegisterAsync(ApplicationUser user)
{
return await _userManager.CreateAsync(user, "P#ssword1");
}
public virtual string EmailToken(string userId)
{
return _userManager.GenerateEmailConfirmationToken(userId);
}
}
My Debug configuration:
uncheck Debug only my code
check activate soupport source server
Debug Symbol
Symbols Microsoft Serveur
with (http:// before)
srv.symbolsource.org/pdb/MyGet
referencesource.microsoft.com/symbols
msdl.microsoft.com/download/symbols
msdl.microsoft.com/download/symbols
I do this :
Put a break point on :
public virtual string EmailToken(string userId){
return _userManager.GenerateEmailConfirmationToken(userId);
}
When I touch F11, it'go to :
using System;
using System.Collections.Generic;
using System.Security.Claims;
namespace Microsoft.AspNet.Identity
{
/// <summary>
/// Extension methods for UserManager
/// </summary>
public static class UserManagerExtensions
{
...
/// <summary>
/// Get the confirmation token for the user
/// </summary>
/// <param name="manager"></param>
/// <param name="userId"></param>
/// <returns></returns>
public static string GenerateEmailConfirmationToken<TUser, TKey>(this UserManager<TUser, TKey> manager,
TKey userId)
where TKey : IEquatable<TKey>
where TUser : class, IUser<TKey>
{
if (manager == null)
{
throw new ArgumentNullException("manager");
}
return AsyncHelper.RunSync(() => manager.GenerateEmailConfirmationTokenAsync(userId));
}
...
}
}
I don't know how to debug :
manager.GenerateEmailConfirmationTokenAsync(userId)
inside
AsyncHelper.RunSync(() =>
Please i need held , it's new for me Task and debug

I solve myself my problem.
When i mock ApplicationUserManager with :
new Mock(_userStore.Object, _dataProvider);
It's create a Castle.Proxie for GenerateEmailConfirmationToken => that couldn't be resolve in the symbol (.pdb)
The solution is to not mock ApplicationUserManager

Related

Xamarin.InAppBilling Android error: Your order could not be processed. Please try again

I am trying to implement in-app purchases, and have followed the documentation to the letter.
The app was published in the store with in-app purchases enabled. Our store account has active products and subscriptions, but trying to buy with ~20 different accounts, we all get "Your order could not be processed. Please try again". after inputting credit card info.
I triple checked our public key for the store and our purchases IDs. Using the Google test IDs, the app works. In-app purchases worked ~6 months ago.
These are the 2 errors I see in my device log:
purchasefragment error purchaseerror type 2 subtype 0
unexpected response code 500 for https://android.clients.google.com/fdfe/ees/commitPurchase
We have written the app in Xamarin and are using the Xamarin.InAppBilling component.
private InAppBillingServiceConnection _serviceConnection;
private IEnumerable<Product> _availableProducts;
//public event EventHandler<PurchaseCanceledEventArgs> PurchaseCanceled;
public event EventHandler<PurchaseFailedEventArgs> PurchaseFailed;
public event EventHandler<PurchaseSucceededEventArgs> PurchaseSucceeded;
public void Buy(string productId)
{
if (_serviceConnection.Connected)
{
if (_availableProducts != null && _availableProducts.Any())
{
var product = _availableProducts.FirstOrDefault(x => x.ProductId.Equals(productId));
if (product != null)
{
_serviceConnection.BillingHandler.BuyProduct(product);
}
}
}
}
public PurchaseProduct GetProduct(string productId)
{
return null;
}
public bool HasSubscriptionFor(string productIdentifier)
{
if (_serviceConnection?.BillingHandler != null)
{
return _serviceConnection.BillingHandler.GetPurchases(ItemType.Subscription).Any(x => x.ProductId == productIdentifier);
}
return false;
}
public void RestorePreviousPurchases()
{
// Restore not required for google purchases (?)
}
public void Disconnect()
{
try
{
_serviceConnection?.Disconnect();
}
catch (Exception ex)
{
}
}
public void Connect(Activity activity)
{
try
{
_serviceConnection = new InAppBillingServiceConnection(activity, "our public key");
_serviceConnection.OnConnected += OnConnected;
_serviceConnection.Connect();
}
catch (Exception ex)
{
}
}
private async void OnConnected()
{
await Task.Run(async () =>
{
if (_serviceConnection?.BillingHandler != null)
{
_serviceConnection.OnInAppBillingError += OnInAppBillingError;
_serviceConnection.BillingHandler.OnProductPurchased += BillingHandlerOnOnProductPurchased;
_serviceConnection.BillingHandler.OnProductPurchasedError += BillingHandlerOnOnProductPurchasedError;
_serviceConnection.BillingHandler.BuyProductError += BillingHandlerOnBuyProductError;
// Test in sandbox mode only
//_availableProducts = await _serviceConnection.BillingHandler.QueryInventoryAsync(new List<string>
//{
// ReservedTestProductIDs.Purchased,
// ReservedTestProductIDs.Refunded,
// ReservedTestProductIDs.Canceled,
// ReservedTestProductIDs.Unavailable
//}, ItemType.Product);
var products = await _serviceConnection.BillingHandler.QueryInventoryAsync(_purchaseConfiguration.Products, ItemType.Product);
var subscriptions = await _serviceConnection.BillingHandler.QueryInventoryAsync(_purchaseConfiguration.Subscriptions, ItemType.Subscription);
_availableProducts = new List<Product>();
if (products?.Any() == true)
{
_availableProducts = _availableProducts.Concat(products);
}
if (subscriptions?.Any() == true)
{
_availableProducts = _availableProducts.Concat(subscriptions);
}
}
});
}
public void HandleResult(int requestCode, object resultCode, object data)
{
_serviceConnection.BillingHandler.HandleActivityResult(requestCode, (Result)resultCode, (Intent)data);
}
private void BillingHandlerOnBuyProductError(int responseCode, string sku)
{
PurchaseFailed?.Invoke(this, new PurchaseFailedEventArgs { Message = "BillingHandlerOnBuyProductError: " + sku });
}
private void BillingHandlerOnOnProductPurchasedError(int responseCode, string sku)
{
PurchaseFailed?.Invoke(this, new PurchaseFailedEventArgs { Message = "BillingHandlerOnBuyProductError: " + sku });
}
private void BillingHandlerOnOnProductPurchased(int response, Purchase purchase, string purchaseData, string purchaseSignature)
{
PurchaseSucceeded?.Invoke(this, new PurchaseSucceededEventArgs(purchase.ProductId));
}
private void OnInAppBillingError(InAppBillingErrorType error, string message)
{
if (!string.IsNullOrEmpty(message))
{
PurchaseFailed?.Invoke(this, new PurchaseFailedEventArgs { Message = message });
}
}
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" android:versionCode="1" android:versionName="3.0.14" package="">
<uses-sdk android:minSdkVersion="17" android:targetSdkVersion="23" />
<application android:label="" android:icon="#drawable/ic_launcher" android:theme="#style/ApplicationBaseTheme" android:largeHeap="true" android:allowBackup="false">
<receiver android:name="com.google.android.gms.gcm.GcmReceiver" android:exported="true" android:permission="com.google.android.c2dm.permission.SEND">
<intent-filter>
<action android:name="com.google.android.c2dm.intent.RECEIVE" />
<category android:name="%PACKAGE_NAME%" />
</intent-filter>
</receiver>
<intent-filter>
<action android:name="com.google.android.c2dm.intent.RECEIVE" />
</intent-filter>
</service>
<service android:name="com.pushwoosh.GCMInstanceIDListenerService" android:exported="false">
<intent-filter>
<action android:name="com.google.android.gms.iid.InstanceID" />
</intent-filter>
</service>
<meta-data android:name="com.facebook.sdk.ApplicationId" android:value="#string/facebook_app_id" />
<meta-data android:name="com.facebook.sdk.ApplicationName" android:value="#string/facebook_app_name" />
</application>
<uses-permission android:name="com.android.vending.BILLING" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.VIBRATE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.DOWNLOAD_WITHOUT_NOTIFICATION" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<permission android:name="%PACKAGE_NAME%.permission.C2D_MESSAGE" android:protectionLevel="signature" />
<uses-permission android:name="%PACKAGE_NAME%.permission.C2D_MESSAGE" />
<uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />
<!--for Samsung-->
<uses-permission android:name="com.sec.android.provider.badge.permission.READ"/>
<uses-permission android:name="com.sec.android.provider.badge.permission.WRITE"/>
<!--for htc-->
<uses-permission android:name="com.htc.launcher.permission.READ_SETTINGS"/>
<uses-permission android:name="com.htc.launcher.permission.UPDATE_SHORTCUT"/>
<!--for sony-->
<uses-permission android:name="com.sonyericsson.home.permission.BROADCAST_BADGE"/>
<!--for apex-->
<uses-permission android:name="com.anddoes.launcher.permission.UPDATE_COUNT"/>
<!--for solid-->
<uses-permission android:name="com.majeur.launcher.permission.UPDATE_BADGE"/>
</manifest>

Wearable.MessageApi.sendMessage returning Success but onMessageReceived is not calling

Working on Wear application, I have created Wear application with Mobile and wear applications. Sending data from mobile application, through "MessageApi.SendMessageResult" and returning status is SUCCESS but message is not received in wear application. Please find the code in below and let me know i am missing any thing.
Mobile App Code:
public class MainActivity extends Activity implements GoogleApiClient.ConnectionCallbacks {
private static final String START_ACTIVITY = "/start_activity";
private static final String WEAR_MESSAGE_PATH = "/message";
private GoogleApiClient mApiClient;
private ArrayAdapter<String> mAdapter;
private ListView mListView;
private EditText mEditText;
private Button mSendButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
init();
initGoogleApiClient();
}
private void initGoogleApiClient() {
mApiClient = new GoogleApiClient.Builder( this )
.addApi( Wearable.API )
.build();
mApiClient.connect();
}
#Override
protected void onDestroy() {
super.onDestroy();
mApiClient.disconnect();
}
private void init() {
mListView = (ListView) findViewById( R.id.list_view );
mEditText = (EditText) findViewById( R.id.input );
mSendButton = (Button) findViewById( R.id.btn_send );
mAdapter = new ArrayAdapter<String>( this, android.R.layout.simple_list_item_1 );
mListView.setAdapter( mAdapter );
mSendButton.setOnClickListener( new View.OnClickListener() {
#Override
public void onClick(View view) {
String text = mEditText.getText().toString();
if (!TextUtils.isEmpty(text)) {
mAdapter.add(text);
mAdapter.notifyDataSetChanged();
sendMessage(WEAR_MESSAGE_PATH, text);
}
}
});
}
private void sendMessage( final String path, final String text ) {
new Thread( new Runnable() {
#Override
public void run() {
//Previous code
NodeApi.GetConnectedNodesResult nodes = Wearable.NodeApi.getConnectedNodes( mApiClient ).await();
Log.d("MessageAPI","nodes :: "+nodes);
for(com.google.android.gms.wearable.Node node : nodes.getNodes()) {
Log.d("MessageAPI","nodes for :: "+node);
MessageApi.SendMessageResult result = Wearable.MessageApi.sendMessage(
mApiClient, node.getId(), path, text.getBytes() ).await();
Log.d("MessageAPI","node.getId() : "+node.getId());
Log.d("MessageAPI","text.getBytes() : "+text.getBytes());
Log.d("MessageAPI","path : "+path);
Log.d("MessageAPI","nodes result Status:: "+result.getStatus().isSuccess());
}
/*PutDataMapRequest putDMR = PutDataMapRequest.create(path);
putDMR.getDataMap().putAll(getDatMap());
PutDataRequest request = putDMR.asPutDataRequest();
DataApi.DataItemResult result = Wearable.DataApi.putDataItem(mApiClient, request).await();
if (result.getStatus().isSuccess()) {
Log.v("MessageAPI", "nodes DataMap: " + getDatMap() + " sent successfully to data layer ");
} else {
// Log an error
Log.v("MessageAPI", "nodes ERROR: failed to send DataMap to data layer");
}*/
runOnUiThread( new Runnable() {
#Override
public void run() {
mEditText.setText( "" );
}
});
}
}).start();
}
#Override
public void onConnected(Bundle bundle) {
sendMessage(START_ACTIVITY, "Wear my TEST MESSAGE");
}
#Override
public void onConnectionSuspended(int i) {
}
private DataMap getDatMap(){
DataMap dataMap = new DataMap();
dataMap.putLong("time", new Date().getTime());
dataMap.putString("hole", "1");
dataMap.putString("front", "250");
dataMap.putString("middle", "260");
dataMap.putString("back", "270");
return dataMap;
}
}
Mobile App manifest:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.ptrprograms.wearmessageapi" >
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<meta-data android:name="com.google.android.gms.version" android:value="#integer/google_play_services_version" />
<activity
android:name=".MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
wearApp Code
public class WearMessageListenerService extends WearableListenerService {
private static final String START_ACTIVITY = "/start_activity";
#Override
public void onMessageReceived(MessageEvent messageEvent) {
Log.d("MessageAPI","onMessageReceived :: "+ messageEvent.getPath());
/* if( messageEvent.getPath().equalsIgnoreCase( START_ACTIVITY ) ) {
Intent intent = new Intent( this, MainActivity.class );
intent.addFlags( Intent.FLAG_ACTIVITY_NEW_TASK );
startActivity( intent );
} else {
super.onMessageReceived(messageEvent);
}*/
showToast("onMessageReceived:: "+messageEvent.getPath());
Intent intent = new Intent( this, MainActivity.class );
intent.addFlags( Intent.FLAG_ACTIVITY_NEW_TASK );
startActivity( intent );
}
private void showToast(String message) {
Toast.makeText(this, message, Toast.LENGTH_LONG).show();
}
#Override
public void onDataChanged(DataEventBuffer dataEventBuffer) {
super.onDataChanged(dataEventBuffer);
Log.d("MessageAPI","onMessageReceived : onDataChanged: ");
}
}
wearApp manifest:
<?xml version="1.0" encoding="utf-8"?>
<uses-feature android:name="android.hardware.type.watch" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#android:style/Theme.DeviceDefault" >
<meta-data android:name="com.google.android.gms.version" android:value="#integer/google_play_services_version" />
<activity
android:name=".MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<!-- <service android:name=".WearMessageListenerService">
<intent-filter>
<action android:name="com.google.android.gms.wearable.BIND_LISTENER" />
</intent-filter>
</service>-->
<service android:name=".WearMessageListenerService">
<action android:name="com.google.android.gms.wearable.MESSAGE_RECEIVED" />
<action android:name="com.google.android.gms.wearable.DATA_CHANGED" />
<data android:scheme="wear" android:host="*" android:pathPrefix="/prefix" />
<!--<data android:scheme="wear" android:host="*"
android:path="/start_activity" />-->
<!--<action android:name="com.google.android.gms.wearable.CAPABILITY_CHANGED" />
<action android:name="com.google.android.gms.wearable.CHANNEL_EVENT" />-->
<!-- <data android:scheme="wear" android:host="*" android:path="/start_activity" />-->
</service>
</application>
1) Problem is in wearApp in WearMessageListenerService. You don't call
super.onMessageReceived(messageEvent);
i.e you consume all messages. When you call super method you pass message to Wearable.MessageApi.addListener(...
2) I don't see in your wear app that you register MessageApi listener.
3) You mix MessageApi with Data Layer api.
4) In wear app in Main activity you need connect with google play services too. To register MessageApi listener in onConnected method.
5) Please check https://github.com/mariopce/android-wear-bilateral-communication.
This is example of using MessageApi for 2-way communication (mobile-wear-mobile)

Xamarin - GCM OnMessageReceived method not called

I'm able to get the registration token id from gcm but my problem is that when i send the message to the client app i don't receive it on Xamarin Android Player. I followed the example on this site : https://developer.xamarin.com/guides/cross-platform/application_fundamentals/notifications/android/remote_notifications_in_android/
Here is my code :
MainActivity.cs
[Activity(Label = "ResApp", MainLauncher = true, Icon = "#drawable/icon")]
public class MainActivity : Activity
{
TextView msgText;
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
// Set our view from the "main" layout resource
SetContentView(Resource.Layout.Main);
msgText = FindViewById<TextView>(Resource.Id.msgText);
if (IsPlayServicesAvailable()) //this check if google play is installed
{
var intent = new Intent(this, typeof(RegistrationIntentService));
StartService(intent);
}
}
public bool IsPlayServicesAvailable()
{
int resultCode = GoogleApiAvailability.Instance.IsGooglePlayServicesAvailable(this);
if (resultCode != ConnectionResult.Success)
{
if (GoogleApiAvailability.Instance.IsUserResolvableError(resultCode))
msgText.Text = GoogleApiAvailability.Instance.GetErrorString(resultCode);
else
{
msgText.Text = "Sorry, this device is not supported";
Finish();
}
return false;
}
else
{
msgText.Text = "Google Play Services is available.";
return true;
}
}
}
RegistrationIntentService.cs
[Service(Exported = false)]
class RegistrationIntentService : IntentService
{
static object locker = new object();
public RegistrationIntentService() : base("RegistrationIntentService") { }
protected override void OnHandleIntent(Intent intent)
{
try
{
Log.Info("RegistrationIntentService", "Calling InstanceID.GetToken");
lock (locker)
{
var SenderID = "xxxxx";
var instanceID = InstanceID.GetInstance(this);
var token = instanceID.GetToken(SenderID, GoogleCloudMessaging.InstanceIdScope, null);
Log.Info("RegistrationIntentService", "GCM Registration Token: " + token);
SendRegistrationToAppServer(token);
Subscribe(token);
}
}
catch (Exception e)
{
Log.Debug("RegistrationIntentService", "Failed to get a registration token");
return;
}
}
void SendRegistrationToAppServer(string token)
{
// Add custom implementation here as needed.
}
void Subscribe(string token)
{
var pubSub = GcmPubSub.GetInstance(this);
pubSub.Subscribe(token, "/topics/global", null);
}
}
InstanceIdListenerService.cs
[Service(Exported = false), IntentFilter(new[] { "com.google.android.gms.iid.InstanceID" })]
class MyInstanceIDListenerService : InstanceIDListenerService
{
public override void OnTokenRefresh()
{
var intent = new Intent(this, typeof(RegistrationIntentService));
StartService(intent);
}
}
GcmListenerService.cs
[Service(Exported = false), IntentFilter(new[] { "com.google.android.c2dm.intent.RECEIVE" })]
public class MyGcmListenerService : GcmListenerService
{
public override void OnMessageReceived(string from, Bundle data)
{
var message = data.GetString("message");
Log.Debug("MyGcmListenerService", "From: " + from);
Log.Debug("MyGcmListenerService", "Message: " + message);
SendNotification(message);
}
void SendNotification(string message)
{
var intent = new Intent(this, typeof(MainActivity));
intent.AddFlags(ActivityFlags.ClearTop);
var pendingIntent = PendingIntent.GetActivity(this, 0, intent, PendingIntentFlags.OneShot);
var notificationBuilder = new Notification.Builder(this)
//.SetSmallIcon(Resource.Drawable.ic_stat_ic_notification)
.SetContentTitle("GCM Message")
.SetContentText(message)
.SetAutoCancel(true)
.SetContentIntent(pendingIntent);
var notificationManager = (NotificationManager)GetSystemService(Context.NotificationService);
notificationManager.Notify(0, notificationBuilder.Build());
}
}
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="co.za.resapp" android:versionCode="1" android:versionName="1.0" android:installLocation="auto">
<uses-sdk android:minSdkVersion="11" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<application android:label="ResApp"></application>
<uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="co.za.resapp.permission.C2D_MESSAGE" />
<uses-permission android:name="android.permission.GET_ACCOUNTS" />
<uses-permission android:name="android.permission.GET_ACCOUNTS_PRIVILEGED" />
<permission android:name="co.za.resapp.permission.C2D_MESSAGE" android:protectionLevel="signature" />
<application android:label="CodeLog">
<receiver android:name="com.google.android.gms.gcm.GcmReceiver" android:exported="true" android:permission="com.google.android.c2dm.permission.SEND">
<intent-filter>
<action android:name="com.google.android.c2dm.intent.RECEIVE" />
<action android:name="com.google.android.c2dm.intent.REGISTRATION" />
<category android:name="co.za.resapp" />
</intent-filter>
</receiver>
</application>
</manifest>
Send Message from Server
var jGcmData = new JObject();
var jData = new JObject();
jData.Add("message", MESSAGE);
jGcmData.Add("to", "/topics/global");
jGcmData.Add("data", jData);
var url = new Uri("https://gcm-http.googleapis.com/gcm/send");
try
{
using (var client = new HttpClient())
{
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.TryAddWithoutValidation("Authorization", "key=" + API_KEY);
Task.WaitAll(client.PostAsync(url,
new StringContent(jGcmData.ToString(), Encoding.Default, "application/json"))
.ContinueWith(response =>
{
Console.WriteLine(response);
Console.WriteLine("Message sent: check the client device notification tray.");
}));
}
}
catch (Exception ex)
{
Console.WriteLine("Unable to send GCM message:");
Console.Error.WriteLine(ex.StackTrace);
}
It seems like there was a problem in the manifest file. I pasted this new code in the manifest code and the program worked :
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="co.za.resapp" android:versionCode="1" android:versionName="1.0" android:installLocation="auto">
<uses-sdk android:minSdkVersion="11" />
<application android:label="GCM_ANDROID">
<receiver android:name="com.google.android.gms.gcm.GcmReceiver" android:exported="true" android:permission="com.google.android.c2dm.permission.SEND">
<intent-filter>
<action android:name="com.google.android.c2dm.intent.RECEIVE" />
<action android:name="com.google.android.c2dm.intent.REGISTRATION" />
<category android:name="co.za.resapp" />
</intent-filter>
</receiver>
</application>
<uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="co.za.resapp.permission.C2D_MESSAGE" />
</manifest>

DbContext not getting inteliisense for SaveChanges()

I am using Entity Framework 6.0.2 and Oracle 11g.
I am trying to Add,Update and Delete objects using entity framework.
I am not getting intellisense for SaveChanges(),Remove(),Add() methods.
What references are required to get these.
I have added the following in packages.config.
here is my package.Config.
<packages>
<package id="EntityFramework" version="6.0.2" targetFramework="net45" />
<package id="odp.net.x64" version="112.3.20" targetFramework="net45" />
<package id="Oracle.DataAccess.x86" version="2.112.1.0" targetFramework="net45" />
<package id="Oracle.ManagedDataAccess" version="12.1.021" targetFramework="net45" />
<package id="Oracle.ManagedDataAccess.EntityFramework" version="12.1.021" targetFramework="net45" />
</packages>
Here is my DbContext.
public class OLADBContext:DbContext,IOLADBContext
{
protected static string m_connectionString = "";
public static OLADBContext Create()
{
ConnectionStringSettings dbSettings = ConfigurationManager.ConnectionStrings["OracleDbContext"];
if (dbSettings != null)
{
m_connectionString = dbSettings.ConnectionString;
}
return new OLADBContext(m_connectionString);
}
public OLADBContext(string connectionString)
: base(connectionString)
{
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.HasDefaultSchema("HRMS2");
modelBuilder.Configurations.Add(new EmployeeMapper());
modelBuilder.Configurations.Add(new EmpAuthMapper());
modelBuilder.Configurations.Add(new SpecialPrivilegesMapper());
modelBuilder.Configurations.Add(new ProbationDetailsMapper());
base.OnModelCreating(modelBuilder);
}
public DbSet<Employee> Employes { get; set; }
public DbSet<EmpAuthentication> Authentication { get; set; }
public DbSet<SpecialPrivileges> SpecialPrivilege { get; set; }
public DbSet<ProbationDetails> ProbationDetails { get; set; }
}
here is my code:
public void CheckEmployeeExists(string EmpId)
{
var userType="N";
var authenticationDetails = _olaDbContext.Authentication.Where(a => a.IsEnabled == "Y" && a.EmployeeId == EmpId).FirstOrDefault();
if (authenticationDetails == null)
{
var emp = _olaDbContext.Employes.Where(e=>e.EmployeeId==EmpId).FirstOrDefault();
if (emp != null)
{
if (emp.IsManager == "Y")
userType = "T";
else if (emp.Designation.ToUpper().Contains("HR EXEC") || emp.Designation_Id == 447)
{
userType = "H";
}
else if (emp.Designation.Contains("Time Office"))
{
userType = "A";
}
var probationDetails = _olaDbContext.ProbationDetails.Where(p => p.EmployeeId == EmpId);
ProbationDetails oprob = new ProbationDetails();
oprob.EmployeeId = "16785";
oprob.ProbatoionPeriod = 3;
_olaDbContext.ProbationDetails.Add(oprob);
}
}
}
Please let me know how can i acheive?
I got it fixed.
I am doing the mistake instead of referencing the OLADbConext directly I am referencing the IOLADbContext in my class
public class OLADBContext:DbContext,IOLADBContext
{
}
i have commented the code referencing the interface and used directly the class
public class OLADataProvider:IOLADataProvider
{
// private IOLADBContext _olaDbContext;
private OLADBContext _olaDbContext;
public OLADataProvider(OLADBContext olaDbContext)
{
if (olaDbContext == null)
throw new ArgumentNullException("olaDbContext is Null");
//_olaDbContext = olaDbContext;
_olaDbContext = olaDbContext;
}

Displaying JSON data in dropdown list in struts2

I was doing good with my code. But i am struck at one problem. I want to populate the json data in my select box in struts2.
What i am doing is..i am sending the ajax request on the click of button and displaying the form.
Form is initially has property display none. when i click on the button it changes to block.
But there is one error coming whenever i am opening my jsp page into the browser.
The requested list key 'categories' could not be resolved as a
collection
my struts.xml
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd"> <struts> <constant name="struts.custom.i18n.resources" value="LoginAction" />
<package name="default" extends="struts-default" namespace="/">
<action name="Login" class="com.agents.cb.LoginAction" >
<result name="success" type="redirect">Welcome.jsp</result>
<result name="input">login.jsp</result>
</action>
<action name="Register" method="register" class="com.agents.cb.LoginAction" >
<result name="success">login.jsp</result>
</action>
</package>
<package name="admin" extends="json-default" namespace="/admin">
<action name="addCategory" method="addCategory" class="com.type.user.Admin" >
<result type="json">
<param name="excludeNullProperties">true</param>
<param name="excludeProperties">
catName,catCode
</param>
</result>
</action>
<action name="categories" method="categories" class="com.type.user.Admin" >
<result type="json">
<param name="excludeNullProperties">true</param>
<param name="excludeProperties">
catName,catCode,status
</param>
</result>
</action>
</package> </struts>
Admin.java file
package com.type.user;
import java.io.PrintWriter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.opensymphony.xwork2.ActionSupport;
import java.util.List;
import java.util.ArrayList;
import java.util.Map;
import java.util.HashMap;
import com.type.product.*;
public class Admin extends ActionSupport {
private String catCode;
private String catName;
private HttpServletRequest request;
private Map<String, String> categories = new HashMap<String, String>();;
private String status;
public Map<String, String> getCategories() {
return categories;
}
public void setCategories(Map<String, String> categories) {
this.categories = categories;
}
public void setServletRequest(HttpServletRequest request) {
this.request = request;
}
public String getCatCode() {
return catCode;
}
public void setCatCode(String catCode) {
this.catCode = catCode;
}
public String getCatName() {
return catName;
}
public void setCatName(String catName) {
this.catName = catName;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String addCategory() {
Product prod = new Product();
boolean flag = prod.addCat(catCode, catName);
//boolean flag=false;
if (flag) {
status=catName+" added successfully.";
return SUCCESS;
} else {
status="Error occurred while adding "+catName;
return SUCCESS;
}
}
public String categories(){
System.out.println("step 1");
Product prod=new Product();
categories=prod.getAllCategories();
return SUCCESS;
}
}
my script on jsp page
$(".add_sub_category").click(function(e){
e.preventDefault();
$.ajax({
url : '/Login/admin/categories',
type : 'POST',
dataType : 'json',
sucess : function(resp) {
console.log(resp);
}
});
});
Please help. Where i am doing wrong? and why i have this problem.
You declared this
<package name="admin" extends="json-default" namespace="/admin">
<action name="categories" method="categories" class="com.type.user.Admin" >
but you are trying to call it at
url : '/Login/admin/categories',
change it to the path you declared:
url : '/admin/categories',
because Login is not defined anywhere as part of the namespace.
Also pay attention when playing with different namespaces...
Hope that helps

Resources