I am trying to create a Morse translator for both IOS and Android using Xamarin and C#. I have tried all kinds of things and in the end used Autofac because I needed to reference main project to android and back. That is so because I have Interface in my main project
namespace SuperMorse
{
public interface ISoundService
{
void PlayDotSound();
void PlayDashSound();
int dot { get; set; }
int dash { get; set; }
}
}
and a class in Android project
namespace SuperMorse.Droid
{
public class SoundService : ISoundService
{
public int dot { get; set; }
public int dash { get; set; }
public SoundService()
{
dot = Android.App.Application.Context.Resources.GetIdentifier("dot", "raw", Android.App.Application.Context.PackageName);
dash = Android.App.Application.Context.Resources.GetIdentifier("dash", "raw", Android.App.Application.Context.PackageName);
}
public void PlayDotSound()
{
var fd = Android.App.Application.Context.Assets.OpenFd("dot.mp3");
MediaPlayer dotPlayer = new MediaPlayer();
dotPlayer.SetDataSource(fd.FileDescriptor, fd.StartOffset, fd.Length);
dotPlayer.Prepare();
dotPlayer.Start();
}
public void PlayDashSound()
{
var fd = Android.App.Application.Context.Assets.OpenFd("dash.mp3");
MediaPlayer dashPlayer = new MediaPlayer();
dashPlayer.SetDataSource(fd.FileDescriptor, fd.StartOffset, fd.Length);
dashPlayer.Prepare();
dashPlayer.Start();
}
}
}
so when I call the PlaySounds functions back in my MainPage function I get a strange error in my terminal: Fatal signal 11 (SIGSEGV), code 2 (SEGV_ACCERR), fault addr 0x7ffc7ad11fb8 in tid 31167 (name.supermorse), pid 31167 (name.supermorse). I debugged it and it seems the error occurs when the line var fd = Android.App.Application.Context.Assets.OpenFd("dot.mp3"); from the SoundService.cs runs.... or a similiar one for the dash. Any idea how to fix?
Tried reading my audio files and changing their format
I have create a new sample to test your code. And the dot.mp3 was displayed when I run the project.
In the Page.cs:
private void button_Clicked(object sender, EventArgs e)
{
ISoundService soundService = DependencyService.Get<ISoundService>();
soundService.PlayDotSound();
}
The interface:
namespace AppTest
{
public interface ISoundService
{
void PlayDotSound();
void PlayDashSound();
int dot { get; set; }
int dash { get; set; }
}
}
The android dependency service:
[assembly: Xamarin.Forms.Dependency(typeof(AppTest.Droid.SoundService))]
namespace AppTest.Droid
{
public class SoundService : ISoundService
{
public int dot { get; set; }
public int dash { get; set; }
public SoundService()
{
dot = Android.App.Application.Context.Resources.GetIdentifier("dot", "raw", Android.App.Application.Context.PackageName);
dash = Android.App.Application.Context.Resources.GetIdentifier("dash", "raw", Android.App.Application.Context.PackageName);
}
public void PlayDotSound()
{
var fd = Android.App.Application.Context.Assets.OpenFd("dot.mp3");
MediaPlayer dotPlayer = new MediaPlayer();
dotPlayer.SetDataSource(fd.FileDescriptor, fd.StartOffset, fd.Length);
dotPlayer.Prepare();
dotPlayer.Start();
}
public void PlayDashSound()
{
var fd = Android.App.Application.Context.Assets.OpenFd("dash.mp3");
MediaPlayer dashPlayer = new MediaPlayer();
dashPlayer.SetDataSource(fd.FileDescriptor, fd.StartOffset, fd.Length);
dashPlayer.Prepare();
dashPlayer.Start();
}
}
}
And the file in the Assets folder:
In addition, the build action of the dot.mp3 is AndroidAsset.
Related
Loading / storing the 3 floats (ID=1, Loc1=3, Loc2=100) into the public class MInput works fine. However, I like to access / use the same dataset in the Forms2 class, which unfortunately gives me zero values only. What is wrong with the call in Forms2 for textBox1.text and textBox2.text ? Thanks for your ideas.
namespace WinForms01
{
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
MInput testDat = new MInput
{
ID = 1F,
Loc1 = 3F,
Loc2 = 100F,
};
{
}
}
namespace WinForms01
{
public class MInput
{
[ColumnName("ID"), LoadColumn(0)]
public float ID { get; set; }
[ColumnName("loc1"), LoadColumn(1)]
public float Loc1 { get; set; }
[ColumnName("loc2"), LoadColumn(2)]
public float Loc2 { get; set; }
[ColumnName("loc3"), LoadColumn(4)]
public float Loc3 { get; set; }
}
}
namespace WinForms01
{
public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
MInput testDat = new MInput();
textBox1.Text = Convert.ToString(testDat.ID);
textBox2.Text = Convert.ToString(testDat.Loc1);
}
}
}
If you want Form2 to access an object you create elsewhere you have to pass the object to form2. Some instance of class X doesn't just magically get access to an instance of Y just because both different places do a new Y and call them the same name, for the same reason that you buying an iPhone and your brother buying an iPhone of the same model and specification, doesn't mean you can read his messages
namespace WinForms01
{
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
MInput testDat = new MInput
{
ID = 1F,
Loc1 = 3F,
Loc2 = 100F,
};
Application.Run(new Form2(testDat));
}
}
}
namespace WinForms01
{
public class MInput
{
[ColumnName("ID"), LoadColumn(0)]
public float ID { get; set; }
[ColumnName("loc1"), LoadColumn(1)]
public float Loc1 { get; set; }
[ColumnName("loc2"), LoadColumn(2)]
public float Loc2 { get; set; }
[ColumnName("loc3"), LoadColumn(4)]
public float Loc3 { get; set; }
}
}
namespace WinForms01
{
public partial class Form2 : Form
{
private MInput _minput;
public Form2(MInput minput)
{
_minput = minput;
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
textBox1.Text = Convert.ToString(_minput.ID);
textBox2.Text = Convert.ToString(_minput.Loc1);
}
}
}
I'm kinda new to programming... And having trouble finding any documentation regarding this eksampel
Ive managed to call this webservice from a console application, with no problem.
I'm now trying to call the same service from รก webformes soulution. Ive placed the classes in the app_code folder.
I have defiend the JobOfferService class.. But when im trying to call the GetJobOffers() in the class, i not finding it ?
JobOfferService js = new JobOfferService();
protected void Page_Load(object sender, EventArgs e)
{
js. ?? - Error right here??
}
public class JobOfferService
{
private const string Url = "https://www.xxx.com/api/v1/xxxxxx/";
public static List<JobOffer> GetJobOffers()
{
using (var client = new WebClient())
{
client.Headers.Add("Accept", "application/json; charset=utf-8");
client.Encoding = Encoding.UTF8;
var response = client.DownloadString(Url);
var jobOffers = JsonConvert.DeserializeObject<List<JobOffer>>(response);
return jobOffers;
}
}
}
public class JobOffer
{
public string Id { get; set; }
public string EmployerName { get; set; }
public string Title { get; set; }
public string Text { get; set; }
public string ContactInfo { get; set; }
public DateTime ValidTo { get; set; }
}
As it's a static method, you should be able to do
var jobOffers = JobOfferService.GetJobOffers();
Make GetJobOffers() method a instance method. Just remove static keyword.
Or make JobOfferService class static too.
I am receiving an exception: "object reference not set to an instance of an object".
I am trying to evaluate if Location and Manufacturing classes method ResetAllProperties() are executed.
What em I doing wrong?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Rhino.Mocks;
namespace Test
{
public class Engine
{
public Engine() { }
public EngineStatus Status { get; internal set; }
public virtual EngineLocation Location { get; set; }
public virtual EngineManufacturing Manufacturing { get; set; }
}
public abstract class EngineStatus
{
protected readonly Engine engine = null;
public EngineStatus(Engine engine)
{
this.engine = engine;
}
public abstract void ResetAllProperties();
}
public class FirstEngineStatus : EngineStatus
{
public FirstEngineStatus(Engine engine) : base(engine) { }
public override void ResetAllProperties()
{
this.engine.Location.ResetAllProperties();
this.engine.Manufacturing.ResetAllProperties();
}
}
public class EngineLocation
{
public string CustomerName { get; set; }
public virtual EngineManufacturing Manufacturing { get; set; }
public virtual Engine Engine { get; set; }
public void ResetAllProperties()
{
this.CustomerName = null;
}
}
public class EngineManufacturing
{
public Nullable<DateTime> EntryDate { get; set; }
public virtual EngineLocation Location { get; set; }
public virtual Engine Engine { get; set; }
public void ResetAllProperties()
{
this.EntryDate = null;
}
}
[TestClass]
public class Test
{
[TestMethod]
public void ResetAllProperties_AssertWasCalled()
{
// Arrange
var engine = MockRepository.GenerateMock<Engine>();
var status = MockRepository.GeneratePartialMock<FirstEngineStatus>(engine);
engine.Stub(action => action.Location.ResetAllProperties());
engine.Stub(action => action.Manufacturing.ResetAllProperties());
// Act
status.ResetAllProperties();
// Assert
engine.AssertWasCalled(action => action.Location.ResetAllProperties());
engine.AssertWasCalled(action => action.Manufacturing.ResetAllProperties());
}
}
}
You are asserting the behaviour of Location and Manufacturing, so these are the objects which should be mocked. Also, when checking that something happens use Expects not Stub. Everything else should be concrete. If you make ResetAllProperties methods virtual then the following works:
[TestMethod]
public void ResetAllProperties_AssertWasCalled()
{
var location = MockRepository.GeneratePartialMock<EngineLocation>();
var manufacturing = MockRepository.GeneratePartialMock<EngineManufacturing>();
// Arrange
var engine = new Engine
{
Location = location,
Manufacturing = manufacturing
};
var status = new FirstEngineStatus(engine);
location.Expect(action => action.ResetAllProperties());
manufacturing.Expect(action => action.ResetAllProperties());
// Act
status.ResetAllProperties();
// Assert
location.VerifyAllExpectations();
manufacturing.VerifyAllExpectations();
}
However, this seems like you are testing the implementation rather than the functionality. What do you actually want to test? It looks to me like you want to test that CustomerName and EntryDate are set to null. You can test this without using any mocking at all as follows:
[TestMethod]
public void ResetAllProperties_AssertWasCalled()
{
// Arrange
var engine = new Engine
{
Location = new EngineLocation { CustomerName = "Dzenan" },
Manufacturing = new EngineManufacturing { EntryDate = DateTime.Today }
};
var status = new FirstEngineStatus(engine);
// Act
status.ResetAllProperties();
// Assert
Assert.IsNull(engine.Location.CustomerName);
Assert.IsNull(engine.Manufacturing.EntryDate);
}
I am a Final Year Computer Science student trying to develop a Windows 8 phone app and I am very new to this type of development.
I am using a Windows Azure account with a mobile service and a database connection to connect to Visual Studio 2012.
I am trying to allow users to create an account to use my app, however when they enter any details they are not being saved to the table in the database. I am getting the following debugging error when I run my code and press the register button:
"Application_UnhandledException"
Below is what my code looks like.
This is from the CreateAccount.xaml.cs file:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using Microsoft.WindowsAzure.MobileServices;
using Newtonsoft.Json;
namespace IME.Miscellaneous
{
public class accountDetails
{
// Setting up the items for inclusion in the createAccount table
public string Id { get; set; }
[JsonProperty(PropertyName = "userpassword")]
public string Password { get; set; }
[JsonProperty(PropertyName = "securityQuestion1")]
public string SecurityQuestion1 { get; set; }
[JsonProperty(PropertyName = "securityQuestion2")]
public string SecurityQuestion2 { get; set; }
[JsonProperty(PropertyName = "securityQuestion3")]
public string SecurityQuestion3 { get; set; }
[JsonProperty(PropertyName = "answer1")]
public string SecurityAnswer1 { get; set; }
[JsonProperty(PropertyName = "answer2")]
public string SecurityAnswer2 { get; set; }
[JsonProperty(PropertyName = "answer3")]
public string SecurityAnswer3 { get; set; }
}
public partial class CreateAccount : PhoneApplicationPage
{
private MobileServiceCollection<accountDetails, accountDetails> items;
private IMobileServiceTable<accountDetails> accountTable = App.MobileService.GetTable<accountDetails>();
public CreateAccount()
{
InitializeComponent();
}
private async void InsertAccountInfo(accountDetails accountDetailsItem)
{
// This code inserts a new item into the database. When the operation completes
// and Mobile Services has assigned an Id, the item is added
await accountTable.InsertAsync(accountDetailsItem);
items.Add(accountDetailsItem);
}
private async void RefreshAccountInfo()
{
// This code refreshes the entries in the list view be querying the createAccount table.
try
{
items = await accountTable
.Where(accountDetailsItem => accountDetailsItem.Password == "")
.ToCollectionAsync();
}
catch (MobileServiceInvalidOperationException e)
{
MessageBox.Show(e.Message, "Error loading items", MessageBoxButton.OK);
}
}
private void Register_Button_Tap(object sender, System.Windows.Input.GestureEventArgs e)
{
// Brings the user to the Home hub page
NavigationService.Navigate(new Uri("/MainPage.xaml", UriKind.Relative));
// When button is clicked the accountDetails table is updated with the password
//var user = new accountDetails { Id = ID_textbox.Text, Password = Password_Text.Password, SecurityQuestion1 = Security_Question_1.Text, SecurityQuestion2 = Security_Question_2.Text,
// SecurityQuestion3 = Security_Question_3.Text, SecurityAnswer1 = Security_Question_1_Answer.Text, SecurityAnswer2 = Security_Question_2_Answer.Text,
// SecurityAnswer3 = Security_Question_3_Answer.Text};
// InsertAccountInfo(user);
}
protected override void OnNavigatedTo(NavigationEventArgs e)
{
RefreshAccountInfo();
}
private void Security_Question_1_Answer_GotFocus(object sender, RoutedEventArgs e)
{
// Sets the textbox to empty when the user clicks on it
TextBox securityAnswerOne = (TextBox)sender;
securityAnswerOne.Text = string.Empty;
securityAnswerOne.GotFocus -= Security_Question_1_Answer_GotFocus;
}
private void Security_Question_2_Answer_GotFocus(object sender, RoutedEventArgs e)
{
// Sets the textbox to empty when the user clicks on it
TextBox securityAnswerTwo = (TextBox)sender;
securityAnswerTwo.Text = string.Empty;
securityAnswerTwo.GotFocus -= Security_Question_2_Answer_GotFocus;
}
private void Security_Question_3_Answer_GotFocus(object sender, RoutedEventArgs e)
{
// Sets the textbox to empty when the user clicks on it
TextBox securityAnswerThree = (TextBox)sender;
securityAnswerThree.Text = string.Empty;
securityAnswerThree.GotFocus -= Security_Question_3_Answer_GotFocus;
}
private void Security_Question_3_Answer_LostFocus(object sender, RoutedEventArgs e)
{
TextBox securityAnswerThree = (TextBox)sender;
if (String.IsNullOrEmpty(Security_Question_3_Answer.Text))
{
securityAnswerThree.Text = "Please Enter an answer";
securityAnswerThree.LostFocus -= Security_Question_3_Answer_LostFocus;
}
}
private void Security_Question_2_Answer_LostFocus(object sender, RoutedEventArgs e)
{
TextBox securityAnswerTwo = (TextBox)sender;
if (String.IsNullOrEmpty(Security_Question_2_Answer.Text))
{
securityAnswerTwo.Text = "Please Enter an answer";
securityAnswerTwo.LostFocus -= Security_Question_2_Answer_LostFocus;
}
}
private void Security_Question_1_Answer_LostFocus(object sender, RoutedEventArgs e)
{
TextBox securityAnswerOne = (TextBox)sender;
if (String.IsNullOrEmpty(Security_Question_3_Answer.Text))
{
securityAnswerOne.Text = "Please Enter an answer";
securityAnswerOne.LostFocus -= Security_Question_3_Answer_LostFocus;
}
}
}
}
This is from the App.xaml.cs file:
// Creating account details table
public class accountDetails
{
public int id { get; set; }
public string userpassword { get; set; }
public string securityQuestion1 { get; set; }
public string securityQuestion2 { get; set; }
public string securityQuestion3 { get; set; }
public string answer1 { get; set; }
public string answer2 { get; set; }
public string answer3 { get; set; }
public accountDetails(string p, string sq1, string sq2, string sq3, string a1, string a2, string a3)
{
// Creating the constructor
userpassword = p;
securityQuestion1 = sq1;
securityQuestion2 = sq2;
securityQuestion3 = sq3;
answer1 = a1;
answer2 = a2;
answer3 = a3;
}
}
The table in the database is called "CreateAccount" also.
Any help would be greatly appreciated.
This is my first time using json.net and I can't figure it out. Here is my code below.
// Constructor
public MainPage()
{
InitializeComponent();
}
private void btnRefreshTweets_Click(object sender, RoutedEventArgs e)
{
string ServerURL = #"http://sampleserver1.arcgisonline.com/ArcGIS/rest/services/Specialty/ESRI_StateCityHighway_USA/MapServer/1/query?text=e&geometry=&geometryType=esriGeometryPoint&inSR=&spatialRel=esriSpatialRelIntersects&relationParam=&objectIds=&where=&time=&returnCountOnly=false&returnIdsOnly=false&returnGeometry=false&maxAllowableOffset=&outSR=&outFields=&f=json";
WebClient webClient = new WebClient();
webClient.DownloadStringCompleted += new DownloadStringCompletedEventHandler(webClient_DownloadStringCompleted);
webClient.DownloadStringAsync(new Uri(ServerURL));
}
void webClient_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
if (e.Error != null)
{
return;
}
List<Attributes> tweets = JsonConvert.DeserializeObject<List<Attributes>>(e.Result);
this.lbTweets.ItemsSource = tweets;
}
public class Attributes
{
public string STATE_NAME { get; set; }
}
I can't deserialize the STATE_NAME attributes. What am I missing?
I keep getting this error
"Cannot deserialize JSON object into type
'System.Collections.Generic.List`1[WPJsonSample.MainPage+Attributes]'.
Line 1, position 20."
Here is your class structure ( I used http://json2csharp.com/)
public class FieldAliases
{
public string STATE_NAME { get; set; }
}
public class Field
{
public string name { get; set; }
public string type { get; set; }
public string alias { get; set; }
public int length { get; set; }
}
public class Attributes
{
public string STATE_NAME { get; set; }
}
public class Feature
{
public Attributes attributes { get; set; }
}
public class RootObject
{
public string displayFieldName { get; set; }
public FieldAliases fieldAliases { get; set; }
public List<Field> fields { get; set; }
public List<Feature> features { get; set; }
}
IF you are trying to hit that endpoint, you should not be manually submitting the query, you should use the ArcGIS WP7 SDK (it's FREE!). Then use the QueryTask.
(if you just need help with parsing JSON, see below)
QueryTask queryTask = new QueryTask("http://sampleserver1.arcgisonline.com/ArcGIS/rest/services/Specialty/ESRI_StateCityHighway_USA/MapServer/1/");
queryTask.ExecuteCompleted += QueryTask_ExecuteCompleted;
queryTask.Failed += QueryTask_Failed;
ESRI.ArcGIS.Client.Tasks.Query query = new ESRI.ArcGIS.Client.Tasks.Query();
query.Text = "e";
query.ReturnGeometry = false;
queryTask.ExecuteAsync(query);
private void QueryTask_ExecuteCompleted(object sender, ESRI.ArcGIS.Client.Tasks.QueryEventArgs args)
{
FeatureSet featureSet = args.FeatureSet
// use the featureSet to do something. It contains everything you need
}
If for whatever reason, you do not want to use the QueryTask, you can still use the FromJson method of the FeatureSet
void webClient_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
var featureSet = ESRI.ArcGIS.Client.Tasks.FeatureSet.FromJson(e.Result);
// Use it
}
If you need help with JSON, here are some key concepts.
1) Curly braces represent an object
2) square brackets represent an array.
3) properties are separated by commas
When using JSON.NET, you should add the JsonProperty attribute to a property. This way you can maintain proper names even if the json sucks
[JsonProperty("STATE_NAME")]
public string StateName { get; set; }
The JSON returned from that url is:
{
"displayFieldName": "STATE_NAME",
"fieldAliases": {
"STATE_NAME": "STATE_NAME"
},
"fields": [
{
"name": "STATE_NAME",
"type": "esriFieldTypeString",
"alias": "STATE_NAME",
"length": 25
}
],
"features": [
{
"attributes": {
"STATE_NAME": "Maine"
}
}
}
So, we can see here the root is an object, not an enumerable like a List<>
You'll have to fix the class structure to match the JSON, or access it with Linq queries (there are some samples of this in the json.net website).