Search Results

Search found 185 results on 8 pages for 'iasyncresult'.

Page 6/8 | < Previous Page | 2 3 4 5 6 7 8  | Next Page >

  • OData Mix10 &ndash; Part Dos

    - by Jon Dalberg
    The other day I had a snazzy post on fetching all the video (WMV) files from Mix ‘10. A simple, console application that grabbed the urls from the OData feed and downloaded the videos. I wanted to change that app to fire the OData query asynchronously so here’s what resulted: 1: static void Main(string[] args) 2: { 3: var mix = new Mix.EventEntities(new Uri("http://api.visitmix.com/OData.svc")); 4:   5: var temp = mix.Files.Where(f => f.TypeName == "WMV"); 6: var query = temp as DataServiceQuery<Mix.File>; 7:   8: query.BeginExecute(OnFileQueryComplete, query); 9:   10: // waiting... 11: Console.ReadLine(); 12: } 13:   14: static void OnFileQueryComplete(IAsyncResult result) 15: { 16: var query = result.AsyncState as DataServiceQuery<Mix.File>; 17: var response = query.EndExecute(result); 18:   19: var web = new WebClient(); 20:   21: var myVideos = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyVideos), "Mix10"); 22:   23: Directory.CreateDirectory(myVideos); 24:   25: foreach (Mix.File f in response) 26: { 27: var fileName = new Uri(f.Url).Segments.Last(); 28: Console.WriteLine(f.Url); 29: web.DownloadFile(f.Url, Path.Combine(myVideos, fileName)); 30: } 31: } There are two important things here that are not explained well in the MSDN docs: See lines 5 and 6? That’s where I query for the WMV files and it returns an IQueryable<T>. You *have* to cast that to a DataServiceQuery<T> and then call BeginExecute. The documented example does not filter so it didn’t show that step. Line 16 shows the correct way to get the previously executed DataServiceQuery<T> from the async result. If you looked at the MSDN example docs it shows (incorrectly) just casting the result, like this: // wrong var query = result as DataServiceQuery<Mix.File>; Other than those items it is relatively straight forward and we’re all async-ified. Enjoy!

    Read the article

  • Unable to read data from the transport connection: An existing connection was forcibly closed by the remote host

    - by Paul J. Warner
    I am having an issue with a program where after 6 mins +- 5 secs we get the above exception. Some more info about the exception stacktrace is below. This all happens pretty religiously, 6 mins goes by and bam the following 3 exeptions. We have the application installed in 2 other environments and it is working fine there. I am hoping to find some server settings either IIS 6 or Server 2003 settings that may be causing this issue to occur. I have reviewed some of the similar questions and don't see very many answers. I am hoping that maybe the information I have provided may help a little bit. 208741,Exception,,,,2011-06-21 00:30:14.193,SERVERNAME,2624,1,CLIENTNAME,The underlying connection was closed: An unexpected error occurred on a receive. , at System.Web.Services.Protocols.WebClientProtocol.GetWebResponse(WebRequest request) at System.Web.Services.Protocols.HttpWebClientProtocol.GetWebResponse(WebRequest request) at Microsoft.Web.Services3.WebServicesClientProtocol.GetResponse(WebRequest request, IAsyncResult result) at System.Web.Services.Protocols.SoapHttpClientProtocol.Invoke(String methodName, Object[] parameters) at System.Net.Sockets.NetworkStream.Read(Byte[] buffer, Int32 offset, Int32 size) at System.Net.FixedSizeReader.ReadPacket(Byte[] buffer, Int32 offset, Int32 count) at System.Net.Security._SslStream.StartFrameHeader(Byte[] buffer, Int32 offset, Int32 count, AsyncProtocolRequest asyncRequest) at System.Net.Security._SslStream.StartReading(Byte[] buffer, Int32 offset, Int32 count, AsyncProtocolRequest asyncRequest) at System.Net.Security._SslStream.ProcessRead(Byte[] buffer, Int32 offset, Int32 count, AsyncProtocolRequest asyncRequest) at System.Net.TlsStream.Read(Byte[] buffer, Int32 offset, Int32 size) at System.Net.PooledStream.Read(Byte[] buffer, Int32 offset, Int32 size) at System.Net.Connection.SyncRead(HttpWebRequest request, Boolean userRetrievedStream, Boolean probeRead),2004437127,114,1 208742,Exception,,,,2011-06-21 00:30:14.227,SERVERNAME,2624,1,CLIENTNAME,Unable to read data from the transport connection: An existing connection was forcibly closed by the remote host. , at System.Net.Sockets.NetworkStream.Read(Byte[] buffer, Int32 offset, Int32 size) at System.Net.FixedSizeReader.ReadPacket(Byte[] buffer, Int32 offset, Int32 count) at System.Net.Security._SslStream.StartFrameHeader(Byte[] buffer, Int32 offset, Int32 count, AsyncProtocolRequest asyncRequest) at System.Net.Security._SslStream.StartReading(Byte[] buffer, Int32 offset, Int32 count, AsyncProtocolRequest asyncRequest) at System.Net.Security._SslStream.ProcessRead(Byte[] buffer, Int32 offset, Int32 count, AsyncProtocolRequest asyncRequest) at System.Net.TlsStream.Read(Byte[] buffer, Int32 offset, Int32 size) at System.Net.PooledStream.Read(Byte[] buffer, Int32 offset, Int32 size) at System.Net.Connection.SyncRead(HttpWebRequest request, Boolean userRetrievedStream, Boolean probeRead),2004437127,114,1 208743,Exception,,,,2011-06-21 00:30:14.287,SERVERNAME,2624,1,CLIENTNAME,An existing connection was forcibly closed by the remote host , at System.Net.Sockets.NetworkStream.Read(Byte[] buffer, Int32 offset, Int32 size),-691097507,62,1

    Read the article

  • SocketException (Timeout) only when running as scheduled task

    - by BVartin
    I'm running a C# web-scrapper application (that I wrote) on a Windows Server 2003 instance under a user belonging to the local Administrator group. When I run it within a desktop/remote-desktop session the application runs successfully but when I schedule it to run under the same user/security-context outside of the desktop session, all socket connections timeout. The scheduled task calls a batch file which in-turn calls the application. The Windows Server 2003 instance has a very basic configuration and isn't even connected to a domain. I cannot find anything in any firewall or security configuration which is preventing this but maybe I have overlooked something, can anyone be of any assistance? System.Net.WebException: Unable to connect to the remote server --- System.Net.Sockets.SocketException: A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond X.X.X.X:443 at System.Net.Sockets.Socket.DoConnect(EndPoint endPointSnapshot, SocketAddress socketAddress) at System.Net.ServicePoint.ConnectSocketInternal(Boolean connectFailure, Socket s4, Socket s6, Socket& socket, IPAddress& address, ConnectSocketState state, IAsyncResult asyncResult, Int32 timeout, Exception& exception) --- End of inner exception stack trace --- at System.Net.HttpWebRequest.GetResponse()

    Read the article

  • Unable to read data from the transport connection: An existing connection was forcibly closed by the remote host.

    - by Paul J. Warner
    I am having an issue with a program where after 6 mins +- 5 secs we get the above exception. Some more info about the exception stacktrace is below. This all happens pretty religiously, 6 mins goes by and bam the following 3 exeptions. We have the application installed in 2 other environments and it is working fine there. I am hoping to find some server settings either IIS 6 or Server 2003 settings that may be causing this issue to occur. I have reviewed some of the similar questions and don't see very many answers. I am hoping that maybe the information I have provided may help a little bit. 208741,Exception,,,,2011-06-21 00:30:14.193,SERVERNAME,2624,1,CLIENTNAME,The underlying connection was closed: An unexpected error occurred on a receive. , at System.Web.Services.Protocols.WebClientProtocol.GetWebResponse(WebRequest request) at System.Web.Services.Protocols.HttpWebClientProtocol.GetWebResponse(WebRequest request) at Microsoft.Web.Services3.WebServicesClientProtocol.GetResponse(WebRequest request, IAsyncResult result) at System.Web.Services.Protocols.SoapHttpClientProtocol.Invoke(String methodName, Object[] parameters) at System.Net.Sockets.NetworkStream.Read(Byte[] buffer, Int32 offset, Int32 size) at System.Net.FixedSizeReader.ReadPacket(Byte[] buffer, Int32 offset, Int32 count) at System.Net.Security._SslStream.StartFrameHeader(Byte[] buffer, Int32 offset, Int32 count, AsyncProtocolRequest asyncRequest) at System.Net.Security._SslStream.StartReading(Byte[] buffer, Int32 offset, Int32 count, AsyncProtocolRequest asyncRequest) at System.Net.Security._SslStream.ProcessRead(Byte[] buffer, Int32 offset, Int32 count, AsyncProtocolRequest asyncRequest) at System.Net.TlsStream.Read(Byte[] buffer, Int32 offset, Int32 size) at System.Net.PooledStream.Read(Byte[] buffer, Int32 offset, Int32 size) at System.Net.Connection.SyncRead(HttpWebRequest request, Boolean userRetrievedStream, Boolean probeRead),2004437127,114,1 208742,Exception,,,,2011-06-21 00:30:14.227,SERVERNAME,2624,1,CLIENTNAME,Unable to read data from the transport connection: An existing connection was forcibly closed by the remote host. , at System.Net.Sockets.NetworkStream.Read(Byte[] buffer, Int32 offset, Int32 size) at System.Net.FixedSizeReader.ReadPacket(Byte[] buffer, Int32 offset, Int32 count) at System.Net.Security._SslStream.StartFrameHeader(Byte[] buffer, Int32 offset, Int32 count, AsyncProtocolRequest asyncRequest) at System.Net.Security._SslStream.StartReading(Byte[] buffer, Int32 offset, Int32 count, AsyncProtocolRequest asyncRequest) at System.Net.Security._SslStream.ProcessRead(Byte[] buffer, Int32 offset, Int32 count, AsyncProtocolRequest asyncRequest) at System.Net.TlsStream.Read(Byte[] buffer, Int32 offset, Int32 size) at System.Net.PooledStream.Read(Byte[] buffer, Int32 offset, Int32 size) at System.Net.Connection.SyncRead(HttpWebRequest request, Boolean userRetrievedStream, Boolean probeRead),2004437127,114,1 208743,Exception,,,,2011-06-21 00:30:14.287,SERVERNAME,2624,1,CLIENTNAME,An existing connection was forcibly closed by the remote host , at System.Net.Sockets.NetworkStream.Read(Byte[] buffer, Int32 offset, Int32 size),-691097507,62,1

    Read the article

  • Applying ServiceKnownTypeAttribute to WCF service with Spring

    - by avidgoffer
    I am trying to apply the ServiceKnownTypeAttribute to my WCF Service but keep getting the error below my config. Does anyone have any ideas? <object id="HHGEstimating" type="Spring.ServiceModel.ServiceExporter, Spring.Services"> <property name="TargetName" value="HHGEstimatingHelper"/> <property name="Name" value="HHGEstimating"/> <property name="Namespace" value="http://www.igcsoftware.com/HHGEstimating"/> <property name="TypeAttributes"> <list> <ref local="wcfErrorBehavior"/> <ref local="wcfSilverlightFaultBehavior"/> <object type="System.ServiceModel.ServiceKnownTypeAttribute, System.ServiceModel"> <constructor-arg name="type" value="IGCSoftware.HHG.Business.UserControl.AtlasUser, IGCSoftware.HHG.Business"/> </object> </list> </property> Error thrown by a dependency of object 'HHGEstimating' defined in 'assembly [IGCSoftware.HHG.WebService, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null], resource [IGCSoftware.HHG.WebService.Resources.Spring.objects.xml] line 46' : '1' constructor arguments specified but no matching constructor found in object 'System.ServiceModel.ServiceKnownTypeAttribute#25A5628' (hint: specify argument indexes, names, or types to avoid ambiguities). while resolving 'TypeAttributes[2]' to 'System.ServiceModel.ServiceKnownTypeAttribute#25A5628' defined in 'assembly [IGCSoftware.HHG.WebService, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null], resource [IGCSoftware.HHG.WebService.Resources.Spring.objects.xml] line 46' Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. Exception Details: Spring.Objects.Factory.ObjectCreationException: Error thrown by a dependency of object 'HHGEstimating' defined in 'assembly [IGCSoftware.HHG.WebService, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null], resource [IGCSoftware.HHG.WebService.Resources.Spring.objects.xml] line 46' : '1' constructor arguments specified but no matching constructor found in object 'System.ServiceModel.ServiceKnownTypeAttribute#25A5628' (hint: specify argument indexes, names, or types to avoid ambiguities). while resolving 'TypeAttributes[2]' to 'System.ServiceModel.ServiceKnownTypeAttribute#25A5628' defined in 'assembly [IGCSoftware.HHG.WebService, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null], resource [IGCSoftware.HHG.WebService.Resources.Spring.objects.xml] line 46' Source Error: An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below. Stack Trace: [ObjectCreationException: Error thrown by a dependency of object 'HHGEstimating' defined in 'assembly [IGCSoftware.HHG.WebService, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null], resource [IGCSoftware.HHG.WebService.Resources.Spring.objects.xml] line 46' : '1' constructor arguments specified but no matching constructor found in object 'System.ServiceModel.ServiceKnownTypeAttribute#25A5628' (hint: specify argument indexes, names, or types to avoid ambiguities). while resolving 'TypeAttributes[2]' to 'System.ServiceModel.ServiceKnownTypeAttribute#25A5628' defined in 'assembly [IGCSoftware.HHG.WebService, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null], resource [IGCSoftware.HHG.WebService.Resources.Spring.objects.xml] line 46'] Spring.Objects.Factory.Support.ObjectDefinitionValueResolver.ResolveInnerObjectDefinition(String name, String innerObjectName, String argumentName, IObjectDefinition definition, Boolean singletonOwner) in l:\projects\spring-net\trunk\src\Spring\Spring.Core\Objects\Factory\Support\ObjectDefinitionValueResolver.cs:300 Spring.Objects.Factory.Support.ObjectDefinitionValueResolver.ResolvePropertyValue(String name, IObjectDefinition definition, String argumentName, Object argumentValue) in l:\projects\spring-net\trunk\src\Spring\Spring.Core\Objects\Factory\Support\ObjectDefinitionValueResolver.cs:150 Spring.Objects.Factory.Support.ObjectDefinitionValueResolver.ResolveValueIfNecessary(String name, IObjectDefinition definition, String argumentName, Object argumentValue) in l:\projects\spring-net\trunk\src\Spring\Spring.Core\Objects\Factory\Support\ObjectDefinitionValueResolver.cs:112 Spring.Objects.Factory.Config.ManagedList.Resolve(String objectName, IObjectDefinition definition, String propertyName, ManagedCollectionElementResolver resolver) in l:\projects\spring-net\trunk\src\Spring\Spring.Core\Objects\Factory\Config\ManagedList.cs:126 Spring.Objects.Factory.Support.ObjectDefinitionValueResolver.ResolvePropertyValue(String name, IObjectDefinition definition, String argumentName, Object argumentValue) in l:\projects\spring-net\trunk\src\Spring\Spring.Core\Objects\Factory\Support\ObjectDefinitionValueResolver.cs:201 Spring.Objects.Factory.Support.ObjectDefinitionValueResolver.ResolveValueIfNecessary(String name, IObjectDefinition definition, String argumentName, Object argumentValue) in l:\projects\spring-net\trunk\src\Spring\Spring.Core\Objects\Factory\Support\ObjectDefinitionValueResolver.cs:112 Spring.Objects.Factory.Support.AbstractAutowireCapableObjectFactory.ApplyPropertyValues(String name, RootObjectDefinition definition, IObjectWrapper wrapper, IPropertyValues properties) in l:\projects\spring-net\trunk\src\Spring\Spring.Core\Objects\Factory\Support\AbstractAutowireCapableObjectFactory.cs:373 Spring.Objects.Factory.Support.AbstractAutowireCapableObjectFactory.PopulateObject(String name, RootObjectDefinition definition, IObjectWrapper wrapper) in l:\projects\spring-net\trunk\src\Spring\Spring.Core\Objects\Factory\Support\AbstractAutowireCapableObjectFactory.cs:563 Spring.Objects.Factory.Support.AbstractAutowireCapableObjectFactory.ConfigureObject(String name, RootObjectDefinition definition, IObjectWrapper wrapper) in l:\projects\spring-net\trunk\src\Spring\Spring.Core\Objects\Factory\Support\AbstractAutowireCapableObjectFactory.cs:1844 Spring.Objects.Factory.Support.AbstractAutowireCapableObjectFactory.InstantiateObject(String name, RootObjectDefinition definition, Object[] arguments, Boolean allowEagerCaching, Boolean suppressConfigure) in l:\projects\spring-net\trunk\src\Spring\Spring.Core\Objects\Factory\Support\AbstractAutowireCapableObjectFactory.cs:918 Spring.Objects.Factory.Support.AbstractObjectFactory.CreateAndCacheSingletonInstance(String objectName, RootObjectDefinition objectDefinition, Object[] arguments) in l:\projects\spring-net\trunk\src\Spring\Spring.Core\Objects\Factory\Support\AbstractObjectFactory.cs:2120 Spring.Objects.Factory.Support.AbstractObjectFactory.GetObjectInternal(String name, Type requiredType, Object[] arguments, Boolean suppressConfigure) in l:\projects\spring-net\trunk\src\Spring\Spring.Core\Objects\Factory\Support\AbstractObjectFactory.cs:2046 Spring.Objects.Factory.Support.DefaultListableObjectFactory.PreInstantiateSingletons() in l:\projects\spring-net\trunk\src\Spring\Spring.Core\Objects\Factory\Support\DefaultListableObjectFactory.cs:505 Spring.Context.Support.AbstractApplicationContext.Refresh() in l:\projects\spring-net\trunk\src\Spring\Spring.Core\Context\Support\AbstractApplicationContext.cs:911 _dynamic_Spring.Context.Support.XmlApplicationContext..ctor(Object[] ) +197 Spring.Reflection.Dynamic.SafeConstructor.Invoke(Object[] arguments) in l:\projects\spring-net\trunk\src\Spring\Spring.Core\Reflection\Dynamic\DynamicConstructor.cs:116 Spring.Context.Support.RootContextInstantiator.InvokeContextConstructor(ConstructorInfo ctor) in l:\projects\spring-net\trunk\src\Spring\Spring.Core\Context\Support\ContextHandler.cs:550 Spring.Context.Support.ContextInstantiator.InstantiateContext() in l:\projects\spring-net\trunk\src\Spring\Spring.Core\Context\Support\ContextHandler.cs:494 Spring.Context.Support.ContextHandler.InstantiateContext(IApplicationContext parentContext, Object configContext, String contextName, Type contextType, Boolean caseSensitive, String[] resources) in l:\projects\spring-net\trunk\src\Spring\Spring.Core\Context\Support\ContextHandler.cs:330 Spring.Context.Support.ContextHandler.Create(Object parent, Object configContext, XmlNode section) in l:\projects\spring-net\trunk\src\Spring\Spring.Core\Context\Support\ContextHandler.cs:280 [ConfigurationErrorsException: Error creating context 'spring.root': Error thrown by a dependency of object 'HHGEstimating' defined in 'assembly [IGCSoftware.HHG.WebService, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null], resource [IGCSoftware.HHG.WebService.Resources.Spring.objects.xml] line 46' : '1' constructor arguments specified but no matching constructor found in object 'System.ServiceModel.ServiceKnownTypeAttribute#25A5628' (hint: specify argument indexes, names, or types to avoid ambiguities). while resolving 'TypeAttributes[2]' to 'System.ServiceModel.ServiceKnownTypeAttribute#25A5628' defined in 'assembly [IGCSoftware.HHG.WebService, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null], resource [IGCSoftware.HHG.WebService.Resources.Spring.objects.xml] line 46'] System.Configuration.BaseConfigurationRecord.EvaluateOne(String[] keys, SectionInput input, Boolean isTrusted, FactoryRecord factoryRecord, SectionRecord sectionRecord, Object parentResult) +202 System.Configuration.BaseConfigurationRecord.Evaluate(FactoryRecord factoryRecord, SectionRecord sectionRecord, Object parentResult, Boolean getLkg, Boolean getRuntimeObject, Object& result, Object& resultRuntimeObject) +1061 System.Configuration.BaseConfigurationRecord.GetSectionRecursive(String configKey, Boolean getLkg, Boolean checkPermission, Boolean getRuntimeObject, Boolean requestIsHere, Object& result, Object& resultRuntimeObject) +1431 System.Configuration.BaseConfigurationRecord.GetSection(String configKey, Boolean getLkg, Boolean checkPermission) +56 System.Configuration.BaseConfigurationRecord.GetSection(String configKey) +8 System.Web.Configuration.HttpConfigurationSystem.GetApplicationSection(String sectionName) +45 System.Web.Configuration.HttpConfigurationSystem.GetSection(String sectionName) +49 System.Web.Configuration.HttpConfigurationSystem.System.Configuration.Internal.IInternalConfigSystem.GetSection(String configKey) +6 System.Configuration.ConfigurationManager.GetSection(String sectionName) +78 Spring.Util.ConfigurationUtils.GetSection(String sectionName) in l:\projects\spring-net\trunk\src\Spring\Spring.Core\Util\ConfigurationUtils.cs:69 Spring.Context.Support.ContextRegistry.InitializeContextIfNeeded() in l:\projects\spring-net\trunk\src\Spring\Spring.Core\Context\Support\ContextRegistry.cs:340 Spring.Context.Support.ContextRegistry.GetContext() in l:\projects\spring-net\trunk\src\Spring\Spring.Core\Context\Support\ContextRegistry.cs:206 Spring.ServiceModel.Activation.ServiceHostFactory.CreateServiceHost(String reference, Uri[] baseAddresses) in l:\projects\spring-net\trunk\src\Spring\Spring.Services\ServiceModel\Activation\ServiceHostFactory.cs:66 System.ServiceModel.HostingManager.CreateService(String normalizedVirtualPath) +11687036 System.ServiceModel.HostingManager.ActivateService(String normalizedVirtualPath) +42 System.ServiceModel.HostingManager.EnsureServiceAvailable(String normalizedVirtualPath) +479 [ServiceActivationException: The service '/HHGEstimating.svc' cannot be activated due to an exception during compilation. The exception message is: Error creating context 'spring.root': Error thrown by a dependency of object 'HHGEstimating' defined in 'assembly [IGCSoftware.HHG.WebService, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null], resource [IGCSoftware.HHG.WebService.Resources.Spring.objects.xml] line 46' : '1' constructor arguments specified but no matching constructor found in object 'System.ServiceModel.ServiceKnownTypeAttribute#25A5628' (hint: specify argument indexes, names, or types to avoid ambiguities). while resolving 'TypeAttributes[2]' to 'System.ServiceModel.ServiceKnownTypeAttribute#25A5628' defined in 'assembly [IGCSoftware.HHG.WebService, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null], resource [IGCSoftware.HHG.WebService.Resources.Spring.objects.xml] line 46'.] System.ServiceModel.AsyncResult.End(IAsyncResult result) +11592858 System.ServiceModel.Activation.HostedHttpRequestAsyncResult.End(IAsyncResult result) +194 System.ServiceModel.Activation.HostedHttpRequestAsyncResult.ExecuteSynchronous(HttpApplication context, Boolean flowContext) +176 System.ServiceModel.Activation.HttpModule.ProcessRequest(Object sender, EventArgs e) +275 System.Web.SyncEventExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +68 System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +75

    Read the article

  • Programação paralela no .NET Framework 4 – Parte I

    - by anobre
    Introdução O avanço de tecnologia nos últimos anos forneceu, a baixo custo, acesso  a workstations com inúmeros CPUs. Facilmente encontramos hoje máquinas clientes com 2, 4 e até 8 núcleos, sem considerar os “super-servidores” com até 36 processadores :) Da wikipedia: A Unidade central de processamento (CPU, de acordo com as iniciais em inglês) ou o processador é a parte de um sistema de computador que executa as instruções de um programa de computador, e é o elemento primordial na execução das funções de um computador. Este termo tem sido usado na indústria de computadores pelo menos desde o início dos anos 1960[1]. A forma, desenho e implementação de CPUs têm mudado dramaticamente desde os primeiros exemplos, mas o seu funcionamento fundamental permanece o mesmo. Fazendo uma analogia, seria muito interessante delegarmos tarefas no mundo real que podem ser executadas independentemente a pessoas diferentes, atingindo desta forma uma  maior performance / produtividade na sua execução. A computação paralela se baseia na idéia que um problema maior pode ser dividido em problemas menores, sendo resolvidos de forma paralela. Este pensamento é utilizado há algum tempo por HPC (High-performance computing), e através das facilidades dos últimos anos, assim como a preocupação com consumo de energia, tornaram esta idéia mais atrativa e de fácil acesso a qualquer ambiente. No .NET Framework A plataforma .NET apresenta um runtime, bibliotecas e ferramentas para fornecer uma base de acesso fácil e rápido à programação paralela, sem trabalhar diretamente com threads e thread pool. Esta série de posts irá apresentar todos os recursos disponíveis, iniciando os estudos pela TPL, ou Task Parallel Library. Task Parallel Library A TPL é um conjunto de tipos localizados no namespace System.Threading e System.Threading.Tasks, a partir da versão 4 do framework. A partir da versão 4 do framework, o TPL é a maneira recomendada para escrever código paralelo e multithreaded. http://msdn.microsoft.com/en-us/library/dd460717(v=VS.100).aspx Task Parallelism O termo “task parallelism”, ou em uma tradução live paralelismo de tarefas, se refere a uma ou mais tarefas sendo executadas de forma simultanea. Considere uma tarefa como um método. A maneira mais fácil de executar tarefas de forma paralela é o código abaixo: Parallel.Invoke(() => TrabalhoInicial(), () => TrabalhoSeguinte()); O que acontece de verdade? Por trás nos panos, esta instrução instancia de forma implícita objetos do tipo Task, responsável por representar uma operação assíncrona, não exatamente paralela: public class Task : IAsyncResult, IDisposable É possível instanciar Tasks de forma explícita, sendo uma alternativa mais complexa ao Parallel.Invoke. var task = new Task(() => TrabalhoInicial()); task.Start(); Outra opção de instanciar uma Task e já executar sua tarefa é: var t = Task<int>.Factory.StartNew(() => TrabalhoInicialComValor());var t2 = Task<int>.Factory.StartNew(() => TrabalhoSeguinteComValor()); A diferença básica entre as duas abordagens é que a primeira tem início conhecido, mais utilizado quando não queremos que a instanciação e o agendamento da execução ocorra em uma só operação, como na segunda abordagem. Data Parallelism Ainda parte da TPL, o Data Parallelism se refere a cenários onde a mesma operação deva ser executada paralelamente em elementos de uma coleção ou array, através de instruções paralelas For e ForEach. A idéia básica é pegar cada elemento da coleção (ou array) e trabalhar com diversas threads concomitantemente. A classe-chave para este cenário é a System.Threading.Tasks.Parallel // Sequential version foreach (var item in sourceCollection) { Process(item); } // Parallel equivalent Parallel.ForEach(sourceCollection, item => Process(item)); Complicado né? :) Demonstração Acesse aqui um vídeo com exemplos (screencast). Cuidado! Apesar da imensa vontade de sair codificando, tome cuidado com alguns problemas básicos de paralelismo. Neste link é possível conhecer algumas situações. Abraços.

    Read the article

  • SSL authentication error: RemoteCertificateChainErrors on ASP.NET on Ubuntu

    - by Frank Krueger
    I am trying to access Gmail's SMTP service from an ASP.NET MVC site running under Mono 2.4.2.3. But I keep getting this error: System.InvalidOperationException: SSL authentication error: RemoteCertificateChainErrors at System.Net.Mail.SmtpClient.m__3 (System.Object sender, System.Security.Cryptography.X509Certificates.X509Certificate certificate, System.Security.Cryptography.X509Certificates.X509Chain chain, SslPolicyErrors sslPolicyErrors) [0x00000] at System.Net.Security.SslStream+c__AnonStorey9.m__9 (System.Security.Cryptography.X509Certificates.X509Certificate cert, System.Int32[] certErrors) [0x00000] at Mono.Security.Protocol.Tls.SslClientStream.OnRemoteCertificateValidation (System.Security.Cryptography.X509Certificates.X509Certificate certificate, System.Int32[] errors) [0x00000] at Mono.Security.Protocol.Tls.SslStreamBase.RaiseRemoteCertificateValidation (System.Security.Cryptography.X509Certificates.X509Certificate certificate, System.Int32[] errors) [0x00000] at Mono.Security.Protocol.Tls.SslClientStream.RaiseServerCertificateValidation (System.Security.Cryptography.X509Certificates.X509Certificate certificate, System.Int32[] certificateErrors) [0x00000] at Mono.Security.Protocol.Tls.Handshake.Client.TlsServerCertificate.validateCertificates (Mono.Security.X509.X509CertificateCollection certificates) [0x00000] at Mono.Security.Protocol.Tls.Handshake.Client.TlsServerCertificate.ProcessAsTls1 () [0x00000] at Mono.Security.Protocol.Tls.Handshake.HandshakeMessage.Process () [0x00000] at (wrapper remoting-invoke-with-check) Mono.Security.Protocol.Tls.Handshake.HandshakeMessage:Process () at Mono.Security.Protocol.Tls.ClientRecordProtocol.ProcessHandshakeMessage (Mono.Security.Protocol.Tls.TlsStream handMsg) [0x00000] at Mono.Security.Protocol.Tls.RecordProtocol.InternalReceiveRecordCallback (IAsyncResult asyncResult) [0x00000] I have installed certificates using: certmgr -ssl -m smtps://smtp.gmail.com:465 with this output: Mono Certificate Manager - version 2.4.2.3 Manage X.509 certificates and CRL from stores. Copyright 2002, 2003 Motus Technologies. Copyright 2004-2008 Novell. BSD licensed. X.509 Certificate v3 Issued from: C=US, O=Equifax, OU=Equifax Secure Certificate Authority Issued to: C=US, O=Google Inc, CN=Google Internet Authority Valid from: 06/08/2009 20:43:27 Valid until: 06/07/2013 19:43:27 *** WARNING: Certificate signature is INVALID *** Import this certificate into the CA store ?yes X.509 Certificate v3 Issued from: C=US, O=Google Inc, CN=Google Internet Authority Issued to: C=US, S=California, L=Mountain View, O=Google Inc, CN=smtp.gmail.com Valid from: 04/22/2010 20:02:45 Valid until: 04/22/2011 20:12:45 Import this certificate into the AddressBook store ?yes 2 certificates added to the stores. In fact, this worked for a month but mysteriously stopped working on May 5. I installed these new certs today, but I am still getting these errors.

    Read the article

  • C# Socket.BeginSend AsyncCallback behavior (timeout?)

    - by mdarsigny
    Hi guys, Here is a scenario with asynchronous sockets that I dont't quite understand... I have 2 Tcp sockets, a client socket & a server socket. My server socket is bound & listening on a port. My client sockets connect to the server socket (using BeginConnect / EndConnect). I then send a message to the server using BeginSend(). On the server side, I don't do a Receive() or BeginReceive(). What happens is that my AsyncCallback specified for my BeginSend call gets invoked & its IAsyncResult tells me that it completed & the call to Socket.EndSend() does not raise any exception... Is there something that I don't get or shouldn't my AsyncCallback be called only if the BeginSend call actually sends something to the server (ie.: callback called after the server has received all bytes)? If there was no receive done on the server, shouldn't my callback be called after the sendtimeout expires and my call to Socket.EndSend then would raise an exception? Thanks

    Read the article

  • How to play non buffered .wav with MediaStreamSource implementation in Silverlight 4?

    - by kyrisu
    Background I'm trying to stream a wave file in Silverlight 4 using MediaStreamSource implementation found here. The problem is I want to play the file while it's still buffering, or at least give user some visual feedback while it's buffering. For now my code looks like that: private void button1_Click(object sender, RoutedEventArgs e) { HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(new Uri(App.Current.Host.Source, "../test.wav")); //request.ContentType = "audio/x-wav"; request.AllowReadStreamBuffering = false; request.BeginGetResponse(new AsyncCallback(RequestCallback), request); } private void RequestCallback(IAsyncResult ar) { this.Dispatcher.BeginInvoke(delegate() { HttpWebRequest request = (HttpWebRequest)ar.AsyncState; HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(ar); WaveMediaStreamSource wavMss = new WaveMediaStreamSource(response.GetResponseStream()); try { me.SetSource(wavMss); } catch (InvalidOperationException) { // This file is not valid } me.Play(); }); } The problem is that after settings request.AllowREadStreamBuffer to false the stream does not support seeking and the above mentioned implementation throws an exception (keep in mind I've put some of the position setting logic into if(stream.CanSeek) block): Read is not supported on the main thread when buffering is disabled Question Is there a way to play wav stream without buffering it in advance?

    Read the article

  • WCF Ria Services Error : Load operation failed for query 'GetTranslationProgress'

    - by Manoj
    Hello, I am using WCF Ria Services beta in my silverlight application. I have a long running task on the server which keeps writing its status to a database table. I have a "GetTranslationProgress" Ria Service Query method which queries the state to get the status. This query method is called continuously at a regular interval of 5 seconds until a status = Finished or Error is retrieved. In some cases if the task on the server is running for a long duration 2-3 minutes then I receives this error:- Load operation failed for query 'GetTranslationProgress'. The server did not provide a meaningful reply; this might be caused by a contract mismatch, a premature session shutdown or an internal server error. at System.Windows.Ria.OperationBase.Complete(Exception error) at System.Windows.Ria.LoadOperation.Complete(Exception error) at System.Windows.Ria.DomainContext.CompleteLoad(IAsyncResult asyncResult) at System.Windows.Ria.DomainContext.<c_DisplayClass17.b_13(Object ) The error occurs intermittently and I have no idea what could be causing this error. I have checked most of the forums and sites but I have not been able to find out any solution to this issue. Please help.

    Read the article

  • Error when creating a new entity foo, editing a previously existing foo, then saving. Generic 4004 e

    - by Tarks
    The steps are as simple as that so I imagine there's something else going on here, the problem is I just get back 4004, no exception anywhere etc, making it annoying to debug, I get this from the ie error window Microsoft JScript runtime error: Unhandled Error in Silverlight Application Code: 4004 Category: ManagedRuntimeError Message: System.Windows.Ria.DomainOperationException: Submit operation failed. An error occurred while updating the entries. See the inner exception for details. at System.Windows.Ria.OperationBase.Complete(Exception error) at System.Windows.Ria.SubmitOperation.Complete(Exception error) at System.Windows.Ria.DomainContext.CompleteSubmitChanges(IAsyncResult asyncResult) at System.Windows.Ria.DomainContext.<c_DisplayClassd.b_5(Object ) public void TurnPage(bool forward) { TurnPageForward = forward; // If the pages are already turning then don't try and skip days, just run the animation function so it inreases the speed if (!workBook.IsTransitioning && !IsWaitingForData) { IsWaitingForData = true; workBook.SnapshotPages(); NoteCtx.SubmitChanges().Completed += (s, a) => { workBook.ClearPageContents(); CurrentDate = CurrentDate.AddDays(forward ? 1 : -1); PullNotes(CurrentDate); }; } else { workBook.BeginTurnPages(TurnPageForward); } } public void PullNotes(DateTime? noteTime) { NoteCtx.NoteItems.Clear(); var loadOp = NoteCtx.Load(NoteCtx.GetNoteItemsForDayQuery(CurrentDate)); loadOp.Completed += new EventHandler(NotesReady); }

    Read the article

  • HttpRequest.BeginWebRequest not executing asynchronously

    - by Shawn Simon
    I have the following code: Private Function CreateRequest() As HttpWebRequest Dim request As HttpWebRequest = HttpWebRequest.Create(_url) request.Method = "POST" request.ContentType = "application/x-www-form-urlencoded" Dim postData As String = String.Join("&", GetPostData().Select(Function(s) String.Format("{0}={1}", s.Key, HttpUtility.UrlEncode(s.Value))).ToArray) Dim data As Byte() = (New ASCIIEncoding).GetBytes(postData) request.Timeout = _maxTimeoutSeconds * 1000 Dim stream = request.GetRequestStream stream.Write(data, 0, data.Length) stream.Close() Return request End Function Public Sub SendAsync(ByVal callback As Action(Of ResponseBase)) Dim request = CreateRequest() _attemptCount += 1 Dim reqID As Integer If _loggingContext IsNot Nothing Then Try reqID = Log.NotesRequest(_url.ToString, GetPostData, _loggingContext) Catch ex As Exception ErrorTracker.LogError(ex) End Try End If Dim responseState As New ResponseState responseState.LoggedNotesRequestID = reqID responseState.Request = request responseState.Callback = callback Dim response = request.BeginGetResponse(New AsyncCallback(AddressOf RespCallback), responseState) End Sub Private Sub RespCallback(ByVal ar As IAsyncResult) Dim responseState As ResponseState = CType(ar.AsyncState, ResponseState) ' Process response... I set up the request to go to a mock server which sleeps for 30 seconds. When I call BeginGetResponse, the application just waits at that line of code for the response. I want it to carry on with the app, and then just run the callback whenever it finishes. This code is run from a web page, and my callback just logs the response and sends an email. I don't want to use to have to wait for the response.

    Read the article

  • RhinoMocks Testing callback method

    - by joblot
    Hi All I have a service proxy class that makes asyn call to service operation. I use a callback method to pass results back to my view model. Doing functional testing of view model, I can mock service proxy to ensure methods are called on the proxy, but how can I ensure that callback method is called as well? With RhinoMocks I can test that events are handled and event raise events on the mocked object, but how can I test callbacks? ViewModel: public class MyViewModel { public void GetDataAsync() { // Use DI framework to get the object IMyServiceClient myServiceClient = IoC.Resolve<IMyServiceClient>(); myServiceClient.GetData(GetDataAsyncCallback); } private void GetDataAsyncCallback(Entity entity, ServiceError error) { // do something here... } } ServiceProxy: public class MyService : ClientBase, IMyServiceClient { // Constructor public NertiAdminServiceClient(string endpointConfigurationName, string remoteAddress) : base(endpointConfigurationName, remoteAddress) { } // IMyServiceClient member. public void GetData(Action<Entity, ServiceError> callback) { Channel.BeginGetData(EndGetData, callback); } private void EndGetData(IAsyncResult result) { Action<Entity, ServiceError> callback = result.AsyncState as Action<Entity, ServiceError>; ServiceError error; Entity results = Channel.EndGetData(out error, result); if (callback != null) callback(results, error); } } Thanks

    Read the article

  • Receiving broadcast messages

    - by Prasad
    Hi, I'm trying to receive broadcast messages using C# code in an ISDN network with BRI interface at my end. I see the packets sent to the broadcast ip address (239.255.255.255) on some ports using Comm View tool. But when I try to listen to this IP address, it says the address is not in a valid context. But when I send broadcast messages to 255.255.255.255 on a port, I can receive those messages with the below code.. What could be the problem with this ip address - 239.255.255.255 ? The code I use to listen to broadcast messages is.. UdpClient udp = new UdpClient(); IPEndPoint receiveEndPoint = new IPEndPoint(IPAddress.Any, 8013); // If I use IPAddress.Parse("239.255.255.255") to listen to, // it says "the address is not in a valid // context." udp.Client.Bind(receiveEndPoint); udp.BeginReceive(_Callback, udp); static private void _Callback(IAsyncResult iar) { try { UdpClient client = (UdpClient)iar.AsyncState; client.BeginReceive(_Callback, client); IPEndPoint ipRemote = new IPEndPoint(IPAddress.Any, 8013); byte[] rgb = client.EndReceive(iar, ref ipRemote); Console.WriteLine("Received {0} bytes: \"{1}\"", rgb.Length.ToString(), Encoding.UTF8.GetString(rgb)); } catch (ObjectDisposedException) { Console.WriteLine("closing listening socket"); } catch (Exception exc) { Console.WriteLine("Listening socket error: \"" + exc.Message + "\""); } } There are packets sent to the broadcast ipaddress (239.255.255.255) which I can see in Commview tool, but can't receive them from the code... Can anybody help me out please? Thanking you in advance, Prasad Kancharla.

    Read the article

  • Webservice returning 403 error

    - by user48408
    I'm wondering whether I'm receiving the 403 errors because there are too many attempted connections being made to the webservice. If this is the case how do I get around it? I've tried creating a new instance of InternalWebService each time and disposing of the old one but I get the same problem. I've disabled the firewall and the webservice is located locally at the moment. I beginning to think it may be a problem with the credentials but the control tree is populated via the webservice at some stage. If I browse to the webmethods in my browser I can run them all. I return an instance of the webservice from my login handler loginsession.cs: static LoginSession() { ... g_NavigatorWebService = new InternalWebService(); g_NavigatorWebService.Credentials = System.Net.CredentialCache.DefaultCredentials; ... } public static InternalWebService NavigatorWebService { get { return g_NavigatorWebService; } } I have a tree view control which uses the webservice to populate itself. IncidentTreeViewControl.cs: public IncidentTreeView() { InitializeComponent(); m_WebService = LoginSession.NavigatorWebService; ... } public void Populate() { m_WebService.BeginGetIncidentSummaryByCompany(new AsyncCallback(IncidentSummaryByClientComplete), null); m_WebService.BeginGetIncidentSummaryByDepartment(new AsyncCallback(IncidentSummaryByDepartmentComplete), null); ... } private void IncidentSummaryByClientComplete(IAsyncResult ar) { MyTypedDataSet data = m_WebService.EndGetIncidentSummaryByCompany(ar); //403 ..cont... } I'm getting the 403 on the last line.

    Read the article

  • C# StreamReader.EndOfStream produces IOException

    - by Ziplin
    I'm working on an application that accepts TCP connections and reads in data until an </File> marker is read and then writes that data to the filesystem. I don't want to disconnect, I want to let the client sending the data to do that so they can send multiple files in one connection. I'm using the StreamReader.EndOfStream around my outter loop, but it throws an IOException when the client disconnects. Is there a better way to do this? private static void RecieveAsyncStream(IAsyncResult ar) { TcpListener listener = (TcpListener)ar.AsyncState; TcpClient client = listener.EndAcceptTcpClient(ar); // init the streams NetworkStream netStream = client.GetStream(); StreamReader streamReader = new StreamReader(netStream); StreamWriter streamWriter = new StreamWriter(netStream); while (!streamReader.EndOfStream) // throws IOException { string file= ""; while (file!= "</File>" && !streamReader.EndOfStream) { file += streamReader.ReadLine(); } // write file to filesystem } listener.BeginAcceptTcpClient(RecieveAsyncStream, listener); }

    Read the article

  • Calling end invoke on an asynchronous call when an exception has fired in WCF.

    - by james.ingham
    Hey, I currently have an asynchronous call with a callback, which fires this method on completion: private void TestConnectionToServerCallback(IAsyncResult iar) { bool result; try { result = testConnectionDelegate.EndInvoke(iar); Console.WriteLine("Connection made!"); } catch (EndpointNotFoundException e) { Console.WriteLine("Server Timeout. Are you connected?"); result = false; } ... } With the EndpointNotFoundException firing when the server is down or no connection can be made. My question is this, if I want to recall the testConnectionDelegate with some kind of re-try button, must I first call testConnectionDelegate.EndInvoke where the exception is caught? When I do call end invoke in the catch, I get another exception on result = testConnectionDelegate.EndInvoke(iar); whenever I call this method for the second time. This is "CommunicationObjectFaultedException". I'm assuming this is because I didn't end it properly, which is what I think I have to do. Any help would be appreciated. Thanks - James

    Read the article

  • WCF object parameter loses values

    - by Josh
    I'm passing an object to a WCF service and wasn't getting anything back. I checked the variable as it gets passed to the method that actually does the work and noticed that none of the values are set on the object at that point. Here's the object: [DataContract] public class Section { [DataMember] public long SectionID { get; set; } [DataMember] public string Title { get; set; } [DataMember] public string Text { get; set; } [DataMember] public int Order { get; set; } } Here's the service code for the method: [OperationContract] public List<Section> LoadAllSections(Section s) { return SectionRepository.Instance().LoadAll(s); } The code that actually calls this method is this and is located in a Silverlight XAML file: SectionServiceClient proxy = new SectionServiceClient(); proxy.LoadAllSectionsCompleted += new EventHandler<LoadAllSectionsCompletedEventArgs>(proxy_LoadAllSectionsCompleted); Section s = new Section(); s.SectionID = 4; proxy.LoadAllSectionsAsync(s); When the code finally gets into the method LoadAllSections(Section s), the parameter's SectionID is not set. I stepped through the code and when it goes into the generated code that returns an IAsyncResult object, the object's properties are set. But when it actually calls the method, LoadAllSections, the parameter received is completely blank. Is there something I have to set to make the proeprty stick between method calls?

    Read the article

  • StreamReader.EndOfStream produces IOException

    - by Ziplin
    I'm working on an application that accepts TCP connections and reads in data until an </File> marker is read and then writes that data to the filesystem. I don't want to disconnect, I want to let the client sending the data to do that so they can send multiple files in one connection. I'm using the StreamReader.EndOfStream around my outter loop, but it throws an IOException when the client disconnects. Is there a better way to do this? private static void RecieveAsyncStream(IAsyncResult ar) { TcpListener listener = (TcpListener)ar.AsyncState; TcpClient client = listener.EndAcceptTcpClient(ar); // init the streams NetworkStream netStream = client.GetStream(); StreamReader streamReader = new StreamReader(netStream); StreamWriter streamWriter = new StreamWriter(netStream); while (!streamReader.EndOfStream) // throws IOException { string file= ""; while (file!= "</File>" && !streamReader.EndOfStream) { file += streamReader.ReadLine(); } // write file to filesystem } listener.BeginAcceptTcpClient(RecieveAsyncStream, listener); }

    Read the article

  • HttpWebRequest.BeginGetResponse() does not return the second time

    - by evilfred
    Hi, I make one HttpWebRequest and call GetResponse() on it to get a synchronous response. Then after processing that response, I make a new HttpWebRequest and call BeginGetResponse() on it. Since BeginGetResponse() is an asynchronous call I expect it to return right away, but it doesn't! Why not? Here is some stripped down sample code: HttpWebRequest request = RequestFactory.MakeSessionCreationRequest(); try { // Get the response from the server. using (WebResponse response = request.GetResponse()) { using (Stream responseStream = response.GetResponseStream()) { ; // Get the response. } } ; // Process the response. } catch (WebException e) { Logger("Caught WebException when attempting to connect: " + e); return; } // Make the second, asynchronous request. HttpWebRequest msgRequest = RequestFactory.MakeMessageRequest(); IAsyncResult result = msgRequest.BeginGetResponse( new AsyncCallback(HandleResponse), msgRequest); // PROBLEM: This line is never reached!!! Logger("Message send started");

    Read the article

  • Question about making Asynchronous call in C# (WPF) to COM object

    - by Andrew
    Hi, Sorry to ask such a basic question but I seem to have a brain freeze on this one! I'm calling a COM (ATL) object from my WPF project. The COM method might take a long time to complete. I thought I'd try and call it asychronously. I have a few demo lines that show the problem. private void checkBox1_Checked(object sender, RoutedEventArgs e) { //DoSomeWork(); AsyncDoWork caller = new AsyncDoWork(DoSomeWork); IAsyncResult result = caller.BeginInvoke(null, null); } private delegate void AsyncDoWork(); private void DoSomeWork() { _Server.DoWork(); } The ATL method DoWork is very exciting. It is: STDMETHODIMP CSimpleObject::DoWork(void) { Sleep(5000); return S_OK; } I had expectations that running this way would result in the checkbox being checked right away (instead of in 5 seconds) and me being able to move the WPF gui around the screen. I can't - for 5 seconds. What am I doing wrong? I'm sure it's something pretty simple. Delegate signature wrong? Thanks.

    Read the article

  • deserialize system.outofmemoryexception

    - by clanier9
    I've got a serializeable class called Cereal with several public fields shown here <Serializable> Public Class Cereal Public id As Integer Public cardType As Type Public attacker As String Public defender As String Public placedOn As String Public attack As Boolean Public placed As Boolean Public played As Boolean Public text As String Public Sub New() End Sub End Class My client computer is sending a new Cereal to the host by serializing it shown here 'sends data to host stream (c1) Private Sub cSendText(ByVal Data As String) Dim bf As New BinaryFormatter Dim c As New Cereal c.text = Data bf.Serialize(mobjClient.GetStream, c) End Sub The host listens to the stream for activity and when something gets put on it, it is supposed to deserialize it to a new Cereal shown here 'accepts data sent from the client, raised when data on host stream (c2) Private Sub DoReceive(ByVal ar As IAsyncResult) Dim intCount As Integer Try 'find how many byte is data SyncLock mobjClient.GetStream intCount = mobjClient.GetStream.EndRead(ar) End SyncLock 'if none, we are disconnected If intCount < 1 Then RaiseEvent Disconnected(Me) Exit Sub End If Dim bf As New BinaryFormatter Dim c As New Cereal c = CType(bf.Deserialize(mobjClient.GetStream), Cereal) If c.text.Length > 0 Then RaiseEvent LineReceived(Me, c.text) Else RaiseEvent CardReceived(Me, c) End If 'starts listening for action on stream again SyncLock mobjClient.GetStream mobjClient.GetStream.BeginRead(arData, 0, 1024, AddressOf DoReceive, Nothing) End SyncLock Catch e As Exception RaiseEvent Disconnected(Me) End Try End Sub when the following line executes, I get a System.OutOfMemoryException and I cannot figure out why this isn't working. c = CType(bf.Deserialize(mobjClient.GetStream), Cereal) The stream is a TCPClient stream. I'm new to serialization/deserialization and using visual studio 11

    Read the article

  • Verify an event was raised by mocked object

    - by joblot
    In my unit test how can I verify that an event is raised by the mocked object. I have a View(UI) -- ViewModel -- DataProvider -- ServiceProxy. ServiceProxy makes async call to serivce operation. When async operation is complete a method on DataProvider is called (callback method is passed as a method parameter). The callback method then raise and event which ViewModel is listening to. For ViewModel test I mock DataProvider and verify that handler exists for event raised by DataProvider. When testing DataProvider I mock ServiceProxy, but how can I test that callback method is called and event is raised. I am using RhinoMock 3.5 and AAA syntax Thanks -- DataProvider -- public partial class DataProvider { public event EventHandler<EntityEventArgs<ProductDefinition>> GetProductDefinitionCompleted; public void GetProductDefinition() { var service = IoC.Resolve<IServiceProxy>(); service.GetProductDefinitionAsync(GetProductDefinitionAsyncCallback); } private void GetProductDefinitionAsyncCallback(ProductDefinition productDefinition, ServiceError error) { OnGetProductDefinitionCompleted(this, new EntityEventArgs<ProductDefinition>(productDefinition, error)); } protected void OnGetProductDefinitionCompleted(object sender, EntityEventArgs<ProductDefinition> e) { if (GetProductDefinitionCompleted != null) GetProductDefinitionCompleted(sender, e); } } -- ServiceProxy -- public class ServiceProxy : ClientBase<IService>, IServiceProxy { public void GetProductDefinitionAsync(Action<ProductDefinition, ServiceError> callback) { Channel.BeginGetProductDefinition(EndGetProductDefinition, callback); } private void EndGetProductDefinition(IAsyncResult result) { Action<ProductDefinition, ServiceError> callback = result.AsyncState as Action<ProductDefinition, ServiceError>; ServiceError error; ProductDefinition results = Channel.EndGetProductDefinition(out error, result); if (callback != null) callback(results, error); } }

    Read the article

  • Fun with "The remote server returned an error: NotFound" - Silverlight4 Out of Browser

    - by Scott Silvi
    Hey all - I'm running SL4 on VS2010. I've got an app that authenticates via a web service to SPROC in my db. Unfortunately this is not WCF/WCF RIA, as I'm inheriting the DB/services from my client. This works perfectly inside of a browser. I'm attempting to move this OOB, and it's at this point that my authentication fails. Here's the steps I took... 1) SL App Properties Enable running app Out of Browser 2) SL App Properties Out of Browser Settings Require elevated trust when running OOB If i set a breakpoint on my logon button click, I see the service call is being made. However, if I step through it (or set a breakpoint on the actual logon web service), the code never gets that far. Here's the block it fails on: public LogonSVC.LogonResponse EndLogon(System.IAsyncResult result) { object[] _args = new object[0]; LogonSVC.LogonResponse _result = ((LogonSVC.LogonResponse)(base.EndInvoke("Logon", _args, result))); return _result; } I know using Elevated Trust means the crossdomain.xml isn't necessary. I dropped one in that allows everything, just to test, and that still fails. here's the code that calls the service: private void loginButton_Click(object sender, RoutedEventArgs e) { string Username = txtUserName.Text; string Password = txtPassword.Password; Uri iSilverlightServiceUriRelative = new Uri(App.Current.Host.Source, "../Services/Logon.asmx"); EndpointAddress iSilverlightServiceEndpoint = new EndpointAddress(iSilverlightServiceUriRelative); BasicHttpBinding iSilverlightServiceBinding = new BasicHttpBinding(BasicHttpSecurityMode.Transport);// Transport if it's HTTPS:// LogonService = new LogonSVC.LogonSoapClient(iSilverlightServiceBinding, iSilverlightServiceEndpoint); LogonService.LogonCompleted += new EventHandler<LogonSVC.LogonCompletedEventArgs>(LogonService_LogonCompleted); LogonService.LogonAsync(Username, Password); } My LogonService_LogonCompleted doesn't fire either (which makes sense, just a heads up). I don't know how to fiddler this, as this is running OOB with the site served via localhost/IIS. I know this works though in browser, so I'm curious what would break it OOB. Thank you, Scott

    Read the article

  • Why MSMQ won't send a space character?

    - by cyclotis04
    I'm exploring MSMQ services, and I wrote a simple console client-server application that sends each of the client's keystrokes to the server. Whenever hit a control character (DEL, ESC, INS, etc) the server understandably throws an error. However, whenever I type a space character, the server receives the packet but doesn't throw an error and doesn't display the space. Server: namespace QIM { class Program { const string QUEUE = @".\Private$\qim"; static MessageQueue _mq; static readonly object _mqLock = new object(); static XmlSerializer xs; static void Main(string[] args) { lock (_mqLock) { if (!MessageQueue.Exists(QUEUE)) _mq = MessageQueue.Create(QUEUE); else _mq = new MessageQueue(QUEUE); } xs = new XmlSerializer(typeof(string)); _mq.BeginReceive(new TimeSpan(0, 1, 0), new object(), OnReceive); while (Console.ReadKey().Key != ConsoleKey.Escape) { } } static void OnReceive(IAsyncResult result) { Message msg; lock (_mqLock) { try { msg = _mq.EndReceive(result); Console.Write("."); Console.Write(xs.Deserialize(msg.BodyStream)); } catch (Exception ex) { Console.Write(ex); } } _mq.BeginReceive(new TimeSpan(0, 1, 0), new object(), OnReceive); } } } Client: namespace QIM_Client { class Program { const string QUEUE = @".\Private$\qim"; static MessageQueue _mq; static void Main(string[] args) { if (!MessageQueue.Exists(QUEUE)) _mq = MessageQueue.Create(QUEUE); else _mq = new MessageQueue(QUEUE); ConsoleKeyInfo key = new ConsoleKeyInfo(); while (key.Key != ConsoleKey.Escape) { key = Console.ReadKey(); _mq.Send(key.KeyChar.ToString()); } } } } Client Input: Testing, Testing... Server Output: .T.e.s.t.i.n.g.,..T.e.s.t.i.n.g...... You'll notice that the space character sends a message, but the character isn't displayed.

    Read the article

< Previous Page | 2 3 4 5 6 7 8  | Next Page >