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.
Related
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
I am trying the get all user media from the instagram api and store into database but how can do that i don't know. i am write the code but using this code just add one media in the database. any one have the idea then please let me know how can do that. here below list the my code.
This is my C# method :
public string makePostFromInstagram()
{
var serializer1 = new System.Web.Script.Serialization.JavaScriptSerializer();
var nodes1 = serializer1.Deserialize<dynamic>(GetData(strInstagramUserId));
foreach (var date in nodes1)
{
if (date.Key == "data")
{
string theKey = date.Key;
var thisNode = date.Value;
int userCount = 0;
foreach (var post in thisNode)
{
if (thisNode[userCount]["username"] == strInstagramUserId)
{
id = thisNode[userCount]["id"].ToString();
}
userCount++;
}
}
}
var serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
Dictionary<string, object> csObj = serializer.Deserialize<Dictionary<string, object>>(GetRecentPost(id, accessToken));
int length = ((ArrayList)csObj["data"]).Count;
var nodes = serializer.Deserialize<dynamic>(GetRecentPost(id, accessToken));
foreach (var date in nodes)
{
if (date.Key == "data")
{
string theKey = date.Key;
var thisNode = date.Value;
foreach (var post in thisNode)
{
UsersOnInstagram objUserInsta = new UsersOnInstagram();
string result = null;
//here i am add just one image so i want to here add multiple image insert
if (post["type"] == "image")
result = UsersOnInstagram.addInstagramPost(strPtId, HttpUtility.UrlEncode(post["caption"]["text"]), post["images"]["standard_resolution"]["url"], UnixTimeStampToDateTime(Convert.ToDouble(post["created_time"])), null, post["type"]);
else if (post["type"] == "video")
result = objUserInsta.addInstagramPost(HttpUtility.UrlEncode(post["caption"]["text"]), strPtId, post["images"]["standard_resolution"]["url"], UnixTimeStampToDateTime(Convert.ToDouble(post["created_time"])), post["videos"]["standard_resolution"]["url"], post["type"]);
}
}
}
Response.End();
}
this is my api method :
public static string GetRecentPost(string instagramaccessid, string instagramaccesstoken)
{
Double MAX_TIMESTAMP = DateTimeToUnixTimestamp(DateTime.Today.AddDays(-1));
Double MIN_TIMESTAMP = DateTimeToUnixTimestamp(DateTime.Today.AddDays(-2));
string url = "https://api.instagram.com/v1/users/" + instagramaccessid + "/media/recent?access_token=" + instagramaccesstoken + "&min_timestamp=" + MIN_TIMESTAMP + "&maz_timestamp=" + MAX_TIMESTAMP;
var webClient = new System.Net.WebClient();
string d = webClient.DownloadString(url);
return d;
}
any one know how can do that please let me know.
I have a Program which should save permanently values to a .txt file. When I debug it by putting a breakpoint into the code it works fine. But when letting it work for a while it only saves the last value caught instead of the last 3.
The method ExecuteStrategy is being executed every minute.
Here is the code:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace Bot_V1._0
{
public class SaveAllMinuteBarsStrategy : IStrategy
{
public Guid StrategyGuid { get; set; }
//private static string[] Data = new string[8];
private string DataDax { get; set; }
private string DataDow { get; set; }
private string DataOil { get; set; }
private string DataGold { get; set; }
private string DataSpy { get; set; }
private string DataEsd { get; set; }
private string DataEgp { get; set; }
private string DataUpy { get; set; }
private string xPath = #"G:\TradingBot\Saved Candles folder";
private DateTime firstEnter;
const char LF = '\n';
public SaveAllMinuteBarsStrategy (Guid StrategyCGuid)
{
this.StrategyGuid = StrategyGuid;
}
public List<ShareAndTimeRange> InitStrategy (Guid stratGuid)
{
firstEnter = DateTime.Now;
var Dax = new ShareAndTimeRange("DAX", 1, stratGuid, null, false);
var Dow = new ShareAndTimeRange("DOW", 1, stratGuid, null, false);
var Oil = new ShareAndTimeRange("OIL", 1, stratGuid, null, false);
var Gold = new ShareAndTimeRange("GOLD", 1, stratGuid, null, false);
var Spy = new ShareAndTimeRange("SPY", 1, stratGuid, null, false);
var Esd = new ShareAndTimeRange("EUR/USD", 1, stratGuid, null, false);
var Egb = new ShareAndTimeRange("EUR/GBP", 1, stratGuid, null, false);
var Ujp = new ShareAndTimeRange("USD/JPY", 1, stratGuid, null, false);
var ElementList = new List<ShareAndTimeRange>();
ElementList.Add(Dax);
ElementList.Add(Dow);
ElementList.Add(Oil);
ElementList.Add(Gold);
ElementList.Add(Spy);
ElementList.Add(Esd);
ElementList.Add(Egb);
ElementList.Add(Ujp);
return ElementList;
}
public void ExecuteStrategy(ShareAndTimeRange Share)
{
SaveDataHourly(Share);
}
private void SaveDataHourly(ShareAndTimeRange Share)
{
if (Share.Candle == null)
return;
var PreparedString = Share.Candle.Time.ToString("yyyyMMdd HHmmss") + ";";
PreparedString = PreparedString + Share.Candle.Open + ";" + Share.Candle.High + ";";
PreparedString = PreparedString + Share.Candle.Low + ";" + Share.Candle.Close;
PreparedString = PreparedString + LF;
switch (Share.ShareName)
{
case ("DAX"):
{
DataDax = DataDax + PreparedString;
//Data[0] = Data[0] +
bool reset = HDMYSaving(Share, DataDax);
if (reset)
DataDax = "";
break;
}
case ("DOW"):
{
DataDow = DataDow + PreparedString;
bool reset = HDMYSaving(Share, DataDow);
if (reset)
DataDow = "";
break;
}
case ("OIL"):
{
DataOil = DataOil + PreparedString;
bool reset = HDMYSaving(Share, DataOil);
if (reset)
DataOil = "";
break;
}
case ("GOLD"):
{
DataGold = DataGold + PreparedString;
bool reset = HDMYSaving(Share, DataGold);
if (reset)
DataGold = "";
break;
}
case ("SPY"):
{
DataSpy = DataSpy + PreparedString;
bool reset = HDMYSaving(Share, DataSpy);
if (reset)
DataSpy = "";
break;
}
case ("EUR/USD"):
{
DataEsd = DataEsd + PreparedString;
bool reset = HDMYSaving(Share, DataEsd);
if (reset)
DataEsd = "";
break;
}
case ("EUR/GBP"):
{
DataEgp = DataEgp + PreparedString;
bool reset = HDMYSaving(Share, DataEgp);
if (reset)
DataEgp = "";
break;
}
case ("USD/JPY"):
{
DataUpy = DataUpy + PreparedString;
bool reset = HDMYSaving(Share, DataUpy);
if (reset)
DataUpy = "";
break;
}
}
}
private void SavePersistentData (string FolderName , string FileName, string Share )
{
if (!System.IO.File.Exists(FolderName))
{
Directory.CreateDirectory(FolderName);
}
string fullPath = System.IO.Path.Combine(FolderName, FileName);
if (!System.IO.File.Exists(fullPath))
{
FileStream fs = File.Create(fullPath);
fs.Dispose();
}
using (StreamWriter sw = new StreamWriter(fullPath, false))
{
sw.Write(Share);
sw.Dispose();
}
//System.IO.File.WriteAllText(fullPath, Share);
}
private void SavePersistent (string ReadFolder , string WriteFolder , string WriteFolderFile)
{
DirectoryInfo ParDir = new DirectoryInfo(ReadFolder);
string dat = "";
foreach (var item in ParDir.GetFiles())
{
var elem = System.IO.Path.Combine(ReadFolder, item.Name);
dat += System.IO.File.ReadAllText(elem);
}
SavePersistentData(WriteFolder, WriteFolderFile, dat);
foreach (var item in ParDir.GetFiles())
{
var del = System.IO.Path.Combine(ReadFolder, item.Name);
File.Delete(del);
}
}
private bool HDMYSaving(ShareAndTimeRange Share, string Values)
{
if (Share.Candle == null)
return false;
bool toReset = false;
string SharePath = System.IO.Path.Combine(xPath, Share.ShareName);//c:\TradingBot\Saved Candles folder\"Sharename"\
string HourPath = System.IO.Path.Combine(SharePath, "Hour Data");//c:\TradingBot\Saved Candles folder\"Sharename"\Hour Data
int res;
int resuzt = Math.DivRem(Share.Candle.Time.Minute,3,out res);
if ( res == 0) //0 Share.Candle.Time.Minute == 0
{
DateTime DateToWriteH = Share.Candle.Time;
string HourFilePath = DateToWriteH.ToString("yyyyMMddHHmm") + ".txt";
SavePersistentData(HourPath, HourFilePath, Values);
toReset = true;
}
DateTime DateToWriteD = Share.Candle.Time.AddDays(-1);
string DayPath = System.IO.Path.Combine(SharePath, "Day Data");//c:\TradingBot\Saved Candles folder\"Sharename"\Day Data
string DayFilePath = System.IO.Path.Combine(DayPath, DateToWriteD.ToString("yyyyMMdd") + ".txt");
if (Share.Candle.Time.Hour == 0 && Share.Candle.Time.Minute == 0 && !System.IO.File.Exists(DayFilePath))
{
SavePersistent(HourPath, DayPath, DateToWriteD.ToString("yyyyMMdd") + ".txt");
}
DateTime DateToWriteM = Share.Candle.Time.AddMonths(-1);
string MonthPath = System.IO.Path.Combine(SharePath, "Month Data");//c:\TradingBot\Saved Candles folder\"Sharename"\Month Data
string MonthFilePath = System.IO.Path.Combine(MonthPath, DateToWriteM.ToString("yyyyMM") + ".txt");
if (Share.Candle.Time.Day == 1 && Share.Candle.Time.Hour == 0 && Share.Candle.Time.Minute == 0 && !System.IO.File.Exists(MonthFilePath))
{
SavePersistent(DayPath, MonthPath, DateToWriteM.ToString("yyyyMM") + ".txt");
}
DateTime DateToWriteY = Share.Candle.Time.AddYears(-1);
string YearPath = System.IO.Path.Combine(SharePath, "Year Data");//c:\TradingBot\Saved Candles folder\"Sharename"\Year Data
string YearFilePath = System.IO.Path.Combine(YearPath, DateToWriteY.ToString("yyyy") + ".txt");
if (Share.Candle.Time.Month == 1 && Share.Candle.Time.Day == 1 && Share.Candle.Time.Hour == 0 && Share.Candle.Time.Minute == 0 && !System.IO.File.Exists(YearFilePath))
{
SavePersistent(MonthPath, YearPath, DateToWriteY.ToString("yyyy") + ".txt");
}
return toReset;
}
}
Is there a problem having a lot of Events which are fired every 2 seconds or every minute?
Thanks!!
i found the problem. It was on another Class. The Fault was firing an event every time the program colleted a new value, but the program schould wait for the other "WebsTakenInCare".
Here is the Code before:
if (DataList.Count() == WebsTakenInCare)
{
FinalizedData = ShortenUpData(DataList);
DataList.Clear();
}
BuildCandles(FinalizedData);
and after changing:
if (DataList.Count() == WebsTakenInCare)
{
FinalizedData = ShortenUpData(DataList);
DataList.Clear();
BuildCandles(FinalizedData);
}
else
return;
regards!
I am creating a method which returns datatable and an int value.I have create a method which returns only datatable.Please take a look on the code
public static DataTable ShutterstockSearchResults(string url)
{
int TotalCont=0;
DataTable dt = new DataTable();
try
{
//intigration using Basic Aouth with authrization headers
var request = (HttpWebRequest)WebRequest.Create(url);
var username = "SC";
var password = "SK";
string credentials = Convert.ToBase64String(Encoding.ASCII.GetBytes(username + ":" + password));
request.Headers[HttpRequestHeader.Authorization] = string.Format("Basic {0}", credentials);
request.UserAgent = "MyApp 1.0";
var response = (HttpWebResponse)request.GetResponse();
using (var stream = response.GetResponseStream())
using (var reader = new StreamReader(stream))
{
JavaScriptSerializer js = new JavaScriptSerializer();
var objText = reader.ReadToEnd();
SearchResult myojb = (SearchResult)js.Deserialize(objText, typeof(SearchResult));
TotalCount = myojb.total_count;
dt.Columns.Add("Id");
dt.Columns.Add("Discription");
dt.Columns.Add("Small_Thumb_URl");
dt.Columns.Add("Large_Thumb_URL");
dt.Columns.Add("Prieview_URL");
dt.Columns.Add("ContributorID");
dt.Columns.Add("aspect");
dt.Columns.Add("image_type");
dt.Columns.Add("is_illustration");
dt.Columns.Add("media_type");
foreach (var item in myojb.data)
{
var row = dt.NewRow();
row["ID"] = item.id;
row["Discription"] = item.description;
row["Small_Thumb_URl"] = item.assets.small_thumb.url;
row["Large_Thumb_URL"] = item.assets.large_thumb.url;
row["Prieview_URL"] = item.assets.preview.url;
row["ContributorID"] = item.contributor.id;
row["aspect"] = item.aspect;
row["image_type"] = item.image_type;
row["is_illustration"] = item.is_illustration;
row["media_type"] = item.media_type;
dt.Rows.Add(row);
}
// List<SearchResult> UserList = JsonConvert.DeserializeObject<List<SearchResult>>(objText);
// Response.Write(reader.ReadToEnd());
}
}
catch (WebException ea)
{
Console.WriteLine(ea.Message);
using (var stream = ea.Response.GetResponseStream())
using (var reader = new StreamReader(stream))
{
Console.WriteLine(reader.ReadToEnd());
}
}
return dt;
}
I want to return datatable and TotalCont.please help
Generally speaking, a method can only return one type.
You have two options:
1) Create a class that has a DataTable and an int field, such as:
public class MyReturnType
{
public DataTable TheDataTable {get; set;}
public int TotalCount {get; set;}
}
And return this type from your method.
2) You can add an out parameter to your method:
public static DataTable ShutterstockSearchResults(string url, out totalCount)
And assign to totalCount within your method.
public static Tuple<DataTable, int> ShutterstockSearchResults(string url)
{
[...]
return new Tuple<DataTable, int>(dt, totalCount);
}
public static void SomeConsumerMethod()
{
var result = ShutterstockSearchResults(myPath);
DataTable dt = result.Item1;
int totalCount = result.Item2;
}
To answer the comments in Klaus answer:
public class MyReturnType
{
public DataTable TheDataTable {get; set;}
public int TotalCount {get; set;}
}
and in your method:
public static MyReturnType ShutterstockSearchResults(string url)
{
MyReturnType result=new MyReturnType();
int TotalCont=0;
DataTable dt = new DataTable();
try
{
//intigration using Basic Aouth with authrization headers
var request = (HttpWebRequest)WebRequest.Create(url);
var username = "SC";
var password = "SK";
string credentials = Convert.ToBase64String(Encoding.ASCII.GetBytes(username + ":" + password));
request.Headers[HttpRequestHeader.Authorization] = string.Format("Basic {0}", credentials);
request.UserAgent = "MyApp 1.0";
var response = (HttpWebResponse)request.GetResponse();
using (var stream = response.GetResponseStream())
using (var reader = new StreamReader(stream))
{
JavaScriptSerializer js = new JavaScriptSerializer();
var objText = reader.ReadToEnd();
SearchResult myojb = (SearchResult)js.Deserialize(objText, typeof(SearchResult));
TotalCount = myojb.total_count;
dt.Columns.Add("Id");
dt.Columns.Add("Discription");
dt.Columns.Add("Small_Thumb_URl");
dt.Columns.Add("Large_Thumb_URL");
dt.Columns.Add("Prieview_URL");
dt.Columns.Add("ContributorID");
dt.Columns.Add("aspect");
dt.Columns.Add("image_type");
dt.Columns.Add("is_illustration");
dt.Columns.Add("media_type");
foreach (var item in myojb.data)
{
var row = dt.NewRow();
row["ID"] = item.id;
row["Discription"] = item.description;
row["Small_Thumb_URl"] = item.assets.small_thumb.url;
row["Large_Thumb_URL"] = item.assets.large_thumb.url;
row["Prieview_URL"] = item.assets.preview.url;
row["ContributorID"] = item.contributor.id;
row["aspect"] = item.aspect;
row["image_type"] = item.image_type;
row["is_illustration"] = item.is_illustration;
row["media_type"] = item.media_type;
dt.Rows.Add(row);
}
// List<SearchResult> UserList = JsonConvert.DeserializeObject<List<SearchResult>>(objText);
// Response.Write(reader.ReadToEnd());
}
}
catch (WebException ea)
{
Console.WriteLine(ea.Message);
using (var stream = ea.Response.GetResponseStream())
using (var reader = new StreamReader(stream))
{
Console.WriteLine(reader.ReadToEnd());
}
}
result.TheDataTable=dt;
result.TotalCount=TotalCount;
return result:
}
Your method needs an additional out parameter if you want to "return" more than one value. Just pass an uninitialized variable of the desired type into your method and assign that variable inside.
public void Test()
{
int i;
DataTable ShutterstockSearchResults("Some string", out i);
}
your ShutterstockSearchResults method needs to be modified accordingly:
public static DataTable ShutterstockSearchResults(string url, out int outParam)
{
outParam = 10;
// do other stuff
}
If you do not change outParam any further inside ShutterstockSearchResults, it will have the value 10 after returning to Test.
You can accomplish this with a Tuple. Consider the following simple example:
public class EmptyClass
{
public static void Main(){
EmptyClass something = new EmptyClass ();
Tuple<String, int> tuple = something.returnMe ();
Console.WriteLine ("Item 1: " + tuple.Item1);
Console.WriteLine ("Item 2: " + tuple.Item2);
}
public EmptyClass ()
{
}
public Tuple<String, int> returnMe() {
return Tuple.Create ("Hello", 2);
}
}
I had error
Object reference not set to an instance of an object
at:
string[] sB64String = payload.Split('.');
When check if user like the my Facebook page, my code-
protected void Page_Load(object sender, EventArgs e)
{
pageLike();
}
public bool ValidateSignedRequest()
{
string facebooksecret =
System.Configuration.ConfigurationManager.AppSettings["FacebookSecret"];
var VALID_SIGNED_REQUEST = Request.Form["signed_request"];
string applicationSecret = facebooksecret;
string[] signedRequest = VALID_SIGNED_REQUEST.Split('.');
string expectedSignature = signedRequest[0];
string payload = signedRequest[1];
// Attempt to get same hash
var Hmac = SignWithHmac(UTF8Encoding.UTF8.GetBytes(payload), UTF8Encoding.UTF8.GetBytes(applicationSecret));
var HmacBase64 = ToUrlBase64String(Hmac);
return (HmacBase64 == expectedSignature);
}
private string ToUrlBase64String(byte[] Input)
{
return Convert.ToBase64String(Input).Replace("=", String.Empty)
.Replace('+', '-')
.Replace('/', '_');
}
private byte[] SignWithHmac(byte[] dataToSign, byte[] keyBody)
{
using (var hmacAlgorithm = new HMACSHA256(keyBody))
{
hmacAlgorithm.ComputeHash(dataToSign);
return hmacAlgorithm.Hash;
}
}
public Dictionary<string, string> DecodePayload(string payload)
{
//Remove the bad part of signed_request
//Begin
string[] sB64String = payload.Split('.');
payload = payload.Replace((sB64String[0] + "."), string.Empty);
//End
var encoding = new UTF8Encoding();
var decodedJson = payload.Replace("=", string.Empty).Replace('-', '+').Replace('_', '/');
var base64JsonArray = Convert.FromBase64String(decodedJson.PadRight(decodedJson.Length + (4 - decodedJson.Length % 4) % 4, '='));
var json = encoding.GetString(base64JsonArray);
var jObject = JObject.Parse(json);
var parameters = new Dictionary<string, string>();
parameters.Add("page", ((bool)jObject["page"]["liked"]).ToString());
parameters.Add("admin", ((bool)jObject["page"]["admin"]).ToString());
return parameters;
}
protected void pageLike()
{
string pageLiked = string.Empty;
var signed_request = Request.Form["signed_request"];
var json = DecodePayload(signed_request);
foreach (KeyValuePair<string, string> objKVP in json)
{
//Note You can also see if a user is an admin by replacing the objKVP.Key with admin
if (objKVP.Key == "page" && objKVP.Value == "True")
{
Response.Redirect("https://facebookapp.elarabygroup.com/instruction.aspx");
//litJson.Text += objKVP.Key + " - " + objKVP.Value + "<br />";
}
}
}
I can't see anything fundamentally wrong with your code, what I suspect is happening is the request form variable is null i.e.
var signed_request = Request.Form["signed_request"];
the payload variable is being set to a null or empty string. I'd check this and make sure the value is what you expect.
A good idea here is to add a guard clause in DecodePayload to make sure the payload variable has a value before calling the Split method.
e.g.
if (string.IsNullOrEmpty(payload))
throw new ArgumentNullException();