plain text with share option list gives error - c#

Okay so i have a weird error here that i can't figure out. I am sharing data with share option list in android "android.intent.action.SEND".
Sharing single image works perfectly, but when i try to share just plain text such as "asdfdgdsfsa", the program throws this error
"Java.Lang.RuntimeException: Unable to instantiate activity
ComponentInfo{com.companyname.Revamp/Revamp.RecieveDataFromApp.RecieveDataFromApp}:
java.lang.ClassNotFoundException: Didn't find class
"Revamp.RecieveDataFromApp.RecieveDataFromApp" on path:
DexPathList[[zip file
"/data/app/com.companyname.Revamp-HFm6SmD1Y-A76OQwcwCXIA==/base.apk"],nativeLibraryDirectories=[/data/app/com.companyname.Revamp-HFm6SmD1Y-A76OQwcwCXIA==/lib/x86,
/system/fake-libs,
/data/app/com.companyname.Revamp-HFm6SmD1Y-A76OQwcwCXIA==/base.apk!/lib/x86,
/system/lib, /vendor/lib]] ".
protected override void OnCreate(Bundle bundle)
{
Intent intent = Intent;
String action = Intent.Action;
String type = intent.Type;
if (Intent.ActionSend.Equals(action) && type != null)
{
// This is what we are trying to get working here.
if ("text/plain".Equals(type))
{
// Handle text being sent
// ...
// ...
// ...
}
else if (type.StartsWith("image/"))
{
// Handle single image being sent
// ...
// ...
// ...
}
}
else if (Intent.ActionSendMultiple.Equals(action) && type != null)
{
//This works
if (type.StartsWith("image/"))
{
// Handle multiple images being sent
// ...
// ...
// ...
}
}
else
{
// Handle other intents, such as being started from the home screen
}
TabLayoutResource = Resource.Layout.Tabbar;
ToolbarResource = Resource.Layout.Toolbar;
base.OnCreate(bundle);
global::Xamarin.Forms.Forms.Init(this, bundle);
LoadApplication(new App());
}
<activity android:name="Revamp.RecieveDataFromApp.RecieveDataFromApp" android:icon="#drawable/ic_home">
<intent-filter>
<action android:name="android.intent.action.SEND" />
<category android:name="android.intent.category.DEFAULT" />
<data android:mimeType="image/*" />
</intent-filter>
<intent-filter>
<action android:name="android.intent.action.SEND" />
<category android:name="android.intent.category.DEFAULT" />
<data android:mimeType="text/plain" />
</intent-filter>
<intent-filter>
<action android:name="android.intent.action.SEND_MULTIPLE" />
<category android:name="android.intent.category.DEFAULT" />
<data android:mimeType="image/*" />
</intent-filter>
<intent-filter>
<action android:name="android.intent.action.GET_CONTENT" />
<category android:name="android.intent.category.DEFAULT" />
<data android:mimeType="*/*" />
</intent-filter>
</activity>

I have tested your code and reproduce the issue. You could try to set the intent-filter in code, not in AndroidManifest.xml.
For example:
[Activity(Label = "RecieveDataFromApp", Icon = "#drawable/icon", Theme = "#style/MainTheme", MainLauncher = true, ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation)]
[IntentFilter(new[] { Intent.ActionSend }, Categories = new[] { Intent.CategoryDefault }, DataMimeType = "image/*", Label = "RecieveDataFromApp")]
[IntentFilter(new[] { Intent.ActionSend }, Categories = new[] { Intent.CategoryDefault }, DataMimeType = "text/plain", Label = "RecieveDataFromApp")]
[IntentFilter(new[] { Intent.ActionSendMultiple }, Categories = new[] { Intent.CategoryDefault }, DataMimeType = "image/*", Label = "RecieveDataFromApp")]
public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsAppCompatActivity
{
...
...
...
}

Related

Repeating Notifications Lost After Android Device Reboot Xamarin Forms App C#

I am working on a Xamarin Forms app in C#. I followed this tutorial to setup local notifications that are repeating:
https://www.c-sharpcorner.com/article/how-to-send-local-notification-with-repeat-interval-in-xamarin-forms/
For the most part everything works with regards to the notifications firing. However if I reboot the device I no longer get any notifications.
Here is my broadcast receiver class:
[BroadcastReceiver(Enabled = true, Label = "Local Notifications Broadcast Receiver")]
[IntentFilter(new[] { Intent.ActionBootCompleted })]
public class ScheduledAlarmHandler : BroadcastReceiver
{
public const string LocalNotificationKey = "LocalNotification";
NotificationManager manager;
const string channelId = "default";
const string channelName = "Default";
const string channelDescription = "The default channel for notifications.";
public const string TitleKey = "title";
public const string MessageKey = "message";
bool channelInitialized = false;
public override void OnReceive(Context context, Intent intent)
{
if (!channelInitialized)
{
CreateNotificationChannel();
}
ComponentName receiver = new ComponentName(AndroidApp.Context, Class.FromType(typeof(ScheduledAlarmHandler)).Name);
PackageManager pm = AndroidApp.Context.PackageManager;
pm.SetComponentEnabledSetting(receiver, ComponentEnabledState.Enabled, ComponentEnableOption.DontKillApp);
var extra = intent.GetStringExtra(LocalNotificationKey);
var notification = DeserializeNotification(extra);
// Generating notification
var builder = new NotificationCompat.Builder(AndroidApp.Context, channelId)
.SetContentTitle(notification.Title)
.SetContentText(notification.Body)
.SetSmallIcon(notification.IconId)
.SetSound(RingtoneManager.GetDefaultUri(RingtoneType.Ringtone))
.SetAutoCancel(true);
var resultIntent = AndroidNotificationManager.GetLauncherActivity();
resultIntent.SetFlags(ActivityFlags.NewTask | ActivityFlags.ClearTask);
var stackBuilder = Android.Support.V4.App.TaskStackBuilder.Create(AndroidApp.Context);
stackBuilder.AddNextIntent(resultIntent);
Random random = new Random();
int randomNumber = random.Next(9999 - 1000) + 1000;
var resultPendingIntent =
stackBuilder.GetPendingIntent(randomNumber, (int)PendingIntentFlags.CancelCurrent);
builder.SetContentIntent(resultPendingIntent);
// Sending notification
var notificationManager = NotificationManagerCompat.From(AndroidApp.Context);
var notificationToNotify = builder.Build();
notificationManager.Notify(randomNumber, notificationToNotify);
}
private LocalNotification DeserializeNotification(string notificationString)
{
var xmlSerializer = new XmlSerializer(typeof(LocalNotification));
using (var stringReader = new StringReader(notificationString))
{
var notification = (LocalNotification)xmlSerializer.Deserialize(stringReader);
return notification;
}
}
void CreateNotificationChannel()
{
manager = (NotificationManager)AndroidApp.Context.GetSystemService(AndroidApp.NotificationService);
if (Build.VERSION.SdkInt >= BuildVersionCodes.O)
{
var channelNameJava = new Java.Lang.String(channelName);
var channel = new NotificationChannel(channelId, channelNameJava, NotificationImportance.Default)
{
Description = channelDescription
};
manager.CreateNotificationChannel(channel);
}
channelInitialized = true;
}
}
The tutorial didn't have the IntentFilter attribute added to the class or updates to the manifest file, but I added those in later while searching for solutions.
Here is my AndroidManifest file:
<manifest xmlns:android="http://schemas.android.com/apk/res/android" android:versionCode="1" android:versionName="1.0" package="com.companyname.service_buddy">
<uses-sdk android:minSdkVersion="21" android:targetSdkVersion="28" />
<application android:label="Service_Buddy.Android"></application>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
<application>
<receiver android:name="ServiceBuddy.Droid.ScheduledAlarmHandler" android:enabled="true" android:permission="android.permission.RECEIVE_BOOT_COMPLETED">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED"></action>
</intent-filter>
</receiver>
</application>
</manifest>```
As far as I know , After rebooting there is no memory ,it is gone , therefor there is nothing to do job .
Don't waste your time , just use Shiny , it is a real problem solver in realm of background and foreground service in xamarin .
shiny getting started

How to Resolve DNN Custom Module Not Rendering?

I'm using DNN 9.3.2 and Chris Hammond's module template to create a custom module. When I load the module onto a page without visibility restrictions, it does not render. The Event Log does not contain any errors after installation or rendering of said page.
Since this is my first DNN MVC module, I'm thinking this has to do with the following controller class I've created:
[DnnHandleError]
public class SignupController : DnnController
{
// GET: Signup
[ModuleAction(ControlKey = "Edit", TitleKey = "AddItem")]
public ActionResult Index()
{
var signups = OnboardingManager.Instance.GetOnboardings(ModuleContext.ModuleId);
return View(signups);
}
[HttpPost]
[DotNetNuke.Web.Mvc.Framework.ActionFilters.ValidateAntiForgeryToken]
public ActionResult Edit(Models.Onboarding onboarding)
{
ProPayService service = new ProPayService();
OnboardingManager.Instance.CreateOnboarding(onboarding);
service.MerchantSignupForProPayAsync();
return RedirectToDefaultRoute();
}
public ActionResult Edit(int onboardingId = -1)
{
DotNetNuke.Framework.JavaScriptLibraries.JavaScript.RequestRegistration(CommonJs.DnnPlugins);
var userlist = UserController.GetUsers(PortalSettings.PortalId);
var users = from user in userlist.Cast<UserInfo>().ToList()
select new SelectListItem { Text = user.DisplayName, Value = user.UserID.ToString() };
ViewBag.Users = users;
var onboarding = (onboardingId == -1) ? new Models.Onboarding{ModuleId = ModuleContext.ModuleId} : OnboardingManager.Instance.GetOnboarding(onboardingId, ModuleContext.ModuleId);
return View(onboarding);
}
}
The service class referenced above is defined as follows:
public class ProPayService
{
private static HttpClient _httpClient = new HttpClient();
//private readonly string _baseUrl = "https://xmltestapi.propay.com/ProPayAPI";
Uri _baseUrl = new Uri("https://xmltestapi/propay.com/ProPayAPI");
public ProPayResponse MerchantSignupForProPayAsync()
{
SignupRequest signupRequest = new SignupRequest();
SignupResponse signupResponse = new SignupResponse();
HttpContent content = new StringContent(signupRequest.ToString());
CancellationToken cancellationToken = new CancellationToken();
var credentials = GetCredentials();
var responseBody = _httpClient.PutAsync(_baseUrl, content, cancellationToken).Result;
try
{
BuildMerchantTestData();
Console.WriteLine(responseBody);
Console.WriteLine(content);
if (WebRequest.Create(_baseUrl) is HttpWebRequest httpRequest)
{
httpRequest.Method = "PUT";
httpRequest.Headers.Add("accept", "applicaiton/json");
httpRequest.Headers.Add("Authorization", credentials);
}
//var httpRequest = new HttpRequestMessage(HttpMethod.Put, _baseUrl);
//httpRequest.Headers.Add("Authorization", credentials);
Console.WriteLine(signupResponse.Status);
}
catch (HttpRequestException e)
{
Console.WriteLine("\nException caught");
Console.WriteLine("Message: {0} ", e.Message);
}
return JsonConvert.DeserializeObject<ProPayResponse>(responseBody.Content.ReadAsStringAsync().Result);
}
private SignupRequest BuildMerchantTestData()
{
int moduleId = 0;
int OnboardingId = 0;
var result = OnboardingManager.Instance.GetOnboarding(OnboardingId, moduleId);
var onboardingList = new List<Models.Onboarding>();
var ownerList = new List<OwnerList>();
SignupRequest signupRequest = new SignupRequest();
if (result != null)
{
Debug.Assert(result != null, nameof(OnboardingList) + " != null");
Console.WriteLine("{0} {1}", result.Email, result.UserId);
List<Owner> owner1 = new List<Owner>
{
new Owner
{
FirstName = result.OwnerFirstName,
LastName = result.OwnerLastName,
Address = result.OwnerAddress,
City = result.OwnerCity,
State = result.OwnerRegion,
Zip = result.OwnerZipCode,
Country = result.OwnerCountry,
DateOfBirth = result.OwnerDob,
SSN = result.OwnerSsn,
Email = result.Email,
Percentage = result.OwnerPercentage,
Title = result.OwnerTitle
}
};
signupRequest = new SignupRequest
{
PersonalData = new PersonalData
{
FirstName = result.FirstName,
MiddleInitial = result.MiddleInitial,
LastName = result.Lastname,
DateOfBirth = result.DateOfBirth,
SocialSecurityNumber = result.Ssn,
SourceEmail = result.Email,
PhoneInformation =
new PhoneInformation
{ DayPhone = result.DayPhone, EveningPhone = result.EveningPhone },
},
InternationalSignUpData = null,
//InternationalSignUpData = new InternationalSignupData
//{
// DocumentExpDateString = result.DocumentExpDate,
// DocumentIssuingState = result.DocumentIssuingState,
// DocumentType = result.DocumentType,
// DriversLicenseVersion = result.DriversLicenseVersion,
// InternationalId = result.InternationalId,
// MedicareCardColor = result.MedicareCardColor,
// MedicareReferenceNumber = result.MedicareReferenceNumber
//},
NotificationEmail = result.Email,
SignupAccountData = new SignupAccountData
{
CurrencyCode = "USD",
//UserId = result.UserId.ToString(),
//PhonePIN = result.PhonePin,
//ExternalId = "12345",
Tier = "Test"
},
BusinessData =
new BusinessData
{
BusinessLegalName = result.BusinessLegalName,
DoingBusinessAs = result.DoingBusinessAs,
EIN = result.Ein,
MerchantCategoryCode = result.MerchantCategoryCode,
WebsiteURL = result.BusinessUrl,
BusinessDescription = result.BusinessDescription,
MonthlyBankCardVolume = result.MonthlyBankCardVolume ?? 0,
AverageTicket = result.AverageTicket ?? 0,
HighestTicket = result.HighestTicket ?? 0
},
Address = new Address
{
ApartmentNumber = result.Address1ApartmentNumber,
Address1 = result.Address1Line1,
Address2 = result.Address1Line1,
City = result.Address1City,
State = result.Address1State,
Country = result.Address1Country,
Zip = result.Address1ZipCode
},
MailAddress = new Address
{
ApartmentNumber = result.OwnerApartmentNumber,
Address1 = result.OwnerAddress,
Address2 = result.OwnerAddress2,
City = result.OwnerCity,
State = result.OwnerRegion,
Country = result.OwnerCountry,
Zip = result.OwnerZipCode
},
BusinessAddress =
new Address
{
ApartmentNumber = result.BusinessApartmentNumber,
Address1 = result.BusinessAddressLine1,
Address2 = result.BusinessAddressLine2,
City = result.BusinessCity,
State = result.BusinessState,
Country = result.BusinessCountry,
Zip = result.BusinessZipCode
},
//CreditCardData = new CreditCardData
//{
// NameOnCard = result.NameOnCard,
// CreditCardNumber = result.CreditCardNumber, // test card number
// ExpirationDate = result.ExpirationDate
//},
BankAccount =
new BankAccount
{
AccountCountryCode = result.BankAccount1CountryCode,
BankAccountNumber = result.BankAccount1Number,
RoutingNumber = result.BankAccount1RoutingNumber,
AccountOwnershipType = result.BankAccount1OwnershipType,
BankName = result.BankAccount1BankName,
AccountType = "Checking",
//AccountType = result.BankAccount1Type,
AccountName = result.BankAccount1Name,
Description = result.BankAccount1Description
},
//SecondaryBankAccount =
// new BankAccount
// {
// AccountCountryCode = result.BankAccount2CountryCode,
// BankAccountNumber = result.BankAccount2Number,
// RoutingNumber = result.BankAccount2RoutingNumber,
// AccountOwnershipType = result.BankAccount2OwnershipType,
// BankName = result.BankAccount2BankName,
// AccountType = result.BankAccount2Type,
// AccountName = result.BankAccount2Name,
// Description = result.BankAccount2Description
// },
//GrossBillingInformation = new GrossBillingInformation
//{
// GrossSettleAddress = new Address
// {
// Address1 = result.OwnerAddress,
// Address2 = result.OwnerAddress2,
// ApartmentNumber = result.OwnerApartmentNumber,
// City = result.OwnerCity,
// Country = result.OwnerCountry,
// State = result.OwnerRegion,
// Zip = result.OwnerZipCode
// },
// GrossSettleBankAccount = new BankAccount
// {
// AccountCountryCode = "USA",
// AccountName = result.BankAccount1Name,
// AccountOwnershipType = result.BankAccount1OwnershipType,
// AccountType = result.BankAccount1Type,
// BankAccountNumber = result.BankAccount1Number,
// BankName = result.BankAccount1BankName,
// Description = result.BankAccount1Description,
// RoutingNumber = result.BankAccount1RoutingNumber
// },
// GrossSettleCardData = new CreditCardData
// {
// CreditCardNumber = result.CreditCardNumber,
// ExpirationDate = result.ExpirationDate,
// NameOnCard = result.NameOnCard
// }
//},
//FraudDetectionData = new FraudDetectionData
//{
// MerchantSourceIp = result.MerchantSourceIp,
// ThreatMetrixPolicy = result.ThreatMetrixPolicy,
// ThreatMetrixSessionId = result.SessionId
//},
//PaymentMethodId = result.PaymentMethodId,
//PaymentBank = new BankAccount
//{
// AccountName = result.PaymentBankAccountName,
// AccountCountryCode = result.PaymentBankCountryCode,
// AccountOwnershipType = result.PaymentBankOwnershipType,
// AccountType = result.PaymentBankAccountType,
// BankAccountNumber = result.PaymentBankAccountNumber,
// BankName = result.PaymentBankName,
// Description = result.PaymentBankAccountDescription,
// RoutingNumber = result.PaymentBankRoutingNumber
//}
BeneficialOwnerData = new BeneficialOwnerData
{
OwnerCount = "1",
Owners = owner1
}
};
Console.WriteLine(JsonConvert.SerializeObject(signupRequest));
}
//return new SignUpRequest();
return signupRequest;
}
private static string GetCredentials()
{
var termId = "myId"; // put affiliate term id here, if you have it
var certString = "myCert"; // put affiliate cert string here
var encodedCredentials = Convert.ToBase64String(Encoding.Default.GetBytes(certString + ":" + termId));
var credentials = $"Basic {encodedCredentials}";
return credentials;
}
}
The DNN manifest file is defined as follows:
<dotnetnuke type="Package" version="5.0">
<packages>
<package name="Onboarding" type="Module" version="00.00.01">
<friendlyName>Onboarding</friendlyName>
<description>Onboarding</description>
<iconFile>~/Icons/Sigma/Software_32X32_Standard.png</iconFile>
<owner>
<name>SocialBodega.com</name>
<organization>SocialBodega.com</organization>
<url>https://www.socialbodega.com/</url>
<email>info#socialbodega.com</email>
</owner>
<license src="License.txt"></license>
<releaseNotes src="ReleaseNotes.txt"></releaseNotes>
<dependencies>
<dependency type="CoreVersion">08.00.00</dependency>
</dependencies>
<components>
<component type="Script">
<scripts>
<basePath>DesktopModules\MVC\Onboarding</basePath>
<script type="Install">
<path>Providers\DataProviders\SqlDataProvider</path>
<name>00.00.01.SqlDataProvider</name>
<version>00.00.01</version>
</script>
<script type="UnInstall">
<path>Providers\DataProviders\SqlDataProvider</path>
<name>Uninstall.SqlDataProvider</name>
<version>00.00.01</version>
</script>
</scripts>
</component>
<component type="ResourceFile">
<resourceFiles>
<basePath>DesktopModules/MVC/Onboarding</basePath>
<resourceFile>
<name>Resources.zip</name>
</resourceFile>
</resourceFiles>
</component>
<component type="Module">
<desktopModule>
<moduleName>Onboarding</moduleName>
<foldername>Onboarding</foldername>
<businessControllerClass>SocialBodega.Onboarding.Components.FeatureController</businessControllerClass>
<supportedFeatures />
<moduleDefinitions>
<moduleDefinition>
<friendlyName>Onboarding</friendlyName>
<defaultCacheTime>0</defaultCacheTime>
<moduleControls>
<!--<moduleControl>
<controlKey />
<controlSrc>SocialBodega.Onboarding.Controllers/Item/Index.mvc</controlSrc>
<supportsPartialRendering>False</supportsPartialRendering>
<controlTitle />
<controlType>View</controlType>
<iconFile />
<helpUrl />
<viewOrder>0</viewOrder>
</moduleControl>-->
<moduleControl>
<controlKey/>
<controlSrc>SocialBodega.Onboarding.Controllers/Signup/Index.mvc</controlSrc>
<supportPartialRendering>False</supportPartialRendering>
<controlTitle/>
<controlType>View</controlType>
<iconFile/>
<helpUrl/>
<viewOrder>0</viewOrder>
<supportsPopUps>True</supportsPopUps>
</moduleControl>
<moduleControl>
<controlKey>Edit</controlKey>
<controlSrc>SocialBodega.Onboarding.Controllers/Signup/Edit.mvc</controlSrc>
<supportsPartialRendering>False</supportsPartialRendering>
<controlTitle>Edit Signups</controlTitle>
<controlType>Edit</controlType>
<iconFile />
<helpUrl />
<viewOrder>0</viewOrder>
<supportsPopUps>True</supportsPopUps>
</moduleControl>
<moduleControl>
<controlKey>Settings</controlKey>
<controlSrc>SocialBodega.Onboarding.Controllers/Settings/Settings.mvc</controlSrc>
<supportsPartialRendering>False</supportsPartialRendering>
<controlTitle>Onboarding Settings</controlTitle>
<controlType>Edit</controlType>
<iconFile />
<helpUrl />
<viewOrder>0</viewOrder>
</moduleControl>
</moduleControls>
</moduleDefinition>
</moduleDefinitions>
</desktopModule>
</component>
<component type="Assembly">
<assemblies>
<assembly>
<name>Onboarding.dll</name>
<path>bin</path>
</assembly>
</assemblies>
</component>
</components>
</package>
</packages>
</dotnetnuke>
Are there changes I should make to my above controller to ensure that the module renders properly? Or are there other items I should review to further diagnose the issue?
Update:
After making a change to the DNN manifest as per comment, I am now unable to add the module to the page and receive the following in admin log:
AbsoluteURL:
DefaultDataProvider:DotNetNuke.Data.SqlDataProvider, DotNetNuke
ExceptionGUID:e229902b-051f-459e-9647-28adcd0d4f50
AssemblyVersion:
PortalId:-1
UserId:-1
TabId:-1
RawUrl:
Referrer:
UserAgent:
ExceptionHash:OLQuqVQLbGm0IndDqnMOfMf2C3Q=
Message:Error Creating BusinessControllerClass
'SocialBodega.Onboarding.Components.FeatureController, SocialBodega.Onboarding' of module(Onboarding) id=(422) in tab(41) and portal(0)
StackTrace:
at DotNetNuke.Services.Search.ModuleIndexer.ThrowLogError(ModuleInfo module,
Exception ex)
InnerMessage:Value cannot be null. Parameter name: type
InnerStackTrace:
at System.Activator.CreateInstance(Type type, Boolean nonPublic) at
System.Activator.CreateInstance(Type type) at
DotNetNuke.Services.Search.ModuleIndexer.GetModuleList(Int32 portalId)
Source:DotNetNuke
My revised DNN Manifest is listed below:
<dotnetnuke type="Package" version="5.0">
<packages>
<package name="Onboarding" type="Module" version="00.00.01">
<friendlyName>Onboarding</friendlyName>
<description>Onboarding</description>
<iconFile>~/Icons/Sigma/Software_32X32_Standard.png</iconFile>
<owner>
<name>SocialBodega.com</name>
<organization>SocialBodega.com</organization>
<url>https://www.socialbodega.com/</url>
<email>info#socialbodega.com</email>
</owner>
<license src="License.txt"></license>
<releaseNotes src="ReleaseNotes.txt"></releaseNotes>
<dependencies>
<dependency type="CoreVersion">08.00.00</dependency>
</dependencies>
<components>
<component type="Script">
<scripts>
<basePath>DesktopModules\MVC\Onboarding</basePath>
<script type="Install">
<path>Providers\DataProviders\SqlDataProvider</path>
<name>00.00.01.SqlDataProvider</name>
<version>00.00.01</version>
</script>
<script type="UnInstall">
<path>Providers\DataProviders\SqlDataProvider</path>
<name>Uninstall.SqlDataProvider</name>
<version>00.00.01</version>
</script>
</scripts>
</component>
<component type="ResourceFile">
<resourceFiles>
<basePath>DesktopModules/MVC/Onboarding</basePath>
<resourceFile>
<name>Resources.zip</name>
</resourceFile>
</resourceFiles>
</component>
<component type="Module">
<desktopModule>
<moduleName>Onboarding</moduleName>
<foldername>Onboarding</foldername>
<businessControllerClass>SocialBodega.Onboarding.
Components.FeatureController,
SocialBodega.Onboarding</businessControllerClass>
<supportedFeatures />
<moduleDefinitions>
<moduleDefinition>
<friendlyName>Onboarding</friendlyName>
<defaultCacheTime>0</defaultCacheTime>
<moduleControls>
<!--<moduleControl>
<controlKey />
<controlSrc>SocialBodega.Onboarding.Controllers/Item/Index.mvc
</controlSrc>
<supportsPartialRendering>False</supportsPartialRendering>
<controlTitle />
<controlType>View</controlType>
<iconFile />
<helpUrl />
<viewOrder>0</viewOrder>
</moduleControl>-->
<moduleControl>
<controlKey/>
<controlSrc>SocialBodega.Onboarding.Controllers/Signup/Index.mvc
</controlSrc>
<supportPartialRendering>False</supportPartialRendering>
<controlTitle/>
<controlType>View</controlType>
<iconFile/>
<helpUrl/>
<viewOrder>0</viewOrder>
<supportsPopUps>True</supportsPopUps>
</moduleControl>
<moduleControl>
<controlKey>Edit</controlKey>
<controlSrc>SocialBodega.Onboarding.Controllers/Signup/Edit.mvc
</controlSrc>
<supportsPartialRendering>False</supportsPartialRendering>
<controlTitle>Edit Signups</controlTitle>
<controlType>Edit</controlType>
<iconFile />
<helpUrl />
<viewOrder>0</viewOrder>
<supportsPopUps>True</supportsPopUps>
</moduleControl>
<moduleControl>
<controlKey>Settings</controlKey>
<controlSrc>SocialBodega.Onboarding.Controllers/Settings/Settings.mvc
</controlSrc>
<supportsPartialRendering>False</supportsPartialRendering>
<controlTitle>Onboarding Settings</controlTitle>
<controlType>Edit</controlType>
<iconFile />
<helpUrl />
<viewOrder>0</viewOrder>
</moduleControl>
</moduleControls>
</moduleDefinition>
</moduleDefinitions>
</desktopModule>
</component>
<component type="Assembly">
<assemblies>
<assembly>
<name>Onboarding.dll</name>
<path>bin</path>
</assembly>
</assemblies>
</component>
</components>
</package>
Update2
I upgraded to DNN 9.4 late last week and took the advice received to comment out all code in my view and just render a label. This worked!! Thus, my view syntax is as per below:
#inherits
DotNetNuke.Web.Mvc.Framework.DnnWebViewPage
<DotNetNuke.Collections.PagedList<SocialBodega.Onboarding.
Models.Onboarding>>
#using System.Linq
#using System.Text.RegularExpressions
#using DotNetNuke.Collections
#using DotNetNuke.Entities.Urls
#using DotNetNuke.Web.Mvc.Helpers
<div id="Onboarding-#Dnn.ModuleContext.ModuleId">
#if (Model == null|| !Model.Any())
{
<p>#Dnn.LocalizeString("NoSignups")</p>
}
else
{
<ul>
#foreach (var onboarding in Model)
{
<li>
<h3>#onboarding.FirstName</h3>
<div>#onboarding.OnboardingId</div>
#{
if (Dnn.ModuleContext.IsEditable)
{
<div>
#Dnn.LocalizeString("EditItem")
</div>
}
}
</li>
}
</ul>
}
</div>
#*#Html.Label("Testing 123");*#
When I build the solution, it succeeds but I do receive 16 error messages in Visual Studio 2019 to the effect of:
Error CS0012 The type 'WebViewPage<>' is defined in an assembly that is
not referenced. You must add a reference to assembly 'System.Web.Mvc,
Version=5.1.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35'.
1_desktopmodules_mvc_onboarding_Views_Signup_Index.cshtml
C:\websites\dnndev.me\DesktopModules\Onboarding\Views\Signup\Index.cshtml
I've added said assembly to web.config in the Views folder of the module and also to the main DNN web.config at C:\websites.dnndev.me using the following:
<compilation debug="true" targetFramework="4.7.2">
<assemblies>
<add assembly="System.Web.Mvc, Version = 5.1.0.0, Culture = neutral, PublicKeyToken = 31bf3856ad364e35"/>
<add assembly ="netstandard, Version = 2.0.0.0, Culture = neutral, PublicKeyToken = cc7b13ffcd2ddd51"/>
</assemblies>
</compilation>
How do I prevent the errors from being thrown and ensure that my view renders as desired?
First, be sure your module is compiling against the correct version of .NET Framework that your DNN instance is targeting. You can look for a line in your web.config file, similar to this one:
<compilation debug="false" strict="false" targetFramework="4.5">
In recent versions of DNN, you'll need to be sure to explicitly tell DNN that permissions that your controller is meant to be responding to. Take note of the DnnModuleAuthorize class decoration in the sample below.
using System;
using System.Web.Mvc;
using DotNetNuke.Entities.Modules;
using DotNetNuke.Security;
using DotNetNuke.Services.Exceptions;
using DotNetNuke.Web.Mvc.Framework.ActionFilters;
namespace SocialBodega.Onboarding.Controllers
{
[DnnModuleAuthorize(AccessLevel = SecurityAccessLevel.View)]
[DnnHandleError]
public class SignupController : DnnBaseController
{
// GET: Signup
[ModuleAction(ControlKey = "Edit", TitleKey = "AddItem")]
public ActionResult Index()
{
var signups = OnboardingManager.Instance.GetOnboardings(ModuleContext.ModuleId);
return View(signups);
}
}
}

xamarin.forms GCM Not Receiving Messages

I'm trying to implement Notifications via GCM in my Xamarin.Forms Project. Here is my code
MainActivity
using Android.App;
using Android.Content.PM;
using Android.OS;
using Android.Gms.Common;
using Android.Content;
namespace AIA.Droid
{
[Activity (Theme = "#style/MyTheme",
ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation)]
public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsApplicationActivity
{
protected override void OnCreate (Bundle bundle)
{
base.OnCreate (bundle);
global::Xamarin.Forms.Forms.Init (this, bundle);
LoadApplication (new AIA.App ());
var x = typeof(Xamarin.Forms.Themes.DarkThemeResources);
x = typeof(Xamarin.Forms.Themes.LightThemeResources);
x = typeof(Xamarin.Forms.Themes.Android.UnderlineEffect);
if (IsPlayServicesAvailable())
{
var intent = new Intent(this, typeof(RegistrationIntentService));
StartService(intent);
}
}
public bool IsPlayServicesAvailable()
{
int resultCode = GoogleApiAvailability.Instance.IsGooglePlayServicesAvailable(this);
if (resultCode != ConnectionResult.Success)
return false;
else
return true;
}
}
}
My RegistrationIntentService.cs
Here ************ is my application number received from Google Play API Console
using System;
using Android.App;
using Android.Content;
using Android.Util;
using Android.Gms.Gcm;
using Android.Gms.Gcm.Iid;
namespace AIA.Droid
{
[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 instanceID = InstanceID.GetInstance(this);
var token = instanceID.GetToken(
"************", 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);
}
}
}
My MyGcmListenerService.cs
using Android.App;
using Android.Content;
using Android.OS;
using Android.Gms.Gcm;
using Android.Util;
namespace AIA.Droid
{
[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.Icon)
.SetContentTitle("Akola Industries Association")
.SetContentText(message)
.SetDefaults(NotificationDefaults.Sound)
.SetContentIntent(pendingIntent);
var notificationManager = (NotificationManager)GetSystemService(Context.NotificationService);
notificationManager.Notify(0, notificationBuilder.Build());
}
}
}
Finally My AndroidMainfeast
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.AIA.Droid" android:installLocation="auto" android:versionCode="1" android:versionName="1.0">
<uses-sdk android:minSdkVersion="16" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="com.AIA.Droid.permission.C2D_MESSAGE" />
<uses-permission android:name="android.permission.BIND_NOTIFICATION_LISTENER_SERVICE"></uses-permission>
<permission android:name="com.AIA.Droid.permission.C2D_MESSAGE" android:protectionLevel="signature" />
<application android:label="AIA" android:icon="#drawable/Icon">
<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="com.AIA.Droid" />
</intent-filter>
</receiver>
</application>
</manifest>
All the above code are in my client App for receiving notifications
Now here is code how I'm sending messages
using System;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json.Linq;
namespace MessageSender
{
class Program
{
public const string API_KEY = "My_API_Key";
public const string MESSAGE = "Welcome to AIA";
static void Main(string[] args)
{
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 e)
{
Console.WriteLine("Unable to send GCM message:");
Console.Error.WriteLine(e.StackTrace);
}
}
}
}
Here is response from server
Id = 13, Status = RanToCompletion, Method = "{null}", Result = "StatusCode: 200, ReasonPhrase: 'OK', Version: 1.1, Content: System.Net.Http.StreamContent, Headers:\r\n{\r\n X-Content-Type-Options: nosniff\r\n X-Frame-Options: SAMEORIGIN\r\n X-XSS-Protection: 1; mode=block\r\n Alt-Svc: quic=\":443\"; ma=2592000; v=\"36,35,34,33,32\"\r\n Vary: Accept-Encoding\r\n Transfer-Encoding: chunked\r\n Accept-Ranges: none\r\n Cache-Control: max-age=0, private\r\n Date: Tue, 25 Oct 2016 05:02:12 GMT\r\n Server: GSE\r\n Content-Type: application/json; charset=UTF-8\r\n Expires: Tue, 25 Oct 2016 05:02:12 GMT\r\n}"
I'm not understanding where I'm wrong.
Please help
Amit Saraf
This links helped me a lot to understand the process of GCM push notifications, you can also use POSTMAN to test the sending of the push notifications:
http://forums.xamarin.com/discussion/comment/217083/#Comment_217083
How to use Push Notifications in Xamarin Forms
http://xamarinhelp.com/push-notifications/
Test them:
https://stackoverflow.com/a/30778643/1207924

Not calling method OnMessageReceived in xamarin

I am implementing remote notification on android using xamarin.
I am doing POC using Walkthrough - Using Remote Notifications in Xamarin.Android
I am not getting notification on mobile, after registering mobile and send notification through sender using GCM.
Is there any mistake in code? or Can I track my notification to get detail why it is not come in mobile?
MyGcmListenerService.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);
}
....
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.yourcompany.LeaveApplication" android:installLocation="auto" android:versionCode="1" android:versionName="1.0">
<uses-sdk android:minSdkVersion="15" />
<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="com.yourcompany.LeaveApplication.permission.C2D_MESSAGE" />
<permission android:name="com.yourcompany.LeaveApplication.permission.C2D_MESSAGE" android:protectionLevel="signature" />
<application android:label="XamarinLeaveApp" >
<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="com.yourcompany.LeaveApplication" />
</intent-filter>
</receiver>
</application>
</manifest>
Message Sender's code
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 =>
{
var response1 = response;
// Console.WriteLine(response);
//Console.WriteLine("Message sent: check the client device notification tray.");
}));
}
}
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 instanceID = InstanceID.GetInstance(Application.Context);
var token = instanceID.GetToken(
"<project number", 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(Application.Context);
pubSub.Subscribe(token, "/topics/global", null);
}
}
in the RegistrationIntentService.cs file, you use Application.Context instead of this. It should be equivalent, but can you try?
Also, I do not see in your code the protected override void OnCreate method that registers the RegistrationIntentService intent. Didn't you paste it here or did you forget to implement it?
HTH

Silverlight not accessing content when using https

I have a SL app that has https and http endpoints. If i access the endpoint on http, then just have a screen which loads an external image
http://somedomain.com/domaimage.jpg
It will work fine.
If i access the SL app on https:// then load the same image it won't even attempt to make the web request for the image.
Why when SL is running on https i doesn't request external content? I have this in my clientaccesspolicy.xml
<?xml version="1.0" encoding="utf-8"?>
<access-policy>
<cross-domain-access>
<policy>
<allow-from http-request-headers="*" http-methods="*">
<domain uri="http://*"/>
<domain uri="https://*"/>
</allow-from>
<grant-to>
<resource path="/" include-subpaths="true"/>
</grant-to>
</policy>
</cross-domain-access>
and this is my crossdomain.xml
<?xml version="1.0"?>
<cross-domain-policy>
<allow-access-from domain="*" />
</cross-domain-policy>
Thanks
Steve
Now using an image proxy to access external content, if it helps anyone
ImageProxy.ashx
public class ImageUrlProxy : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
try
{
string url = context.Request.Headers["Url"];
var client = new WebClient();
byte[] imageDataBytes = client.DownloadData(url);
context.Response.ContentType = "application/json;";
context.Response.Write(JsonConvert.SerializeObject(imageDataBytes));
}
catch (Exception)
{
throw;
}
}
public bool IsReusable
{
get
{
return false;
}
}
}
Helper class:
public static class ImageProxyHelper
{
public static void GetImageByProxy(string url, Action<BitmapImage> callback)
{
if (callback == null) return;
var client = new WebClient();
client.DownloadStringCompleted += (sender, args) =>
{
if (args.Error == null)
{
var buffer = JsonConvert.DeserializeObject<byte[]>(args.Result);
var im = new BitmapImage() { CreateOptions = BitmapCreateOptions.None };
im.SetSource(new MemoryStream(buffer));
callback(im);
}
};
client.Headers["Url"] = url;
client.DownloadStringAsync(UrlBuilder("ImageUrlProxy.ashx"));
}
public static Uri UrlBuilder(string fragment)
{
var uriBuilder = new UriBuilder(Application.Current.Host.Source.Scheme,
Application.Current.Host.Source.Host,
Application.Current.Host.Source.Port, fragment);
return uriBuilder.Uri;
}
}
Then from silverlight:
ImageProxyHelper.GetImageByProxy("http://externaldomain.com/image.jpg", p=>{
//Do something here
})
This can be extended to return any external content ^^
You are having the same problem as this question
Https and http Image URL Not loading in silverlight
It is down to cross scheme calls in silverlight

Categories