It is necessary to replace the direct connection to the database with API.
I use this code to directly connect to MySQL db and change pin information:
public async void DatabaseConnection(List<CustomPin> pins)
{
string ConnectionString = "server=192.168.0.1;uid=user;port=4444;pwd=pass;database=dbName;";
MySqlConnection Conn = new MySqlConnection(ConnectionString);
try
{
Conn.Open();
string query = "SELECT * FROM sel_alert_level s;";
MySqlCommand myCommand = new MySqlCommand(query, Conn);
MySqlDataReader myReader;
myReader = myCommand.ExecuteReader();
try
{
while (myReader.Read())
{
int codeNum = myReader.GetInt32(4);
int level = myReader.GetInt32(3);
int mapCode = myReader.GetInt32(0);
foreach (var item in pins)
{
if (item.CodeNum == codeNum)
{
item.AlertLevel = level;
item.CodeNum = codeNum;
item.MapCode = mapCode;
//await DisplayAlert("Alert", mapCode.ToString(), "ok");
}
}
//await DisplayAlert("Database Connection", "Connected .." + Environment.NewLine + myReader.GetInt32(0) + Environment.NewLine + myReader.GetString(1) + Environment.NewLine + myReader.GetString(2) + Environment.NewLine + myReader.GetInt32(3) + Environment.NewLine + myReader.GetInt32(4), "OK");
}
}
finally
{
myReader.Close();
Conn.Close();
}
}
catch (Exception ex)
{
await DisplayAlert("Database Connection", "Not Connected ..." + Environment.NewLine + ex.ToString(), "OK");
}
}
With this code I successfully update the pin information.
Now I create the same method with API Response and what to do the same like DatabaseConnection(); just try to update the information, but not work for me :(
public async void APIConnection(List<CustomPin> pins)
{
try
{
WaterBindingData waterData = await _restServiceData.GetWaterDataForecast(GenerateRequestUriStations(Constants.EndPoint), GenerateRequestUri(Constants.EndPoint));
foreach (var water in waterData.WaterStation.Stations)
{
foreach (var item in pins)
{
if (item.CodeNum == water.CodeNum)
{
item.AlertLevel = water.AlertLevelStation;
item.CodeNum = water.CodeNum;
item.MapCode = water.MapCode;
}
}
}
}
catch (Exception ex)
{
await DisplayAlert("Data Alert", "Error:" + Environment.NewLine + ex.ToString(), "OK");
}
}
I not have any errors here. waterData come with the data, but data not changed in the pins.. I don't know why...
And Now my information are not changed ..
MapCode and other variables not changed.
I call this two methods in the constructor like that:
DatabaseConnection(customMap.CustomPins);
APIConnection(customMap.CustomPins);
So... When I start the project I receive message like this:
/Applications/Visual Studio.app/Contents/Resources/lib/monodevelop/bin/MSBuild/Current/bin/Microsoft.Common.CurrentVersion.targets(5,5): Warning MSB3276: Found conflicts between different versions of the same dependent assembly. Please set the "AutoGenerateBindingRedirects" property to true in the project file. For more information, see http://go.microsoft.com/fwlink/?LinkId=294190. (MSB3276) (MaritsaTundzhaForecast.iOS)
And I check this link but I not have properties option, because I use mac. I have only options on the projects.
Is it possible that this does not change the content in the pins аnd what would be the reason it didn't work ?
I checked the if statement in the loop and she work:
Since it is an asynchronous method , I suggest you try to assign customMap.CustomPins in APIConnection method .
Something like that
//constructor
List<CustomPin> pins = xxxxx;
APIConnection(pins);
public async void APIConnection(List<CustomPin> pins)
{
try
{
WaterBindingData waterData = await _restServiceData.GetWaterDataForecast(GenerateRequestUriStations(Constants.EndPoint), GenerateRequestUri(Constants.EndPoint));
foreach (var water in waterData.WaterStation.Stations)
{
foreach (var item in pins)
{
if (item.CodeNum == water.CodeNum)
{
item.AlertLevel = water.AlertLevelStation;
item.CodeNum = water.CodeNum;
item.MapCode = water.MapCode;
}
}
}
customMap.CustomPins = pins; //assign the value in this line
}
catch (Exception ex)
{
await DisplayAlert("Data Alert", "Error:" + Environment.NewLine + ex.ToString(), "OK");
}
}
Related
I am working on a Xamarin App where I am facing an issue.
Case 1:
Mode: Debug
Error: System.NullReferenceException: 'Object reference not set to an instance of an object'
Explanation:
No value is being set and passed to ViewModel, Controller.
Even I tried setting static values to variables and parameters.
LoginModel logtest = new LoginModel();
logtest.Username = "Test#user.com"; //uName;
logtest.Password = "2342534"; //pWord;
Tried solution:
In the beginning, I tried many different solutions nothing worked.
Then I create a new project and moved all the code to the new project, then it started working.
Case 2:
Mode: release
Now the same issue I am getting in release mode.
No value is being set and passed to ViewModels and Controller.
I have already tried moving code to a new project.
How can I resolve this? I am not sure is this a Visual studio issue or Xamarin issue or Apple.
I have tried updating Visual Studio enterprise 2019 and Xcode on Mac.
Deleted and recreated Provisioning Profiles and Signing Identities.
Code From LoginPage.xaml.cs
private async void LoginButtonClicked(object sender, EventArgs e)
{
await ((LoginViewModel)BindingContext).Login();
}
protected async override void OnAppearing()
{
//App.Current.MainPage = new Navigation(new DashboardPage());
//load the login page
Device.BeginInvokeOnMainThread(() =>
{
try
{
((LoginViewModel)BindingContext).IsLoading = false;
((LoginViewModel)BindingContext).RememberMe = DeviceStorage.RememberMe;
if (DeviceStorage.RememberMe == true)
{
((LoginViewModel)BindingContext).UserName = "Test#user.ca"; //Trying set static values here
((LoginViewModel)BindingContext).Password = "password"; //Trying set static values here
}
//RememberMeToggle.Toggled += switcher_Toggled;
((LoginViewModel)BindingContext).Load();
}
catch (Exception ex)
{
//logger.Error(App.LogPrefix() + "Error opening Navigation Page: " + ex.Message);
Console.WriteLine(App.LogPrefix() + "Error opening Load(): " + ex.Message);
}
});
}
Code from LoginViewModel.cs
public async Task Login()
{
IsLoading = true;
await TokenController.GetAuthorizationToken(UserName, Password);
}
Code from TokenController.cs
public static async Task GetAuthorizationToken(string uName, string pWord)
{
bool tokenReturned = false;
string tokenGetResponse = string.Empty;
// Have tried setting them static values as well
LoginModel logtest = new LoginModel();
logtest.Username = uName;
logtest.Password = pWord;
logtest.AppType = Constants.AppDetails.APP_CODE;
logtest.SystemCode = Constants.AppDetails.SYSTEM_CODE;
logtest.Push.PushSystem = PushAddressModel.PushSystemCode.FireBase;
logtest.Push.Address = ((App)App.Current).PushNotificationToken;
logtest.Push.AppCode = Constants.AppDetails.APP_CODE;
string uri = URI.message_Chat_Endpoint;
(tokenReturned, tokenGetResponse) = await ApiFunctions.Post(logtest, URI.token_Endpoint, false);
if (tokenReturned)
{
try
{
//deserialize the return object
TokenModel token = JsonConvert.DeserializeObject<TokenModel>(tokenGetResponse);
((App)App.Current).token = token;
}
catch (Exception ex)
{
Console.WriteLine("Error: " + ex.Message);
//logger.Error(App.LogPrefix() + "Error: " + ex.Message);
}
Console.WriteLine("Profile Token loaded: " + ((App)App.Current).token.access_token);
}
else
{
Console.WriteLine("Error: Error loading profile token ");
//logger.Error(App.LogPrefix() + "Error loading profile token");
}
}
I have prepared xml files with some content and want to load it while playing on iOS device but also I want to change loaded data and serialize it in the same file again.
In Unity Editor (Windows) it works perfectly, but when I test it on iOS device it seems that I can read from StreamingAssets using WWW class, but I can't write into it.
Also I have found that I can read and write into path created by Application.persistentDataPath. But it seems that location somewhere in device and I can't put my xml into that location and users have access to that folder so that isn't good solution, isn't it?
Here code that I use to load and save the data.
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.IO;
using System.Xml;
public class testxml : MonoBehaviour {
public Text result;
public InputField firstPart, secondPart;
public Toggle toggle;
private List<int> listToSave;
// Use this for initialization
void Start () {
listToSave = new List<int>();
}
public void Save()
{
Serialize();
}
public void Load()
{
StartCoroutine(Deserialize());
}
private void Serialize()
{
string path = GetPath();
try
{
Debug.Log("trying to save");
var serializer = new XmlSerializer(typeof(List<int>));
using (var fs = new FileStream(path, FileMode.OpenOrCreate))
{
serializer.Serialize(fs, listToSave);
}
}
catch (XmlException e)
{
result.text = "error";
Debug.LogError(path + " with " + (toggle.isOn ? "persistent data path" : "data path"));
Debug.LogError("xml exc while des file : " + e.Message);
}
catch (System.Exception e)
{
result.text = "error";
Debug.LogError("exc while des file : " + e.Message);
Debug.LogError(path + " with " + (toggle.isOn ? "persistent data path" : "data path"));
System.Exception exc = e.InnerException;
int i = 0;
while (exc != null)
{
Debug.Log("inner " + i + ": " + exc.Message);
i++;
exc = exc.InnerException;
}
}
}
private IEnumerator Deserialize()
{
Debug.Log("trying to load");
string path = GetPath();
var www = new WWW(path);
yield return www;
if (www.isDone && string.IsNullOrEmpty(www.error))
{
try
{
var serializer = new XmlSerializer(typeof(List<int>));
MemoryStream ms = new MemoryStream(www.bytes);
listToSave = serializer.Deserialize(ms) as List<int>;
ms.Close();
result.text += "Done\n";
foreach (var i in listToSave)
result.text += i + "\n";
}
catch (XmlException e)
{
result.text = "error";
Debug.LogError(path + " with " + (toggle.isOn?"persistent data path":"data path"));
Debug.LogError("xml exc while des file : " + e.Message);
}
catch (System.Exception e)
{
result.text = "error";
Debug.LogError("exc while des file : " + e.Message);
Debug.LogError(path + " with " + (toggle.isOn ? "persistent data path" : "data path"));
System.Exception exc = e.InnerException;
int i = 0;
while(exc!=null)
{
Debug.Log("inner "+i+": " + exc.Message);
i++;
exc = exc.InnerException;
}
}
yield break;
}
else
{
Debug.LogError("www exc while des file " + www.error);
Debug.LogError(path + " with " + (toggle.isOn ? "persistent data path" : "data path"));
yield break;
}
}
private string GetPath()
{
string path = firstPart.text;
if (toggle.isOn)
{
path += Application.persistentDataPath;
}
else
path += Application.dataPath;
path += secondPart.text;
return path;
}
}
"I want to put my xml file in this folder, and then read it. It's like default info for game"
easy, just put it in your assets. go like this...
public TextAsset myXMLFile;
in Inspector drag the file there. You're done.
"but then I also want to change that file and save"
Fair enough. What you have to do is
(1) make a path p = Application.persistentDataPath + "values.txt"
(2) program launches.
(3) check if "p" exists. if yes, read it and go to (6)
(4) IF NOT, read the textasset and save that to "p"
(5) go to point (3)
(6) you're done.
It's the only way to do it. This is indeed the normal procedure in Unity, you do it in every Unity app. There's no other way!
I have a form an one button on it,
below is very really simple my code:
private void ConnectDb()
{
try
{
connect = new OleDbConnection();
connect.ConnectionString = #"Provider=Microsoft.ACE.OLEDB.15.0;Data Source=MySong.accdb;Persist Security Info=false;";
connect.Open();
statusText.Text = "Database connected";
command = connect.CreateCommand();
}
catch (Exception)
{
statusText.Text = "ERROR::Database failed";
}
}
private void CloseConnectDb()
{
if (connect != null)
{
connect.Close();
statusText.Text = "Database Closed";
}
}
private void btnTambah_Click(object sender, EventArgs e)
{
DateTime tanggal = DateTime.Today;
Band = txtArtis.Text;
Title = txtJudul.Text;
this.ConnectDb();
command.CommandText = "INSERT INTO TableLagu (Tanggal, Artis, Title, Status) VALUES ('" + tanggal + "', '" + Band + "', '" + Title + "', 'Belum ada')";
if (command.ExecuteNonQuery() != 0) //executenonquery returns number of row affected
{
statusText.Text = "ADD--Data Success inserted";
txtArtis.Text = "";
txtJudul.Text = "";
}
else statusText.Text = "ERROR::Insert failed";
this.CloseConnectDb();
}
When i click on my 'btnTambah' button, it always say "object reference not set to an instance of an object" and display "ERROR::Database failed" on its statusText.
any solution??
i think this code doesn't run while try to call ConnectDb method.
you can see my connection string
Provider=Microsoft.ACE.OLEDB.15.0;
actually, when i creating it, i have microsoft access database 2013 installed on my machine. it works good.
now, i'm trying to run my application on my friends computer that microsoft access installed version 2007. and got an error like above.
I am trying to extract header and body information from email, the following code retrieves the header and body in their raw form. I have an email object that contains the fields from, subject, date, and body. I would like to extract these values from the email and assign them to the email object. How do I get around it? I have tried several ways like getting the header info and using a streamReader.ReadLine() to get a line but I got illegal path exceptions. I know I can use a library but I need to achieve it this way.
What I mean is this, IMAP command returns header information. And I want to extract subject value, date value, sender e-amil, etc. and assign them to my email objects corresponding values like
emailObject.subject = "subjectValue"
public class Imap
{
static void Main(string[] args)
{
try
{
path = Environment.CurrentDirectory + "\\emailresponse.txt";
if (System.IO.File.Exists(path))
System.IO.File.Delete(path);
sw = new System.IO.StreamWriter(System.IO.File.Create(path));
tcpc = new System.Net.Sockets.TcpClient("imap.gmail.com", 993);
ssl = new System.Net.Security.SslStream(tcpc.GetStream());
ssl.AuthenticateAsClient("imap.gmail.com");
receiveResponse("");
Console.WriteLine("username : ");
username = Console.ReadLine();
Console.WriteLine("password : ");
password = Console.ReadLine();
receiveResponse("$ LOGIN " + username + " " + password + " \r\n");
Console.Clear();
receiveResponse("$ LIST " + "\"\"" + " \"*\"" + "\r\n");
receiveResponse("$ SELECT INBOX\r\n");
receiveResponse("$ STATUS INBOX (MESSAGES)\r\n");
Console.WriteLine("enter the email number to fetch :");
int number = int.Parse(Console.ReadLine());
Console.WriteLine("*************Header************");
Console.WriteLine("");
// receiveResponse("$ FETCH " + number + " body[header]\r\n");
// BODY.PEEK[HEADER.FIELDS (SUBJECT)]
// StringBuilder sb = receiveResponse("$ FETCH " + number + " BODY.PEEK[HEADER.FIELDS (From Subject Date)]\r\n");
StringBuilder sb= receiveResponse("$ FETCH " + number + " body.peek[header]\r\n");
Console.WriteLine(sb);
Console.WriteLine("");
Console.WriteLine("Body");
sb = new StringBuilder();
sb=receiveResponse("$ FETCH " + number + " body[text]\r\n");
System.Text.ASCIIEncoding enc = new System.Text.ASCIIEncoding();
byte[] serverbuff = new Byte[1024];
int count = 0;
string retval = enc.GetString(serverbuff, 0, count);
Console.WriteLine(sb.ToString());
receiveResponse("$ LOGOUT\r\n");
}
catch (Exception ex)
{
Console.WriteLine("error: " + ex.Message);
}
finally
{
if (sw != null)
{
sw.Close();
sw.Dispose();
}
if (ssl != null)
{
ssl.Close();
ssl.Dispose();
}
if (tcpc != null)
{
tcpc.Close();
}
}
Console.ReadKey();
}
static StringBuilder receiveResponse(string command)
{
sb = new StringBuilder();
try
{
if (command != "")
{
if (tcpc.Connected)
{
dummy = Encoding.ASCII.GetBytes(command);
ssl.Write(dummy, 0, dummy.Length);
}
else
{
throw new ApplicationException("TCP CONNECTION DISCONNECTED");
}
}
ssl.Flush();
buffer = new byte[2048];
bytes = ssl.Read(buffer, 0, 2048);
sb.Append(Encoding.ASCII.GetString(buffer));
// Console.WriteLine(sb.ToString());
sw.WriteLine(sb.ToString());
// sb = new StringBuilder();
return sb;
}
catch (Exception ex)
{
throw new ApplicationException(ex.Message);
}
}
You said you do not want to use an IMAP library. This means that you will have to implement your own. You should start by reading RFC 3501 because there is no chance you could get the protocol right without reading the docs carefuly. In particular, you're issuing a STATUS command on the currently selected mailbox, which is explicitly forbidden by the protocol specification. The rest of the code supports the assumption that you have not read the RFC yet.
How can I get the all HTTP request headers, method, the suffix of the connection, and all parameters that I added to the request?
Try something like this (I ran this code on a background thread, which I why I use UiApplication.invokeLater() to display results):
try {
ConnectionFactory factory = new ConnectionFactory(); // for OS 5.0+
factory.setPreferredTransportTypes(new int[] {
TransportInfo.TRANSPORT_TCP_WIFI,
TransportInfo.TRANSPORT_TCP_CELLULAR
});
// For OS < 5.0
//HttpConnection conn = (HttpConnection) Connector.open("http://www.google.com;interface=wifi");
HttpConnection conn = (HttpConnection) factory.getConnection("http://www.google.com").getConnection();
conn.setRequestProperty("sessionId", "ABCDEF0123456789");
final StringBuffer results = new StringBuffer();
String key = "";
int index = 0;
// loop over all the header fields, and record their values
while (key != null) {
key = conn.getHeaderFieldKey(index);
if (key != null) {
String value = conn.getHeaderField(key);
results.append(key + " = " + value + "\n\n");
}
index++;
}
results.append("method = " + conn.getRequestMethod() + "\n\n");
// we (should) know which request properties we've set, so we ask
// for them by name here
String sessionId = conn.getRequestProperty("sessionId");
results.append("sessionId = " + sessionId + "\n\n");
String url = conn.getURL();
results.append("URL = " + url);
// show the result on screen (UI thread)
UiApplication.getUiApplication().invokeLater(new Runnable() {
public void run() {
textField.setText(results.toString());
}
});
} catch (IOException e) {
e.printStackTrace();
}