Search Results

Search found 958 results on 39 pages for 'dispose'.

Page 27/39 | < Previous Page | 23 24 25 26 27 28 29 30 31 32 33 34  | Next Page >

  • Using Appendbuffers in unity for terrain generation

    - by Wardy
    Like many others I figured I would try and make the most of the monster processing power of the GPU but I'm having trouble getting the basics in place. CPU code: using UnityEngine; using System.Collections; public class Test : MonoBehaviour { public ComputeShader Generator; public MeshTopology Topology; void OnEnable() { var computedMeshPoints = ComputeMesh(); CreateMeshFrom(computedMeshPoints); } private Vector3[] ComputeMesh() { var size = (32*32) * 4; // 4 points added for each x,z pos var buffer = new ComputeBuffer(size, 12, ComputeBufferType.Append); Generator.SetBuffer(0, "vertexBuffer", buffer); Generator.Dispatch(0, 1, 1, 1); var results = new Vector3[size]; buffer.GetData(results); buffer.Dispose(); return results; } private void CreateMeshFrom(Vector3[] generatedPoints) { var filter = GetComponent<MeshFilter>(); var renderer = GetComponent<MeshRenderer>(); if (generatedPoints.Length > 0) { var mesh = new Mesh { vertices = generatedPoints }; var colors = new Color[generatedPoints.Length]; var indices = new int[generatedPoints.Length]; //TODO: build this different based on topology of the mesh being generated for (int i = 0; i < indices.Length; i++) { indices[i] = i; colors[i] = Color.blue; } mesh.SetIndices(indices, Topology, 0); mesh.colors = colors; mesh.RecalculateNormals(); mesh.Optimize(); mesh.RecalculateBounds(); filter.sharedMesh = mesh; } else { filter.sharedMesh = null; } } } GPU code: #pragma kernel Generate AppendStructuredBuffer<float3> vertexBuffer : register(u0); void genVertsAt(uint2 xzPos) { //TODO: put some height generation code here. // could even run marching cubes / dual contouring code. float3 corner1 = float3( xzPos[0], 0, xzPos[1] ); float3 corner2 = float3( xzPos[0] + 1, 0, xzPos[1] ); float3 corner3 = float3( xzPos[0], 0, xzPos[1] + 1); float3 corner4 = float3( xzPos[0] + 1, 0, xzPos[1] + 1 ); vertexBuffer.Append(corner1); vertexBuffer.Append(corner2); vertexBuffer.Append(corner3); vertexBuffer.Append(corner4); } [numthreads(32, 1, 32)] void Generate (uint3 threadId : SV_GroupThreadID, uint3 groupId : SV_GroupID) { uint2 currentXZ = unint2( groupId.x * 32 + threadId.x, groupId.z * 32 + threadId.z); genVertsAt(currentXZ); } Can anyone explain why when I call "buffer.GetData(results);" on the CPU after the compute dispatch call my buffer is full of Vector3(0,0,0), I'm not expecting any y values yet but I would expect a bunch of thread indexes in the x,z values for the Vector3 array. I'm not getting any errors in any of this code which suggests it's correct syntax-wise but maybe the issue is a logical bug. Also: Yes, I know I'm generating 4,000 Vector3's and then basically round tripping them. However, the purpose of this code is purely to learn how round tripping works between CPU and GPU in Unity.

    Read the article

  • JOGL2 test compiles, but doesn't execute - help?

    - by Chuchinyi
    I have a problem with JOGL2. My JOGL2Template.java compiles fine, but executing it results in the following error: D:\java\java\jogl>javac JOGL2Template.java <== compile ok D:\java\java\jogl>java JOGL2Template <== execute error Exception in thread "main" java.lang.ExceptionInInitializerError at javax.media.opengl.GLProfile.<clinit>(GLProfile.java:1176) at JOGL2Template.<init>(JOGL2Template.java:24) at JOGL2Template.main(JOGL2Template.java:57) Caused by: java.lang.SecurityException: no certificate for gluegen-rt.dll in D:\ java\lib\gluegen-rt-natives-windows-i586.jar at com.jogamp.common.util.JarUtil.validateCertificate(JarUtil.java:350) at com.jogamp.common.util.JarUtil.validateCertificates(JarUtil.java:324) at com.jogamp.common.util.cache.TempJarCache.validateCertificates(TempJa rCache.java:328) at com.jogamp.common.util.cache.TempJarCache.bootstrapNativeLib(TempJarC ache.java:283) at com.jogamp.common.os.Platform$3.run(Platform.java:308) at java.security.AccessController.doPrivileged(Native Method) at com.jogamp.common.os.Platform.loadGlueGenRTImpl(Platform.java:298) at com.jogamp.common.os.Platform.<clinit>(Platform.java:207) ... 3 more Here is the JOGL2Template.java source code: import java.awt.Dimension; import java.awt.Frame; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import javax.media.opengl.GLAutoDrawable; import javax.media.opengl.GLCapabilities; import javax.media.opengl.GLEventListener; import javax.media.opengl.GLProfile; import javax.media.opengl.awt.GLCanvas; import com.jogamp.opengl.util.FPSAnimator; import javax.swing.JFrame; /* * JOGL 2.0 Program Template For AWT applications */ public class JOGL2Template extends JFrame implements GLEventListener { private static final int CANVAS_WIDTH = 640; // Width of the drawable private static final int CANVAS_HEIGHT = 480; // Height of the drawable private static final int FPS = 60; // Animator's target frames per second // Constructor to create profile, caps, drawable, animator, and initialize Frame public JOGL2Template() { // Get the default OpenGL profile that best reflect your running platform. GLProfile glp = GLProfile.getDefault(); // Specifies a set of OpenGL capabilities, based on your profile. GLCapabilities caps = new GLCapabilities(glp); // Allocate a GLDrawable, based on your OpenGL capabilities. GLCanvas canvas = new GLCanvas(caps); canvas.setPreferredSize(new Dimension(CANVAS_WIDTH, CANVAS_HEIGHT)); canvas.addGLEventListener(this); // Create a animator that drives canvas' display() at 60 fps. final FPSAnimator animator = new FPSAnimator(canvas, FPS); addWindowListener(new WindowAdapter() { // For the close button @Override public void windowClosing(WindowEvent e) { // Use a dedicate thread to run the stop() to ensure that the // animator stops before program exits. new Thread() { @Override public void run() { animator.stop(); System.exit(0); } }.start(); } }); add(canvas); pack(); setTitle("OpenGL 2 Test"); setVisible(true); animator.start(); // Start the animator } public static void main(String[] args) { new JOGL2Template(); } @Override public void init(GLAutoDrawable drawable) { // Your OpenGL codes to perform one-time initialization tasks // such as setting up of lights and display lists. } @Override public void display(GLAutoDrawable drawable) { // Your OpenGL graphic rendering codes for each refresh. } @Override public void reshape(GLAutoDrawable drawable, int x, int y, int w, int h) { // Your OpenGL codes to set up the view port, projection mode and view volume. } @Override public void dispose(GLAutoDrawable drawable) { // Hardly used. } } Any ideas what might be the cause of these errors?

    Read the article

  • Identity in .NET 4.5&ndash;Part 2: Claims Transformation in ASP.NET (Beta 1)

    - by Your DisplayName here!
    In my last post I described how every identity in .NET 4.5 is now claims-based. If you are coming from WIF you might think, great – how do I transform those claims? Sidebar: What is claims transformation? One of the most essential features of WIF (and .NET 4.5) is the ability to transform credentials (or tokens) to claims. During that process the “low level” token details are turned into claims. An example would be a Windows token – it contains things like the name of the user and to which groups he belongs to. That information will be surfaced as claims of type Name and GroupSid. Forms users will be represented as a Name claim (all the other claims that WIF provided for FormsIdentity are gone in 4.5). The issue here is, that your applications typically don’t care about those low level details, but rather about “what’s the purchase limit of alice”. The process of turning the low level claims into application specific ones is called claims transformation. In pre-claims times this would have been done by a combination of Forms Authentication extensibility, role manager and maybe ASP.NET profile. With claims transformation all your identity gathering code is in one place (and the outcome can be cached in a single place as opposed to multiple ones). The structural class to do claims transformation is called ClaimsAuthenticationManager. This class has two purposes – first looking at the incoming (low level) principal and making sure all required information about the user is present. This is your first chance to reject a request. And second – modeling identity information in a way it is relevant for the application (see also here). This class gets called (when present) during the pipeline when using WS-Federation. But not when using the standard .NET principals. I am not sure why – maybe because it is beta 1. Anyhow, a number of people asked me about it, and the following is a little HTTP module that brings that feature back in 4.5. public class ClaimsTransformationHttpModule : IHttpModule {     public void Dispose()     { }     public void Init(HttpApplication context)     {         context.PostAuthenticateRequest += Context_PostAuthenticateRequest;     }     void Context_PostAuthenticateRequest(object sender, EventArgs e)     {         var context = ((HttpApplication)sender).Context;         // no need to call transformation if session already exists         if (FederatedAuthentication.SessionAuthenticationModule != null &&             FederatedAuthentication.SessionAuthenticationModule.ContainsSessionTokenCookie(context.Request.Cookies))         {             return;         }         var transformer = FederatedAuthentication.FederationConfiguration.IdentityConfiguration.ClaimsAuthenticationManager;         if (transformer != null)         {             var transformedPrincipal = transformer.Authenticate(context.Request.RawUrl, context.User as ClaimsPrincipal);             context.User = transformedPrincipal;             Thread.CurrentPrincipal = transformedPrincipal;         }     } } HTH

    Read the article

  • Running Powershell from within SharePoint

    - by Norgean
    Just because something is a daft idea, doesn't mean it can't be done. We sometimes need to do some housekeeping - like delete old files or list items or… yes, well, whatever you use Powershell for in a SharePoint world. Or it could be that your solution has "issues" for which you have Powershell solutions, but not the budget to transform into proper bug fixes. So you create a "how to" for the ITPro guys. Idea: What if we keep the scripts in a list, and have SharePoint execute the scripts on demand? An announcements list (because of the multiline body field). Warning! Let us be clear. This list needs to be locked down; if somebody creates a malicious script and you run it, I cannot help you. First; we need to figure out how to start Powershell scripts from C#. Hit teh interwebs and the Googlie, and you may find jpmik's post: http://www.codeproject.com/Articles/18229/How-to-run-PowerShell-scripts-from-C. (Or MS' official answer at http://msdn.microsoft.com/en-us/library/ee706563(v=vs.85).aspx) public string RunPowershell(string powershellText, SPWeb web, string param1, string param2) { // Powershell ~= RunspaceFactory - i.e. Create a powershell context var runspace = RunspaceFactory.CreateRunspace(); var resultString = new StringBuilder(); try { // load the SharePoint snapin - Note: you cannot do this in the script itself (i.e. add-pssnapin etc does not work) PSSnapInException snapInError; runspace.RunspaceConfiguration.AddPSSnapIn("Microsoft.SharePoint.PowerShell", out snapInError); runspace.Open(); // set a web variable. runspace.SessionStateProxy.SetVariable("webContext", web); // and some user defined parameters runspace.SessionStateProxy.SetVariable("param1", param1); runspace.SessionStateProxy.SetVariable("param2", param2); var pipeline = runspace.CreatePipeline(); pipeline.Commands.AddScript(powershellText); // add a "return" variable pipeline.Commands.Add("Out-String"); // execute! var results = pipeline.Invoke(); // convert the script result into a single string foreach (PSObject obj in results) { resultString.AppendLine(obj.ToString()); } } finally { // close the runspace runspace.Close(); } // consider logging the result. Or something. return resultString.ToString(); } Ok. We've written some code. Let us test it. var runner = new PowershellRunner(); runner.RunPowershellScript(@" $web = Get-SPWeb 'http://server/web' # or $webContext $web.Title = $param1 $web.Update() $web.Dispose() ", null, "New title", "not used"); Next step: Connect the code to the list, or more specifically, have the code execute on one (or several) list items. As there are more options than readers, I'll leave this as an exercise for the reader. Some alternatives: Create a ribbon button that calls RunPowershell with the body of the selected itemsAdd a layout pageSpecify list item from query string (possibly coupled with content editor webpart with html that links directly to this page with querystring)WebpartListing with an "execute" columnList with multiselect and an execute button Etc!Now that you have the code for executing powershell scripts, you can easily expand this into a timer job, which executes scripts at regular intervals. But if the previous solution was dangerous, this is even worse - the scripts will usually be run with one of the admin accounts, and can do pretty much anything...One more thing... Note that as this is running "consoleless" calls to Write-Host will fail. Two solutions; remove all output, or check if the script is run in a console-window or not.  if ($host.Name -eq "ConsoleHost") { Write-Host 'If I agreed with you we'd both be wrong' }

    Read the article

  • Best way to process a queue in C# (PDF treatment)

    - by Bartdude
    First of all let me expose what I would like to do : I already dispose of a long-time running webapp developed in ASP.NET (C#) 2.0. In this app, users can upload standard PDF files (text+pics). The app is running in production on a Windows Server 2003 and has a dedicated database server (SQL server 2008) also running Windows Server 2003. I myself am a quite experienced web developer, but never actually programmed anything non-web (or at least nothing serious). I plan on adding a functionality to the webapp for which I would need a jpg snapshot of each page of the PDF. Creating these "thumbnails" isn't the big deal as such, I already do it inside my webapp using ghostscript. I've only done it on 1 page documents for now though, and the new functionality will need to process bigger documents. In order for this process to be transparent aswell for the admins as the final users, I would like to implement some kind of queue to delay the processing of the thumbnails. There again, no problem to create the queue, it will consist of records in a table, with enough info to find the pdf document back. Then I will need to process this queue, and that's were my interrogations start. Obviously the best solution to process it isn't an ASP script or so, so I will have to get out of my known environment. No problem, but I have no idea which direction to go. Therefore, a few questions : What should I develop ? I presumably need something that is "standby" on the server, runs when needed, then returns to idle state until further notice.Should I be looking into Windows service ? Is there another more appropriate type of project ? Depending on the first answer, what will be the approach ? Should I have somehow SQL server "tell" the program/service/... to process the queue, or should I have that program/service/... periodically check the state of the queue and treat new items. In both case, which functionality can I use ? we're not talking about hundreds of PDF a day (max 50 maybe), I can totally afford to treat the queue 1 item at a time. Can you confirm I don't have to look much further on threads and so ? (I found a lot of answers talking about threads in queue treatment, but it looks quite overkill for my needs) Maybe linked to the previous question : what about concurrent call to the program, whatever it is ? Let's suppose it is currently running, and a new record comes in the queue, what should be the behaviour ? I don't need much detailed answers and would already be happy with answers like "You can do the processing with a service, and yes it's possible to have sqlserver on machine A trigger a service start on machine B" or "You have to develop xxx and then use the scheduler to run it every xxx minutes". I don't mind reading articles and so, but I can hardly afford to spend too much time learning stuff to finally realize I went the wrong way for this project, so basically I'm trying to narrow down the scope of matters I need to investigate. Thanks for reading me, I hope I'll find some helping hands on here :-)

    Read the article

  • Exception converting Office files to PDF using ABCpdf.NET onWindows Server 2008

    - by drivendevelopment
    Has anyone delt with this exception from ABCpdf? We're running on Server 2008 and only have issues converting Office files (Word and Excel). This all worked well on Server 2003. Because we're only having issues with Office files I wonder if it's related to the XPS support on Server 2008? The code that calls into this function is running as a Windows Service. Private Overloads Function ConvertMicrosoftOfficeDocToPdf(ByVal inputFile As Byte(), ByVal fileExt As String) As Byte() Dim abcDoc As WebSupergoo.ABCpdf7.Doc = Nothing Try abcDoc = New WebSupergoo.ABCpdf7.Doc() Dim xro As New WebSupergoo.ABCpdf7.XReadOptions() xro.FileExtension = fileExt Try abcDoc.Read(inputFile, xro) Catch ex As Exception System.Diagnostics.Trace.Write(ex.ToString()) Throw ex End Try Dim fileBytes As Byte() = abcDoc.GetData() Return fileBytes Finally If Not abcDoc Is Nothing Then abcDoc.Clear() abcDoc.Dispose() End If End Try End Function WebSupergoo.ABCpdf7.Internal.PDFException: Attempted to read or write protected memory. This is often an indication that other memory is corrupt. --- System.AccessViolationException: Attempted to read or write protected memory. This is often an indication that other memory is corrupt. at WebSupergoo.ABCpdf7.Internal.NDoc._InvokeMethod(IntPtr inDoc, Int32 inMethod, Int32 inIndex, Int32 inFlags, String inParams, String& outErr) at WebSupergoo.ABCpdf7.Internal.NDoc.InvokeMethod(IntPtr inDoc, Int32 inMethod, Int32 inIndex, Int32 inFlags, String inParams, String& outErr) at WebSupergoo.ABCpdf7.Doc.PrintToXps(String inputFile, String outputFile, Int32 timeout, String printerName) at WebSupergoo.ABCpdf7.Operations.XpsImportOperation.ImportAny(Doc doc, String path, Int32 timeout) at WebSupergoo.ABCpdf7.XReadOptions.ImportXpsAny(Doc doc, String path, Boolean clear) at WebSupergoo.ABCpdf7.XReadOptions.Read(Doc doc, Byte[] data, ReadModuleType module) at WebSupergoo.ABCpdf7.XReadOptions.Read(Doc doc, Byte[] data)

    Read the article

  • Linq The specified type 'string' is not a valid provider type.

    - by Joe Pitz
    Using Linq to call a stored procedure that passes a single string, The stored procedure returns a data set row that contains a string and an int. Code: PESQLDataContext pe = new PESQLDataContext(strConnStr); pe.ObjectTrackingEnabled = false; gvUnitsPassed.DataSource = pe.PassedInspection(Line); gvUnitsPassed.DataBind(); pe.dispose(); When the code runs an exception gets called below: The exception is thrown at the IExecuteResult result = statement: Enclosed is my result class in the designer.cs file. [Function(Name = "dbo.PassedInspection")] public ISingleResult<PassedInspectionResult> PassedInspection([Parameter(Name = "Model", DbType = "VarChar(4)")] string model) { IExecuteResult result = this.ExecuteMethodCall(this, ((MethodInfo)(MethodInfo.GetCurrentMethod())), model); return ((ISingleResult<PassedInspectionResult>)(result.ReturnValue)); } public partial class PassedInspectionResult { private string _Date; private int _Passed; public PassedInspectionResult() { } [Column(Storage = "_Date", DbType = "string NULL")] public string Date { get { return this._Date; } set { if ((this._Date != value)) { this._Date = value; } } } [Column(Storage = "_Passed", DbType = "Int NULL")] public int Passed { get { return this._Passed; } set { if ((this._Passed != value)) { this._Passed = value; } } } } } I have other stored procedures with similar arguments that run just fine. Thanks

    Read the article

  • Using Unit of Work design pattern / NHibernate Sessions in an MVVM WPF

    - by Echiban
    I think I am stuck in the paralysis of analysis. Please help! I currently have a project that Uses NHibernate on SQLite Implements Repository and Unit of Work pattern: http://blogs.hibernatingrhinos.com/nhibernate/archive/2008/04/10/nhibernate-and-the-unit-of-work-pattern.aspx MVVM strategy in a WPF app Unit of Work implementation in my case supports one NHibernate session at a time. I thought at the time that this makes sense; it hides inner workings of NHibernate session from ViewModel. Now, according to Oren Eini (Ayende): http://msdn.microsoft.com/en-us/magazine/ee819139.aspx He convinces the audience that NHibernate sessions should be created / disposed when the view associated with the presenter / viewmodel is disposed. He presents issues why you don't want one session per windows app, nor do you want a session to be created / disposed per transaction. This unfortunately poses a problem because my UI can easily have 10+ view/viewmodels present in an app. He is presenting using a MVP strategy, but does his advice translate to MVVM? Does this mean that I should scrap the unit of work and have viewmodel create NHibernate sessions directly? Should a WPF app only have one working session at a time? If that is true, when should I create / dispose a NHibernate session? And I still haven't considered how NHibernate Stateless sessions fit into all this! My brain is going to explode. Please help!

    Read the article

  • Tracking changes in Entity Framework 4.0 using POCO Dynamic Proxies across multiple data contexts.

    - by Rob Packwood
    I started messing with EF 4.0 because I am curious about the POCO possibilities... I wanted to simulate disconnected web environment and wrote the following code to simulate this: Save a test object in the database. Retrieve the test object Dispose of the DataContext associated with the test object I used to retrieve it Update the test object Create a new data context and persist the changes on the test object that are automatically tracked within the DynamicProxy generated against my POCO object. The problem is that when I call dataContext.SaveChanges in the Test method above, the updates are not applied. The testStore entity shows a status of "Modified" when I check its EntityStateTracker, but it is no longer modified when I view it within the new dataContext's Stores property. I would have thought that calling the Attach method on the new dataContext would also bring the object's "Modified" state over, but that appears to not be the case. Is there something I am missing? I am definitely working with self-tracking POCOs using DynamicProxies. private static void SaveTestStore(string storeName = "TestStore") { using (var context = new DataContext()) { Store newStore = context.Stores.CreateObject(); newStore.Name = storeName; context.Stores.AddObject(newStore); context.SaveChanges(); } } private static Store GetStore(string storeName = "TestStore") { using (var context = new DataContext()) { return (from store in context.Stores where store.Name == storeName select store).SingleOrDefault(); } } [Test] public void Test_Store_Update_Using_Different_DataContext() { SaveTestStore(); Store testStore = GetStore(); testStore.Name = "Updated"; using (var dataContext = new DataContext()) { dataContext.Stores.Attach(testStore); dataContext.SaveChanges(SaveOptions.DetectChangesBeforeSave); } Store updatedStore = GetStore("Updated"); Assert.IsNotNull(updatedStore); }

    Read the article

  • OpenOffice with C# iterate throught all paragraphs and read text

    - by Darius Kucinskas
    How to iterate through all paragraphs in OpenOffice Writer document and output text. I have Java examples, but don't know how to convert code to C#. Java example could be found here: http://wiki.services.openoffice.org/wiki/API/Samples/Java/Writer/TextDocumentStructure My C# code: InitOpenOfficeEnvironment(); XMultiServiceFactory multiServiceFactory = connect(); XComponentLoader componentLoader = XComponentLoader)multiServiceFactory.createInstance("com.sun.star.frame.Desktop"); //set the property PropertyValue[] propertyValue = new PropertyValue[1]; PropertyValue aProperty = new PropertyValue(); aProperty.Name = "Hidden"; aProperty.Value = new uno.Any(false); propertyValue[0] = aProperty; XComponent xComponent = componentLoader.loadComponentFromURL( @"file:///C:/code/test3.doc", "_blank", 0, propertyValue); XEnumerationAccess xEnumerationAccess = (XEnumerationAccess)xComponent; XEnumeration xParagraphEnumeration = xEnumerationAccess.createEnumeration(); while ( xParagraphEnumeration.hasMoreElements() ) { // ??? // The problem is here nextElement() returns uno.Any but // I some how should get XTextContent???? uno.Any textElement = xParagraphEnumeration.nextElement(); // create another enumeration to get all text portions of //the paragraph XEnumeration xParaEnumerationAccess = textElement.createEnumeration(); //step 3 Through the Text portions Enumeration, //get interface to each individual text portion } xComponent.dispose(); xComponent = null;

    Read the article

  • httpModules not working on iis7

    - by roncansan
    Hi, I have the following module public class LowerCaseRequest : IHttpModule { public void Init(HttpApplication context) { context.BeginRequest += new EventHandler(this.OnBeginRequest); } public void Dispose() { } public void OnBeginRequest(Object s, EventArgs e) { HttpApplication app = (HttpApplication)s; if (app.Context.Request.Url.ToString().ToLower().EndsWith(".aspx")) { if (app.Context.Request.Url.ToString() != app.Context.Request.Url.ToString().ToLower()) { HttpResponse response = app.Context.Response; response.StatusCode = (int)HttpStatusCode.MovedPermanently; response.Status = "301 Moved Permanently"; response.RedirectLocation = app.Context.Request.Url.ToString().ToLower(); response.SuppressContent = true; response.End(); } if (!app.Context.Request.Url.ToString().StartsWith(@"http://zeeprico.com")) { HttpResponse response = app.Context.Response; response.StatusCode = (int)HttpStatusCode.MovedPermanently; response.Status = "301 Moved Permanently"; response.RedirectLocation = app.Context.Request.Url.ToString().ToLower().Replace(@"http://zeeprico.com", @"http://www.zeeprico.com"); response.SuppressContent = true; response.End(); } } } } the web.config looks like <system.web> <httpModules> <remove name="WindowsAuthentication" /> <remove name="PassportAuthentication" /> <remove name="AnonymousIdentification" /> <remove name="UrlAuthorization" /> <remove name="FileAuthorization" /> <add name="LowerCaseRequest" type="LowerCaseRequest" /> <add name="UrlRewriter" type="Intelligencia.UrlRewriter.RewriterHttpModule, Intelligencia.UrlRewriter" /> <add name="ScriptModule" type="System.Web.Handlers.ScriptModule, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" /> </httpModules> </system.web> It works grate on my PC running XP and IIS 5.1 but on my webserver running IIS7 and WS 2008 dosn't works, please help I don't know how to work this out. Thanks

    Read the article

  • Why does this silverlight code get a "catastrophic failure" when reading a BitmapImage out of Isolat

    - by Edward Tanguay
    In a Silverlight app, I save a Bitmap like this: public static void SaveBitmapImageToIsolatedStorageFile(OpenReadCompletedEventArgs e, string fileName) { using (IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForApplication()) { using (IsolatedStorageFileStream isfs = new IsolatedStorageFileStream(fileName, FileMode.Create, isf)) { Int64 imgLen = (Int64)e.Result.Length; byte[] b = new byte[imgLen]; e.Result.Read(b, 0, b.Length); isfs.Write(b, 0, b.Length); isfs.Flush(); isfs.Close(); isf.Dispose(); } } } and read it back out like this: public static BitmapImage LoadBitmapImageFromIsolatedStorageFile(string fileName) { string text = String.Empty; using (IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForApplication()) { if (!isf.FileExists(fileName)) return null; using (IsolatedStorageFile isoStore = IsolatedStorageFile.GetUserStoreForApplication()) { using (IsolatedStorageFileStream isoStream = isoStore.OpenFile(fileName, FileMode.Open)) { BitmapImage bitmapImage = new BitmapImage(); bitmapImage.SetSource(isoStream); return bitmapImage; // "Catastrophic Failure: HRESULT: 0x8000FFFF (E_UNEXPECTED))" } } } } but this always gives me a "Catastrophic Failure: HRESULT: 0x8000FFFF (E_UNEXPECTED))" error. I've seen this error before when I tried to read a png file* off a server which was actually a **text file, so I assume the Bitmap is not being saved correctly, I got the code here. Can anyone see how the BitmapImage is not being saved correctly? Or why it would be giving me this error?

    Read the article

  • Parsing concatenated, non-delimited XML messages from TCP-stream using C#

    - by thaller
    I am trying to parse XML messages which are send to my C# application over TCP. Unfortunately, the protocol can not be changed and the XML messages are not delimited and no length prefix is used. Moreover the character encoding is not fixed but each message starts with an XML declaration <?xml>. The question is, how can i read one XML message at a time, using C#. Up to now, I tried to read the data from the TCP stream into a byte array and use it through a MemoryStream. The problem is, the buffer might contain more than one XML messages or the first message may be incomplete. In these cases, I get an exception when trying to parse it with XmlReader.Read or XmlDocument.Load, but unfortunately the XmlException does not really allow me to distinguish the problem (except parsing the localized error string). I tried using XmlReader.Read and count the number of Element and EndElement nodes. That way I know when I am finished reading the first, entire XML message. However, there are several problems. If the buffer does not yet contain the entire message, how can I distinguish the XmlException from an actually invalid, non-well-formed message? In other words, if an exception is thrown before reading the first root EndElement, how can I decide whether to abort the connection with error, or to collect more bytes from the TCP stream? If no exception occurs, the XmlReader is positioned at the start of the root EndElement. Casting the XmlReader to IXmlLineInfo gives me the current LineNumber and LinePosition, however it is not straight forward to get the byte position where the EndElement really ends. In order to do that, I would have to convert the byte array into a string (with the encoding specified in the XML declaration), seek to LineNumber,LinePosition and convert that back to the byte offset. I try to do that with StreamReader.ReadLine, but the stream reader gives no public access to the current byte position. All this seams very inelegant and non robust. I wonder if you have ideas for a better solution. Thank you. EDIT: I looked around and think that the situation is as follows (I might be wrong, corrections are welcome): I found no method so that the XmlReader can continue parsing a second XML message (at least not, if the second message has an XmlDeclaration). XmlTextReader.ResetState could do something similar, but for that I would have to assume the same encoding for all messages. Therefor I could not connect the XmlReader directly to the TcpStream. After closing the XmlReader, the buffer is not positioned at the readers last position. So it is not possible to close the reader and use a new one to continue with the next message. I guess the reason for this is, that the reader could not successfully seek on every possible input stream. When XmlReader throws an exception it can not be determined whether it happened because of an premature EOF or because of a non-wellformed XML. XmlReader.EOF is not set in case of an exception. As workaround I derived my own MemoryBuffer, which returns the very last byte as a single byte. This way I know that the XmlReader was really interested in the last byte and the following exception is likely due to a truncated message (this is kinda sloppy, in that it might not detect every non-wellformed message. However, after appending more bytes to the buffer, sooner or later the error will be detected. I could cast my XmlReader to the IXmlLineInfo interface, which gives access to the LineNumber and the LinePosition of the current node. So after reading the first message I remember these positions and use it to truncate the buffer. Here comes the really sloppy part, because I have to use the character encoding to get the byte position. I am sure you could find test cases for the code below where it breaks (e.g. internal elements with mixed encoding). But up to now it worked for all my tests. The parser class follows here -- may it be useful (I know, its very far from perfect...) class XmlParser { private byte[] buffer = new byte[0]; public int Length { get { return buffer.Length; } } // Append new binary data to the internal data buffer... public XmlParser Append(byte[] buffer2) { if (buffer2 != null && buffer2.Length > 0) { // I know, its not an efficient way to do this. // The EofMemoryStream should handle a List<byte[]> ... byte[] new_buffer = new byte[buffer.Length + buffer2.Length]; buffer.CopyTo(new_buffer, 0); buffer2.CopyTo(new_buffer, buffer.Length); buffer = new_buffer; } return this; } // MemoryStream which returns the last byte of the buffer individually, // so that we know that the buffering XmlReader really locked at the last // byte of the stream. // Moreover there is an EOF marker. private class EofMemoryStream: Stream { public bool EOF { get; private set; } private MemoryStream mem_; public override bool CanSeek { get { return false; } } public override bool CanWrite { get { return false; } } public override bool CanRead { get { return true; } } public override long Length { get { return mem_.Length; } } public override long Position { get { return mem_.Position; } set { throw new NotSupportedException(); } } public override void Flush() { mem_.Flush(); } public override long Seek(long offset, SeekOrigin origin) { throw new NotSupportedException(); } public override void SetLength(long value) { throw new NotSupportedException(); } public override void Write(byte[] buffer, int offset, int count) { throw new NotSupportedException(); } public override int Read(byte[] buffer, int offset, int count) { count = Math.Min(count, Math.Max(1, (int)(Length - Position - 1))); int nread = mem_.Read(buffer, offset, count); if (nread == 0) { EOF = true; } return nread; } public EofMemoryStream(byte[] buffer) { mem_ = new MemoryStream(buffer, false); EOF = false; } protected override void Dispose(bool disposing) { mem_.Dispose(); } } // Parses the first xml message from the stream. // If the first message is not yet complete, it returns null. // If the buffer contains non-wellformed xml, it ~should~ throw an exception. // After reading an xml message, it pops the data from the byte array. public Message deserialize() { if (buffer.Length == 0) { return null; } Message message = null; Encoding encoding = Message.default_encoding; //string xml = encoding.GetString(buffer); using (EofMemoryStream sbuffer = new EofMemoryStream (buffer)) { XmlDocument xmlDocument = null; XmlReaderSettings settings = new XmlReaderSettings(); int LineNumber = -1; int LinePosition = -1; bool truncate_buffer = false; using (XmlReader xmlReader = XmlReader.Create(sbuffer, settings)) { try { // Read to the first node (skipping over some element-types. // Don't use MoveToContent here, because it would skip the // XmlDeclaration too... while (xmlReader.Read() && (xmlReader.NodeType==XmlNodeType.Whitespace || xmlReader.NodeType==XmlNodeType.Comment)) { }; // Check for XML declaration. // If the message has an XmlDeclaration, extract the encoding. switch (xmlReader.NodeType) { case XmlNodeType.XmlDeclaration: while (xmlReader.MoveToNextAttribute()) { if (xmlReader.Name == "encoding") { encoding = Encoding.GetEncoding(xmlReader.Value); } } xmlReader.MoveToContent(); xmlReader.Read(); break; } // Move to the first element. xmlReader.MoveToContent(); // Read the entire document. xmlDocument = new XmlDocument(); xmlDocument.Load(xmlReader.ReadSubtree()); } catch (XmlException e) { // The parsing of the xml failed. If the XmlReader did // not yet look at the last byte, it is assumed that the // XML is invalid and the exception is re-thrown. if (sbuffer.EOF) { return null; } throw e; } { // Try to serialize an internal data structure using XmlSerializer. Type type = null; try { type = Type.GetType("my.namespace." + xmlDocument.DocumentElement.Name); } catch (Exception e) { // No specialized data container for this class found... } if (type == null) { message = new Message(); } else { // TODO: reuse the serializer... System.Xml.Serialization.XmlSerializer ser = new System.Xml.Serialization.XmlSerializer(type); message = (Message)ser.Deserialize(new XmlNodeReader(xmlDocument)); } message.doc = xmlDocument; } // At this point, the first XML message was sucessfully parsed. // Remember the lineposition of the current end element. IXmlLineInfo xmlLineInfo = xmlReader as IXmlLineInfo; if (xmlLineInfo != null && xmlLineInfo.HasLineInfo()) { LineNumber = xmlLineInfo.LineNumber; LinePosition = xmlLineInfo.LinePosition; } // Try to read the rest of the buffer. // If an exception is thrown, another xml message appears. // This way the xml parser could tell us that the message is finished here. // This would be prefered as truncating the buffer using the line info is sloppy. try { while (xmlReader.Read()) { } } catch { // There comes a second message. Needs workaround for trunkating. truncate_buffer = true; } } if (truncate_buffer) { if (LineNumber < 0) { throw new Exception("LineNumber not given. Cannot truncate xml buffer"); } // Convert the buffer to a string using the encoding found before // (or the default encoding). string s = encoding.GetString(buffer); // Seek to the line. int char_index = 0; while (--LineNumber > 0) { // Recognize \r , \n , \r\n as newlines... char_index = s.IndexOfAny(new char[] {'\r', '\n'}, char_index); // char_index should not be -1 because LineNumber>0, otherwise an RangeException is // thrown, which is appropriate. char_index++; if (s[char_index-1]=='\r' && s.Length>char_index && s[char_index]=='\n') { char_index++; } } char_index += LinePosition - 1; var rgx = new System.Text.RegularExpressions.Regex(xmlDocument.DocumentElement.Name + "[ \r\n\t]*\\>"); System.Text.RegularExpressions.Match match = rgx.Match(s, char_index); if (!match.Success || match.Index != char_index) { throw new Exception("could not find EndElement to truncate the xml buffer."); } char_index += match.Value.Length; // Convert the character offset back to the byte offset (for the given encoding). int line1_boffset = encoding.GetByteCount(s.Substring(0, char_index)); // remove the bytes from the buffer. buffer = buffer.Skip(line1_boffset).ToArray(); } else { buffer = new byte[0]; } } return message; } }

    Read the article

  • Apache Mina Server Restart java.net.BindException: Address already in use

    - by Kosaki
    Hello, I have a rather annoying problem in my server application. I bind Apache Mina with the following code: acceptor.bind(new InetSocketAddress(PORT)); Where acceptor is an NioSocketAcceptor. Over a HTTP interface I can shutdown the server so I can restart it. Server.ioAcceptor.unbind(new InetSocketAddress(Server.PORT)); for(IoSession session: Server.ioAcceptor.getManagedSessions().values()){ if(session.isConnected() && !session.isClosing()){ session.close(false); } } Server.ioAcceptor.dispose(); Main.transport.stop(); Logger.getRootLogger().warn("System going down. Request from "+context.getRemoteAddress()); System.exit(10); This is the code I use to stop the Mina server. However if I try to start the server again in the next couple of minutes. (Somewhere between 5 minutes and 15 minutes) I get the following exception on start up: java.net.BindException: Address already in use I also tried a simple ioAcceptor.unbind() but there was no difference. The server runs on Centos 5 with OpenJDK. Apache Mina version is 2.0 RC1. Thank you in advance for any ideas on how to resolve this.

    Read the article

  • Why is OracleDataAdapter.Fill() Very Slow?

    - by John Gietzen
    I am using a pretty complex query to retrieve some data out of one of our billing databases. I'm running in to an issue where the query seems to complete fairly quickly when executed with SQL Developer, but does not seem to ever finish when using the OracleDataAdapter.Fill() method. I'm only trying to read about 1000 rows, and the query completes in SQL Developer in about 20 seconds. What could be causing such drastic differences in performance? I have tons of other queries that run quickly using the same function. Here is the code I'm using to execute the query: using Oracle.DataAccess.Client; ... public DataTable ExecuteExternalQuery(string connectionString, string providerName, string queryText) { DbConnection connection = null; DbCommand selectCommand = null; DbDataAdapter adapter = null; switch (providerName) { case "System.Data.OracleClient": case "Oracle.DataAccess.Client": connection = new OracleConnection(connectionString); selectCommand = connection.CreateCommand(); adapter = new OracleDataAdapter((OracleCommand)selectCommand); break; ... } DataTable table = null; try { connection.Open(); selectCommand.CommandText = queryText; selectCommand.CommandTimeout = 300000; selectCommand.CommandType = CommandType.Text; table = new DataTable("result"); table.Locale = CultureInfo.CurrentCulture; adapter.Fill(table); } finally { adapter.Dispose(); if (connection.State != ConnectionState.Closed) { connection.Close(); } } return table; } And here is the general outline of the SQL I'm using: with trouble_calls as ( select work_order_number, account_number, date_entered from work_orders where date_entered >= sysdate - (15 + 31) -- Use the index to limit the number of rows scanned and wo_status not in ('Cancelled') and wo_type = 'Trouble Call' ) select account_number, work_order_number, date_entered from trouble_calls wo where wo.icoms_date >= sysdate - 15 and ( select count(*) from trouble_calls repeat where wo.account_number = repeat.account_number and wo.work_order_number <> repeat.work_order_number and wo.date_entered - repeat.date_entered between 0 and 30 ) >= 1

    Read the article

  • NETCF - Optimized Repaint (onPaint)

    - by Nullstr1ng
    Hi Guys, I want to ask for suggestions on how to optimize a repaint in Compact Framework? GetHashCode() didn't help because it always return a different hash code. Anyway, I have a program which you can drag and resize an object in run time. This object is a transparent object and it has a PNG image which also dynamically resize relative to object client size. Though I noticed, (e.g. I have 4 transparent object and I'm dragging or resizing one) all 4 of them triggers OnPaintBackground even if the 3 are not moving. Another one when am just tapping on the one object .. it sill triggers onPaintBacground(). Anyway, I don't have a problem when this events get triggered. What I like to do is optimization and that means I only have to repaint the object when it's necessary. Can you guys please give a suggestions? here's my pseudo C# code Bitmap _backBuff; onResize() { if(_backBuff != null) _backBuff.Dispose(); _backBuff = new Bitmap(ClientSize.Width, ClientSize.Height); Invalidate(); } onPaintBackground(e) /*have to use onPaintBackground because MSDN said it's faster*/ { using(Graphics g = Graphics.FromImage(_backBuff)) { g.Clear(Color.Black); // draw background ....some interface calling here ....and paint the background // draw alpha PNG .. get hDc .. paint PNG .. release hDc } e.Graphics.DrawImage(_backBuff,0,0); } Thanks in advance.

    Read the article

  • C# Process Exited event not firing from within webservice

    - by davidpizon
    I am attempting to wrap a 3rd party command line application within a web service. If I run the following code from within a console application: Process process= new System.Diagnostics.Process(); process.StartInfo.FileName = "some_executable.exe"; // Do not spawn a window for this process process.StartInfo.CreateNoWindow = true; process.StartInfo.ErrorDialog = false; // Redirect input, output, and error streams process.StartInfo.UseShellExecute = false; process.StartInfo.RedirectStandardOutput = true; process.StartInfo.RedirectStandardError = true; process.StartInfo.RedirectStandardInput = true; process.EnableRaisingEvents = true; process.ErrorDataReceived += (sendingProcess, eventArgs) => { // Make note of the error message if (!String.IsNullOrEmpty(eventArgs.Data)) if (this.WarningMessageEvent != null) this.WarningMessageEvent(this, new MessageEventArgs(eventArgs.Data)); }; process.OutputDataReceived += (sendingProcess, eventArgs) => { // Make note of the message if (!String.IsNullOrEmpty(eventArgs.Data)) if (this.DebugMessageEvent != null) this.DebugMessageEvent(this, new MessageEventArgs(eventArgs.Data)); }; process.Exited += (object sender, EventArgs e) => { // Make note of the exit event if (this.DebugMessageEvent != null) this.DebugMessageEvent(this, new MessageEventArgs("The command exited")); }; process.Start(); process.StandardInput.Close(); process.BeginOutputReadLine(); process.BeginErrorReadLine(); process.WaitForExit(); int exitCode = process.ExitCode; process.Close(); process.Dispose(); if (this.DebugMessageEvent != null) this.DebugMessageEvent(this, new MessageEventArgs("The command exited with code: " + exitCode)); All events, including the "process.Exited" event fires as expected. However, when this code is invoked from within a web service method, all events EXCEPT the "process.Exited" event fire. The execution appears to hang at the line: process.WaitForExit(); Would anyone be able to shed some light as to what I might be missing?

    Read the article

  • MS Chart in WPF, Setting the DataSource is not creating the Series

    - by Shaik Phakeer
    Hi All, Here I am trying to assign the datasource (using same code given in the sample application) and create a graph, only difference is i am doing it in WPF WindowsFormsHost. due to some reason the datasource is not being assigned properly and i am not able to see the series ("Series 1") being created. wired thing is that it is working in the Windows Forms application but not in the WPF one. am i missing something and can somebody help me? Thanks <Window x:Class="SEDC.MDM.WinUI.WindowsFormsHostWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:wf="clr-namespace:System.Windows.Forms;assembly=System.Windows.Forms" xmlns:CHR="clr- namespace:System.Windows.Forms.DataVisualization.Charting;assembly=System.Windows.Forms.Dat aVisualization" Title="HostingWfInWpf" Height="230" Width="338"> <Grid x:Name="grid1"> </Grid> </Window> private void drawChartDataBinding() { System.Windows.Forms.Integration.WindowsFormsHost host = new System.Windows.Forms.Integration.WindowsFormsHost(); string fileNameString = @"C:\Users\Shaik\MSChart\WinSamples\WinSamples\data\chartdata.mdb"; // initialize a connection string string myConnectionString = "PROVIDER=Microsoft.Jet.OLEDB.4.0;Data Source=" + fileNameString; // define the database query string mySelectQuery = "SELECT * FROM REPS;"; // create a database connection object using the connection string OleDbConnection myConnection = new OleDbConnection(myConnectionString); // create a database command on the connection using query OleDbCommand myCommand = new OleDbCommand(mySelectQuery, myConnection); Chart Chart1 = new Chart(); // set chart data source Chart1.DataSource = myCommand; // set series members names for the X and Y values Chart1.Series"Series 1".XValueMember = "Name"; Chart1.Series"Series 1".YValueMembers = "Sales"; // data bind to the selected data source Chart1.DataBind(); myCommand.Dispose(); myConnection.Close(); host.Child = Chart1; this.grid1.Children.Add(host); } Shaik

    Read the article

  • error: unable to open database file, SQLiteException was unhandled

    - by rose
    My project has a reference to SQLite.Interop.066.dll and even after putting in the correct path to the SQLite database, the application is still unable to find it. A SQLiteException was unhandled is returned. SQLiteConnection conn = new SQLiteConnection(); //SQLiteDataAdapter da; SQLiteCommandBuilder cb; DataTable dt=new DataTable(); int row = 0; conn.ConnectionString = "Data Source=C:\\database\\info"; conn.Open(); DataRow dr = dt.NewRow(); dr["name"] = txtName.Text; dr["address"] = txtAddress.Text; dr["phone"] = txtPhone.Text; dr["position"] = txtPosition.Text; dt.Rows.Add(dr); da.Update(dt); row = dt.Rows.Count - 1; txtName.Text = dt.Rows[row]["name"].ToString(); txtAddress.Text = dt.Rows[row]["address"].ToString(); txtPhone.Text = dt.Rows[row]["phone"].ToString(); txtPosition.Text = dt.Rows[row]["position"].ToString(); da.Fill(dt); cb = new SQLiteCommandBuilder(da); conn.Dispose(); conn.Close(); The exception occur at line: conn.Open(); sorry for the mistake title error before...

    Read the article

  • Change the Default Application Pool in IIS7 using .net?

    - by EdenMachine
    I'm using the following function to create a IIS7 Application and/or Virtual Directory. How would I also set the Application to use a different Application Pool? Private Sub CreateVirtualDir(ByVal WebSite As String, ByVal AppName As String, ByVal Path As String, Optional ByVal IsApplication As Boolean = True, Optional ByVal RunScripts As Boolean = True, Optional ByVal IsWrite As Boolean = True) Dim IISSchema As New System.DirectoryServices.DirectoryEntry("IIS://" & WebSite & "/Schema/AppIsolated") Dim CanCreate As Boolean = Not IISSchema.Properties("Syntax").Value.ToString.ToUpper() = "BOOLEAN" IISSchema.Dispose() If CanCreate Then Dim PathCreated As Boolean Try Dim IISAdmin As New System.DirectoryServices.DirectoryEntry("IIS://" & WebSite & "/W3SVC/1/Root") 'make sure folder exists If Not System.IO.Directory.Exists(Path) Then System.IO.Directory.CreateDirectory(Path) PathCreated = True End If 'If the virtual directory already exists then delete it For Each VD As System.DirectoryServices.DirectoryEntry In IISAdmin.Children If VD.Name = AppName Then IISAdmin.Invoke("Delete", New String() {VD.SchemaClassName, AppName}) IISAdmin.CommitChanges() Exit For End If Next VD 'Create and setup new virtual directory Dim VDir As System.DirectoryServices.DirectoryEntry = IISAdmin.Children.Add(AppName, "IIsWebVirtualDir") VDir.Properties("Path").Item(0) = Path If IsApplication Then VDir.Properties("AppFriendlyName").Item(0) = AppName End If VDir.Properties("EnableDirBrowsing").Item(0) = False VDir.Properties("AccessRead").Item(0) = True VDir.Properties("AccessExecute").Item(0) = False VDir.Properties("AccessWrite").Item(0) = IsWrite VDir.Properties("AccessScript").Item(0) = RunScripts VDir.Properties("AuthNTLM").Item(0) = True VDir.Properties("EnableDefaultDoc").Item(0) = True VDir.Properties("DefaultDoc").Item(0) = "default.htm,default.aspx,default.asp" VDir.Properties("AspEnableParentPaths").Item(0) = True 'VDir.Properties("AppCreate").Item(0) = False VDir.CommitChanges() 'the following are acceptable params 'INPROC = 0 'OUTPROC = 1 'POOLED = 2 If IsApplication Then VDir.Invoke("AppCreate", 1) Else VDir.Invoke("AppCreate", False) End If Catch Ex As Exception If PathCreated Then System.IO.Directory.Delete(Path) End If 'MsgBox(Ex.Message) End Try End If End Sub

    Read the article

  • WPF custom BalloonTips problem with multithreading

    - by Erika
    Hi, I have read other related question but i cant really get them to relate to this so I thought it were best to ask, Im pretty new to WPF and so on so please bear with me. I am using this http://www.codeproject.com/KB/WPF/wpf_notifyicon.aspx api to work with custom WPF Windows (in particular FancyBalloon). However, i'm coming across the following problem, I seem unable to start off BalloonTips in a separate thread ( i need this because i'm parsing emails and hence if there are 3 emails for instance, it displays the first email (that works fine), but when it comes to the second email it crashes with a TargetInvocationException , {"Specified element is already the logical child of another element. Disconnect it first."}. Thing is, im supposedly working with the same instance and i have attempted calling it to close it before, disposing it etc but to no avail. (then again if i dispose it, i cant create another instance as apparently WPF UI components must be called from a static thread so throughout the looping of emails + displaying balloon, i am trying to use the same BalloonTip. Any suggestions please? I am really at a loss here and i've been on it for quite a while now :/ I was wondering if there was anyone

    Read the article

  • Memory leak when using Workflow 4.0 SqlWorkflowInstanceStore and PersistableIdleAction.Unload

    - by Rohland
    Hi, This particular problem is driving me nuts. I wonder if anyone has experienced a similar problem. If I load up a workflow then unload it and perform a memory snapshot then the result is predictable - my workflow is no longer in memory. However, if I load up a workflow and set the PersistableIdle action to PersistableIdleAction.Unload and let the workflow idle the workflow remains in memory even though the Unload action fires. I used ANTS Memory Profiler to debug this issue. This is the object retention graph outputted showing that an internal object is hanging onto my workflow instance. Can anyone else verify this problem? My code amounts to the following: Create SqlWorkflowInstanceStore and setup lock owner handle -- At this point I take a memory snapshot Create an instance of Workflow1 Set the PersistableIdle action Apply the instancestore to Workflow1 Setup action event handlers for Idle, Unload, UnhandledException etc. Persist the workflow instance Run the workflow instance Wait for instance to idle (caused by Delay activity) Ensure the Unload action is fired -- At this point I take a second memory snapshot From the above image, it is clear that the only object referencing Workflow1 is some internal event handlers result which I have no ability to dispose of. Any clues?

    Read the article

  • MSMQ first Message.Body in queue is OK, all following Message.Body in queue are empty

    - by Andrew A
    I send a handful of identical (except for Id#, obviously) messages to an MSMQ queue on my local machine. The body of the messages is a serialized XElement object. When I try to process the first message in the queue, I am able to successfully de-serialize the Message.Body object and save it to file. However, when trying to process the next (or any subsequent) message, the Message.Body is absent, and an exception is thrown. I have verified the Message ID's are correct for the message attempting to be processed. The XML being serialized is properly formed. Any ideas? I am basing my code on the Microsoft MSMQ Book order sample found here: http://msdn.microsoft.com/en-us/library/ms180970%28VS.80%29.aspx // Create Envelope XML object XElement envelope = new XElement(env + "Envelope", new XAttribute(XNamespace.Xmlns + "env", env.NamespaceName) <snip> //Send envelope as message body MessageQueue myQueue = new MessageQueue(String.Format(@"FORMATNAME:DIRECT=OS:localhost\private$\mqsample")); myQueue.DefaultPropertiesToSend.Recoverable = true; // Prepare message Message myMessage = new Message(); myMessage.ResponseQueue = new MessageQueue(String.Format(System.Globalization.CultureInfo.InvariantCulture, @"FORMATNAME:DIRECT=TCP:192.168.1.217\private$\mqdemoAck")); myMessage.Body = envelope; // Send the message into the queue. myQueue.Send(myMessage,"message label"); //Retrieve messages from queue LabelIdMapping labelID = (LabelIdMapping)mqlistBox3.SelectedItem; System.Messaging.Message message = mqOrderQueue.ReceiveById(labelID.Id); The Message.Body value I see on the 1st retrieve is as expected: <?xml version="1.0" encoding="utf-8"?> <string>Some String</string> However, the 2nd and subsequent retrieve operations Message.Body is: "Cannot deserialize the message passed as an argument. Cannot recognize the serialization format." How does this work fine the first time but not after that? I have tried message.Dispose() after retrieving it but it did not help. Thank you very much for any help on this!

    Read the article

  • Problem with my whiteboard application

    - by swift
    I have to develop a whiteboard application in which both the local user and the remote user should be able to draw simultaneously, is this possible? If possible then any logic? I have already developed a code but in which i am not able to do this, when the remote user starts drawing the shape which i am drawing is being replaced by his shape and co-ordinates. This problem is only when both draw simultaneously. any idea guys? Here is my code class Paper extends JPanel implements MouseListener,MouseMotionListener,ActionListener { static BufferedImage image; int bpressed; Color color; Point start; Point end; Point mp; Button elipse=new Button("elipse"); Button rectangle=new Button("rect"); Button line=new Button("line"); Button empty=new Button(""); JButton save=new JButton("Save"); JButton erase=new JButton("Erase"); String selected; int ex,ey;//eraser DatagramSocket dataSocket; JButton button = new JButton("test"); Client client; Point p=new Point(); int w,h; public Paper(DatagramSocket dataSocket) { this.dataSocket=dataSocket; client=new Client(dataSocket); System.out.println("paper"); setBackground(Color.white); addMouseListener(this); addMouseMotionListener(this); color = Color.black; setBorder(BorderFactory.createLineBorder(Color.black)); //save.setPreferredSize(new Dimension(100,20)); save.setMaximumSize(new Dimension(75,27)); erase.setMaximumSize(new Dimension(75,27)); } public void paintComponent(Graphics g) { try { g.drawImage(image, 0, 0, this); Graphics2D g2 = (Graphics2D)g; g2.setPaint(Color.black); if(selected==("elipse")) g2.drawOval(start.x, start.y,(end.x-start.x),(end.y-start.y)); else if(selected==("rect")) g2.drawRect(start.x, start.y, (end.x-start.x),(end.y-start.y)); else if(selected==("line")) g2.drawLine(start.x,start.y,end.x,end.y); } catch(Exception e) {} } //Function to draw the shape on image public void draw() { Graphics2D g2 = image.createGraphics(); g2.setPaint(color); if(selected=="line") g2.drawLine(start.x, start.y, end.x, end.y); if(selected=="elipse") g2.drawOval(start.x, start.y, (end.x-start.x),(end.y-start.y)); if(selected=="rect") g2.drawRect(start.x, start.y, (end.x-start.x),(end.y-start.y)); repaint(); g2.dispose(); start=null; } //To add the point to the board which is broadcasted by the server public synchronized void addPoint(Point ps,String varname,String shape,String event) { try { if(end==null) end = new Point(); if(start==null) start = new Point(); if(shape.equals("elipse")) selected="elipse"; else if(shape.equals("line")) selected="line"; else if(shape.equals("rect")) selected="rect"; else if(shape.equals("erase")) { selected="erase"; erase(); } if(end!=null && start!=null) { if(varname.equals("end")) end=ps; if(varname.equals("mp")) mp=ps; if(varname.equals("start")) start=ps; if(event.equals("drag")) repaint(); else if(event.equals("release")) draw(); } } catch(Exception e) { e.printStackTrace(); } } //To set the size of the image public void setWidth(int x,int y) { System.out.println("("+x+","+y+")"); w=x; h=y; image = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB); Graphics2D g2 = image.createGraphics(); g2.setPaint(Color.white); g2.fillRect(0,0,w,h); g2.dispose(); } //Function which provides the erase functionality public void erase() { Graphics2D pic=(Graphics2D) image.getGraphics(); pic.setPaint(Color.white); pic.fillRect(start.x, start.y, 10, 10); } //Function to add buttons into the panel, calling this function returns a panel public JPanel addButtons() { JPanel buttonpanel=new JPanel(); JPanel row1=new JPanel(); JPanel row2=new JPanel(); JPanel row3=new JPanel(); JPanel row4=new JPanel(); buttonpanel.setPreferredSize(new Dimension(80,80)); //buttonpanel.setMinimumSize(new Dimension(150,150)); row1.setLayout(new BoxLayout(row1,BoxLayout.X_AXIS)); row1.setPreferredSize(new Dimension(150,150)); row2.setLayout(new BoxLayout(row2,BoxLayout.X_AXIS)); row3.setLayout(new BoxLayout(row3,BoxLayout.X_AXIS)); row4.setLayout(new BoxLayout(row4,BoxLayout.X_AXIS)); buttonpanel.setLayout(new BoxLayout(buttonpanel,BoxLayout.Y_AXIS)); elipse.addActionListener(this); rectangle.addActionListener(this); line.addActionListener( this); save.addActionListener( this); erase.addActionListener( this); buttonpanel.add(Box.createRigidArea(new Dimension(10,10))); row1.add(elipse); row1.add(Box.createRigidArea(new Dimension(5,0))); row1.add(rectangle); buttonpanel.add(row1); buttonpanel.add(Box.createRigidArea(new Dimension(10,10))); row2.add(line); row2.add(Box.createRigidArea(new Dimension(5,0))); row2.add(empty); buttonpanel.add(row2); buttonpanel.add(Box.createRigidArea(new Dimension(10,10))); row3.add(save); buttonpanel.add(row3); buttonpanel.add(Box.createRigidArea(new Dimension(10,10))); row4.add(erase); buttonpanel.add(row4); return buttonpanel; } //To save the image drawn public void save() { try { ByteArrayOutputStream bos = new ByteArrayOutputStream(); JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(bos); JFileChooser fc = new JFileChooser(); fc.showSaveDialog(this); encoder.encode(image); byte[] jpgData = bos.toByteArray(); FileOutputStream fos = new FileOutputStream(fc.getSelectedFile()+".jpeg"); fos.write(jpgData); fos.close(); //add replce confirmation here } catch (IOException e) { System.out.println(e); } } public void mouseClicked(MouseEvent arg0) { // TODO Auto-generated method stub } @Override public void mouseEntered(MouseEvent arg0) { } public void mouseExited(MouseEvent arg0) { // TODO Auto-generated method stub } public void mousePressed(MouseEvent e) { if(selected=="line"||selected=="erase") { start=e.getPoint(); client.broadcast(start,"start", selected,"press"); } else if(selected=="elipse"||selected=="rect") { mp = e.getPoint(); client.broadcast(mp,"mp", selected,"press"); } } public void mouseReleased(MouseEvent e) { if(start!=null) { if(selected=="line") { end=e.getPoint(); client.broadcast(end,"end", selected,"release"); } else if(selected=="elipse"||selected=="rect") { end.x = Math.max(mp.x,e.getX()); end.y = Math.max(mp.y,e.getY()); client.broadcast(end,"end", selected,"release"); } draw(); } //start=null; } public void mouseDragged(MouseEvent e) { if(end==null) end = new Point(); if(start==null) start = new Point(); if(selected=="line") { end=e.getPoint(); client.broadcast(end,"end", selected,"drag"); } else if(selected=="erase") { start=e.getPoint(); erase(); client.broadcast(start,"start", selected,"drag"); } else if(selected=="elipse"||selected=="rect") { start.x = Math.min(mp.x,e.getX()); start.y = Math.min(mp.y,e.getY()); end.x = Math.max(mp.x,e.getX()); end.y = Math.max(mp.y,e.getY()); client.broadcast(start,"start", selected,"drag"); client.broadcast(end,"end", selected,"drag"); } repaint(); } @Override public void mouseMoved(MouseEvent arg0) { // TODO Auto-generated method stub } public void actionPerformed(ActionEvent e) { if(e.getSource()==elipse) selected="elipse"; if(e.getSource()==line) selected="line"; if(e.getSource()==rectangle) selected="rect"; if(e.getSource()==save) save(); if(e.getSource()==erase) { selected="erase"; erase(); } } } class Button extends JButton { String name; public Button(String name) { this.name=name; Dimension buttonSize = new Dimension(35,35); setMaximumSize(buttonSize); } public void paintComponent(Graphics g) { super.paintComponent(g); Graphics2D g2 = (Graphics2D)g; g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); //g2.setStroke(new BasicStroke(1.2f)); if (name == "line") g.drawLine(5,5,30,30); if (name == "elipse") g.drawOval(5,7,25,20); if (name== "rect") g.drawRect(5,5,25,23); } }

    Read the article

  • wcf configuration for this code

    - by user208081
    I have the following code and would like to convert a lot of code into configuration settings for WCF. As you can see, the code is using wshttpbinding. I appreciate any help on this. try { // Provides a unique network address that a client uses to communicate with a service endpoint. EndpointAddress endpointAddress = new EndpointAddress(new Uri(FAXServiceSettings.Default.FAXReceiveServiceURL)); // Specify the protocols, transports, and message encoders used for communication between the client and the service. // WSHttpBinding represents an interoperable binding that supports distributed transactions and secure, reliable sessions. // Spefically, SOAP message security is enabled for secure transmission of the message content. WSHttpBinding clientBinding = new WSHttpBinding(SecurityMode.Message); clientBinding.OpenTimeout = TimeSpan.FromSeconds(FAXServiceSettings.Default.FAXReceiveServiceOpenTimeoutInSeconds); clientBinding.SendTimeout = TimeSpan.FromSeconds(FAXServiceSettings.Default.FAXReceiveServiceOpenTimeoutInSeconds); // Use the ChannelFactory to enable the creation of channels to the binding and endpoint. using (ChannelFactory<IReceiveFAX> channelFactory = new ChannelFactory<IReceiveFAX>(clientBinding, endpointAddress)) { // Creates a channel of a specified type to a specified endpoint address. IReceiveFAX channel = channelFactory.CreateChannel(); if (channel != null) { try { // Submit the FaxSchedule instance for routing. channel.SubmitFAXForRouting(CreateNewFaxScheduleContainerInstance()); // Explicitly close the channel using the IClientChannel interface. CloseChannel((channel as IClientChannel)); } finally { // Explicitly dispose of the channel using IDisposable interface. DisposeOfChannel((channel as IDisposable)); channel = null; } } // This method causes a CommunicationObject to gracefully transition from any state, other than the Closed state, into the Closed state. The Close method allows any // unfinished work to be completed before returning. For example, finish sending any buffered messages. channelFactory.Close(); } } catch { throw; } Pratik

    Read the article

< Previous Page | 23 24 25 26 27 28 29 30 31 32 33 34  | Next Page >