HTML ExportToExcel Button - html

I have an ExportToExcel button in my application which is seen all the time. I want this to be changed to be shown only after I click submit and the result is shown.
Here is the code:
<asp:Button ID="btnExport" runat="server" Text="Export To Excel" OnClick = "ExportToExcel" />
protected void ExportToExcel(object sender, EventArgs e)
{
Response.Clear();
Response.Buffer = true;
Response.ContentType = "text/xls";
Response.AddHeader("content-disposition", "attachment;filename=HistoricalReporting.xls");
Response.Charset = "";
using (StringWriter sw = new StringWriter())
{
HtmlTextWriter hw = new HtmlTextWriter(sw);
//To Export all pages
GridView1.AllowPaging = false;
this.BindGridView();
GridView1.HeaderRow.BackColor = Color.White;
foreach (TableCell cell in GridView1.HeaderRow.Cells)
{
cell.BackColor = GridView1.HeaderStyle.BackColor;
}
foreach (GridViewRow row in GridView1.Rows)
{
row.BackColor = Color.White;
foreach (TableCell cell in row.Cells)
{
if (row.RowIndex % 2 == 0)
{
cell.BackColor = GridView1.AlternatingRowStyle.BackColor;
}
else
{
cell.BackColor = GridView1.RowStyle.BackColor;
}
cell.CssClass = "textmode";
}
}
GridView1.RenderControl(hw);
//style to format numbers to string
string style = #"<style> .textmode { } </style>";
Response.Write(style);
Response.Output.Write(sw.ToString());
Response.Flush();
Response.End();
}
}
public override void VerifyRenderingInServerForm(Control control)
{
/* Verifies that the control is rendered */
}

Related

Toggle Button Checked Property Windows Phone 8

I add a toggle button on Windows Phone 8 . When i checked (on), its save a value in Isolated storage and I check that value in constructor whatever it has a toggle value or null. If there is a toggle value I want to display toggle button checked . But I dont know the property to how to checked it when application is run .
Toggle Button XAML :
<toolkit:ToggleSwitch x:Name="toggle" Content="On" Width="165" FontSize="28" VerticalAlignment="Center" HorizontalAlignment="Right"/>
C# :
public Subscription()
{
InitializeComponent();
this.toggle.Checked += new EventHandler<RoutedEventArgs>(toggle_Checked);
this.toggle.Unchecked += new EventHandler<RoutedEventArgs>(toggle_Unchecked);
var appSettings = IsolatedStorageSettings.ApplicationSettings;
if (HasSValue() == "NoValue")
{
// Here i want to Display toggle button unchecked
}
else
{
// Here i want to Display toggle button checked
}
}
void toggle_Unchecked(object sender, RoutedEventArgs e)
{
this.toggle.Content = "Off";
this.toggle.SwitchForeground = new SolidColorBrush(Colors.Red);
var appSettings = IsolatedStorageSettings.ApplicationSettings;
appSettings.Remove("toggleValue");
appSettings.Save();
}
void toggle_Checked(object sender, RoutedEventArgs e)
{
this.toggle.Content = "On";
this.toggle.SwitchForeground = new SolidColorBrush(Colors.Green);
MessageBox.Show("R U Sure ?");
var appSettings = IsolatedStorageSettings.ApplicationSettings;
appSettings.Add("toggleValue", "MAHIN");
appSettings.Save();
}
public string HasSValue()
{
var appSettings = IsolatedStorageSettings.ApplicationSettings;
if (appSettings.Contains("toggleValue"))
{
return (string) appSettings["toggleValue"];
}
else
{
return "NoValue";
}
}
Try this
if (HasSValue() == "NoValue")
{
this.toggle.IsChecked = false;
}
else
{
this.toggle.IsChecked = true;
}
Hope this helps
Update your Constructor as follows
public Subscription()
{
InitializeComponent();
var appSettings = IsolatedStorageSettings.ApplicationSettings;
if (HasSValue() == "NoValue")
{
// Here i want to Display toggle button unchecked
}
else
{
// Here i want to Display toggle button checked
}
this.toggle.Checked += new EventHandler<RoutedEventArgs>(toggle_Checked);
this.toggle.Unchecked += new EventHandler<RoutedEventArgs>(toggle_Unchecked);
}

WP8 issue with html agility pack

This is the function I used to get the string content from the website ..the problem is when executed first I cannot get the string content (App.Data2 = userprofile.InnerText;) since it skips to the next line (App.savecontent(App.Data2);) so that I get an empty string. If I recall the function I could get the string. Is there any possibility to solve this issue I need the string value first time automatically
This is my Page.cs code :
namespace Project_Future1
{
public partial class Page1 : PhoneApplicationPage
{
public Page1()
{
InitializeComponent();
{
string url = "http://www.astrosage.com/horoscope/daily-";
HtmlWeb.LoadAsync(url + App.Data + "-horoscope.asp", DownLoad);
}
data();
App.loadContent();
change2();
}
public void change2()
{
try
{
Util.LiveTile.UpdateLiveTile(App.Data2);
}
catch (Exception)
{
}
}
public void DownLoad(object sender, HtmlDocumentLoadCompleted e)
{
if (e.Error == null)
{
HtmlDocument doc = e.Document;
if (doc != null)
{
var userprofile = doc.DocumentNode.SelectSingleNode("//div[#class = 'ui-large-content']");
App.Data2 = userprofile.InnerText;
App.savecontent(App.Data2);
}
}
}
private void data()
{
SelectedSign.Text = App.Data;
SSContent.Text = App.Data2;
}
private void Refresh_click(object sender, EventArgs e)
{
SSContent.Text = App.Data2;
}
private void Fb_Click(object sender, EventArgs e)
{
NavigationService.Navigate(new Uri("/FB.xaml", UriKind.Relative));
}
}
}
this is my App.Xaml.cs File :
public static void savecontent(string save)
{
try
{
if (!string.IsNullOrEmpty(appFileName1))
{
IsolatedStorageFile oIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication();
oIsolatedStorage.CreateDirectory(appFolder1);
StreamWriter writeFile = new StreamWriter(new IsolatedStorageFileStream(appFolder1 + "\\" + appFileName1, FileMode.OpenOrCreate, oIsolatedStorage));
writeFile.WriteLine(save);
writeFile.Close();
}
}
catch (Exception)
{
throw;
}
}
this is my code to load the content from the storage :
public static void loadContent()
{
IsolatedStorageFile oIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication();
if (oIsolatedStorage.DirectoryExists(appFolder1))
{
IsolatedStorageFileStream fileStream = oIsolatedStorage.OpenFile(appFolder1 + "\\" + appFileName1, FileMode.Open, FileAccess.Read);
using (StreamReader reader = new StreamReader(fileStream))
{
App.Data2 = reader.ReadLine();
reader.Close();
}
}
}

How cancel Async Call in Windows Phone?

I have a list wich is loaded with elements each time the user make a research...These elements contain an Icon which is dowloaded with an async method GetByteArrayAsync of the HttpClient object. I have an issue when the user make a second research while the icon of the first list are still downloading.Because the list of elements is changing while Icon downloads are processing on each element of the first list. So my guess is that I need to cancel these requests each time the user proceed to a new research...Ive readen some stuuf on Task.run and CancellationTokenSource but I can't find really helpful example for my case so here is my code...Hope you can help me with that ...Thank you
public static async Task<byte[]> DownloadElementFile(BdeskElement bdeskElement)
{
//create and send the request
DataRequest requesteur = new DataRequest();
byte[] encryptedByte = await requesteur.GetBytesAsync(dataRequestParam);
return encryptedByte;
}
public async Task<Byte[]> GetBytesAsync(DataRequestParam datarequesparam)
{
var handler = new HttpClientHandler { Credentials = new NetworkCredential(datarequesparam.AuthentificationLogin, datarequesparam.AuthentificationPassword, "bt0d0000") };
HttpClient httpClient = new HttpClient(handler);
try
{
byte[] BytesReceived = await httpClient.GetByteArrayAsync(datarequesparam.TargetUri);
if (BytesReceived.Length > 0)
{
return BytesReceived;
}
else
{
return null;
}
}
catch (WebException)
{
throw new MyException(MyExceptionsMessages.Webexception);
}
}
EDIT
public async Task<Byte[]> GetBytesAsync(DataRequestParam datarequesparam)
{
var handler = new HttpClientHandler { Credentials = new NetworkCredential(datarequesparam.AuthentificationLogin, datarequesparam.AuthentificationPassword, "bt0d0000") };
HttpClient httpClient = new HttpClient(handler);
try
{
cts = new CancellationTokenSource();
HttpResponseMessage reponse = await httpClient.GetAsync(datarequesparam.TargetUri,cts.Token);
if (reponse.StatusCode == HttpStatusCode.OK)
{
byte[] BytesReceived = reponse.Content.ReadAsByteArrayAsync().Result;
if (BytesReceived.Length > 0)
{
return BytesReceived;
}
else
{
return null;
}
}
else
{
return null;
}
}
catch (WebException)
{
throw new MyException(MyExceptionsMessages.Webexception);
}
catch(OperationCanceledException)
{
throw new OperationCanceledException();
}
EDIT2
I need to cancel this funntion when the user make a new research and the list "listBoxGetDocsLibs" changed.
private async void LoadIconDocLibs()
{
foreach (var doclib in listBoxGetDocsLibs)//ERROR HERE COLLECTION HAS CHANGED
{
doclib.Icon = new BitmapImage();
try
{
byte[] Icon = await ServerFunctions.GetDocLibsIcon(doclib);
if (Icon != null)
{
{
var ms = new MemoryStream(Icon);
BitmapImage photo = new BitmapImage();
photo.DecodePixelHeight = 64;
photo.DecodePixelWidth = 92;
photo.SetSource(ms);
doclib.Icon = photo;
}
}
}
catch(OperationCanceledException)
{
}
}
}
First you need to define CancellationTokenSource:
private System.Threading.CancellationTokenSource cts;
place above code somewhere, where you can access it with your Button or other method.
Unfortunately GetByteArrayAsync lacks Cancelling - so it cannot be used with cts.Token, but maybe you can accomplish your task using GetAsync - which supports Cancelling:
ctsDownload = new System.Threading.CancellationTokenSource();
HttpResponseMessage response = await httpClient.GetAsync(requestUri, cts.Token);
Then you can get your content from response.
And when you want to Cancel your Task it can look like this:
private void cancelBtn_Click(object sender, RoutedEventArgs e)
{
if (this.cts != null)
this.cts.Cancel();
}
When you Cancel task an Exception will be thrown.
If you want to cancel your own async Task, a good example you can find at Stephen Cleary blog.
EDIT - you can also build your own method (for example with HttpWebRequest) which will support Cancelling:
For this purpose you will have to extend HttpWebRequest (under WP it lacks GetResponseAsync):
// create a static class in your namespace
public static class Extensions
{
public static Task<HttpWebResponse> GetResponseAsync(this HttpWebRequest webRequest)
{
TaskCompletionSource<HttpWebResponse> taskComplete = new TaskCompletionSource<HttpWebResponse>();
webRequest.BeginGetResponse(
asyncResponse =>
{
try
{
HttpWebRequest responseRequest = (HttpWebRequest)asyncResponse.AsyncState;
HttpWebResponse someResponse = (HttpWebResponse)responseRequest.EndGetResponse(asyncResponse);
taskComplete.TrySetResult(someResponse);
}
catch (WebException webExc)
{
HttpWebResponse failedResponse = (HttpWebResponse)webExc.Response;
taskComplete.TrySetResult(failedResponse);
}
catch (Exception exc) { taskComplete.SetException(exc); }
}, webRequest);
return taskComplete.Task;
}
}
Then your method can look like this:
public async Task<Byte[]> GetBytesAsync(DataRequestParam datarequesparam, CancellationToken ct)
{
HttpWebRequest request = HttpWebRequest.CreateHttp(datarequesparam.TargetUri);
request.Method = "GET";
request.Credentials = new NetworkCredential(datarequesparam.AuthentificationLogin, datarequesparam.AuthentificationPassword, "bt0d0000");
request.AllowReadStreamBuffering = false;
try
{
if (request != null)
{
using (HttpWebResponse response = await request.GetResponseAsync())
using (Stream mystr = response.GetResponseStream())
using (MemoryStream output = new MemoryStream())
{
const int BUFFER_SIZE = 10 * 1024;
byte[] buf = new byte[BUFFER_SIZE];
int bytesread = 0;
while ((bytesread = await mystr.ReadAsync(buf, 0, BUFFER_SIZE)) > 0)
{
output.Write(buf, 0, bytesread);
ct.ThrowIfCancellationRequested();
}
return output.ToArray();
}
}
else return null;
}
catch (WebException)
{
throw new MyException(MyExceptionsMessages.Webexception);
}
}
You can freely change Buffer Size which will affect how often Cancellation will be checked.
I haven't tried this but I think it should work.

Cross fade page transitions Windows phone 8 toolkit

I'm implementing the NavigationTransition with the TransitionService provided by the Windows Phone 8 toolkit and Microsoft.Phone.Controls. I was expecting the pages to cross fade during the transition but they don't crossfade by default.
For instance if I'm going back to a previous page using a fade out transition, the origin page fades to full opacity before the target page appears, producing a "popping" effect.
I hoping that someone could provide guidance on getting that effect to happen.
Please check the type of your RootFrame in App.xaml.cs, it must be TransitionFrame if want to use NavigationTransition.
I ended up using some slight-of-hand with screen shots and the far background plane to make the phone pages appear to "cross-fade" - here with edited out biz-details:
public class FormPage : PhoneApplicationPage {
public FormPage() {
InitializeComponent();
PrepareAnimationIn(FormApp.frameTransition);
}
void PrepareAnimationIn(string pageAnimation) {
AnimatedPageFactory.SetNavigationInTransition(pageAnimation, this);
}
public void PrepareAnimationOut(string pageAnimation) {
AnimatedPageFactory.SetNavigationOutTransition(pageAnimation, this);
}
void StoreScreenShot(string name, WriteableBitmap bitmap) {
using (IsolatedStorageFile store = IsolatedStorageFile.GetUserStoreForApplication()) {
string path = Path.Combine(screenshotDir, name + screenFileType);
store.CreateDirectory(screenshotDir);
using (IsolatedStorageFileStream stream = new IsolatedStorageFileStream(path, FileMode.Create, store)) {
using (BinaryWriter writer = new BinaryWriter(stream)) {
int count = bitmap.Pixels.Length * sizeof(int);
byte[] pixels = new byte[count];
Buffer.BlockCopy(bitmap.Pixels, 0, pixels, 0, count);
writer.Write(pixels, 0, pixels.Length);
}
}
}
}
WriteableBitmap FetchScreenShot(string name) {
WriteableBitmap bitmap = new WriteableBitmap((int)this.ActualWidth, (int)this.ActualHeight);
using (IsolatedStorageFile store = IsolatedStorageFile.GetUserStoreForApplication()) {
string path = Path.Combine(screenshotDir, name + screenFileType);
if (store.FileExists(path)) {
using (IsolatedStorageFileStream stream = new IsolatedStorageFileStream(path, FileMode.Open, store)) {
using (BinaryReader reader = new BinaryReader(stream)) {
int count = bitmap.Pixels.Length * sizeof(int);
byte[] pixels = new byte[count];
reader.Read(pixels, 0, count);
Buffer.BlockCopy(pixels, 0, bitmap.Pixels, 0, count);
}
}
store.DeleteFile(path);
}
}
return bitmap;
}
WriteableBitmap ScreenShot() {
WriteableBitmap bmpCurrentScreenImage = new WriteableBitmap((int)this.ActualWidth, (int)this.ActualHeight);
bmpCurrentScreenImage.Render(_canvas, new MatrixTransform());
bmpCurrentScreenImage.Invalidate();
return bmpCurrentScreenImage;
}
ImageBrush ImageBrushFromBitmap(WriteableBitmap bitmap) {
return new ImageBrush { ImageSource = bitmap };
}
static Stack<string> formImages = new Stack<string>();
static string screenFileType = ".frmscn";
static string screenshotDir = "frmscrn";
protected override void OnNavigatingFrom(NavigatingCancelEventArgs e) {
var app = Application.Current as App;
if (e.NavigationMode == NavigationMode.New &&
e.Uri.ToString().Contains("FormPage.xaml")) {
WriteableBitmap screenShot = ScreenShot();
app.RootFrame.Background = ImageBrushFromBitmap(screenShot);
formImages.Push(Name);
StoreScreenShot(Name, screenShot);
} else if (e.NavigationMode == NavigationMode.Back) {
if (formImages.Count > 0)
app.RootFrame.Background = ImageBrushFromBitmap(FetchScreenShot(formImages.Pop()));
else {
//we're backing out of the last form so reset the background
app.RootFrame.Background = null;
RemoveCachedScreenshots();
}
}
}
public static void RemoveCachedScreenshots() {
using (IsolatedStorageFile store = IsolatedStorageFile.GetUserStoreForApplication()) {
string path = Path.Combine(screenshotDir, "*" + screenFileType);
try {
string[] fileList = store.GetFileNames(path);
foreach (string f in fileList) {
store.DeleteFile(Path.Combine(screenshotDir, f));
}
} catch {
}
}
}
}

Waiting and Return a result with DownloadStringAsync WP8

I do a webrequest with DownloadStringAsync() but I need to return the result only when the DownloadStringCompleted event has been called. After the downloadasync-method, I need to wait for the result and then I could return it in a string property. So I implemented a while(Result == "") but I don't know what to do there. I already tried Thread.sleep(500) but it seems the download never gets completed. And the code remains in the while forever.
string Result = "";
public String Query(DataRequestParam dataRequestParam)
{
try
{
WebClient web = new WebClient();
if (!string.IsNullOrEmpty(dataRequestParam.AuthentificationLogin))
{
System.Net.NetworkCredential account = new NetworkCredential(dataRequestParam.AuthentificationLogin, dataRequestParam.AuthentificationPassword);
web.Credentials = account;
}
web.DownloadStringCompleted += OnDownloadStringCompleted;
web.DownloadStringAsync(dataRequestParam.TargetUri);
while (Result == "")
{
//What am i supposed to do here ?
}
return Result;
}
catch(WebException we)
{
MessageBox.Show(we.Message);
return null;
}
}
private void OnDownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
if (e.Error != null)
{
//Error treating
}
else
{
Result = e.Result;
}
}
UI CODE
protected override void OnNavigatedTo(NavigationEventArgs e)
{
base.OnNavigatedTo(e);
if (e.NavigationMode != NavigationMode.Back)
{
ServerFunctions.SetUserProfil(User.UserLogin,User.UserPassword);
this.listBoxGetDocsLibs.Clear();
List<BdeskDocLib> list = new List<BdeskDocLib>();
try
{
//HERE THE START OF THE DOWNLOAD
ServerFunctions.GetDocLibs(true);
}
catch (Exception ex)
{
//error
}
foreach (BdeskDocLib docLib in list)
{
this.listBoxGetDocsLibs.Add(docLib);
}
}
}
the ServerFunction static class
public static List<BdeskDocLib> GetDocLibs(bool onlyDocLibPerso)
{
string xmlContent = GetXml(URL_GETDOCLIBS);
List<BdeskDocLib> result = BdeskDocLib.GetListFromXml(xmlContent, onlyDocLibPerso);
return result;
}
private static String GetXml(string partialUrl)
{
string url = GenerateUrl(partialUrl);
DataRequestParam dataRequestParam = new DataRequestParam();
dataRequestParam.TargetUri = new Uri(url);
dataRequestParam.UserAgent = "BSynchro";
dataRequestParam.AuthentificationLogin = userLogin;
dataRequestParam.AuthentificationPassword = userPwd;
//HERE I START THE QUERY method
// NEED QUERY RETURNS A STRING or Task<String>
DataRequest requesteur = new DataRequest();
xmlResult=requesteur.Query(dataRequestParam);
if (CheckErrorConnexion(xmlResult) == false)
{
throw new Exception("Erreur du login ou mot de passe");
}
return xmlResult;
}
There is nothing good in blocking main UI (unless you really need to). But if you want to wait for your result you can make some use of async-await and TaskCompletitionSource - you can find more about on this blog and how to use TCS in this answer:
public static Task<string> myDownloadString(DataRequestParam dataRequestParam)
{
var tcs = new TaskCompletionSource<string>();
var web = new WebClient();
if (!string.IsNullOrEmpty(dataRequestParam.AuthentificationLogin))
{
System.Net.NetworkCredential account = new NetworkCredential(dataRequestParam.AuthentificationLogin, dataRequestParam.AuthentificationPassword);
web.Credentials = account;
}
web.DownloadStringCompleted += (s, e) =>
{
if (e.Error != null) tcs.TrySetException(e.Error);
else if (e.Cancelled) tcs.TrySetCanceled();
else tcs.TrySetResult(e.Result);
};
web.DownloadStringAsync(dataRequestParam.TargetUri);
return tcs.Task;
}
public async Task<string> Query(DataRequestParam dataRequestParam)
{
string Result = "";
try
{
Result = await myDownloadString(dataRequestParam);
}
catch (WebException we)
{
MessageBox.Show(we.Message);
return null;
}
return Result;
}
(I've not tried this code, there maight be some mistakes, but it should work)
Basing on this code you can also extend your WebClient with awaitable version of download string.