Xamarin google Native Ads IOS - c#

I am trying to implement Native ads in xamarin it works fine with android but I have a problem with ios
Here is my code
public class AdMobNativeAdRenderer : ViewRenderer<Controls.NativeAdView, UnifiedNativeAdView>, IAdLoaderDelegate, IUnifiedNativeAdDelegate, IUnifiedNativeAdLoaderDelegate, IVideoControllerDelegate
{
public UnifiedNativeAdView nativeAdView = null;
public void DidReceiveUnifiedNativeAd(AdLoader adLoader, UnifiedNativeAd nativeAd)
{
// A unified native ad has loaded, and can be displayed.
nativeAd.Delegate = this;
// The headline and mediaContent are guaranteed to be present in every native ad.
nativeAdView.NativeAd = nativeAd;
if (nativeAdView.HeadlineView==null)
{
nativeAdView.HeadlineView= new UILabel();
}
(nativeAdView.HeadlineView as UILabel).Text = nativeAd.Headline;
if (nativeAdView.MediaView == null) {
nativeAdView.MediaView = new MediaView();
}
if (nativeAdView.MediaView.MediaContent == null)
{
nativeAdView.MediaView.MediaContent = new MediaContent();
}
nativeAdView.MediaView.MediaContent = nativeAd.MediaContent;
nativeAdView.MediaView.ContentMode = UIViewContentMode.ScaleAspectFill;
if (nativeAdView.BodyView==null)
{
nativeAdView.BodyView = new UILabel();
}
(nativeAdView.BodyView as UILabel).Text = nativeAd.Body;
nativeAdView.BodyView.Hidden = nativeAd.Body == null;
if (nativeAdView.CallToActionView==null)
{
nativeAdView.CallToActionView = new UIButton();
}
(nativeAdView.CallToActionView as UIButton).SetTitle(nativeAd.CallToAction,UIControlState.Normal);
nativeAdView.CallToActionView.Hidden = nativeAd.CallToAction == null;
if (nativeAdView.IconView==null)
{
nativeAdView.IconView = new UIImageView();
}
(nativeAdView.IconView as UIImageView).Image = nativeAd.Icon.Image;
nativeAdView.IconView.Hidden = nativeAd.Icon == null;
if (nativeAdView.StoreView==null)
{
nativeAdView.StoreView = new UILabel();
}
(nativeAdView.StoreView as UILabel).Text = nativeAd.Store;
nativeAdView.StoreView.Hidden = nativeAd.Store == null;
if (nativeAdView.PriceView==null)
{
nativeAdView.PriceView = new UILabel();
}
(nativeAdView.PriceView as UILabel).Text = nativeAd.Price;
nativeAdView.PriceView.Hidden = nativeAd.Price == null;
if (nativeAdView.AdvertiserView==null)
{
nativeAdView.AdvertiserView = new UILabel();
}
if (nativeAdView.StoreView==null)
{
nativeAdView.StoreView = new UILabel();
}
(nativeAdView.StoreView as UILabel).Text = nativeAd.Store;
(nativeAdView.AdvertiserView as UILabel).Text = nativeAd.Advertiser;
nativeAdView.AdvertiserView.Hidden = nativeAd.Advertiser == null;
nativeAdView.CallToActionView.UserInteractionEnabled = false;
nativeAdView.NativeAd = nativeAd;
try
{
nativeAdView.BackgroundColor = UIColor.Green;
SetNativeControl(nativeAdView);
}
catch (Exception ex)
{
Debug.WriteLine(ex.Message);
}
}
[Export("adLoaderDidFinishLoading:")]
void DidFinishLoading(AdLoader adLoader)
{
// The adLoader has finished loading ads, and a new request can be sent.
}
public void DidFailToReceiveAd(AdLoader adLoader, RequestError error)
{
}
protected override void OnElementChanged(ElementChangedEventArgs<Controls.NativeAdView> e)
{
base.OnElementChanged(e);
try
{
if (e.OldElement != null)
{
try
{
e.OldElement.Content=null;
}
catch (Exception)
{
}
SetNativeControl(nativeAdView);
}
if (e.NewElement != null)
{
if (Control == null)
{
// Instantiate the native control and assign it to the Control property with
CreateAdView();
try
{
e.NewElement.Content = null;
}
catch (Exception)
{
}
SetNativeControl(nativeAdView);
}
}
}
catch (Exception ex)
{
Debug.WriteLine(ex.Message);
}
}
AdLoader adLoader;
private void CreateAdView()
{
//if (Element == null) return;
var multipleAdsOptions = new MultipleAdsAdLoaderOptions { NumberOfAds = 1 };
adLoader = new AdLoader("ca-app-pub-3940256099942544/3986624511", GetVisibleViewController(), new[] { AdLoaderType.UnifiedNative }, new[] { multipleAdsOptions })
{
Delegate = this
};
var request = Request.GetDefaultRequest();
request.TestDevices = new string[] { Request.SimulatorId };
if (nativeAdView == null)
{
nativeAdView = new UnifiedNativeAdView();
};
try
{
adLoader.LoadRequest(request);
}
catch (Exception e)
{
Debug.WriteLine(e.Message);
}
Debug.WriteLine("Loading: " + adLoader.IsLoading);
}
private UIViewController GetVisibleViewController()
{
var windows = UIApplication.SharedApplication.Windows;
foreach (var window in windows)
{
if (window.RootViewController != null)
{
return window.RootViewController;
}
}
return null;
}
}
Every thing is working as anticipated and I receive the ad and the event DidReceiveUnifiedNativeAd fires but I get an empty ad although when I debug the code I see that the content of the ad is not empty and the control color is green so the control is loaded but why it doesn't show the ad content
Please can anyone help is solving this

Related

How to create custom validation based on xml in .net 6

I am trying to perform validation using custom class attributes. I have to keep my model validation rules inside XML files. Custom Class attribute specifies the path to the XML file and custom attributes will contain the logic to read XML files and get the validation rules for that class. When I will call Model.Isvalidate() that time Validation will get executed. I already have this working in .Net 4.5 MVC application. The same thing I am trying in .Net 6 its not working.
public class CustomDynamicModelValidatorProvider : DataAnnotationsModelValidatorProvider,IModelValidatorProvider
{
protected override IEnumerable<ModelValidator> GetValidators(ModelMetadata metadata, IEnumerable<ModelValidatorProvider> validatorProviders, IEnumerable<Attribute> attributes)
{
string resourceKeyPath = string.Empty;
IList<Attribute> newAttributes = new List<Attribute>(attributes);
CustomDynamicValidatorsAttribute resourceMapperAttr = attributes.FirstOrDefault(a => a is CustomDynamicValidatorsAttribute) as CustomDynamicValidatorsAttribute;
if (resourceMapperAttr == null)
{
System.Reflection.MemberInfo classInfo = metadata.ContainerType;
if (classInfo != null)
{
var resourceMapperRootAttr = classInfo.GetCustomAttributes(typeof(ResourceMappingRootAttribute), false).FirstOrDefault() as ResourceMappingRootAttribute;
if (resourceMapperRootAttr != null)
{
resourceKeyPath = resourceMapperRootAttr.Path + "." + metadata.PropertyName;
}
}
}
else
{
resourceKeyPath = resourceMapperAttr.ResourceKeyPath;
}
if (!string.IsNullOrEmpty(resourceKeyPath))
{
string[] validators = ResourceManager.GetValidators(resourceKeyPath).Replace(" ", "").Split(',');
var maxLength = ResourceManager.GetMaxLength(resourceKeyPath);
if (!string.IsNullOrEmpty(maxLength))
{
var required = new MaxLengthAttribute(maxLength.ToInteger());
required.ErrorMessage = string.Format(CustomAttributeHelper.GetResourceText("Shared.Messages.MaximumLengthExceeded"), maxLength);
newAttributes.Add(required);
}
for (int i = 0; i < validators.Length; i++)
{
if (string. Equals(validators[i], "required", StringComparison.OrdinalIgnoreCase))
{
var required = new CustomRequiredAttribute();
newAttributes.Add(required);
}
else if (validators[i].StartsWith("email", StringComparison.OrdinalIgnoreCase))
{
var email = new CustomEmailAttribute();
newAttributes.Add(email);
}
}
}
return base.GetValidators(metadata,validatorProviders);
}
public static IDictionary<string, object> GetValidatorAttributes(string validators)
{
IDictionary<string, object> attributes = new Dictionary<string, object>();
string[] validatorList = !string.IsNullOrEmpty(validators) ? validators.Replace(" ", "").Split(',') : new string[] { };
foreach (var item in validatorList)
{
if (!attributes.Keys.Contains("data-val"))
{
attributes.Add("data-val", "true");
}
if (string.Equals(item, "required", StringComparison.OrdinalIgnoreCase))
{
attributes.Add("data-val-required", CustomAttributeHelper.GetResourceText("Shared.Messages.Mandatory"));
}
else if (item.StartsWith("email", StringComparison.OrdinalIgnoreCase))
{
attributes.Add("data-val-email", CustomAttributeHelper.GetResourceText("Shared.Messages.vEmailField"));
}
else if (item.StartsWith("phone", StringComparison.OrdinalIgnoreCase))
{
attributes.Add("data-val-phone", CustomAttributeHelper.GetResourceText("Shared.Messages.vPhoneField"));
}
else if (item.StartsWith("zipcode", StringComparison.OrdinalIgnoreCase))
{
attributes.Add("data-val-zipcode", CustomAttributeHelper.GetResourceText("Shared.Messages.vZipCodeField"));
}
else if (item.StartsWith("mark", StringComparison.OrdinalIgnoreCase))
{
string min = string.Empty;
string max = string.Empty;
string rangeValidatorMessage = string.Empty;
if (item.Contains("-"))
{
var rangeArray = item.Split('-');
if (rangeArray.Length > 2)
{
min = rangeArray[1];
max = rangeArray[2];
rangeValidatorMessage = CustomAttributeHelper.GetResourceText("Shared.Messages.NumberRange");
}
else
{
max = rangeArray[1];
rangeValidatorMessage = CustomAttributeHelper.GetResourceText("Shared.Messages.vNumericLimited");
}
}
else
{
max = "10000";
}
if (!string.IsNullOrWhiteSpace(min))
{
attributes.Add("data-val-range-min", min);
}
attributes.Add("data-val-range-max", max);
attributes.Add("data-val-range", rangeValidatorMessage);
}
else if (item.StartsWith("number", StringComparison.OrdinalIgnoreCase))
{
attributes.Add("data-val-number", CustomAttributeHelper.GetResourceText("Shared.Messages.NumberRange"));
}
else if (item.StartsWith("number", StringComparison.OrdinalIgnoreCase))
{
attributes.Add("data-val-decimal", string.Format(CustomAttributeHelper.GetResourceText("Shared.Messages.DecimalRange"), CustomAttributeHelper.GetResourceText("Shared.Limits.Decimal")));
}
else if (item.StartsWith("file-", StringComparison.OrdinalIgnoreCase))
{
attributes.Add("data-val-filetype", item.Split('-')[1]);
}
}
return attributes;
}
public void CreateValidators(ModelValidatorProviderContext context)
{
}
}

Producer terminating with 1 message (39bytes) still in queue or transit. Kafka

How do I solve this terminating with kafka? I have the following error: https://i.stack.imgur.com/bY2j3.png
Code:
public class KafkaHelper
{
public static async Task<bool> SendMessage(KafkaSettings settings, string topic, string key, string val)
{
var succeed = false;
var config = new ProducerConfig
{
BootstrapServers = settings.Server,
ClientId = Dns.GetHostName(),
};
using (var adminClient = new AdminClientBuilder(config).Build())
{
try
{
await adminClient.CreateTopicsAsync(new List<TopicSpecification> {
new TopicSpecification {
Name = topic,
NumPartitions = settings.NumPartitions,
ReplicationFactor = settings.ReplicationFactor } });
}
catch (CreateTopicsException e)
{
if (e.Results[0].Error.Code != ErrorCode.TopicAlreadyExists)
{
Console.WriteLine($"An error occured creating topic {topic}: {e.Results[0].Error.Reason}");
}
else
{
Console.WriteLine("Topic already exists");
}
}
}
using (var producer = new ProducerBuilder<string, string>(config).Build())
{
producer.Produce(topic, new Message<string, string>
{
Key = key,
Value = val
}, (deliveryReport) =>
{
if (deliveryReport.Error.Code != ErrorCode.NoError)
{
Console.WriteLine($"Failed to deliver message: {deliveryReport.Error.Reason}");
}
else
{
Console.WriteLine($"Produced message to: {deliveryReport.TopicPartitionOffset}");
succeed = true;
}
});
producer.Flush(TimeSpan.FromSeconds(10));
}
return await Task.FromResult(succeed);
}
}

Is there a way to pass list from android project to MainPage in xamarin.forms project

I have CustomMapRenderer class in my android project in which when you press a marker on the map the list is filling from database with this code:
using System;
using System.Collections.Generic;
using System.Linq;
using Android.Content;
using Android.Gms.Maps;
using Android.Gms.Maps.Model;
using Android.Widget;
using MaritsaTundzhaForecast;
using MaritsaTundzhaForecast.Models;
using MaritsaTundzhaForecast.Droid;
using MySqlConnector;
using Xamarin.Forms;
using Xamarin.Forms.Maps;
using Xamarin.Forms.Maps.Android;
[assembly: ExportRenderer(typeof(CustomMap), typeof(CustomMapRenderer))]
namespace MaritsaTundzhaForecast.Droid
{
public class CustomMapRenderer : MapRenderer, GoogleMap.IInfoWindowAdapter
{
List<CustomPin> customPins;
public CustomMapRenderer(Context context) : base(context)
{
}
protected override void OnElementChanged(Xamarin.Forms.Platform.Android.ElementChangedEventArgs<Map> e)
{
base.OnElementChanged(e);
if (e.OldElement != null)
{
NativeMap.InfoWindowClick -= OnInfoWindowClick;
}
if (e.NewElement != null)
{
var formsMap = (CustomMap)e.NewElement;
customPins = formsMap.CustomPins;
}
}
protected override void OnMapReady(GoogleMap map)
{
base.OnMapReady(map);
NativeMap.InfoWindowClick += OnInfoWindowClick;
NativeMap.SetInfoWindowAdapter(this);
}
protected override MarkerOptions CreateMarker(Pin pin)
{
var marker = new MarkerOptions();
marker.SetPosition(new LatLng(pin.Position.Latitude, pin.Position.Longitude));
marker.SetTitle(pin.Label);
marker.SetSnippet(pin.Address);
//marker.SetIcon(BitmapDescriptorFactory.FromResource(Resource.Drawable.green));
var custom = customPins.Where(x => x.Label == pin.Label && x.Address == pin.Address).FirstOrDefault();
if (custom != null)
{
if (custom.AlertLevel == 1)
{
marker.SetIcon(BitmapDescriptorFactory.FromResource(Resource.Drawable.green));
}
if (custom.AlertLevel == 2)
{
marker.SetIcon(BitmapDescriptorFactory.FromResource(Resource.Drawable.yellow));
}
if (custom.AlertLevel == 3)
{
marker.SetIcon(BitmapDescriptorFactory.FromResource(Resource.Drawable.orange));
}
if (custom.AlertLevel == 4)
{
marker.SetIcon(BitmapDescriptorFactory.FromResource(Resource.Drawable.red));
}
}
return marker;
}
void OnInfoWindowClick(object sender, GoogleMap.InfoWindowClickEventArgs e)
{
var customPin = GetCustomPin(e.Marker);
if (customPin == null)
{
throw new Exception("Custom pin not found");
}
if (!string.IsNullOrWhiteSpace(customPin.Url))
{
var url = Android.Net.Uri.Parse(customPin.Url);
var intent = new Intent(Intent.ActionView, url);
intent.AddFlags(ActivityFlags.NewTask);
Android.App.Application.Context.StartActivity(intent);
}
}
public Android.Views.View GetInfoContents(Marker marker)
{
var inflater = Android.App.Application.Context.GetSystemService(Context.LayoutInflaterService) as Android.Views.LayoutInflater;
if (inflater != null)
{
Android.Views.View view;
var customPin = GetCustomPin(marker);
if (customPin == null)
{
throw new Exception("Custom pin not found");
}
if (customPin.Name.Equals("Xamarin"))
{
view = inflater.Inflate(Resource.Layout.XamarinMapInfoWindow, null);
}
else
{
view = inflater.Inflate(Resource.Layout.MapInfoWindow, null);
}
CustomPin pin = GetCustomPin(marker);
int CodeNum = pin.CodeNum;
int AlertLevel = pin.AlertLevel;
var infoTitle = view.FindViewById<TextView>(Resource.Id.InfoWindowTitle);
var infoSubtitle = view.FindViewById<TextView>(Resource.Id.InfoWindowSubtitle);
var infoSubtitle2 = view.FindViewById<TextView>(Resource.Id.InfoWindowSubtitle2);
var infoSubtitle3 = view.FindViewById<TextView>(Resource.Id.InfoWindowSubtitle3);
if (infoTitle != null)
{
infoTitle.Text = marker.Title;
}
if (infoSubtitle != null)
{
infoSubtitle.Text = marker.Snippet;
}
if (infoSubtitle2 != null)
{
infoSubtitle2.Text = "Тревога: (1-4): " + AlertLevel;
}
if (infoSubtitle3 != null)
{
infoSubtitle3.Text = "Код на станция: " + CodeNum;
}
return view;
}
return null;
}
public Android.Views.View GetInfoWindow(Marker marker)
{
return null;
}
public IEnumerable<AlertLevel> DataBaseConnection(int mapCode)
{
string ConnectionString = "server=192.168.0.1;uid=username;port=3389;pwd=password;database=dbName;";
MySqlConnection Conn = new MySqlConnection(ConnectionString);
var listAlert = new List<AlertLevel>();
try
{
Conn.Open();
//replace(2) with mapCode
string query = "CALL Get_Alert_levels_Station(" + mapCode + ");";
MySqlCommand myCommand = new MySqlCommand(query, Conn);
MySqlDataReader myReader;
myReader = myCommand.ExecuteReader();
try
{
while (myReader.Read())
{
var currentData = new AlertLevel()
{
dateForecast = myReader.GetDateTime(0),
levelForecast = myReader.GetInt32(1)
};
listAlert.Add(currentData);
}
}
finally
{
myReader.Close();
Conn.Close();
}
}
catch (Exception ex)
{
Console.WriteLine("Database Connection", "Not Connected ..." + ex.ToString(), "OK");
}
return listAlert;
}
CustomPin GetCustomPin(Marker annotation)
{
string id = annotation.Id.Substring(1);
int mapCode = int.Parse(id);
var result = DataBaseConnection(mapCode);
MessagingCenter.Send(this, "PinSelected", result);
var position = new Position(annotation.Position.Latitude, annotation.Position.Longitude);
foreach (var pin in customPins)
{
if (pin.Position == position)
{
return pin;
}
}
return null;
}
}
}
In the GetCustomPin method I want to pass to MainPage.cs this line of code:
var result = DataBaseConnection(mapCode);
In the same method I try to pass with this line of code:
MessagingCenter.Send(this, "PinSelected", result);
So I delete AlertLevel.cs object in the android project and create a new object AlertLevel.cs in xamarin.forms project. In the MainPage.cs I set using MaritsaTundzhaForecast.Models; to use AlertLevel.cs and with this code I try to receive the method from the android project:
MessagingCenter.Subscribe<CustomMapRenderer, IEnumerable<AlertLevel>>(this, "PinSelected", async (sender, arg) =>
{
// do something here with arg, which is IEnumerable<AlertLevel>
});
But I receive error:
The type or namespace name 'CustomMapRenderer' could not be found (are you missing a using directive or an assembly reference?)
Is there a way to fix that and how can I fill a ListView from MainPage with this result from CustomMapRenderer ?
in MainPage use MessagingCenter to listen for messages from the map control
MessagingCenter.Subscribe<object, IEnumerable<AlertLevel>>(this, "PinSelected", async (sender, arg) =>
{
// do something here with arg, which is IEnumerable<AlertLevel>
});
in your map renderer, send the message with result as a parameter
MessagingCenter.Send<object, IEnumerable<AlertLevel>>(this, "PinSelected", result);

Proper Unit Test for ASP.NET MVC5

I have got following code and I have no clue which proper Unit Test I have write out for those methods and how it can be done. Basically I would like to use NUnit.Framework.
Thank you in advance for ANY clue!
[AllowAnonymous]
public ActionResult ForgotPassword(string id)
{
var model = new ForgotPasswordViewModel();
if (!string.IsNullOrEmpty(id))
{
#region Process Reset Password Key
try
{
var forgotPasswordEvent = AppModel.ForgotPasswordEvents.SingleOrDefault(x => x.UIDHash == id);
if (forgotPasswordEvent != null)
{
var stringToHash = string.Format("{0}---{1}---{2}", forgotPasswordEvent.UID.ToString(),
forgotPasswordEvent.UserId.ToString(), forgotPasswordEvent.Created.ToString());
var readyHash = SecurityHelper.GetHashString(stringToHash);
if (id == readyHash)
{
var forgotPasswordEventUserId = forgotPasswordEvent.UserId.ToString();
var realUser = AppModel.AspNetUsers.SingleOrDefault(x => x.Id == forgotPasswordEventUserId);
if (realUser != null)
{
var resetPasswordViewModel = new ResetPasswordViewModel();
resetPasswordViewModel.ResetPasswordData = id;
resetPasswordViewModel.UserName = realUser.UserName;
return RedirectToAction("ResetPassword", "Account", resetPasswordViewModel); // ResetPassword(resetPasswordViewModel);
}
}
}
else
{
return RedirectToAction("Index", "Home");
}
}
catch (Exception)
{
}
#endregion
}
#region Check if the user is logged in and fill out fileds for him.
var sessionManager = SessionWrapper.GetFromSession<SessionManager>("_SessionManager");
if (sessionManager != null)
{
var clientId = sessionManager.AppUser.ClientId;
if (clientId != null)
{
model.Email = sessionManager.AppUser.EmailID;
model.UserName = sessionManager.AppUser.UserName;
model.IsLoggedInUser = true;
}
}
#endregion
return View(model);
}
[HttpPost]
[AllowAnonymous]
public ActionResult ForgotPassword(ForgotPasswordViewModel model, FormCollection formCollection)
{
if (ModelState.IsValid)
{
try
{
#region Check user input
var user = AppModel.AspNetUsers.SingleOrDefault(x => x.UserName == model.UserName);
var areErrors = false;
if (user == null)
{
ModelState.AddModelError("UserDoesnotExist", DLMModelEntities.Properties.Resource.UserDoesNotExist);
areErrors = true;
}
if (user.EmailID != model.Email)
{
ModelState.AddModelError("EmailIsWrong", DLMModelEntities.Properties.Resource.EmailIsWrong);
areErrors = true;
}
if (areErrors)
return View(model);
#endregion
#region Send Email and inform user
try
{
var forgotPasswordEvent = new ForgotPasswordEvent();
var resetPasswordEmailUserState = new ResetPasswordEmailUserState();
resetPasswordEmailUserState.ForgotPasswordEventId = Guid.NewGuid();
resetPasswordEmailUserState.UserId = Guid.Parse(user.Id);
resetPasswordEmailUserState.Created = DateTime.Now;
forgotPasswordEvent.UID = resetPasswordEmailUserState.ForgotPasswordEventId;
forgotPasswordEvent.UserId = resetPasswordEmailUserState.UserId;
forgotPasswordEvent.IsSent = false;
forgotPasswordEvent.Created = resetPasswordEmailUserState.Created;
var stringToHash = string.Format("{0}---{1}---{2}", resetPasswordEmailUserState.ForgotPasswordEventId.ToString(),
resetPasswordEmailUserState.UserId.ToString(), resetPasswordEmailUserState.Created.ToString());
forgotPasswordEvent.UIDHash = SecurityHelper.GetHashString(stringToHash);
AppModel.ForgotPasswordEvents.Add(forgotPasswordEvent);
AppModel.SaveChanges();
var smtp = (SmtpSection)ConfigurationManager.GetSection("system.net/mailSettings/smtp");
// Set the MailerModel properties that will be passed to the MvcMailer object.
var m = new MailerModel();
m.UserName = user.UserName;
m.ResetPasswordLink = string.Format("{0}/{1}", Request.Url.AbsoluteUri, forgotPasswordEvent.UIDHash);
m.FromEmail = smtp.From;
m.Subject = AppConfiguration.ResetEmailSubject;
m.ToEmail = model.Email;
var client = new SmtpClientWrapper();
client.SendCompleted += (sender, e) =>
{
if (e.Error != null || e.Cancelled)
{
// Handle Error
}
else
{
try
{
var forgotPasswordEventsToUpdate = AppModel.ForgotPasswordEvents.SingleOrDefault(x => x.UID == resetPasswordEmailUserState.ForgotPasswordEventId);
if (forgotPasswordEventsToUpdate != null)
{
forgotPasswordEventsToUpdate.IsSent = true;
AppModel.SaveChanges();
}
}
catch (Exception ex)
{
ModelState.AddModelError("EmailEx", ex.Message);
}
}
};
Mailer.PasswordReset(m).SendAsync(resetPasswordEmailUserState, client);
model.IsResetEMailSent = true;
}
catch (Exception ex)
{
ModelState.AddModelError("EmailEx", ex.Message);
}
#endregion
}
catch (Exception ex)
{
ModelState.AddModelError("EmailEx", ex.Message);
}
}
return View(model);
}
As your code looks ltl messed up with more than one responsibility.
For Starter what you can do here is:
Refactor your code into small code snippets and move those dependencies into another classes.
when you will be done with first step you will be able to mock those classes using MOQ or NMock or another framework.
Let me know if you have any doubt in above points.

pivot view with dynamic data

i'm working on a windows phone application using pivot view to preview data for the user, the data comes from a web service, then i put it in List then i add the item to the pivot view
but when i call the web service the view doesn't wait till i get the data from the server to add to the view and the view adds nothing , here is my code
public class downloads : List<Downloaded>
{
List<string> downoladedList = new List<string>();
public downloads()
{
BuildCollection();
}
//private const string IMG_PATH = "../Images/";
public ObservableCollection<Downloaded> DataCollection { get; set; }
public ObservableCollection<Downloaded> BuildCollection()
{
// int x=0;
Downloaded downObject = new Downloaded();
ServiceReference1.Service1Client service = new ServiceReference1.Service1Client();
service.GetDownloadsCompleted += new EventHandler<ServiceReference1.GetDownloadsCompletedEventArgs>(GetDownLoads);
System.Threading.Thread.Sleep(100000);
service.GetDownloadsAsync(20019);
DataCollection = new ObservableCollection<Downloaded>();
foreach (var elem in downoladedList)
{
string[] elemProp = new string[8];
elemProp = elem.Split('=');
if (elemProp[3] == "1")
elemProp[3] = "downloaded";
else
elemProp[3] = "in progress";
DataCollection.Add(new Downloaded(elemProp[1], elemProp[3], "test.png"));
}
return DataCollection;
}
public void GetDownLoads(object sender, ServiceReference1.GetDownloadsCompletedEventArgs e)
{
try
{
downoladedList = e.Result.ToList<string>();
}
catch (Exception ee)
{
}
}
}
You cannot call thread.sleep. This will block entire UI thread.
Declare DataCollection = new ObservableCollection();
outside scope.
You should put all your code on completed like this :
public void GetDownLoads(object sender, ServiceReference1.GetDownloadsCompletedEventArgs e)
{
try
{
downoladedList = e.Result.ToList<string>();
foreach (var elem in downoladedList)
{
string[] elemProp = new string[8];
elemProp = elem.Split('=');
if (elemProp[3] == "1")
elemProp[3] = "downloaded";
else
elemProp[3] = "in progress";
DataCollection.Add(new Downloaded(elemProp[1], elemProp[3], "test.png"));
}
}
catch (Exception ee)
{
}
}

Categories

Resources