FormatException in application iOS Xamarin(C#) - c#

In my mobile app (iOS) I have FormatException in this code:
public partial class DetailTovarProsmotr : UIViewController
{
public JsonValue myjsondetail;
int count_product;
float price_defoult;
public string Code1;
public DetailTovarProsmotr (IntPtr handle) : base (handle)
{
}
public async Task<UIImage> LoadImage (string imageUrl)
{
var httpClient = new HttpClient();
Task<byte[]> contentsTask = httpClient.GetByteArrayAsync (imageUrl);
// await! control returns to the caller and the task continues to run on another thread
var contents = await contentsTask;
// load from bytes
return UIImage.LoadFromData (NSData.FromArray (contents));
}
public async override void ViewDidLoad ()
{
base.ViewDidLoad ();
// Console.Out.WriteLine (detailtitle+" ViewDidLoad metod is run" + myjsondetail["ID"].ToString());
Code1 = myjsondetail ["sku"];
titleproduct001.Text = myjsondetail["post_title"];
postSingleProduct.Text = myjsondetail["post_excerpt"];
Weight001.Text = myjsondetail["weight"]+" г";
price001.Text = myjsondetail["price"]+" грн";
postImage.Image =await this.LoadImage (myjsondetail["img_url"]);
count_product = 1;
countproduct.Text = "1";
//float price_defoult = float.Parse(price001.Text, CultureInfo.InvariantCulture) ;
price_defoult = float.Parse( ((string)myjsondetail["price"]).Replace(".00", ".0") );
plus.TouchUpInside += (o,s) => {
//Console.Out.WriteLine("Нажали плюс!!!!");
countproduct.Text = string.Format("{0}", ++count_product);
price001.Text = string.Format("{0}", count_product*price_defoult + "грн");
};
mines.TouchUpInside += (o,s) => {
// Console.Out.WriteLine("Нажали минусссс!!!!");
countproduct.Text = string.Format("{0}", count_product > 1 ? --count_product : 1);
price001.Text = string.Format("{0}", count_product * price_defoult + "грн");
};
addToCart.TouchUpInside += (o,s) => {
var documents = Environment.GetFolderPath (Environment.SpecialFolder.MyDocuments);
var filePath = Path.Combine (documents, "myFile.xml");
Console.Out.WriteLine("Добавить в корзину!!!!!");
Console.Out.WriteLine(countproduct.Text);
//MessageBarStyleSheet styles = new MessageBarStyleSheet ();
//UIColor colorb = UIColor.Black;
//styles.BackgroundColorForMessageType(MessageType.Info).GetWhite;
// style.BackgroundColorForMessageType = UIColor.Black;
MessageBarManager.SharedInstance.ShowMessage ("Товар добавлен ", "в корзину", MessageType.Info);
//Posrednic singleprod = new Posrednic(myjsondetail);
CartProduct cart = new CartProduct();
int productQty = int.Parse(countproduct.Text);
for (int i = 0; i< productQty; i++) {
cart.Add(myjsondetail.ToString());
}
CartProduct.PrintProducts(cart);
//singleprod.myjsondetail =myjsondetail;
XDocument doc = XDocument.Load(filePath);
var product = new XElement("Product", new XAttribute("Code", Code1), new XAttribute("Qty", countproduct.Text));
var products = doc.Descendants("Products").First(); // Get the first Products node. Throw an exception if not found.
products.Add(product);
File.WriteAllText(filePath, doc.ToString());
doc.Save (filePath);
Console.WriteLine("Smotri tut");
Console.WriteLine (doc.ToString());
};
}
}
I think my problem in this line
price_defoult = float.Parse( ((string)myjsondetail["price"]).Replace(".00", ".0") );
but I don't now where my problem. In simulator my code is working, but in iphone 5s I have:
FormatException Input string was not in a correct format. (mscorlib)
SIGABRT Crash in System_Runtime_CompilerServices_AsyncMethodBuilderCore__ThrowAsyncm__0_object
SIGABRT Crash in System_Xml_XmlTextReaderImpl_Read

I'm solved my problem:
delete line 6 float price_defoult;
in line price001.Text = myjsondetail["price"]+" грн"; deleting +" грн"
use this line float price_defoult = float.Parse(price001.Text, CultureInfo.InvariantCulture) for bringing type.

Related

How to fix "Value was either too large or too small for a UInt32" C#

I am trying to convert ActionScript3 code to C# that's like the main thing. However, with trying to convert one of the functions I got the error which is in the title when I was trying to convert a hexadecimal string to an int.
Basically, this code is supposed to take information for example user data and then do somethings and in the end return Base64 encoded text. The main error that I am aware of is at the part where "loc9 = Convert.ToInt32(loc8, 16);" is as that is where I am getting the error said in the title. I have tried researching similar issues others have had with something like this, but it just didn't seem the same and didn't really help me out.
(Btw I am sorry if this doesn't sound so clear, correct me or ask more questions if not understood)
Screenshot of error when called
My C# Code:
private static string hasher(string input)
{
MD5 md5 = System.Security.Cryptography.MD5.Create();
byte[] inputBytes = System.Text.Encoding.ASCII.GetBytes(input);
byte[] hash = md5.ComputeHash(inputBytes);
StringBuilder sb = new StringBuilder();
for (int i = 0; i < hash.Length; i++)
{
sb.Append(hash[i].ToString("x2"));
}
return sb.ToString();
}
public static string p(string param1)
{
var loc6 = "";
var loc7 = "";
var loc8 = "";
var loc9 = 0;
var loc2 = hasher(param1);
var loc4 = 0;
MemoryStream loc0 = new MemoryStream();
var loc3 = new byte[] { };
while(loc4 < loc2.Length * 2)
{
loc6 = loc2.Substring(loc4, loc4 + 1);
loc7 = loc2.Substring(loc4 + 1, loc4 + 2);
loc8 = "0x" + loc6 + loc7;
loc9 = Convert.ToInt32(loc8, 16);
new BinaryWriter(loc0).Write(loc9);
loc4 = loc4 + 2;
}
loc0.Position = 0;
loc3 = loc0.ToArray();
return Convert.ToBase64String(loc3, 0, 16);
}
public string calculateFromNewActorCreationData(string username, string password, byte[] small, byte[] full)
{
return calculateFromStrings(username, password, small, full);
}
public string calculateFromStrings(string param1, string param2, object param3, object param4)
{
var loc5 = param1 + param2 + fromByteArray(param3 as byte[]) + fromByteArray(param4 as byte[]) + p();
return p(loc5);
}
private string fromByteArray(byte[] param1)
{
var ms = new MemoryStream(param1);
List<byte> list2 = new List<byte>();
if (param1.Length <= 20)
return HexStringFromBytes(param1);
var loc3 = new byte[] { };
var loc4 = param1.Length / 20;
var loc5 = 0;
while (loc5 < 20)
{
ms.Position = loc4 * loc5;
list2.Add(new BinaryReader(ms).ReadByte());
loc5++;
}
loc3 = list2.ToArray();
return HexStringFromBytes(loc3);
}
private static string HexStringFromBytes(byte[] bytes)
{
var sb = new StringBuilder();
foreach (byte b in bytes)
{
var hex = b.ToString("x2");
sb.Append(hex);
}
return sb.ToString();
}
private string p()
{
MemoryStream stream = new MemoryStream();
new BinaryWriter(stream).Write(120);
new BinaryWriter(stream).Write(-38);
new BinaryWriter(stream).Write(99);
new BinaryWriter(stream).Write(16);
new BinaryWriter(stream).Write(32);
new BinaryWriter(stream).Write(51);
new BinaryWriter(stream).Write(41);
new BinaryWriter(stream).Write(-110);
new BinaryWriter(stream).Write(12);
new BinaryWriter(stream).Write(50);
new BinaryWriter(stream).Write(81);
new BinaryWriter(stream).Write(73);
new BinaryWriter(stream).Write(49);
new BinaryWriter(stream).Write(-56);
new BinaryWriter(stream).Write(13);
new BinaryWriter(stream).Write(48);
new BinaryWriter(stream).Write(54);
new BinaryWriter(stream).Write(54);
new BinaryWriter(stream).Write(14);
new BinaryWriter(stream).Write(48);
new BinaryWriter(stream).Write(46);
new BinaryWriter(stream).Write(2);
new BinaryWriter(stream).Write(0);
new BinaryWriter(stream).Write(45);
new BinaryWriter(stream).Write(-30);
new BinaryWriter(stream).Write(4);
new BinaryWriter(stream).Write(-16);
stream.Position = 0;
return Encoding.UTF8.GetString(stream.ToArray());
}
ActionScript3 Code:
private static function p(param1:String) : String
{
var _loc6_:String = null;
var _loc7_:String = null;
var _loc8_:String = null;
var _loc9_:int = 0;
var _loc2_:String = MD5.hash(param1);
var _loc3_:ByteArray = new ByteArray();
var _loc4_:int = 0;
while(_loc4_ < _loc2_.length * 2)
{
_loc6_ = _loc2_.slice(_loc4_,_loc4_ + 1);
_loc7_ = _loc2_.slice(_loc4_ + 1,_loc4_ + 2);
_loc8_ = "0x" + _loc6_ + _loc7_;
_loc9_ = int(_loc8_);
_loc3_.writeByte(_loc9_);
_loc4_ = _loc4_ + 2;
}
_loc3_.position = 0;
var _loc5_:Base64Encoder = new Base64Encoder();
_loc5_.encodeBytes(_loc3_,0,16);
return _loc5_.toString();
}
public function calculateFromNewActorCreationData(param1:NewActorCreationData, param2:ByteArray, param3:ByteArray) : String
{
return this.calculateFromStrings(param1.ChosenActorName,param1.ChosenPassword,param2,param3);
}
public function calculateFromStrings(param1:String, param2:String, param3:Object, param4:Object) : String
{
var _loc5_:String = param1 + param2 + this.fromByteArray(param3) + this.fromByteArray(param4) + this.p();
return p(_loc5_);
}
private function fromByteArray(param1:Object) : String
{
if(param1 == null)
{
return "";
}
var _loc2_:int = 20;
if(param1.length <= _loc2_)
{
return Hex.fromArray(param1 as ByteArray);
}
var _loc3_:ByteArray = new ByteArray();
var _loc4_:int = param1.length / _loc2_;
var _loc5_:int = 0;
while(_loc5_ < _loc2_)
{
param1.position = _loc4_ * _loc5_;
_loc3_.writeByte(param1.readByte());
_loc5_++;
}
return Hex.fromArray(_loc3_);
}
private function p() : String
{
var _loc1_:ByteArray = new ByteArray();
_loc1_.writeByte(120);
_loc1_.writeByte(-38);
_loc1_.writeByte(99);
_loc1_.writeByte(16);
_loc1_.writeByte(12);
_loc1_.writeByte(51);
_loc1_.writeByte(41);
_loc1_.writeByte(-118);
_loc1_.writeByte(12);
_loc1_.writeByte(50);
_loc1_.writeByte(81);
_loc1_.writeByte(73);
_loc1_.writeByte(49);
_loc1_.writeByte(-56);
_loc1_.writeByte(13);
_loc1_.writeByte(48);
_loc1_.writeByte(54);
_loc1_.writeByte(54);
_loc1_.writeByte(14);
_loc1_.writeByte(48);
_loc1_.writeByte(46);
_loc1_.writeByte(2);
_loc1_.writeByte(0);
_loc1_.writeByte(45);
_loc1_.writeByte(-30);
_loc1_.writeByte(4);
_loc1_.writeByte(-16);
_loc1_.uncompress();
_loc1_.position = 0;
return _loc1_.readUTF();
}
What I am expecting in the end is to be able to call the function having the returned Base64 encoded data show in a MessageBox (using messagebox as a test) instead of any errors popping up.
P.S - Besides the main problem I am having with this code, I also feel like the other functions I had converted aren't perfect or just might not be the same. So, if my main problem can be solved, if someone can also double check the other functions of my code make sure they are accurate that would be amazing and thanks in advance.
Looking at this overall, it appears the AS3 code is attempting to convert the MD5.hash result into a Base64 encoded string in the worst way possible (I believe it can be done in one line.)
So, instead of copying all the code to translate the hash to a hex string only to poorly translate it back to a binary array, just use the C# result which is already a binary array directly:
public static string p(string param1) {
byte[] loc3 = System.Security.Cryptography.MD5.Create().ComputeHash(System.Text.Encoding.ASCII.GetBytes(param1));
return Convert.ToBase64String(loc3, 0, 16);
}

Fragment cannot find variable from other Fragment

I have a problem. I have 2 Android.Support.V4.App.Fragments
In the first Framgent I use this code:
AgentSpinnerAdapter = new ArrayAdapter<string>(Context, Android.Resource.Layout.SimpleSpinnerDropDownItem);
AgentSpinner.Adapter = AgentSpinnerAdapter;
foreach (string[] str in NamesArray)
{
string AgentId = str[0];
string Owner = str[1];
string Exchange = str[2];
string Remark = str[3];
AgentSpinnerAdapter.Add("Agent " + AgentId + " - " + Owner + " - " + Remark);
}
In the second Fragment I call this line:
dbValue = Fragment1.AgentSpinnerAdapter.GetItem(0);
But it says that AgentSpinnerAdapter is a nullreference, which is weird, because it get's filled. I have set the AgentSpinnerAdapter to Public static. Also in my MainActivity I first create Fragment1 and then Fragment2 like this:
Fragment1 = Fragment1.NewInstance();
Fragment2 = Fragment2.NewInstance();
What am I doing wrong?
UPDATE
Here is the full Fragment1.cs method
public void LoadAgentSpinner()
{
string json = "";
try
{
string html = string.Empty;
string url = "https://www.efy.nl/app/getagents.php";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
IgnoreBadCertificates();
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
using (Stream stream = response.GetResponseStream())
using (StreamReader reader = new StreamReader(stream))
{
json = reader.ReadToEnd();
}
}
catch (Exception ex1)
{
try
{
WebClient client = new WebClient();
NameValueCollection fields = new NameValueCollection();
fields.Add("error", ex1.GetBaseException().ToString());
string url = "https://www.mywebsite.com";
IgnoreBadCertificates();
byte[] respBytes = client.UploadValues(url, fields);
string resp = client.Encoding.GetString(respBytes);
SelectedQuantity.Text = "";
SelectedLimit.Text = "";
}
catch (Exception ex2)
{
string exFullName = (ex2.GetType().FullName);
string ExceptionString = (ex2.GetBaseException().ToString());
}
}
//Parse json content
var jObject = JObject.Parse(json);
//Create Array from everything inside Node:"Coins"
var agentPropery = jObject["Agents"] as JArray;
//Create List to save Coin Data
agentList = new List<agent>();
//Find every value in Array: coinPropery
foreach (var property in agentPropery)
{
//Convert every value in Array to string
var propertyList = JsonConvert.DeserializeObject<List<agent>>(property.ToString());
//Add all strings to List
agentList.AddRange(propertyList);
}
//Get all the values from Name, and convert it to an Array
string[][] NamesArray = agentList.OrderBy(i => i.AgentId)
.Select(i => new string[] { i.AgentId.ToString(), i.Owner, i.Exchange, i.Remark })
.Distinct()
.ToArray();
AgentSpinnerAdapter = new ArrayAdapter<string>(Context, Android.Resource.Layout.SimpleSpinnerDropDownItem);
AgentSpinner.Adapter = AgentSpinnerAdapter;
foreach (string[] str in NamesArray)
{
string AgentId = str[0];
string Owner = str[1];
string Exchange = str[2];
string Remark = str[3];
AgentSpinnerAdapter.Add("Agent " + AgentId + " - " + Owner + " - " + Remark); // format your string here
}
if(MainActivity.db.CheckExistTableSettings("Default Agent") == true)
{
string Value = MainActivity.db.SelectValueFromTableSettings("Default Agent");
int spinnerPosition = AgentSpinnerAdapter.GetPosition(Value);
AgentSpinner.SetSelection(spinnerPosition);
}
else
{
AgentSpinner.SetSelection(0);
}
}
In a few of my applications it's necessary to access the other fragments from my main Activity, so we do the following:
public class MainActivity : AppCompatActivity, BottomNavigationView.IOnNavigationItemSelectedListener
{
public static Dictionary<string, Fragment> FragmentList { get; set; }
private Fragment currentFragment = null;
private BottomNavigationView navigation;
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
SetContentView(Resource.Layout.layout_mainactivity);
// create our fragments and initialise them early.
if (FragmentList == null)
{
FragmentList = new Dictionary<string, Fragment>
{
{ "main", MainFragment.NewInstance() },
{ "bugreport", BugReportFragment.NewInstance() },
{ "settings", SettingsFragment.NewInstance() }
};
}
navigation = FindViewById<BottomNavigationView>(Resource.Id.bottom_nav);
navigation.SetOnNavigationItemSelectedListener(this);
navigation.SelectedItemId = Resource.Id.navigation_main;
}
public bool OnNavigationItemSelected(IMenuItem item)
{
if (!popAction)
{
navigationResourceStack.Push(item.ItemId);
}
switch (item.ItemId)
{
case Resource.Id.navigation_main:
currentFragment = FragmentList["main"];
break;
case Resource.Id.navigation_settings:
currentFragment = FragmentList["settings"];
break;
case Resource.Id.navigation_bugreport:
currentFragment = FragmentList["bugreport"];
break;
}
if (currentFragment == null)
{
return false;
}
else
{
FragmentManager.BeginTransaction().Replace(Resource.Id.frame_content, currentFragment).Commit();
return true;
}
}
}
What this means is you could do something like MainActivity.FragmentList["main"] and then call any public method on the actual initialized class because a pointer to it is stored within the dictionary.

Xamarin C# - What is the fastest way to refresh a gridview every second

I have a problem.
In my Android app I use a: Android.Support.V4.View.ViewPager to swap between a summary and a wallet. The summary page is filled with 3 TextViews and the Wallet is created with 1 GridView. Both the pages are getting filled with data from a HTTPS call from where the response will be parsed into a List. Now I want to refresh both the pages every second. So I tried this:
public void LoadOrderPage()
{
Android.Support.V4.View.ViewPager SummaryWalletSwitcher = FindViewById<Android.Support.V4.View.ViewPager>(Resource.Id.SummaryWalletSwitcher);
List<View> viewlist = new List<View>();
viewlist.Add(LayoutInflater.Inflate(Resource.Layout.AgentSummary, null, false));
viewlist.Add(LayoutInflater.Inflate(Resource.Layout.AgentWallet, null, false));
SummaryWalletAdapter ViewSwitchAdapter = new SummaryWalletAdapter(viewlist);
SummaryWalletSwitcher.Adapter = ViewSwitchAdapter;
Timer AgentInfo_Timer = new Timer();
AgentInfo_Timer.Interval = 1000;
AgentInfo_Timer.Elapsed += LoadAgentInfo;
AgentInfo_Timer.Enabled = true;
}
public void LoadAgentInfo(object sender, ElapsedEventArgs e)
{
TextView TextPortfolioValue = FindViewById<TextView>(Resource.Id.txtPortfolioValue);
TextView TextValueUSDT = FindViewById<TextView>(Resource.Id.txtValueUSDT);
TextView TextTotalValue = FindViewById<TextView>(Resource.Id.txtTotalValue);
GridView GridviewWallet = FindViewById<GridView>(Resource.Id.GridviewWallet);
if (FirstWalletRun == true)
{
List<wallet> EmptyWalletList = new List<wallet>();
WalletListAdapter = new WalletListAdapter(this, EmptyWalletList);
GridviewWallet.Adapter = WalletListAdapter;
FirstWalletRun = false;
}
PortfolioValue = 0;
ValueUSDT = 0;
TotalValue = 0;
string response = "";
AgentId = getSelectedAgentId();
if (AgentId == 0)
{
AgentId = 1;
}
try
{
WebClient client = new WebClient();
var reqparm = new System.Collections.Specialized.NameValueCollection();
reqparm.Add("agentid", AgentId.ToString());
reqparm.Add("devicetoken", DeviceToken);
byte[] responsebytes = client.UploadValues("https://www.test.nl/getagentwallet.php", "POST", reqparm);
IgnoreBadCertificates();
response = Encoding.UTF8.GetString(responsebytes);
response = response.Replace("\n", "").Replace("\t", "");
}
catch (Exception ex)
{
string exFullName = (ex.GetType().FullName);
string ExceptionString = (ex.GetBaseException().ToString());
TextPortfolioValue.Text = "Unknown";
TextValueUSDT.Text = "Unknown";
TextTotalValue.Text = "Unknown";
}
if (response != "No updates")
{
//Parse json content
var jObject = JObject.Parse(response);
//Create Array from everything inside Node:"Coins"
var walletPropery = jObject["Wallet"] as JArray;
//Create List to save Coin Data
walletList = new List<wallet>();
//Find every value in Array: coinPropery
foreach (var property in walletPropery)
{
//Convert every value in Array to string
var propertyList = JsonConvert.DeserializeObject<List<wallet>>(property.ToString());
//Add all strings to List
walletList.AddRange(propertyList);
}
//Get all the values from Name, and convert it to an Array
string[][] NamesArray = walletList.OrderBy(i => i.AgentId)
.Select(i => new string[] { i.AgentId.ToString(), i.Coin, i.Quantity.ToString(), i.AvgPrice.ToString(), i.Value.ToString() })
.Distinct()
.ToArray();
foreach (string[] str in NamesArray)
{
if (str[1] != "USDT")
{
PortfolioValue += decimal.Parse(str[4]);
}
else
{
ValueUSDT += decimal.Parse(str[4]);
}
}
TotalValue = PortfolioValue + ValueUSDT;
TextPortfolioValue.Text = Math.Round(PortfolioValue, 8).ToString();
TextValueUSDT.Text = Math.Round(ValueUSDT, 8).ToString();
TextTotalValue.Text = Math.Round(TotalValue, 8).ToString();
SortedWalletList = walletList.OrderBy(o => o.Coin).ToList();
if (WalletListAdapter == null)
{
//Fill the DataSource of the ListView with the Array of Names
WalletListAdapter = new WalletListAdapter(this, SortedWalletList);
GridviewWallet.Adapter = WalletListAdapter;
}
else
{
WalletListAdapter.refresh(SortedWalletList);
AgentInfoNeedsUpdate = true;
}
}
else
{
AgentInfoNeedsUpdate = false;
}
}
And in my WalletListAdapter I created the refresh function:
public void refresh(List<wallet> mItems)
{
this.mItems = mItems;
NotifyDataSetChanged();
}
But the GridviewWallet never get's filled or doesn't get shown. What am I doing wrong?
EDIT:
Maybe there is something wrong in the WalletListAdapter, so here is the code of the class:
public class WalletListAdapter : BaseAdapter<wallet>
{
public List<wallet> mItems;
private Context mContext;
public WalletListAdapter(Context context, List<wallet> items)
{
mItems = items;
mContext = context;
}
public override int Count
{
get { return mItems.Count; }
}
public void refresh(List<wallet> mItems)
{
this.mItems = mItems;
NotifyDataSetChanged();
}
public override long GetItemId(int position)
{
return position;
}
public override wallet this[int position]
{
get { return mItems[position]; }
}
public override View GetView(int position, View convertView, ViewGroup parent)
{
View row = convertView;
if (row == null)
{
row = LayoutInflater.From(mContext).Inflate(Resource.Layout.walletlist_row, null, false);
var txtWalletCoin = row.FindViewById<TextView>(Resource.Id.txtWalletCoin);
var txtWalletQuantity = row.FindViewById<TextView>(Resource.Id.txtWalletQuantity);
var txtAvgPrice = row.FindViewById<TextView>(Resource.Id.txtWalletAvgPrice);
var txtWalletValue = row.FindViewById<TextView>(Resource.Id.txtWalletValue);
var txtProfitUSDT = row.FindViewById<TextView>(Resource.Id.txtWalletProfitUSDT);
var txtProfitPerc = row.FindViewById<TextView>(Resource.Id.txtWalletProfitPerc);
row.Tag = new WalletViewHolder()
{
txtWalletCoin = txtWalletCoin,
txtWalletQuantity = txtWalletQuantity,
txtAvgPrice = txtAvgPrice,
txtWalletValue = txtWalletValue,
txtProfitUSDT = txtProfitUSDT,
txtProfitPerc = txtProfitPerc
};
}
var holder = (WalletViewHolder)row.Tag;
holder.txtWalletCoin.Text = mItems[position].Coin;
holder.txtWalletQuantity.Text = Math.Round(mItems[position].Quantity, 2).ToString();
holder.txtAvgPrice.Text = Math.Round(mItems[position].AvgPrice, 2).ToString();
holder.txtWalletValue.Text = Math.Round(mItems[position].Value, 2).ToString();
if (mItems[position].Coin != "USDT")
{
holder.txtProfitUSDT.Text = Math.Round(mItems[position].ProfitUSDT, 2).ToString();
holder.txtProfitPerc.Text = Math.Round(mItems[position].ProfitPerc, 1).ToString();
}
else
{
holder.txtProfitUSDT.Text = Math.Round(0.00, 2).ToString();
holder.txtProfitPerc.Text = Math.Round(0.00, 1).ToString();
}
return row;
}
}
Hope this discussion provides some insights to fix the gridview refresh using Xamarin. According to it, the grid has to be recreated.
https://forums.xamarin.com/discussion/115256/refresh-a-gridview

app crashes before the request is sent to the server

I'm building an android app with Xamarin which communicates with an ASP.net server's API. I'm trying to upload a file to the server using the following lines of code:
public async Task<HttpResponseMessage> UploadFile(byte[] file)
{
var progress = new System.Net.Http.Handlers.ProgressMessageHandler();
//progress.HttpSendProgress += progress_HttpSendProgress;
using (var client = HttpClientFactory.Create(progress))
{
client.BaseAddress = new Uri(GlobalVariables.host);
// Set the Accept header for BSON.
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/bson"));
var request = new uploadFileModel { data = file, dateCreated = DateTime.Now, fileName = "myvideooo.mp4", username = "psyoptica" };
// POST using the BSON formatter.
MediaTypeFormatter bsonFormatter = new BsonMediaTypeFormatter();
var m = client.MaxResponseContentBufferSize;
var result = await client.PostAsync("api/media/upload", request, bsonFormatter);
return result.EnsureSuccessStatusCode();
}
}
The app crashes before the server receives the request. The file I'm trying to upload could be a video or an audio file. The server receives the request after the app has crashed. This works fine on the local server but the crash happens with the live server. My server side code looks like this:
[HttpPost]
[Route("upload")]
public async Task<HttpResponseMessage> Upload(uploadFileModel model)
{
var result = new HttpResponseMessage(HttpStatusCode.OK);
if (ModelState.IsValid)
{
string thumbname = "";
string resizedthumbname = Guid.NewGuid() + "_yt.jpg";
string FfmpegPath = Encoding_Settings.FFMPEGPATH;
string tempFilePath = Path.Combine(HttpContext.Current.Server.MapPath("~/tempuploads"), model.fileName);
string pathToFiles = HttpContext.Current.Server.MapPath("~/tempuploads");
string pathToThumbs = HttpContext.Current.Server.MapPath("~/contents/member/" + model.username + "/thumbs");
string finalPath = HttpContext.Current.Server.MapPath("~/contents/member/" + model.username + "/flv");
string resizedthumb = Path.Combine(pathToThumbs, resizedthumbname);
var outputPathVid = new MediaFile { Filename = Path.Combine(finalPath, model.fileName) };
var inputPathVid = new MediaFile { Filename = Path.Combine(pathToFiles, model.fileName) };
int maxWidth = 380;
int maxHeight = 360;
var namewithoutext = Path.GetFileNameWithoutExtension(Path.Combine(pathToFiles, model.fileName));
thumbname = model.VideoThumbName;
string oldthumbpath = Path.Combine(pathToThumbs, thumbname);
var fileName = model.fileName;
File.WriteAllBytes(tempFilePath, model.data);
if (model.fileName.Contains("audio"))
{
File.WriteAllBytes(Path.Combine(finalPath, model.fileName), model.data);
string audio_thumb = "mic_thumb.jpg";
string destination = Path.Combine(pathToThumbs, audio_thumb);
string source = Path.Combine(pathToFiles, audio_thumb);
if (!System.IO.File.Exists(destination))
{
System.IO.File.Copy(source, destination, true);
}
Video_Struct vd = new Video_Struct();
vd.CategoryID = 0; // store categoryname or term instead of category id
vd.Categories = "";
vd.UserName = model.username;
vd.Title = "";
vd.Description = "";
vd.Tags = "";
vd.OriginalVideoFileName = model.fileName;
vd.VideoFileName = model.fileName;
vd.ThumbFileName = "mic_thumb.jpg";
vd.isPrivate = 0;
vd.AuthKey = "";
vd.isEnabled = 1;
vd.Response_VideoID = 0; // video responses
vd.isResponse = 0;
vd.isPublished = 1;
vd.isReviewed = 1;
vd.Thumb_Url = "none";
//vd.FLV_Url = flv_url;
vd.Embed_Script = "";
vd.isExternal = 0; // website own video, 1: embed video
vd.Type = 0;
vd.YoutubeID = "";
vd.isTagsreViewed = 1;
vd.Mode = 0; // filter videos based on website sections
long videoid = VideoBLL.Process_Info(vd, false);
}
else
{
using (var engine = new Engine())
{
engine.GetMetadata(inputPathVid);
// Saves the frame located on the 15th second of the video.
var outputPathThumb = new MediaFile { Filename = Path.Combine(pathToThumbs, thumbname+".jpg") };
var options = new ConversionOptions { Seek = TimeSpan.FromSeconds(0), CustomHeight = 360, CustomWidth = 380 };
engine.GetThumbnail(inputPathVid, outputPathThumb, options);
}
Image image = Image.FromFile(Path.Combine(pathToThumbs, thumbname+".jpg"));
//var ratioX = (double)maxWidth / image.Width;
//var ratioY = (double)maxHeight / image.Height;
//var ratio = Math.Min(ratioX, ratioY);
var newWidth = (int)(maxWidth);
var newHeight = (int)(maxHeight);
var newImage = new Bitmap(newWidth, newHeight);
Graphics.FromImage(newImage).DrawImage(image, 0, 0, newWidth, newHeight);
Bitmap bmp = new Bitmap(newImage);
bmp.Save(Path.Combine(pathToThumbs, thumbname+"_resized.jpg"));
//File.Delete(Path.Combine(pathToThumbs, thumbname));
using (var engine = new Engine())
{
var conversionOptions = new ConversionOptions
{
VideoSize = VideoSize.Hd720,
AudioSampleRate = AudioSampleRate.Hz44100,
VideoAspectRatio = VideoAspectRatio.Default
};
engine.GetMetadata(inputPathVid);
engine.Convert(inputPathVid, outputPathVid, conversionOptions);
}
File.Delete(tempFilePath);
Video_Struct vd = new Video_Struct();
vd.CategoryID = 0; // store categoryname or term instead of category id
vd.Categories = "";
vd.UserName = model.username;
vd.Title = "";
vd.Description = "";
vd.Tags = "";
vd.Duration = inputPathVid.Metadata.Duration.ToString();
vd.Duration_Sec = Convert.ToInt32(inputPathVid.Metadata.Duration.Seconds.ToString());
vd.OriginalVideoFileName = model.fileName;
vd.VideoFileName = model.fileName;
vd.ThumbFileName = thumbname+"_resized.jpg";
vd.isPrivate = 0;
vd.AuthKey = "";
vd.isEnabled = 1;
vd.Response_VideoID = 0; // video responses
vd.isResponse = 0;
vd.isPublished = 1;
vd.isReviewed = 1;
vd.Thumb_Url = "none";
//vd.FLV_Url = flv_url;
vd.Embed_Script = "";
vd.isExternal = 0; // website own video, 1: embed video
vd.Type = 0;
vd.YoutubeID = "";
vd.isTagsreViewed = 1;
vd.Mode = 0; // filter videos based on website sections
//vd.ContentLength = f_contentlength;
vd.GalleryID = 0;
long videoid = VideoBLL.Process_Info(vd, false);
}
return result;
}
else
{
throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.NotAcceptable, "This request is not properly formatted"));
}
}`
What am I doing wrong here that's making the app crash. Is there a better way to do this?
Any help is appreciated.

Creating a source to destination map view for windows phone

I have a default geocoordinate. Another geocoorinate which the user will provide. I want to change the change the map view such such that the source and destination can be clearly seen on the phone window with max zoom possible. Please help on how to approach this problem. I tried using setview() but i coudn't find an overload which could do the task.
public async void ShowMyLocationOnTheMap(string mapvariable)
{
JObject o = JObject.Parse(mapvariable);
string successcallback = o["successCallback"].ToString();
string failutecallback = o["failureCallback"].ToString();
var markerifo = o["markerInfo"];
int count = markerifo.Count();
try
{
for (int i = 0; i < count; i++)
{
drawmap(markerifo[i],"red");
}
Geolocator myGeolocator = new Geolocator();
Geoposition myGeoposition = await myGeolocator.GetGeopositionAsync();
JObject current = new JObject();
current["locationLatitude"] = myGeoposition.Coordinate.Latitude.ToString();
current["locationLongitude"] = myGeoposition.Coordinate.Longitude.ToString();
current["locationDescription"] = "Your Current Location";
current["locationName"] = "";
drawmap(current,"blue");
GeoCoordinate myGeoCoordinate = new GeoCoordinate(myGeoposition.Coordinate.Latitude, myGeoposition.Coordinate.Longitude);
MapAppzillon.SetView(myGeoCoordinate1,6);
gobject.ContentPanel.Children.Add(MapAppzillon);
var jsonstring = "{\"successMessage\":\" Map Displayed \"}";
string[] param = { successcallback, jsonstring };
gobject.invokeScript("StringToJsonObject", param);
}
catch (Exception ex)
{
var jsonstring = "{\"errorCode\":\"APZ-CNT-107\"}";
string[] param = { failutecallback, jsonstring };
gobject.invokeScript("StringToJsonObject", param);
}
}
public void drawmap(JToken markerifo,string color)
{
double latitude = Convert.ToDouble(markerifo["locationLatitude"].ToString());
double longitude = Convert.ToDouble(markerifo["locationLongitude"].ToString());
myGeoCoordinate1 = new GeoCoordinate(latitude, longitude);
Ellipse myCircle = new Ellipse();
if (color == "red")
{
myCircle.Fill = new SolidColorBrush(Colors.Red);
}
else
myCircle.Fill = new SolidColorBrush(Colors.Blue);
myCircle.Height = 20;
myCircle.Width = 20;
myCircle.Opacity = 50;
myCircle.Tap += (sender, e) => myCircle_Tap(sender, markerifo["locationDescription"].ToString(), markerifo["locationName"].ToString());
// myCircle.Tap += myCircle_Tap;
MapOverlay myLocationOverlay = new MapOverlay();
myLocationOverlay.Content = myCircle;
myLocationOverlay.PositionOrigin = new System.Windows.Point(0.5, 0.5);
myLocationOverlay.GeoCoordinate = myGeoCoordinate1;
MapLayer myLocationLayer = new MapLayer();
myLocationLayer.Add(myLocationOverlay);
MapAppzillon.Layers.Add(myLocationLayer);
}
Edit: I tried using dispatcher.Invoke and it finally worked. but now its loading only once . when i press the back button and specify another geocoordinate setview dosent work. Is there any solution to this.
List<GeoCoordinate> the2Points = new List<GeoCoordinate>();
the2Points.Add(myGeoCoordinate1);
the2Points.Add(myGeoCoordinate);
rect = LocationRectangle.CreateBoundingRectangle(the2Points);
gobject.ContentPanel.Children.Add(MapAppzillon);
MapAppzillon.Dispatcher.BeginInvoke(() =>
{
MapAppzillon.SetView(rect);
});
await Task.Delay(150);
You do need to use the SetView method on the Map control. But it needs a BoundingRectangle to work!
So a quick code snippet:
List<GeoCoordinate> the2Points = new List<GeoCoordinate>();
the2Points.Add(point1);
the2Points.Add(point2);
LocationRectangle rect = LocationRectangle.CreateBoundingRectangle(the2Points);
TheMapControl.SetView(rect);

Categories