How to implement async. completed event for external usage in .NET? - c#

I have this simple project to grab HTML element inner data. This is a DLL Project.
public class WebGrabber
{
public string URL { set; get; }
public string Element { set; get; }
public bool FindByID { set; get; }
private WebBrowser b { set; get; }
private mshtml.IHTMLDocument2 doc { set; get; }
public void GetPageElementInnerHTML(string url, string element, bool findById)
{
URL = url;
Element = element;
FindByID = findById;
b = new WebBrowser();
b.Navigate(url);
b.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(b_DocumentCompleted);
}
void b_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
doc = (IHTMLDocument2)b.Document.DomDocument;
string result = "<html>";
IHTMLElement head = (IHTMLElement)((IHTMLElementCollection)doc.all.tags("head")).item(null, 0);
result += "<head>" + head.innerHTML + "</head>";
if (null != doc)
{
foreach (IHTMLElement element in doc.all)
{
if (element is mshtml.IHTMLDivElement)
{
dynamic div = element as HTMLDivElement;
if (FindByID)
{
string id = div.id;
if (id == Element)
{
result += "<body>" + div.IHTMLElement_innerHTML + "</body></html>";
break;
}
}
else
{
string className = div.className;
if (className == Element)
{
result += "<body>" + div.IHTMLElement_innerHTML + "</body></html>";
break;
}
}
}
}
}
doc.close();
}
}
What I need is to implement access to string result variable.
So it could be possible to get asynchronously this variable from other project.
Perhaps I need some GetResult(); method?....
How I can do it?
Thank you!

You can pass the eventhandler as an argument then work with the result in the app no in the class library o just pass a callback and invoke after download is complete.
I'm new here so i hope i did understand what you wanted.
Passing the evnthandler
public void GetPageElementInnerHTML(string url, string element, bool findById, WebBrowserDocumentCompletedEventHandler downloadComplete)
Using a delegate:
public class WebGrabber
{
public string URL { set; get; }
public string Element { set; get; }
public bool FindByID { set; get; }
private WebBrowser b { set; get; }
private mshtml.IHTMLDocument2 doc { set; get; }
public delegate void DownloadCompletedDelegate(string result);
private DownloadCompletedDelegate _downloadedComplete;
public void GetPageElementInnerHTML(string url, string element, bool findById, DownloadCompletedDelegate downloadComplete)
{
_downloadedComplete = downloadComplete;
URL = url;
Element = element;
FindByID = findById;
b = new WebBrowser();
b.Navigate(url);
b.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(b_DocumentCompleted);
}
void b_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
doc = (IHTMLDocument2)b.Document.DomDocument;
string result = "<html>";
IHTMLElement head = (IHTMLElement)((IHTMLElementCollection)doc.all.tags("head")).item(null, 0);
result += "<head>" + head.innerHTML + "</head>";
if (null != doc)
{
foreach (IHTMLElement element in doc.all)
{
if (element is mshtml.IHTMLDivElement)
{
dynamic div = element as HTMLDivElement;
if (FindByID)
{
string id = div.id;
if (id == Element)
{
result += "<body>" + div.IHTMLElement_innerHTML + "</body></html>";
break;
}
}
else
{
string className = div.className;
if (className == Element)
{
result += "<body>" + div.IHTMLElement_innerHTML + "</body></html>";
break;
}
}
}
}
}
doc.close();
_downloadedComplete.Invoke(result);
}
}
In the APP
GetPageElementInnerHTML(URL, element, true/false, CompletedCallback);
private void CompletedCallback(string result)
{
//your code
}

Here is working code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using mshtml;
using System.Collections;
namespace MyCompany.WebpageGrabber
{
// A delegate type for hooking up change notifications.
public delegate void ChangedEventHandler(object sender, EventArgs e);
public class WebGrabber : ArrayList
{
// An event that clients can use to be notified whenever the
// elements of the list change.
public event ChangedEventHandler Changed;
// Invoke the Changed event; called whenever list changes
protected virtual void OnChanged(EventArgs e)
{
if (Changed != null)
Changed(this, e);
}
// Override some of the methods that can change the list;
// invoke event after each
public override int Add(object value)
{
int i = base.Add(value);
OnChanged(EventArgs.Empty);
return i;
}
public override void Clear()
{
base.Clear();
OnChanged(EventArgs.Empty);
}
public override object this[int index]
{
set
{
base[index] = value;
OnChanged(EventArgs.Empty);
}
}
public string URL { set; get; }
public string Element { set; get; }
public bool FindByID { set; get; }
private WebBrowser b { set; get; }
private mshtml.IHTMLDocument2 doc { set; get; }
public void GetPageElementInnerHTML(string url, string element, bool findById)
{
URL = url;
Element = element;
FindByID = findById;
b = new WebBrowser();
b.Navigate(url);
b.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(b_DocumentCompleted);
}
void b_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
doc = (IHTMLDocument2)b.Document.DomDocument;
string result = "<html>";
IHTMLElement head = (IHTMLElement)((IHTMLElementCollection)doc.all.tags("head")).item(null, 0);
result += "<head>" + head.innerHTML + "</head>";
if (null != doc)
{
foreach (IHTMLElement element in doc.all)
{
if (element is mshtml.IHTMLDivElement)
{
dynamic div = element as HTMLDivElement;
if (FindByID)
{
string id = div.id;
if (id == Element)
{
result += "<body>" + div.IHTMLElement_innerHTML + "</body></html>";
break;
}
}
else
{
string className = div.className;
if (className == Element)
{
result += "<body>" + div.IHTMLElement_innerHTML + "</body></html>";
break;
}
}
}
}
}
doc.close();
this.Add(result);
}
}
}
and here is code how we call it:
private void Window_Loaded(object sender, RoutedEventArgs e)
{
WebGrabber g = new WebGrabber();
g.GetPageElementInnerHTML("http://www.google.com/web/guest/home", "portlet-borderless-container", false);
g.Changed += new ChangedEventHandler(g_Changed);
}
void g_Changed(object sender, EventArgs e)
{
var html = ((WebGrabber)sender)[0];
}

Related

Showing a few popupmenu on one click button in RecyclerView Xamarin Android

I have problem with showing popupmenu. When I clicked on ImageButton , on display shown a few popupmenu(for different elements - in click listener of ClickedPopUpMenu I show toast with position).
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text.RegularExpressions;
using Android.App;
using Android.Support.V7.Widget;
using Android.Views;
using Android.Widget;
using DexpensMobile.Core.Models;
using DexpensMobile.Core.Services;
using DexpensMobile.Core.Services.AuthService;
using DexpensMobile.Droid.Screens;
using UniversalImageLoader.Core;
using UniversalImageLoader.Core.Display;
using PopupMenu = Android.Widget.PopupMenu;
namespace DexpensMobile.Droid.Adapters
{
public class PostListAdapter : RecyclerView.Adapter
{
protected Activity context = null;
protected IList<PostModel> tasks = new List<PostModel>();
ImageLoader _imageLoader;
private int popPosition;
private int TYPE_HEADER = 0;
private int TYPE_ITEM = 1;
public event EventHandler<int> ItemClick;
public PostListAdapter(IList<PostModel> tasks, Activity context)
{
this.tasks = tasks;
_imageLoader = ImageLoader.Instance;
this.context = context;
}
public PostListAdapter() { }
public override long GetItemId(int position)
{
return position;
}
public override int GetItemViewType(int position)
{
if (IsPositionHeader(position))
return Resource.Layout.wall_header;
return Resource.Layout.ItemPost;
}
private bool IsPositionHeader(int position)
{
return position == 0;
}
public override void OnBindViewHolder(RecyclerView.ViewHolder holder, int position)
{
if (holder.GetType() == typeof(PostViewHodler))
{
PostViewHodler vh = holder as PostViewHodler;
var item = tasks[position-1];
var _userData = ServiceLocator.GetService<IAuthService>().GetUserData();
vh.ShowPopUpMenuButton.Click += (sender, e) => button_Click(sender, e, position);
var tempText = item.Text;
if (tempText.EndsWith("<br/>"))
tempText = tempText.Substring(0, tempText.Length - 5);
tempText = tempText.Replace("<br/>", "\n");
tempText = Regex.Replace(tempText, #"^\s+$[\n]*", "", RegexOptions.Multiline);
vh.PostText.Text = tempText;
vh.OwnerFullName.Text = item.CreatorName;
vh.DateText.Text = item.CreatedDate.ToString(CultureInfo.InvariantCulture);
vh.LikeText.Text = item.Like.LikesCount > 0
? item.Like.LikesCount.ToString()
: "";
vh.CommentText.Text = item.Comments.Any() ? item.Comments.Count().ToString() : "";
vh.RepostText.Text = item.SharedCount > 0 ? item.SharedCount.ToString() : "";
var options =
new DisplayImageOptions.Builder()
.CacheInMemory(false)
.CacheOnDisk(false)
.Displayer(new RoundedBitmapDisplayer(500))
.Build();
_imageLoader.DisplayImage(item.AvatarUrl, vh.AvatarProfile, options);
}
else if (holder.GetType() == typeof(PostViewHodlerHeader))
{
PostViewHodlerHeader vh = holder as PostViewHodlerHeader;
vh.OwnerNameHeader.Text = "Hi from header :-)";
}
}
private void button_Click(object sender, EventArgs eventArgs, int position)
{
ImageButton im = sender as ImageButton;
PopupMenu menu = new PopupMenu(im.Context, im);
menu.Inflate(Resource.Menu.popup_menu);
//if (item.ApplicationUserId != _userData.UserId)
//{
menu.Menu.FindItem(Resource.Id.editPopUp).SetVisible(false);
menu.Menu.FindItem(Resource.Id.deletePopUp).SetVisible(false);
//}
menu.Show();
Toast.MakeText(context, position.ToString(), ToastLength.Long).Show();
menu.MenuItemClick += (o, args) => PopUpMenuClickListener(o, args, position);
}
public override RecyclerView.ViewHolder OnCreateViewHolder(ViewGroup parent, int viewType)
{
View itemView = null;
if (viewType == Resource.Layout.wall_header)
{
itemView = LayoutInflater.From(parent.Context).Inflate(Resource.Layout.wall_header, parent, false);
PostViewHodlerHeader vhHeader = new PostViewHodlerHeader(itemView);
return vhHeader;
}
else if(viewType == Resource.Layout.ItemPost)
{
itemView = LayoutInflater.From(parent.Context).Inflate(Resource.Layout.ItemPost, parent, false);
PostViewHodler vhBody = new PostViewHodler(itemView, OnClick, tasks);
return vhBody;
}
return null;
}
private void OnClick(int position)
{
if (ItemClick != null)
ItemClick(this, position);
}
public override int ItemCount
{
get { return tasks.Count +1; }
}
private void PopUpMenuClickListener(object sender, PopupMenu.MenuItemClickEventArgs e, int position)
{
switch(e.Item.ItemId)
{
case Resource.Id.copyLinkPopUp:
break;
case Resource.Id.editPopUp:
((WallActivity)context).EditPost(popPosition);
break;
case Resource.Id.deletePopUp:
((WallActivity)context).DeleteItem(popPosition);
break;
}
}
}
public class PostViewHodler : RecyclerView.ViewHolder
{
public TextView OwnerFullName { get; private set; }
public ImageView AvatarProfile { get; private set; }
public TextView DateText { get; private set; }
public TextView PostText { get; private set; }
public TextView LikeText { get; private set; }
public TextView CommentText { get; private set; }
public TextView RepostText { get; private set; }
public ImageButton ShowPopUpMenuButton { get; private set; }
public PostViewHodler(View itemView, Action<int> listener, IList<PostModel> posts) : base(itemView)
{
OwnerFullName = itemView.FindViewById<TextView>(Resource.Id.UserName);
AvatarProfile = itemView.FindViewById<ImageView>(Resource.Id.postAva);
DateText = itemView.FindViewById<TextView>(Resource.Id.dateText);
PostText = itemView.FindViewById<TextView>(Resource.Id.postText);
LikeText = itemView.FindViewById<TextView>(Resource.Id.likeText);
CommentText = itemView.FindViewById<TextView>(Resource.Id.commentText);
RepostText = itemView.FindViewById<TextView>(Resource.Id.repostText);
ShowPopUpMenuButton = itemView.FindViewById<ImageButton>(Resource.Id.popupMenuButton);
itemView.Click += (sender, e) => listener(base.Position);
}
}
public class PostViewHodlerHeader : RecyclerView.ViewHolder
{
public TextView OwnerNameHeader{ get; private set; }
public ImageView AvatarProfileHeader { get; private set; }
public PostViewHodlerHeader(View itemView) : base(itemView)
{
OwnerNameHeader = itemView.FindViewById<TextView>(Resource.Id.details);
AvatarProfileHeader = itemView.FindViewById<ImageView>(Resource.Id.avatar_image);
}
}
}
I think problem bind with recycling elements.
Video link with problem.
How to show only one popupmenu only for current item in recyclerview? Why this problem occur?

Why are the values not showing up in my C# program's read-only labels?

I have been working on a program that requires two class definitions (clsCustomer and clsOrder) and a driver that is used for simulating an order form that calculates totals and prints a mailing label. The instructor provided partial code and I got rid of the previous errors that it had, but when I run the program and enter the information (name, address, quantity, price, etc.) only a "." shows up as the mailing label and both the extension and total price appear as "0.00". I tried playing with it and cannot seem to fix the issue. Here is the code:
namespace CS8
{
public partial class frmCS8 : Form
{
public frmCS8()
{
InitializeComponent();
}
private void btnCalculate_Click(object sender, EventArgs e)
{
string strMailingLabel;
try
{
//Create an instance of clsCustomer using the overloaded constructor
clsCustomer cobjCustomer = new clsCustomer(txtName.Text, txtStreet.Text,
txtCity.Text, txtState.Text, txtZip.Text);
//Build mailing label using the Get methods for Customer.
strMailingLabel = cobjCustomer.Name + "\n" +
cobjCustomer.Street + "\n" +
cobjCustomer.City + ", " +
cobjCustomer.State + " " + cobjCustomer.Zip;
//Display mailing address
lblMailingLabel.Text = strMailingLabel;
//Create an instance of clsOrder using the overloaded constructor
clsOrder cobjOrder = new clsOrder
(txtDescription.Text,
int.Parse(txtQuantity.Text),
decimal.Parse(txtPrice.Text));
//Test the calculate Extended Price method
cobjOrder.calcExtendedPrice();
//Update the totals in shared variables.
cobjOrder.accumulateTotals();
//Test the Get property method of extended priced
lblExtension.Text = cobjOrder.ExtendedPrice.ToString("C");
//Shared properties are accessed using class name
//Test the Get Property methods of ReadOnly Shared properties
lblTotalCount.Text = clsOrder.TotalCount.ToString("N0");
lblTotalPrice.Text = clsOrder.TotalPrice.ToString("C");
}
catch (Exception ex)
{
MessageBox.Show("Error :" + ex.Message
+ "\n" + ex.StackTrace,
"Try/Catch - Unexpected Error",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}//end try
}
private void btnNextItem_Click(object sender, EventArgs e)
{
//clear the item fields
txtDescription.Clear();
txtQuantity.Clear();
txtPrice.Clear();
lblExtension.Text = "";
txtDescription.Focus();
}
private void btnResetSummary_Click(object sender, EventArgs e)
{
//Reset totals using the class name to access the shared method
clsOrder.resetTotals();
lblTotalPrice.Text = "";
lblTotalCount.Text = "";
lblMailingLabel.Text = "";
//Clear the rest of the form using next item method
btnNextItem_Click(sender, e);
}
private void btnExit_Click(object sender, EventArgs e)
{
this.Close();
}
}
}
namespace CS8
{
public class clsOrder
{
//declare class variables
protected string cstrDescription;
protected int cintQuantity;
protected decimal cdecPrice;
protected decimal cdecExtendedPrice;
//shared variables
static decimal cdecTotalPrice;
static int cintTotalCount;
//declare constructors
public clsOrder()
{
}
public clsOrder(string strDescription,
int intQuantity, decimal decPrice)
//declare property methods
{
this.Description = cstrDescription;
this.Quantity = cintQuantity;
this.Price = cdecPrice;
}
//declare read-only properties
public decimal ExtendedPrice
{
get
{
return cdecExtendedPrice;
}
set
{
cdecExtendedPrice = value;
}
}
public string Description
{
get
{
return cstrDescription;
}
set
{
cstrDescription = value;
}
}
public int Quantity
{
get
{
return cintQuantity;
}
set
{
cintQuantity = value;
}
}
public decimal Price
{
get
{
return cdecPrice;
}
set
{
cdecPrice = value;
}
}
//declare Shared (static) ReadOnly Properites
public static decimal TotalPrice
{
get
{
return cdecTotalPrice;
}
}
public static int TotalCount
{
get
{
return cintTotalCount;
}
set
{
cintTotalCount = value;
}
}
//declare supporting methods
public void calcExtendedPrice()
{
cdecExtendedPrice = cintQuantity * cdecPrice;
}
public void accumulateTotals()
{
cdecTotalPrice += cdecExtendedPrice;
cintTotalCount += 1;
}
public static void resetTotals()
{
cdecTotalPrice = 0;
cintTotalCount = 0;
}
}//end of Class
}//end of namespace
namespace CS8
{
public class clsCustomer
{
//declare class variables
private string cstrName;
private string cstrStreet;
private string cstrCity;
private string cstrState;
private string cstrZip;
//declare constructors
public clsCustomer()
{
}
public clsCustomer(string strName,
string strStreet, string strCity,
string strState, string strZip)
{
this.Name = cstrName;
this.Street = cstrStreet;
this.City = cstrCity;
this.State = cstrState;
this.Zip = cstrZip;
}
public string Name
{
get
{
return cstrName;
}
set
{
cstrName = value;
}
}
public string Street
{
get
{
return cstrStreet;
}
set
{
cstrStreet = value;
}
}
public string City
{
get
{
return cstrCity;
}
set
{
cstrCity = value;
}
}
public string State
{
get
{
return cstrState;
}
set
{
cstrState = value;
}
}
public string Zip
{
get
{
return cstrZip;
}
set
{
cstrZip = value;
}
}
}
}
Any assistance would be very much appreciated...
Use parameters, not class fields:
public clsOrder(string strDescription,
int intQuantity, decimal decPrice)
{
this.Description = strDescription;
this.Quantity = intQuantity;
this.Price = decPrice;
}
public clsCustomer(string strName,
string strStreet, string strCity,
string strState, string strZip)
{
this.Name = strName;
this.Street = strStreet;
this.City = strCity;
this.State = strState;
this.Zip = strZip;
}

C# event is null even though it is subscribed [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I have a Flight class and a Form class, I want to send Log messages to a textfield from the Flight class to the Form.
I have an already working one for another class called Airport, but this one is practically identical, yet the event LogMessage is always null, even after subscribing.
-- MainForm --
namespace FlightSim
{
public partial class MainForm : Form
{
Airport airport = new Airport();
Luggage luggage = new Luggage();
Flight flight = new Flight();
DAO db = new DAO();
public MainForm()
{
InitializeComponent();
InitializeEvents();
}
private void InitializeEvents()
{
this.airport.ErrorMessage += new System.EventHandler(OnErrorReceived);
this.flight.LogMessage += new System.EventHandler(OnLogReceived);
}
public void OnErrorReceived(object sender, System.EventArgs e)
{
string msgContent = ((Airport.MessageEventArgs)e).msgContent;
this.mainLog.AppendText(msgContent);
}
public void OnLogReceived(object sender, System.EventArgs e)
{
string msgcontent = ((Flight.MessageEventArgs)e).msgContent;
this.mainLog.AppendText(msgcontent);
}
}
}
-- Flight --
namespace FlightSim
{
public class Flight
{
public class MessageEventArgs : System.EventArgs
{
public string msgContent;
}
public event System.EventHandler LogMessage;
DAO db = new DAO();
public Flight(string flightNumber, string departure, string destination, int totalLoadCapacity)
{
this.FlightNumber = flightNumber;
this.Departure = departure;
this.Destination = destination;
this.TotalLoadCapacity = totalLoadCapacity;
//LogMessage += (s, o) => { };
}
public void StartFlight()
{
string tmpDeparture = this.Departure;
string tmpDestination = this.Destination;
this.OnLogUpdate("Taking off from " + tmpDeparture + " now.");
this.Destination = tmpDeparture;
Thread.Sleep(1000);
this.OnLogUpdate("Arriving in " + tmpDestination + " now.");
this.Departure = tmpDestination;
}
protected void OnLogUpdate(string logMessage)
{
if (logMessage == "")
return;
MessageEventArgs e = new MessageEventArgs();
var handler = LogMessage;
if (handler != null)
{
e.msgContent = logMessage;
handler(this, e);
}
}
}
}
So, what can be the cause for an event being null even though it is subscribed?
Given the constructor with arguments and the initialization without arguments, you probably are creating another Flight class somewhere else. All you have to do is make sure that you subscribe the same event upon creation. Do something like this;
Flight someOtherFlight = new Flight("1", "Amsterdam", "Hong Kong", 500);
someOtherFlight.LogMessage += new System.EventHandler(OnLogReceived);
And you should be fine.
Edit: This MCVE works fine
Program.cs
namespace StackOverflowPlayground
{
class Program
{
static void Main(string[] args)
{
var sim = new AirportSim();
sim.flight.StartFlight();
}
}
}
FlightSim.cs
using System;
using System.Threading;
namespace StackOverflowPlayground
{
public class AirportSim
{
public Flight flight = new Flight("1","","",1);
public AirportSim()
{
InitializeEvents();
}
private void InitializeEvents()
{
flight.LogMessage += OnLogReceived;
}
public void OnLogReceived(object sender, System.EventArgs e)
{
string msgcontent = ((Flight.MessageEventArgs)e).msgContent;
Console.WriteLine(msgcontent);
}
}
public class Flight
{
public class MessageEventArgs : EventArgs
{
public string msgContent;
}
public event EventHandler LogMessage;
public Flight(string flightNumber, string departure, string destination, int totalLoadCapacity)
{
FlightNumber = flightNumber;
Departure = departure;
Destination = destination;
TotalLoadCapacity = totalLoadCapacity;
//LogMessage += (s, o) => { };
}
public string Destination { get; set; }
public int TotalLoadCapacity { get; set; }
public string Departure { get; set; }
public string FlightNumber { get; set; }
public void StartFlight()
{
string tmpDeparture = this.Departure;
string tmpDestination = this.Destination;
OnLogUpdate("Taking off from " + tmpDeparture + " now.");
Destination = tmpDeparture;
Thread.Sleep(1000);
OnLogUpdate("Arriving in " + tmpDestination + " now.");
Departure = tmpDestination;
}
protected void OnLogUpdate(string logMessage)
{
if (logMessage == "")
return;
var e = new MessageEventArgs();
var handler = LogMessage;
if (handler != null)
{
e.msgContent = logMessage;
handler(this, e);
}
}
}
}

Get back panel from clipboard

This is my class, I always get a null insted of my panel...
Can someone give me a hint on how to do this?
[Serializable]
public class DragDropBlock : Panel
{
public DragDropBlock()
{
this.MouseDown += new MouseEventHandler(Mouse_Down);
this.MouseUp += new MouseEventHandler(Mouse_Up);
}
void Mouse_Down(object sender, System.Windows.Forms.MouseEventArgs e)
{
Clipboard.SetData("DragDropBlock", this);
}
void Mouse_Up(object sender, System.Windows.Forms.MouseEventArgs e)
{
IDataObject IBlock = Clipboard.GetDataObject();
DragDropBlock Block = (DragDropBlock)IBlock.GetData(typeof(DragDropBlock));
}
}
Given a class:
[Serializable]
class Test
{
public string Data
{
get;
set;
}
}
This works:
Test t = new Test()
{
Data = "DERP!"
};
Clipboard.SetData("Test", t);
Test newT = (Test)Clipboard.GetData("Test");
Console.WriteLine(newT.Data);
And if you want to use data objects:
Test t = new Test()
{
Data = "DERP!"
};
Clipboard.SetDataObject(new DataObject("Test", t));
Test newT = (Test)Clipboard.GetDataObject().GetData("Test");
Console.WriteLine(newT.Data);
The output to both of those is:
DERP!
This is the correction of my class: Working!!!
[Serializable]
class DragBlock
{
public string Data
{
get;
set;
}
}
public class DragDropBlock : Panel
{
DragBlock Block;
public DragDropBlock()
{
this.MouseDown += new MouseEventHandler(Mouse_Down);
this.MouseUp += new MouseEventHandler(Mouse_Up);
Block = new DragBlock()
{
Data = "TEST!"
};
}
void Mouse_Down(object sender, System.Windows.Forms.MouseEventArgs e)
{
Clipboard.SetDataObject(new DataObject("DragBlock", Block));
}
void Mouse_Up(object sender, System.Windows.Forms.MouseEventArgs e)
{
DragBlock newBlock = (DragBlock)Clipboard.GetDataObject().GetData("DragBlock");
Console.WriteLine(newBlock.Data);
}
}

wb.DownloadFileAsync throw "WebClient does not support concurrent I/O operations." exception

I need help with this code
#region Events
public class DownloadProgressChangedEventArg
{
private long _ProgressPercentage;
private long _BytesReceived;
private long _TotalBytesToReceive;
public DownloadProgressChangedEventArg(long BytesReceived, long TotalBytesToReceive)
{
_BytesReceived = BytesReceived;
_TotalBytesToReceive = TotalBytesToReceive;
_ProgressPercentage = BytesReceived * 100 / (TotalBytesToReceive);
}
public long BytesReceived { get { return _BytesReceived; } set { _BytesReceived = value; } }
public long ProgressPercentage { get { return _ProgressPercentage; } set { _ProgressPercentage = value; } }
public long TotalBytesToReceive { get { return _TotalBytesToReceive; } set { _TotalBytesToReceive = value; } }
}
public delegate void DownloadProgressChangedEventHandler(Api.GetSong.GetObject.Object Sender, DownloadProgressChangedEventArg e);
public event DownloadProgressChangedEventHandler DownloadProgressChangedEvent;
public class DownloadCompletedEventArg
{
private bool _Cancelled;
private Exception _Error;
public DownloadCompletedEventArg(Exception Error, bool Cancelled)
{
_Cancelled = Cancelled;
_Error = Error;
}
public bool Cancelled { get { return _Cancelled; } set { _Cancelled = value; } }
public Exception Error { get { return _Error; } set { _Error = value; } }
}
public delegate void DownloadCompletedEventHandler(Api.GetSong.GetObject.Object Sender, DownloadCompletedEventArg e);
public event DownloadCompletedEventHandler DownloadCompletedEvent;
#endregion
WebClient wb;
public void DownloadFileAsync(Api.GetSong.GetObject.Object Object, String FileLocation)
{
String DownloadLink = GetStreamUri(Object);
String FileTitle = Object.Title + "." + Object.Type;
String FileLocations = Path.Combine(FileLocation,FileTitle);
if (!DownloadLink.StartsWith("rtmp"))
{
if (wb == null)
{
wb = new WebClient();
wb.DownloadFileCompleted += delegate(object sender, AsyncCompletedEventArgs e) { DownloadCompletedEvent(Object, new DownloadCompletedEventArg(e.Error, e.Cancelled)); };
wb.DownloadProgressChanged += delegate(object sender, DownloadProgressChangedEventArgs e) { DownloadProgressChangedEvent(Object, new DownloadProgressChangedEventArg(e.BytesReceived, e.TotalBytesToReceive)); };
}
wb.DownloadFileAsync(new Uri(DownloadLink), FileLocations);
//throw:
//WebClient does not support concurrent I/O operations.
}
else
{
//Düzenlencek
}
}
public void DownloadFileCancel()
{
if (wb.IsBusy && wb != null)
{
wb.CancelAsync();
}
}
When calling DownloadFileAsync method you have to make sure it completes before trying to download again.
This answer will help you.

Categories