|
Pete O'Hanlon wrote: I don't think they will make me an MVP now
Well, maybe they should, but not before you helped them plugging all the leaks.
Luc Pattyn [Forum Guidelines] [My Articles] Nil Volentibus Arduum
Please use <PRE> tags for code snippets, they preserve indentation, improve readability, and make me actually look at the code.
|
|
|
|
|
Sadly they don't seem interested in fixing the leaks. That's what we were arguing about.
|
|
|
|
|
Do you recall the location of the discussion over on WPF Disciples? (can you provide a link?)
"I need build Skynet. Plz send code"
|
|
|
|
|
I believe the comment was in this[^] thread. This was the bitterest thread that we kicked off - the problem is, it may also be in one of the Disciples private threads.
Actually, I've found the very comment in that thread:
"Here is the hard question I will be asking: Why are memory leaks in Silverlight 4 such a low priority for Microsoft? I cringe every time somebody comes on the WCF RIA Services forum waving an ANTS report trying to figure out where their memory is going."
|
|
|
|
|
I am trying to test a web service that is encapsulated in an IP Phone which is only accessible through HTTPS. I tried HTTP, but it redirects to the secure site.
The system is not connected to the internet and I would like to know if there is a way to make my .NET client ignore the fact it cannot verify the certificate and just proceed with the request. I am using VS 2010 and the class System.ServiceModel.ClientBase<t> (the client code generated with the Add Service Reference feature).
Thank you
|
|
|
|
|
You should be able to do this by overriding the client certificate:
System.Net.ServicePointManager.ServerCertificateValidationCallback = ((sender, certificate, chain, sslPolicyErrors) => true); Obviously you want to only apply this during your testing phase, so I'd surround this in a conditional if I were you.
|
|
|
|
|
Absolutely. We just want to test how well we can integrate with the phones and deploy custom services.
Thanks for the answer, it is working well.
|
|
|
|
|
Good job.
|
|
|
|
|
Hey Peter, since you seem to master this topic, I am stuck with the authentication part.
The server requires basic authentication, in the form of a HTTP header:
Authorization: basic <username:passord in base64>
Would you be able to help?
|
|
|
|
|
If you're using WCF, you need to set the authorisation as part of the OperationContextScope. It's fairly straightforward:
MyClient myClient = new MyClient();
using (OperationContextScope scope = new OperationContextScope(myClient.InnerChannel))
{
var reqProperty = new HttpRequestMessageProperty();
reqProperty.Headers[HttpRequestHeader.Authorization] = "Basic " +
Convert.ToBase64String(Encoding.ASCII.GetBytes(myClient.ClientCredentials.UserName.UserName + ":" +
myClient.ClientCredentials.UserName.Password));
OperationContext.Current.OutgoingMessageProperties[HttpRequestMessageProperty.Name] = reqProperty;
}
|
|
|
|
|
Done!
if(CodeProject.UserProvider.GetUser("Pete O'Hanlon") == CodeProject.UserProvider.GetUser("Le GauChiste")){
System.Net.ServicePointManager.ServerCertificateValidationCallback = ((sender, certificate, chain, sslPolicyErrors) => true);
}
"Whether you think you can, or you think you can't--either way, you are right."
— Henry Ford
|
|
|
|
|
Hi there,
I am willing to declare a class, where one of its attributes has to be an Array of integers.
1st question:
How should I write the set and get methods, cause the following is not working.
class Testclass
{
........
private int[] _number;
public int number
{
get { return _number[]; }
set { _number[] = value; }
}
........
}
2nd question:
Not knowing how to deal with the above methods ani in order to advance into coding I declared the attribute as public
public int[] number;
Although I declare a new Object in the Form class (it should be a windows App)
Testclass Myclass = new Testclass();
the programme crashes
Myclass.number[i] = i + 2;
saying that System.NullReferenceException was unhandled and asking me to create a new object instance for Myclass.number[i]
A bit confusing for me...
|
|
|
|
|
There are a few things here. First of all, the return type from number would be int[] not int - the two are not comparable. Secondly, you don't return _number[], you return _number. Finally, why use an array at all? Arrays have the nasty habit of becoming complicated to manage - why not look into a generic List? So this becomes:
class TestClass
{
public TestClass()
{
Number = new List<int>();
}
public List<int> Number { get; set; }
}
|
|
|
|
|
Is this a different list than an ArrayList?
http://msdn.microsoft.com/en-us/library/system.collections.arraylist%28v=VS.100%29.aspx
|
|
|
|
|
class Testclass
{
private int[] _number;
public int[] number
{
get { return _number; }
set { _number = value; }
}
}
number will be null unless you initialize it somehow.
|
|
|
|
|
This is all you need:
public class TestClass
{
public int[] Numbers { get; set; }
}
However, I would probably use a List<int> in the following form:
public class NumbersList : List<int>
{
}
...which would allow you then to do this:
public class TestClass
{
public NumbersList Numbers { get; set; }
}
...as well as being much more flexible than a mere array.
".45 ACP - because shooting twice is just silly" - JSOP, 2010 ----- You can never have too much ammo - unless you're swimming, or on fire. - JSOP, 2010 ----- "Why don't you tie a kerosene-soaked rag around your ankles so the ants won't climb up and eat your candy ass." - Dale Earnhardt, 1997
|
|
|
|
|
Ditto what others have said regarding arrays.
Personally I'd only use an int[] if it is being initialised once, and then will not have elements added or removed. That could be useful for certain specific applications.
For example...
public class Simple
{
private int[] _int = { 1, 2, 3, 4, 5 };
public int[] MyInt { get { return _int; } }
}
private static void TestSimple()
{
Simple s = new Simple();
s.MyInt[0] += 1;
}
...is fine. But as others have said if the size of the array is to be dynamic (items being added) I'd use say a List<int> probably.
|
|
|
|
|
Thank you all for your help. This is a great forum indeed!
I will definately use a List, as there will be numbers of unknown quantity and value in the beginning of the programme.
|
|
|
|
|
Hello
I'm some kind of new to c# and tried out a tutorial to download some comic images from an rss feed.
Now I want to optimize the program, so that the UI-Thread isn't blocked anymore. I've read that I should use Backgroundworker und HttpWebRequest instead of WebClient.
Problem: I tried out backgroundworker and httpwebrequest instead of webclient, but the UI is still freezing and I don't really understand why.
Hope somebody can explain me, what I'm doing wrong.
public class FailsViewModel :INotifyPropertyChanged
{
static int i = 0;
public FailsViewModel()
{
this.Fails = new ObservableCollection<FailViewModel>();
InitializeBackgoundWorker();
LoadFailsAsync();
}
private void InitializeBackgoundWorker()
{
_bw = new BackgroundWorker();
_bw.WorkerReportsProgress = true;
_bw.WorkerSupportsCancellation = true;
_bw.DoWork += new DoWorkEventHandler(bw_DoWork);
_bw.ProgressChanged += new ProgressChangedEventHandler(bw_ProgressChanged);
_bw.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bw_RunWorkerCompleted);
}
public void LoadFailsAsync()
{
var request = (HttpWebRequest)WebRequest.Create(new Uri("http://schabus.knor.net/rss"));
request.BeginGetResponse(r =>
{
var httpRequest = (HttpWebRequest)r.AsyncState;
var httpResponse = (HttpWebResponse)httpRequest.EndGetResponse(r);
using (var reader = new StreamReader(httpResponse.GetResponseStream()))
{
var response = reader.ReadToEnd();
_bw.RunWorkerAsync(response);
}
}, request);
}
private Collection<FailViewModel> LoadItems(string e)
{
Collection<FailViewModel> fvmc = new Collection<FailViewModel>();
XElement xel = XElement.Parse(e);
Collection<FailViewModel> fails = new Collection<FailViewModel>();
var items = xel.Descendants(XName.Get("item"));
foreach (var item in items)
{
var desc = item.Descendants(XName.Get("encoded", "http://purl.org/rss/1.0/modules/content/")).SingleOrDefault();
var title = item.Descendants(XName.Get("title")).SingleOrDefault();
if (desc != null && title != null)
{
string url = desc.Value.Substring(desc.Value.IndexOf("src=\"") + 5);
string localUrl = url.Substring(0, url.IndexOf("\""));
string absoluteUrl = "http://schabus.knor.net" + localUrl;
FailViewModel fvm = new FailViewModel();
fvm.Title = title.Value;
fvm.Uri = new Uri(absoluteUrl, UriKind.Absolute);
fvmc.Add(fvm);
}
}
return fvmc;
}
private Collection<FailViewModel> LoadItems_WebRequest(DownloadStringCompletedEventArgs e)
{
Collection<FailViewModel> fvmc = new Collection<FailViewModel>();
XElement xel = XElement.Parse(e.Result);
Collection<FailViewModel> fails = new Collection<FailViewModel>();
var items = xel.Descendants(XName.Get("item"));
foreach (var item in items)
{
var desc = item.Descendants(XName.Get("encoded", "http://purl.org/rss/1.0/modules/content/")).SingleOrDefault();
var title = item.Descendants(XName.Get("title")).SingleOrDefault();
if (desc != null && title != null)
{
string url = desc.Value.Substring(desc.Value.IndexOf("src=\"") + 5);
string localUrl = url.Substring(0, url.IndexOf("\""));
string absoluteUrl = "http://schabus.knor.net" + localUrl;
FailViewModel fvm = new FailViewModel();
fvm.Title = title.Value;
fvm.Uri = new Uri(absoluteUrl, UriKind.Absolute);
fvmc.Add(fvm);
}
}
return fvmc;
}
#region Properties
private BackgroundWorker _bw = null;
public volatile bool isComplete = false;
private ObservableCollection<FailViewModel> _Fails = default(ObservableCollection<FailViewModel>);
public ObservableCollection<FailViewModel> Fails
{
get
{
return _Fails;
}
set
{
_Fails = value;
OnPropertyChanged("Fails");
}
}
private FailViewModel _SelectedFail = default(FailViewModel);
public FailViewModel SelectedFail
{
get
{
return _SelectedFail;
}
set
{
_SelectedFail = value;
OnPropertyChanged("SelectedFail");
}
}
#endregion
protected virtual void OnPropertyChanged(string propertyName)
{
if(this.PropertyChanged != null)
this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
public event PropertyChangedEventHandler PropertyChanged;
#region BackgroundWorker
private void bw_DoWork(object sender, DoWorkEventArgs e)
{
BackgroundWorker worker = sender as BackgroundWorker;
e.Result = LoadItems((string)e.Argument);
}
void client_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
((WebClient)sender).DownloadStringCompleted -= client_DownloadStringCompleted;
if (e.Error == null && e.Cancelled == false)
{
MessageBox.Show("DSC-" + (i++) +"\n"+e.Result );
_bw.RunWorkerAsync(e);
}
}
private void bw_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
Collection<FailViewModel> c = e.Result as Collection<FailViewModel>;
for(int i=0; i<c.Count;i++)
{
this.Fails.Add(c.ElementAt(i));
Thread.Sleep(1);
}
MessageBox.Show("fertig - bw_RunWorkerCompleted");
_bw.DoWork -= bw_DoWork;
_bw.ProgressChanged -= bw_ProgressChanged;
_bw.RunWorkerCompleted -= bw_RunWorkerCompleted;
}
private void bw_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
MessageBox.Show("Progress");
}
#endregion
|
|
|
|
|
I didn't study all that in detail, however I noticed you still have a LoadFailsAsync method running on the main thread, so I guess the problem is there. I would perform all web communication in synchronous mode inside the DoWork handler, once you are using an extra thread (or BGW) there no longer is a need to go asynchronously and things should become simpler...
Luc Pattyn [Forum Guidelines] [My Articles] Nil Volentibus Arduum
Please use <PRE> tags for code snippets, they preserve indentation, improve readability, and make me actually look at the code.
|
|
|
|
|
Got already an implementation like that, where the the LoadFailsAsync- method calls the web communication asynchronously with HttpWebRequest and load the images inside it. (commentented out code in the LoadFailsAsync() above)
But got also the same effect.
public void LoadFailsAsync()
{
var request = (HttpWebRequest)WebRequest.Create(new Uri("http://schabus.knor.net/rss"));
request.BeginGetResponse(r =>
{
var httpRequest = (HttpWebRequest)r.AsyncState;
var httpResponse = (HttpWebResponse)httpRequest.EndGetResponse(r);
using (var reader = new StreamReader(httpResponse.GetResponseStream()))
{
var response = reader.ReadToEnd();
Collection<FailViewModel> c = LoadItems(response);
Deployment.Current.Dispatcher.BeginInvoke(() =>
{
for (int i = 0; i < c.Count; i++)
{
this.Fails.Add(c.ElementAt(i));
Thread.Sleep(1);
}
MessageBox.Show("fertig - bw_RunWorkerCompleted");
});
}
}, request);
}
|
|
|
|
|
what a mess. That isn't synchronous at all, every Begin , End , Async word points to an asynchronous implementation which is harder to get right and most often meaningless when running on a separate thread or BGW.
Luc Pattyn [Forum Guidelines] [My Articles] Nil Volentibus Arduum
Please use <PRE> tags for code snippets, they preserve indentation, improve readability, and make me actually look at the code.
|
|
|
|
|
thank you Luc so far, but I think synchronous HttpWebRequest / WebClient methods aren't supportet for WP7. So it was unfortunately impossible for me to use BackGroundWorker with synchronous HttpWebRequest-methods.
So I write it completely new but it's still freezing the UI.
How Luc told me I tried to avoid any use of nested asyn mehtods/threads.
My Idea was to use HttpWebRequest to download it asynyhronous (without other threads... because HttpWebRequest is already asynchronous)
hope the code is better structured then the code above
public class ComicsViewModel : INotifyPropertyChanged
{
public ComicsViewModel()
{
if (!DesignerProperties.IsInDesignTool)
{
this.ComicList = new ObservableCollection<ComicViewModel>();
this.IsReading = true;
LoadComicsRss2();
}
}
private void LoadComicsRss2()
{
Uri uri = new Uri("http://schabus.knor.net/rss", UriKind.Absolute);
HttpWebRequest req = HttpWebRequest.CreateHttp(uri);
req.BeginGetResponse(HandleGetComicsResponse, req);
}
private void HandleGetComicsResponse(IAsyncResult result)
{
HttpWebRequest state = (HttpWebRequest)result.AsyncState;
using (var response = state.EndGetResponse(result))
{
using (var streamReader = new StreamReader(response.GetResponseStream()))
{
var data = streamReader.ReadToEnd();
Deployment.Current.Dispatcher.BeginInvoke(() => { this.ComicList.Clear(); });
XElement xel = XElement.Parse(data);
var items = xel.Descendants(XName.Get("item"));
foreach (var item in items)
{
var desc = item.Descendants(XName.Get("encoded",
"http://purl.org/rss/1.0/modules/content/")).SingleOrDefault();
var title = item.Descendants(XName.Get("title")).SingleOrDefault();
if (desc != null && title != null)
{
string url = desc.Value.Substring(desc.Value.IndexOf("src=\"") + 5);
string localUrl = url.Substring(0, url.IndexOf("\""));
string absoluteUrl = "http://schabus.knor.net" + localUrl;
ComicViewModel vm = new ComicViewModel();
vm.Title = title.Value;
vm.Uri = new Uri(absoluteUrl, UriKind.Absolute);
Deployment.Current.Dispatcher.BeginInvoke(() => { this.ComicList.Add(vm);});
}
}
}
}
Deployment.Current.Dispatcher.BeginInvoke(() => { this.IsReading = false; });
}
}
<phone:PhoneApplicationPage.Resources>
<DataTemplate x:Key="ComicViewModelTemplate">
<StackPanel>
<TextBlock Text="{Binding Title}" HorizontalAlignment="Center"/>
<Image Source="{Binding Uri}"/>
</StackPanel>
</DataTemplate>
</phone:PhoneApplicationPage.Resources>
<Grid x:Name="LayoutRoot" Background="Transparent" DataContext="{Binding Source={StaticResource ComicsViewModelDataSource}}">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
<ListBox Margin="10,0" ItemTemplate="{StaticResource ComicViewModelTemplate}" ItemsSource="{Binding ComicList}" SelectedItem="{Binding SelectedComic, Mode=TwoWay}">
<Custom:Interaction.Triggers>
<Custom:EventTrigger EventName="SelectionChanged">
<ic:NavigateToPageAction TargetPage="/ComicPage.xaml"/>
</Custom:EventTrigger>
</Custom:Interaction.Triggers>
</ListBox>
</Grid>
</Grid>
|
|
|
|
|
Hi Peter,
1.
I'm not familiar with WP7, and am unaware of what .NET parts are missing over there, sorry.
2.
"it's still freezing the UI" isn't informative enough: is it just dead for a while and in the end produces all the output hoped for? does it do anything at all? or is it just dead permanently right from the start?
3.
I still see a foreach loop with a BeginInvoke inside. That could go wrong in at least two ways: either the BeginInvoke for some reason is blocking, turning the whole loop in a long operation, hence freezing the GUI for a long while. Or all those Invokes get queued or even launched somehow, possibly overloading the system.
Suggestions:
- add logging with timestamps, so you KNOW what is happening;
- reduce the loop to just one or two iterations.
In general: when in trouble, simplify, improve observability, get the facts.
Luc Pattyn [Forum Guidelines] [My Articles] Nil Volentibus Arduum
Please use <PRE> tags for code snippets, they preserve indentation, improve readability, and make me actually look at the code.
|
|
|
|
|
2. I meant the UI wasn't responsive for some time minute
luckily I found my answer in those two Links here:
http://tinyurl.com/28zb9x3
http://tinyurl.com/636qz5z
anyways thank you Luc!
|
|
|
|
|