Dropbox without AsyncTask class - android-asynctask

I am using following function to download file from Dropbox.It runs perfectly when i call the async class to download file.But giving error when i call on normal class to download file with "Failed to download"
public void dropboxcopy()
{
SharedPreferences prefernces = getSharedPreferences("Drop", Context.MODE_PRIVATE);
SharedPreferences.Editor editor_first = prefernces.edit();
String first_time_login= prefernces.getString("FirstRun",null);
if (!isLoggedIn) {
editor_first.putString("FirstRun","Yes");
editor_first.commit();
dropbox.getSession().startAuthentication(Update_Database.this);
}
else {
DownloadFileFromDropbox download = new DownloadFileFromDropbox(this, dropbox,
FILE_DIR,myInternalFile);
download.execute();
}
}
Async Class File:
public class DownloadFileFromDropbox extends AsyncTask<Void, Void, Boolean> {
private static final String DATABASE_NAME = "GirviDrop";
private DropboxAPI<?> dropbox;
private String path;
private Context context;
private Boolean fileexist;
private File internal;
public DownloadFileFromDropbox(Context context, DropboxAPI<?> dropbox,
String path,File internal) {
this.context = context.getApplicationContext();
this.dropbox = dropbox;
this.path = path;
this.internal=internal;
}
#Override
protected Boolean doInBackground(Void... params) {
try {
File data = Environment.getDataDirectory();
if(internal.exists())
{
internal.delete();
internal.createNewFile();
}
Entry existingentry= dropbox.metadata( path ,1000,null,true,null);
if (existingentry.contents.size() != 0)
{
for (Entry ent :existingentry.contents)
{
String name = ent.fileName();
if(name.equals(DATABASE_NAME))
{ FileOutputStream outputStream = new FileOutputStream(internal);
dropbox.getFile(path + DATABASE_NAME, null, outputStream, null);
return true;
}
}
}
} catch (IOException e) {
e.printStackTrace();
} catch (DropboxException e) {
e.printStackTrace();
}
return false;
}
#Override
protected void onPostExecute(Boolean result) {
if (result) {
Toast.makeText(context, "File Downloaded Successfully from dropbox!",
Toast.LENGTH_LONG).show();
} else {
if(fileexist=true)
{
Toast.makeText(context, "databse not present on app!",
Toast.LENGTH_LONG).show();
}
Toast.makeText(context, "Failed to Download file", Toast.LENGTH_LONG)
.show();
}
}
}
Above code runs perfectly....
Modified Code:
public void dropboxcopy()
{
SharedPreferences prefernces = getSharedPreferences("Drop", Context.MODE_PRIVATE);
SharedPreferences.Editor editor_first = prefernces.edit();
String first_time_login= prefernces.getString("FirstRun",null);
if (!isLoggedIn) {
editor_first.putString("FirstRun","Yes");
editor_first.commit();
dropbox.getSession().startAuthentication(Update_Database.this);
}
else {
DownFile dd=new DownFile(this, dropbox,FILE_DIR,myInternalFile);
Boolean result=dd.exe();
if (result) {
Toast.makeText(context, "File Downloaded Successfully from dropbox!",
Toast.LENGTH_LONG).show();
} else {
Toast.makeText(context, "Failed to Download file", Toast.LENGTH_LONG)
.show();
}
Toast.makeText(this, "after login previously", Toast.LENGTH_LONG).show();
}
}
Normal Class File:
public class DownFile {
private static final String DATABASE_NAME = "GirviDrop";
private DropboxAPI<?> dropbox;
private String path;
private Context context;
private Boolean fileexist;
private File internal;
public DownFile(Context context, DropboxAPI<?> dropbox,
String path,File internal) {
this.context = context.getApplicationContext();
this.dropbox = dropbox;
this.path = path;
this.internal=internal;
}
public boolean exe() {
try {
File data = Environment.getDataDirectory();
if(internal.exists())
{
internal.delete();
internal.createNewFile();
}
Entry existingentry= dropbox.metadata( path ,1000,null,true,null);
if (existingentry.contents.size() != 0)
{
for (Entry ent :existingentry.contents)
{
String name = ent.fileName();
if(name.equals(DATABASE_NAME))
{ FileOutputStream outputStream = new FileOutputStream(internal);
dropbox.getFile(path + DATABASE_NAME, null, outputStream, null);
return true;
}
}
}
} catch (IOException e) {
e.printStackTrace();
} catch (DropboxException e) {
e.printStackTrace();
}catch(NetworkOnMainThreadException e)
{e.printStackTrace();}
return false;
}
}
Error:
"Failed to download File" which means exe() returning false.
LogCat:
07-15 18:58:55.673 2311-2311/loginscreen.example.com.girviapp W/System.err﹕ android.os.NetworkOnMainThreadException
07-15 18:58:55.673 2311-2311/loginscreen.example.com.girviapp W/System.err﹕ at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1147)
07-15 18:58:55.673 2311-2311/loginscreen.example.com.girviapp W/System.err﹕ at java.net.InetAddress.lookupHostByName(InetAddress.java:418)
07-15 18:58:55.673 2311-2311/loginscreen.example.com.girviapp W/System.err﹕ at java.net.InetAddress.getAllByNameImpl(InetAddress.java:252)
07-15 18:58:55.673 2311-2311/loginscreen.example.com.girviapp W/System.err﹕ at java.net.InetAddress.getAllByName(InetAddress.java:215)
07-15 18:58:55.674 2311-2311/loginscreen.example.com.girviapp W/System.err﹕ at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:137)
07-15 18:58:55.674 2311-2311/loginscreen.example.com.girviapp W/System.err﹕ at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
07-15 18:58:55.674 2311-2311/loginscreen.example.com.girviapp W/System.err﹕ at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
07-15 18:58:55.674 2311-2311/loginscreen.example.com.girviapp W/System.err﹕ at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:360)
07-15 18:58:55.674 2311-2311/loginscreen.example.com.girviapp W/System.err﹕ at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
07-15 18:58:55.677 2311-2311/loginscreen.example.com.girviapp W/System.err﹕ at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
07-15 18:58:55.678 2311-2311/loginscreen.example.com.girviapp W/System.err﹕ at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
07-15 18:58:55.679 2311-2311/loginscreen.example.com.girviapp W/System.err﹕ at com.dropbox.client2.RESTUtility.execute(RESTUtility.java:387)
07-15 18:58:55.679 2311-2311/loginscreen.example.com.girviapp W/System.err﹕ at com.dropbox.client2.RESTUtility.execute(RESTUtility.java:339)
07-15 18:58:55.679 2311-2311/loginscreen.example.com.girviapp W/System.err﹕ at com.dropbox.client2.RESTUtility.streamRequest(RESTUtility.java:194)
07-15 18:58:55.679 2311-2311/loginscreen.example.com.girviapp W/System.err﹕ at com.dropbox.client2.RESTUtility.request(RESTUtility.java:124)
07-15 18:58:55.679 2311-2311/loginscreen.example.com.girviapp W/System.err﹕ at com.dropbox.client2.DropboxAPI.metadata(DropboxAPI.java:1919)
07-15 18:58:55.687 2311-2311/loginscreen.example.com.girviapp W/System.err﹕ at loginscreen.example.com.girviapp.DownFile.exe(DownFile.java:49)
07-15 18:58:55.687 2311-2311/loginscreen.example.com.girviapp W/System.err﹕ at loginscreen.example.com.girviapp.Update_Database.dropboxcopy(Update_Database.java:181)
07-15 18:58:55.687 2311-2311/loginscreen.example.com.girviapp W/System.err﹕ at loginscreen.example.com.girviapp.Update_Database.Update_data(Update_Database.java:140)
07-15 18:58:55.687 2311-2311/loginscreen.example.com.girviapp W/System.err﹕ at loginscreen.example.com.girviapp.Update_Database.onButtonClicker124(Update_Database.java:126)
07-15 18:58:55.687 2311-2311/loginscreen.example.com.girviapp W/System.err﹕ at java.lang.reflect.Method.invoke(Native Method)
07-15 18:58:55.687 2311-2311/loginscreen.example.com.girviapp W/System.err﹕ at java.lang.reflect.Method.invoke(Method.java:372)
07-15 18:58:55.687 2311-2311/loginscreen.example.com.girviapp W/System.err﹕ at android.view.View$1.onClick(View.java:4002)
07-15 18:58:55.687 2311-2311/loginscreen.example.com.girviapp W/System.err﹕ at android.view.View.performClick(View.java:4756)
07-15 18:58:55.687 2311-2311/loginscreen.example.com.girviapp W/System.err﹕ at android.view.View$PerformClick.run(View.java:19749)
07-15 18:58:55.687 2311-2311/loginscreen.example.com.girviapp W/System.err﹕ at android.os.Handler.handleCallback(Handler.java:739)
07-15 18:58:55.687 2311-2311/loginscreen.example.com.girviapp W/System.err﹕ at android.os.Handler.dispatchMessage(Handler.java:95)
07-15 18:58:55.687 2311-2311/loginscreen.example.com.girviapp W/System.err﹕ at android.os.Looper.loop(Looper.java:135)
07-15 18:58:55.687 2311-2311/loginscreen.example.com.girviapp W/System.err﹕ at android.app.ActivityThread.main(ActivityThread.java:5221)
07-15 18:58:55.687 2311-2311/loginscreen.example.com.girviapp W/System.err﹕ at java.lang.reflect.Method.invoke(Native Method)
07-15 18:58:55.687 2311-2311/loginscreen.example.com.girviapp W/System.err﹕ at java.lang.reflect.Method.invoke(Method.java:372)
07-15 18:58:55.687 2311-2311/loginscreen.example.com.girviapp W/System.err﹕ at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
07-15 18:58:55.687 2311-2311/loginscreen.example.com.girviapp W/System.err﹕ at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
07-15 18:58:55.774 2311-2330/loginscreen.example.com.girviapp W/EGL_emulation﹕ eglSurfaceAttrib not implemented
07-15 18:58:55.774 2311-2330/loginscreen.example.com.girviapp W/OpenGLRenderer﹕ Failed to set EGL_SWAP_BEHAVIOR on surface 0xa00264e0, error=EGL_SUCCESS
07-15 18:58:59.297 2311-2330/loginscreen.example.com.girviapp W/EGL_emulation﹕ eglSurfaceAttrib not implemented
07-15 18:58:59.298 2311-2330/loginscreen.example.com.girviapp W/OpenGLRenderer﹕ Failed to set EGL_SWAP_BEHAVIOR on surface 0xa00264e0, error=EGL_SUCCESS

Related

Naas.link problems with Run

Anyone playing on Naas.link? Setup my node. deployed an Oracle Contract. connected the node to the oracle. created a get>uint256. created the atestnetconsumer, but can't get it to run. and my current price just stays at zero
job specs in toml, but I didn't know how to insert toml so i used javascript option
type = "directrequest"
schemaVersion = 1
name = "Get > Uint256"
# Optional External Job ID: Automatically generated if unspecified
# externalJobID = "b1d42cd5-4a3a-4200-b1f7-25a68e48aad8"
contractAddress = "YOUR_ORACLE_CONTRACT_ADDRESS"
maxTaskDuration = "0s"
observationSource = """
decode_log [type="ethabidecodelog"
abi="OracleRequest(bytes32 indexed specId, address requester, bytes32 requestId, uint256 payment, address callbackAddr, bytes4 callbackFunctionId, uint256 cancelExpiration, uint256 dataVersion, bytes data)"
data="$(jobRun.logData)"
topics="$(jobRun.logTopics)"]
decode_cbor [type="cborparse" data="$(decode_log.data)"]
fetch [type="http" method=GET url="$(decode_cbor.get)"]
parse [type="jsonparse" path="$(decode_cbor.path)" data="$(fetch)"]
multiply [type="multiply" input="$(parse)" times=100]
encode_data [type="ethabiencode" abi="(uint256 value)" data="{ \\"value\\": $(multiply) }"]
encode_tx [type="ethabiencode"
abi="fulfillOracleRequest(bytes32 requestId, uint256 payment, address callbackAddress, bytes4 callbackFunctionId, uint256 expiration, bytes32 data)"
data="{\\"requestId\\": $(decode_log.requestId), \\"payment\\": $(decode_log.payment), \\"callbackAddress\\": $(decode_log.callbackAddr), \\"callbackFunctionId\\": $(decode_log.callbackFunctionId), \\"expiration\\": $(decode_log.cancelExpiration), \\"data\\": $(encode_data)}"
]
submit_tx [type="ethtx" to="YOUR_ORACLE_CONTRACT_ADDRESS" data="$(encode_tx)"]
decode_log -> decode_cbor -> fetch -> parse -> multiply -> encode_data -> encode_tx -> submit_tx
"""
here's the kovan etherscan hash:
0x2db26a43becadb046fa2bec8dc3466729b17c39406f88c2888f33c0447eef163
here's the consumer contract
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.7;
import "#chainlink/contracts/src/v0.8/ChainlinkClient.sol";
import "#chainlink/contracts/src/v0.8/ConfirmedOwner.sol";
contract ATestnetConsumer is ChainlinkClient, ConfirmedOwner {
using Chainlink for Chainlink.Request;
uint256 constant private ORACLE_PAYMENT = 1 * LINK_DIVISIBILITY;
uint256 public currentPrice;
int256 public changeDay;
bytes32 public lastMarket;
event RequestEthereumPriceFulfilled(
bytes32 indexed requestId,
uint256 indexed price
);
event RequestEthereumChangeFulfilled(
bytes32 indexed requestId,
int256 indexed change
);
event RequestEthereumLastMarket(
bytes32 indexed requestId,
bytes32 indexed market
);
constructor() ConfirmedOwner(msg.sender){
setPublicChainlinkToken();
}
function requestEthereumPrice(address _oracle, string memory _jobId)
public
onlyOwner
{
Chainlink.Request memory req = buildChainlinkRequest(stringToBytes32(_jobId), address(this), this.fulfillEthereumPrice.selector);
req.add("get", "https://min-api.cryptocompare.com/data/price?fsym=ETH&tsyms=USD");
req.add("path", "USD");
req.addInt("times", 100);
sendChainlinkRequestTo(_oracle, req, ORACLE_PAYMENT);
}
function requestEthereumChange(address _oracle, string memory _jobId)
public
onlyOwner
{
Chainlink.Request memory req = buildChainlinkRequest(stringToBytes32(_jobId), address(this), this.fulfillEthereumChange.selector);
req.add("get", "https://min-api.cryptocompare.com/data/pricemultifull?fsyms=ETH&tsyms=USD");
req.add("path", "RAW.ETH.USD.CHANGEPCTDAY");
req.addInt("times", 1000000000);
sendChainlinkRequestTo(_oracle, req, ORACLE_PAYMENT);
}
function requestEthereumLastMarket(address _oracle, string memory _jobId)
public
onlyOwner
{
Chainlink.Request memory req = buildChainlinkRequest(stringToBytes32(_jobId), address(this), this.fulfillEthereumLastMarket.selector);
req.add("get", "https://min-api.cryptocompare.com/data/pricemultifull?fsyms=ETH&tsyms=USD");
string[] memory path = new string[](4);
path[0] = "RAW";
path[1] = "ETH";
path[2] = "USD";
path[3] = "LASTMARKET";
req.addStringArray("path", path);
sendChainlinkRequestTo(_oracle, req, ORACLE_PAYMENT);
}
function fulfillEthereumPrice(bytes32 _requestId, uint256 _price)
public
recordChainlinkFulfillment(_requestId)
{
emit RequestEthereumPriceFulfilled(_requestId, _price);
currentPrice = _price;
}
function fulfillEthereumChange(bytes32 _requestId, int256 _change)
public
recordChainlinkFulfillment(_requestId)
{
emit RequestEthereumChangeFulfilled(_requestId, _change);
changeDay = _change;
}
function fulfillEthereumLastMarket(bytes32 _requestId, bytes32 _market)
public
recordChainlinkFulfillment(_requestId)
{
emit RequestEthereumLastMarket(_requestId, _market);
lastMarket = _market;
}
function getChainlinkToken() public view returns (address) {
return chainlinkTokenAddress();
}
function withdrawLink() public onlyOwner {
LinkTokenInterface link = LinkTokenInterface(chainlinkTokenAddress());
require(link.transfer(msg.sender, link.balanceOf(address(this))), "Unable to transfer");
}
function cancelRequest(
bytes32 _requestId,
uint256 _payment,
bytes4 _callbackFunctionId,
uint256 _expiration
)
public
onlyOwner
{
cancelChainlinkRequest(_requestId, _payment, _callbackFunctionId, _expiration);
}
function stringToBytes32(string memory source) private pure returns (bytes32 result) {
bytes memory tempEmptyStringTest = bytes(source);
if (tempEmptyStringTest.length == 0) {
return 0x0;
}
assembly { // solhint-disable-line no-inline-assembly
result := mload(add(source, 32))
}
}
the tutorial tells me to put in the address of the network I'm using (kovan). It says there should be an input field next to the deploy button. But there is no input field.
here's the link to the tutorial
https://docs.chain.link/docs/fulfilling-requests/
I stopped here.

I have a picker that is in a collectionview but I'm unsure how to get the value

I have a collectionview which has a [Label(day of the week] - [checkbox] - [picker with times].
I want the user to be able to select a day and time, after that I want to then pass those values to my database. So far I am able to select the day and pass this value on. However I am struggling to refence the value in the picker. I think this is due to it being a list in my object. I have tried booking.Listtimes but that is just a list. I want the value selected.
My ViewModel:
public class RepeatMonthly
{
public string Day { get; set; }
public bool Selected { get; set; }
public List<WalkTimes> _ListTimes { get; set; }
}
private WalkTimes _selectedTimes;
public WalkTimes SelectedTimes
{
get
{
return _selectedTimes;
}
set
{
SetProperty(ref _selectedTimes, value);
}
}
public ObservableCollection<RepeatMonthly> DayList { get; set; }
public CreateWeeklyScheduleViewModel()
{
ListTimes = WalkTimesService.GetTimes().OrderBy(c => c.Key).ToList();
DayList = new ObservableCollection<RepeatMonthly>()
{
new RepeatMonthly(){Day="Every Monday", Selected = false, _ListTimes = ListTimes},
new RepeatMonthly(){Day="Every Tuesday", Selected = false, _ListTimes = ListTimes},
new RepeatMonthly(){Day="Every WednesDay", Selected = false, _ListTimes = ListTimes},
new RepeatMonthly(){Day="Every Thursday", Selected = false, _ListTimes = ListTimes},
new RepeatMonthly(){Day="Every Friday", Selected = false, _ListTimes = ListTimes},
new RepeatMonthly(){Day="Every Saturday", Selected = false, _ListTimes = ListTimes},
new RepeatMonthly(){Day="Every Sunday", Selected = false, _ListTimes = ListTimes}
};
source = new ObservableCollection<PetProfile>();
}
My Xaml:
<CollectionView x:Name="RepeatCollectionView" HorizontalOptions="Center" ItemsSource="{Binding DayList}" HeightRequest="350">
<CollectionView.ItemTemplate>
<DataTemplate>
<Grid Padding="0" RowDefinitions="25, 20" ColumnDefinitions="*,*">
<Label Text="{Binding Day}" FontAttributes="Bold" FontSize="Medium"
Margin="5,0"
VerticalTextAlignment="Center" HorizontalTextAlignment="Start"/>
<CheckBox x:Name="SelectDayCheckBox" Grid.Row="0" HorizontalOptions="End" IsChecked="{Binding Selected, Mode=TwoWay}" BindingContext="{Binding .}" CheckedChanged="SelectDayCheckBox_CheckedChanged"/>
<Picker x:Name="SelectTimeOfWalkPicker" Title="--Select Walk Start Time--" Grid.Column="1" ItemsSource="{Binding _ListTimes}" ItemDisplayBinding="{Binding Value}" VerticalTextAlignment="Center" HorizontalTextAlignment="Center" SelectedItem="{Binding SelectedTimes}" />
</Grid>
</DataTemplate>
</CollectionView.ItemTemplate>
</CollectionView>
my .cs page:
private async void SubmitBtn_Clicked(object sender, EventArgs e)
{
foreach (RepeatMonthly booking in (BindingContext as CreateWeeklyScheduleViewModel).DayList)
{
if (booking.Selected)
{
await passtoDataBase(booking.Day, "where time variable goes");
}
}
await DisplayAlert("Success", "Booked Successfully", "OK");
await Shell.Current.GoToAsync($"//{nameof(MyBookingsPage)}");
}
properties of WalkTimes object:
public class WalkTimes
{
public int Key { get; set; }
public string Value { get; set; }
}

updating progress bar using Task parallel library

I am trying to update the list of progress bars to show the image download progress using Task Parallel Library in Xamarin.Forms
For now I have written a block of code to simulate the download process by using a delay.
Here is my Xaml file where a ListView named MediaList resides with one caption and progress bar per item.
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage
xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="ImageTask.View.ImageTaskView">
<ContentPage.Content>
<ListView ItemsSource="{Binding MediaList}" CachingStrategy = "RecycleElement" VerticalOptions="FillAndExpand" >
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<StackLayout Orientation="Vertical">
<Label Text = "{Binding mediaName}" FontSize="22" />
<ProgressBar Progress="{Binding mediaProgress}"></ProgressBar>
</StackLayout>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</ContentPage.Content>
</ContentPage>
Here is my view model in which I have created one action block that takes the entire list of media object and tries to update the progress bar.
However, my main issue is I am not able to see the progress updated in my UI , so I don't know how shall I update my UI.
public class ImageTaskViewModel : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
private IList<MediaInfo> _mediaList;
protected void OnPropertyChanged(string propertyName)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
public IList<MediaInfo> MediaList
{
get { return _mediaList; }
set
{
_mediaList = value;
OnPropertyChanged("MediaList");
}
}
public ImageTaskViewModel()
{
Action<IList<MediaInfo>> progressActionBlock = mediaInfoList =>
{
// infinite loop to simulate download
while (true)
{
IEnumerator<MediaInfo> dataList = mediaInfoList.GetEnumerator();
Task.Delay(2000).Wait();
while (dataList.MoveNext())
{
MediaInfo mediaInfo = dataList.Current;
Debug.WriteLine("media name " + mediaInfo.mediaName + " progress " + mediaInfo.mediaProgress);
if (mediaInfo.mediaProgress == 1)
{
Debug.WriteLine("media name " + mediaInfo.mediaName + " Done ");
break;
}
else
{
mediaInfo.mediaProgress = mediaInfo.mediaProgress + 0.1;
}
}
}
};
var opts = new ExecutionDataflowBlockOptions()
{
MaxDegreeOfParallelism = 2
};
var progressAction = new ActionBlock<IList<MediaInfo>>(progressActionBlock, opts);
MediaList = new List<MediaInfo>();
for (int i = 1; i < 6; i++)
{
MediaInfo mediaInfo = new MediaInfo();
mediaInfo.mediaName = i.ToString();
MediaList.Add(mediaInfo);
}
// Exectue Action block
progressAction.Post(MediaList);
}
}
Model of MediaInfo:
public class MediaInfo
{
public string mediaId { get; set; }
public string mediaName { get; set; }
public string mediaPath { get; set; }
public byte[] mediaStream { get; set; }
public double mediaProgress { get; set; } = 0.1;
}
In your View model you don't have mediaProgress. You should add
Double _mediaProgress;
public Double mediaProgress{
get{
return _mediaProgress;
} set{
_mediaProgress = value;
OnPropertyChanged("Email");
}
}
And then in your all method you use mediaProgress to set the progress.

SQL Reporting Services report only loads on second click

I have a local .rdlc report rigged to show on a button click, but for some reason the report only shows up on the 2nd button click event. I have no idea why the report doesn't show on the first button click... This is the function I call on the click event of the button.
private void ShowReport(string accountingCompanyId, string companyId, string approvalUnitId, DateTime startDate, DateTime finishDate, string supplierId,
string documentNumber, string documentType, string documentState, string costCenterId, string chargingKeyId,
string dim1Value, string dim1Description, string dim1Id, string dim2Value, string dim2Description, string dim2Id,
string dim3Value, string dim3Description, string dim3Id, bool showDetails) {
//this.ReportViewer1.Reset();
//Set report mode for local processing.
this.ReportViewer1.ProcessingMode = ProcessingMode.Local;
ISettingsReader settingsReader = SettingsReaderFactory.Instance.CreateSettingsReader();
this.ReportViewer1.LocalReport.ReportPath = settingsReader.GetSetting("ReportViewer", "FinancialReportPath" + (showDetails ? "" : "Small"), true, null);
ReportsBL reports = new ReportsBL();
// Clear out any previous datasources.
this.ReportViewer1.LocalReport.DataSources.Clear();
// Load the company dataSource.
DataTable company = reports.GetCompanyDataSet(accountingCompanyId).Tables[0];
ReportDataSource dataSourceCompany = new ReportDataSource(company.TableName, company);
this.ReportViewer1.LocalReport.DataSources.Add(dataSourceCompany);
// Load the dataSource.
DataTable report = reports.GetReportFinanceiroSmallDataSet(companyId, startDate, finishDate, chargingKeyId, costCenterId, documentNumber, documentType, dim1Value, dim2Value, dim3Value, dim1Id, dim2Id, dim3Id, supplierId, approvalUnitId, documentState, accountingCompanyId).Tables[0];
ReportDataSource dataSourceReport = new ReportDataSource(report.TableName, report);
this.ReportViewer1.LocalReport.DataSources.Add(dataSourceReport);
this.ReportViewer1.LocalReport.Refresh();
this.pnlReport.Visible = true;
}
Strangely, if I uncomment the line this.ReportViewer.Reset(); then the report will never show up regardless of the number of clicks I generate... Does anybody know if this is normal? How can work around the problem?
Thanks in advance,
I guess the problem might be that the click event is fired after the page is rendered. Try calling the method in the Page_Load event.
protected void Page_Load(object sender, EventArgs e)
{
if (IsCallback)
{
ShowReport(
// params
);
}
}
If that works, you know it has something to do with the order of execution.
I've never had to call ReportViewer.DataBind(); Below is what I typically do:
IEnumerable<ReportClass> ds = DataTranslator.GetReportData(Int64.Parse(<someId>));
report.LocalReport.ReportPath = "<some_path_to_report.rdlc>";
report.LocalReport.DataSources.Add(new ReportDataSource("DataSet", ds));
report.Visible = true;
report.LocalReport.Refresh();
After a lot of trial and error, I got it working by calling the databind() method on the the pageload event. After the pageload databinds (with no datasource set), the subsequent
button click starts working as expected.
I'm included the code in case somebody else encounters this error. (Would love to know why I need to databind in the pageload though...)
Update 2
I finally figured out the problem... Turns out the .rdlc was migrated from an old 2005 .rdl report, and that the new .rdlc contained old report parameters+sql which was somehow messing up the report loading. After I removed the unused report parameteres+sql everything started working perfectly... I've updated the code bellow to reflect what I'm now using in my project...
protected void Page_Load(object sender, System.EventArgs e) {
}
protected void btGenStats_Click(object sender, System.EventArgs e) {
...
this.ShowReport(accountingCompanyId, companyId, approvalUnitId, startDate, finishDate, supplierId, documentNumber, documentType, documentState,
costCenterId, chargingKeyId, dim1, dim1Desc, dim1Id, dim2, dim2Desc, dim2Id, dim3, dim3Desc, dim3Id, showDetails);
}
private void ShowReport(string accountingCompanyId, string companyId, string approvalUnitId, DateTime startDate, DateTime finishDate, string supplierId, string documentNumber, string documentType, string documentState, string costCenterId, string chargingKeyId, string dim1Value, string dim1Description, string dim1Id, string dim2Value, string dim2Description, string dim2Id, string dim3Value, string dim3Description, string dim3Id, bool showDetails) {
this.ReportViewer1.Reset();
//Set report mode for local processing.
this.ReportViewer1.ProcessingMode = ProcessingMode.Local;
ISettingsReader settingsReader = SettingsReaderFactory.Instance.CreateSettingsReader();
string reportPath = settingsReader.GetSetting("ReportViewer", "FinancialReportPath"+( showDetails? "" : "Small" ), true, null);
this.ReportViewer1.LocalReport.ReportPath = Server.MapPath(reportPath);
ReportsBL reports = new ReportsBL();
// Clear out any previous datasources.
this.ReportViewer1.LocalReport.DataSources.Clear();
// Load the company dataSource.
DataTable company = reports.GetCompanyDataSet(accountingCompanyId).Tables[0];
ReportDataSource dataSourceCompany = new ReportDataSource(company.TableName, company);
this.ReportViewer1.LocalReport.DataSources.Add(dataSourceCompany);
if (showDetails)
{
// Load the dataSource.
DataTable report = reports.GetReportFinanceiroDataSet(companyId, approvalUnitId, startDate, finishDate, chargingKeyId, costCenterId, documentNumber, documentType, dim1Value, dim2Value, dim3Value, dim1Id, dim2Id, dim3Id, supplierId, documentState, accountingCompanyId).Tables[0];
ReportDataSource dataSourceReport = new ReportDataSource(report.TableName, report);
this.ReportViewer1.LocalReport.DataSources.Add(dataSourceReport);
}
else
{
// Load the dataSource.
DataTable report = reports.GetReportFinanceiroSmallDataSet(companyId, approvalUnitId, startDate, finishDate, chargingKeyId, costCenterId, documentNumber, documentType, dim1Value, dim2Value, dim3Value, dim1Id, dim2Id, dim3Id, supplierId, documentState, accountingCompanyId).Tables[0];
ReportDataSource dataSourceReport = new ReportDataSource(report.TableName, report);
this.ReportViewer1.LocalReport.DataSources.Add(dataSourceReport);
}
this.pnlReport.Visible = true;
}
Try this code:
protected void btnSubmit_Click(object sender, EventArgs e)
{
string pstrType;
pstrType = Request.QueryString["Type"];
LoadReport();
}
public class CustomReportCredentials : Microsoft.Reporting.WebForms.IReportServerCredentials
{
// local variable for network credential.
private string _UserName;
private string _PassWord;
private string _DomainName;
public CustomReportCredentials(string UserName, string PassWord, string DomainName)
{
_UserName = UserName;
_PassWord = PassWord;
_DomainName = DomainName;
}
public System.Security.Principal.WindowsIdentity ImpersonationUser
{
get
{
return null; // not use ImpersonationUser
}
}
public System.Net.ICredentials NetworkCredentials
{
get
{
// use NetworkCredentials
return new NetworkCredential(_UserName, _PassWord, _DomainName);
}
}
public bool GetFormsCredentials(out Cookie authCookie, out string user, out string password, out string authority)
{
// not use FormsCredentials unless you have implements a custom autentication.
authCookie = null;
user = password = authority = null;
return false;
}
}
void LoadReport()
{
string strCompanyName = objSession.SelCompanyName;
string strHeading = "";
string strBranchName = objSession.SelBranchName;
rptvwMain.ProcessingMode = ProcessingMode.Remote;
rptvwMain.ServerReport.ReportServerCredentials = new CustomReportCredentials(AppConfig.ReportServerUserName, AppConfig.ReportServerPassword, AppConfig.ReportServerDomain);
string strReportServerUrl = AppConfig.ReportServerUrl + AppConfig.ReportServerFolder;
rptvwMain.ServerReport.ReportServerUrl = new Uri(strReportServerUrl);
List<ReportParameter> parameters = new List<ReportParameter>();
if (pstrType == "OB")
{
strHeading = "Ledger Opening Balance";
rptvwMain.ServerReport.ReportPath = "/Account/OpeningBalance";
}
parameters.Add(new ReportParameter("FyId", Convert.ToInt16(objSession.FyId).ToString()));
parameters.Add(new ReportParameter("AccountGroupId", cmbAccountGroup.SelectedValue));
parameters.Add(new ReportParameter("LedgerId", cmbLedgerId.SelectedValue));
parameters.Add(new ReportParameter("BranchId", Convert.ToInt64(objSession.BranchId).ToString()));
parameters.Add(new ReportParameter("StDate", Convert.ToDateTime(RadDtpFromDate.SelectedDate).ToString()));
parameters.Add(new ReportParameter("EnDate", Convert.ToDateTime(RadDtpToDate.SelectedDate).ToString()));
parameters.Add(new ReportParameter("CompanyName", strCompanyName.ToString()));
parameters.Add(new ReportParameter("BranchName", strBranchName.ToString()));
parameters.Add(new ReportParameter("Heading",strHeading.ToString()));
rptvwMain.ServerReport.SetParameters(parameters);
rptvwMain.ServerReport.SetDataSourceCredentials(new[] { new DataSourceCredentials() { Name =AppConfig.ReportServerDataSource , UserId = AppConfig.ReportServerDSUserName, Password = AppConfig.ReportServerDSPassword } });
rptvwMain.ShowZoomControl = true;
rptvwMain.ServerReport.Refresh();
}
}

How to Populate a silverlight chart WP7

I need to create a (WP7) chart containing multiple series. The data I'm trying to visualize:
F.ex following collection, containing UserName, Date, Points:
User1,2011-11-09,6
User2,2011-11-09,8
User1,2011-11-02,9
User2,2011-11-02,8
There can be more than two users in the data.
XAML Namespace
xmlns:chartingToolkit="clr-namespace:System.Windows.Controls.DataVisualization.Charting;assembly=System.Windows.Controls.DataVisualization.Toolkit"
CodeBehind
mdChart.Series.Add(MDSeries);
mdChart.Title = "Statistics";
MDSeries.SetBinding(ColumnSeries.ItemsSourceProperty, new Binding());
MDSeries.ItemsSource = lCompetitionStats;
MDSeries.DependentValuePath = "Points";
series.IndependentValuePath = "Date";
MDSeries.IndependentValuePath = "UserName";
XAML
<controls:PanoramaItem Header="mdscores">
<Grid>
<charting:Chart x:Name="mdChart" Foreground="Blue" Background="Black">
<charting:ColumnSeries Background="Black"/>
</charting:Chart>
</Grid>
</controls:PanoramaItem>
As a result, i have the users on X-axis and Points on the Y-axis. I would need dates on X-axis, Points on Y-Axis and a separate serie for earch user. How to create/populate such a chart runtime?
Try the following:
CodeBehind
public class ColumnChartValues
{
#region Variables
public string Label { get; private set; }
public double Value { get; private set; }
#endregion
#region Constructor and Initialization
public ColumnChartValues()
{
Label = string.Empty;
Value = 0;
}
public ColumnChartValues(string label, double value)
{
Label = label;
Value = value;
}
#endregion
}
public partial class StatsPage : Page
{
public ObservableCollection<ColumnChartValues> ColumnChartDatabase { get; private set; }
public StatsPage()
{
DataContext = this;
InitializeColumnChart();
}
private void InitializeColumnChart()
{
mdChart.Title = "Statistics";
ColumnChartDatabase = new ObservableCollection<BarChartValues>();
ColumnChartDatabase.Add(new ColumnChartValues("Value One: ", 1));
ColumnChartDatabase.Add(new ColumnChartValues("Value Two: ", 2));
ColumnChartDatabase.Add(new ColumnChartValues("Value Three: ", 3));
}
}
XAML
<charting:Chart x:Name="mdChart" Foreground="Blue" Background="Black">
<charting:ColumnSeries Background="Black" ItemsSource="{Binding ColumnChartDatabase}" IndependentValueBinding="{Binding Label}" DependentValueBinding="{Binding Value}"/>
</charting:Chart>
FYI
You will have to edit the ColumnChartValues chart to suit your needs

Resources