Search Results

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

Page 11/39 | < Previous Page | 7 8 9 10 11 12 13 14 15 16 17 18  | Next Page >

  • How to retrieve a binary file from .NET assembly?

    - by Rahul Soni
    I have an excel file that I want to embed in my C# assembly. I have changed the build action of the XLSX file to "Embedded Resource". During runtime, I have to retrieve this XLSX file from the assembly. Assembly assembly = Assembly.GetExecutingAssembly(); StreamReader sr = new StreamReader(assembly.GetManifestResourceStream("AssemblyName.Output.xlsx"), true); StreamWriter sw = new StreamWriter(strPath); sw.Write(sr.ReadToEnd()); sr.Dispose(); sw.Dispose(); System.Diagnostics.Process.Start(strPath); As expected, this fails for the XLSX file since it is a binary data. This could works well with a text file. I tried binary read/write, but I am not able to get the code running. Thoughts?

    Read the article

  • .NET and Closing SQL Server connections

    - by user307076
    I am having a hard time figuring out why the following constructor will not close connnections. When I view the active connections. Here is the code that I have. Public Sub New(ByVal UserID As Integer) Dim oConn As New SqlConnection(ConfigurationManager.ConnectionStrings("connStr").ToString()) Dim cmd As New SqlCommand("stored proc", oConn) Dim sdr As SqlDataReader cmd.CommandType = CommandType.StoredProcedure cmd.Parameters.AddWithValue("@userID", UserID) oConn.Open() sdr = cmd.ExecuteReader() Try If Not sdr.HasRows Then sdr.Close() If Not oConn Is Nothing Then If oConn.State <> ConnectionState.Closed Then oConn.Close() End If End If cmd.Dispose() Exit Sub End If 'User has account in WATS, proceed to load account information While sdr.Read _firstname = Convert.ToString(sdr("First Name")) _lastname = Convert.ToString(sdr("Last Name")) End While Catch ex As Exception 'Throw New Exception("User Error: " + ex.Message) Finally sdr.Close() If Not oConn Is Nothing Then If oConn.State <> ConnectionState.Closed Then oConn.Close() End If End If cmd.Dispose() End Try End Sub

    Read the article

  • IDisposable: is it necessary to check for null on finally {}?

    - by BlackTigerX
    In most examples that you find on the web when explicitly not using "using", the pattern looks something like: SqlConnection c = new SqlConnection(@"..."); try { c.Open(); ... } finally { if (c != null) //<== check for null c.Dispose(); } If you do use "using" and look at the generated IL code, you can see that it generates the check for null L_0024: ldloc.1 L_0025: ldnull L_0026: ceq L_0028: stloc.s CS$4$0000 L_002a: ldloc.s CS$4$0000 L_002c: brtrue.s L_0035 L_002e: ldloc.1 L_002f: callvirt instance void [mscorlib]System.IDisposable::Dispose() L_0034: nop L_0035: endfinally I understand why the IL gets translated to check for null (doesn't know what you did inside the using block), but if you're using try..finally and you have full control of how the IDisposable object gets used inside the try..finally block, do you really need to check for null? if so, why?

    Read the article

  • .NET and Closing MSSQL connections

    - by user307076
    I am having a hard time figuring out why the following constructor will not close connnections. When I view the active connections. Here is the code that I have. Public Sub New(ByVal UserID As Integer) Dim oConn As New SqlConnection(ConfigurationManager.ConnectionStrings("connStr").ToString()) Dim cmd As New SqlCommand("stored proc", oConn) Dim sdr As SqlDataReader cmd.CommandType = CommandType.StoredProcedure cmd.Parameters.AddWithValue("@userID", UserID) oConn.Open() sdr = cmd.ExecuteReader() Try If Not sdr.HasRows Then sdr.Close() If Not oConn Is Nothing Then If oConn.State <> ConnectionState.Closed Then oConn.Close() End If End If cmd.Dispose() Exit Sub End If 'User has account in WATS, proceed to load account information While sdr.Read _firstname = Convert.ToString(sdr("First Name")) _lastname = Convert.ToString(sdr("Last Name")) End While Catch ex As Exception 'Throw New Exception("User Error: " + ex.Message) Finally sdr.Close() If Not oConn Is Nothing Then If oConn.State <> ConnectionState.Closed Then oConn.Close() End If End If cmd.Dispose() End Try End Sub

    Read the article

  • How does "Require SSL" affect ASP.NET MVC application lifecycle?

    - by Ragesh
    I have an application that taps into BeginRequest and EndRequest to set up and tear down NHibernate sessions like this: BeginRequest += delegate { CurrentSessionContext.Bind(SessionFactory.OpenSession()); }; EndRequest += delegate { var session = CurrentSessionContext.Unbind(SessionFactory); session.Dispose(); Container.Release(session); }; This works fine when deployed in IIS, until I check the "Require SSL" box. Once I do this, I get a NullReferenceException at session.Dispose(). I haven't debugged this yet and, yes, the fix is trivial, but I'm just curious about how "Require SSL" affects the lifecycle of a request. Is a session not set up on the server in these cases?

    Read the article

  • how to find maximum frequent item sets from large transactional data file

    - by ANIL MANE
    Hi, I have the input file contains large amount of transactions like Transaction ID Items T1 Bread, milk, coffee, juice T2 Juice, milk, coffee T3 Bread, juice T4 Coffee, milk T5 Bread, Milk T6 Coffee, Bread T7 Coffee, Bread, Juice T8 Bread, Milk, Juice T9 Milk, Bread, Coffee, T10 Bread T11 Milk T12 Milk, Coffee, Bread, Juice i want the occurrence of every unique item like Item Name Count Bread 9 Milk 8 Coffee 7 Juice 6 and from that i want an a fp-tree now by traversing this tree i want the maximal frequent itemsets as follows The basic idea of method is to dispose nodes in each “layer” from bottom to up. The concept of “layer” is different to the common concept of layer in a tree. Nodes in a “layer” mean the nodes correspond to the same item and be in a linked list from the “Head Table”. For nodes in a “layer” NBN method will be used to dispose the nodes from left to right along the linked list. To use NBN method, two extra fields will be added to each node in the ordered FP-Tree. The field tag of node N stores the information of whether N is maximal frequent itemset, and the field count’ stores the support count information in the nodes at left. In Figure, the first node to be disposed is “juice: 2”. If the min_sup is equal to or less than 2 then “bread, milk, coffee, juice” is a maximal frequent itemset. Firstly output juice:2 and set the field tag of “coffee:3” as “false” (the field tag of each node is “true” initially ). Next check whether the right four itemsets juice:1 be the subset of juice:2. If the itemset one node “juice:1” corresponding to is the subset of juice:2 set the field tag of the node “false”. In the following process when the field tag of the disposed node is FALSE we can omit the node after the same tagging. If the min_sup is more than 2 then check whether the right four juice:1 is the subset of juice:2. If the itemset one node “juice:1” corresponding to is the subset of juice:2 then set the field count’ of the node with the sum of the former count’ and 2 After all the nodes “juice” disposed ,begin to dispose the node “coffee:3”. Any suggestions or available source code, welcome. thanks in advance

    Read the article

  • Is this a correct way to host a WCF service?

    - by mafutrct
    For some testing code, I'd like to be able to host a WCF service in only a few lines. I figured I'd write a simple hosting class: public class WcfHost : IDisposable where Implementation : class where Contract : class { public readonly string Address = "net.tcp://localhost:8000/"; private ServiceHost _Host; public WcfHost () { _Host = new ServiceHost (typeof (Implementation)); var binding = new NetTcpBinding (); var address = new Uri (Address); _Host.AddServiceEndpoint ( typeof (Contract), binding, address); _Host.Open (); } public void Dispose () { ((IDisposable) _Host).Dispose (); } } That can be used like this: using (var host = new WcfHost<ImplementationClass, ContractClass> ()) { Is there anything wrong with this approach? Is there a flaw in the code (esp. about the disposing)?

    Read the article

  • How to free virtual memory ?

    - by Mehdi Amrollahi
    I have a crawler application (with C#) that downloads pages from web . The application take more virtual memory , even i dispose every object and even use GC.Collect() . This , have 10 thread and each thread has a socket that downloads pages . I use dispose method and even use GC.Collect() in my application , but in 3 hour my application take 500 MB on virtual memory (500 MB on private bytes in Process explorer) . Then my system will be hang and i should restart my pc . Is there any way that i use to free vitual memory ? Thanks .

    Read the article

  • Getting my string value from my form into my class( not another form)

    - by jovany
    Hello all, I have a question regarding the some data which is being transfered from one form to my class. It's not going quite the way i'd like to , so I figured maybe there is someone who could help me. This is my code in my class Public Class DrawableTextBox Inherits Drawable Dim i_testString As Integer Private s_InsertLabel As String Private drawFont As Font Public Sub New(ByVal fore_color As Color, ByVal fill_color As Color, Optional ByVal line_width As Integer = 0, Optional ByVal new_x1 As Integer = 0, Optional ByVal new_y1 As Integer = 0, Optional ByVal new_x2 As Integer = 1, Optional ByVal new_y2 As Integer = 1) MyBase.New(fore_color, fill_color, line_width) X1 = new_x1 Y1 = new_y1 X2 = new_x2 Y2 = new_y2 Trace.WriteLine(s_InsertLabel) End Sub Friend WriteOnly Property _textBox() As String Set(ByVal Value As String) s_InsertLabel = Value Trace.WriteLine(s_InsertLabel) End Set End Property ' Draw the object on this Graphics surface. Public Overrides Sub Draw(ByVal gr As System.Drawing.Graphics) ' Make a Rectangle representing this rectangle. Dim rect As Rectangle = GetBounds() ' Fill the rectangle as usual. Dim fill_brush As New SolidBrush(FillColor) gr.FillRectangle(fill_brush, rect) fill_brush.Dispose() ' See if we're selected. If IsSelected Then ' Draw the rectangle highlighted. Dim highlight_pen As New Pen(Color.Yellow, LineWidth) gr.DrawRectangle(highlight_pen, rect) highlight_pen.Dispose() ' Draw grab handles. Trace.WriteLine("drawing the lines for my textbox") DrawGrabHandle(gr, X1, Y1) DrawGrabHandle(gr, X1, Y2) DrawGrabHandle(gr, X2, Y2) DrawGrabHandle(gr, X2, Y1) Else 'TextBox() Dim fg_pen As New Pen(Color.Red, LineWidth) 'Dim fontSize As Single = 0.1 + ((Y2 - Y1) / 2) Dim fontSize As Single = 20 Try Dim drawFont As New Font("Arial", fontSize, FontStyle.Bold) Trace.WriteLine(s_InsertLabel) gr.DrawString(s_InsertLabel, drawFont, Brushes.Brown, X1, Y1) Catch ex As ArgumentException End Try gr.DrawRectangle(Pens.Azure, rect) ' gr.DrawRectangle(fg_pen, rect) fg_pen.Dispose() End If End Sub Public Function GetValueString(ByVal ValueType As String) Return ValueType End Function ' Return the object's bounding rectangle. Public Overrides Function GetBounds() As System.Drawing.Rectangle Return New Rectangle( _ Min(X1, X2), _ Min(Y1, Y2), _ Abs(100), _ Abs(30)) Trace.WriteLine("don't forget to make variables in GetBounds DrawableTextbox") End Function ' Return True if this point is on the object. Public Overrides Function IsAt(ByVal x As Integer, ByVal y As Integer) As Boolean Return (x >= Min(X1, X2)) AndAlso _ (x <= Max(X1, X2)) AndAlso _ (y >= Min(Y1, Y2)) AndAlso _ (y <= Max(Y1, Y2)) End Function ' Move the second point. Public Overrides Sub NewPoint(ByVal x As Integer, ByVal y As Integer) X2 = x Y2 = y End Sub ' Return True if the object is empty (e.g. a zero-length line). Public Overrides Function IsEmpty() As Boolean Return (X1 = X2) AndAlso (Y1 = Y2) End Function End Class I've got a form with a textbox( form1) in which the text is being inserted and passed through a buttonclick (al via properties). As you can see I've placed several traces and in the property of the class my trace works fine , however if I look in my Draw function it is already gone. And I get a blank trace. Does anyone know what's happening here. thanks in advance. (forgive me I'm new )

    Read the article

  • VB.NET, make a function with return type generic ?

    - by Quandary
    Currently I have written a function to deserialize XML as seen below. How do I change it so I don't have to replace the type every time I want to serialize another object type ? The current object type is cToolConfig. How do I make this function generic ? Public Shared Function DeserializeFromXML(ByRef strFileNameAndPath As String) As XMLhandler.XMLserialization.cToolConfig Dim deserializer As New System.Xml.Serialization.XmlSerializer(GetType(cToolConfig)) Dim srEncodingReader As IO.StreamReader = New IO.StreamReader(strFileNameAndPath, System.Text.Encoding.UTF8) Dim ThisFacility As cToolConfig ThisFacility = DirectCast(deserializer.Deserialize(srEncodingReader), cToolConfig) srEncodingReader.Close() srEncodingReader.Dispose() Return ThisFacility End Function Public Shared Function DeserializeFromXML1(ByRef strFileNameAndPath As String) As System.Collections.Generic.List(Of XMLhandler.XMLserialization.cToolConfig) Dim deserializer As New System.Xml.Serialization.XmlSerializer(GetType(System.Collections.Generic.List(Of cToolConfig))) Dim srEncodingReader As IO.StreamReader = New IO.StreamReader(strFileNameAndPath, System.Text.Encoding.UTF8) Dim FacilityList As System.Collections.Generic.List(Of cToolConfig) FacilityList = DirectCast(deserializer.Deserialize(srEncodingReader), System.Collections.Generic.List(Of cToolConfig)) srEncodingReader.Close() srEncodingReader.Dispose() Return FacilityList End Function

    Read the article

  • returning a memoryStream as a string

    - by WeNeedAnswers
    What is wrong with this statement? return new ASCIIEncoding().GetString(memoryStream.ToArray()); I know about the Dispose pattern, have checked out the underlying memoryStream and seen that there is nothing really happening in the dispose. So why shouldn't I allow one of my developers to do this. The aim is to make the code succinct and not create references that are not required, Hopefully getting the Garbage Collector to kick in soon as. Its just niggling me, I feel that the memoryStream lets the party down, when compared to what the other streams do and why they implement the IDispose. Can someone please give me a good reason not to allow the code above. I got a gut feeing about the code not being right but need some back up. :)

    Read the article

  • Database Logon Error in crystal report

    - by yasar arafat
    am really very dumb as this problem is being answered so many times but eally its above my head. i dont have any idea about working with crystal reports or asp.net but due to some reason i have to work on it. after trying very hard i m able to design on crystal report connecting it with mysql database. now when i see in the crystalreport preview i am able to see the report and the data ![enter image description here][1] but when i try to run it on server it says database logon failed![enter image description here][2] now i really dont know what to do i am pasting my aspx and aspx.vb code here and please repley in english not computer language believe me i m super dumb enter code here aspx codes <%@ Page Title="" Language="VB" MasterPageFile="~/Master/Site.master"AutoEventWireup="false" CodeFile="ManHourCostExpenditure.aspx.vb" Inherits="ManHourCostExpenditure" %> <%@ Register assembly="CrystalDecisions.Web, Version=13.0.2000.0, Culture=neutral, PublicKeyToken=692fbea5521e1304" namespace="CrystalDecisions.Web" tagprefix="CR" %> <asp:Content ID="Content1" ContentPlaceHolderID="head" Runat="Server"> </asp:Content> <asp:Content ID="Content2" ContentPlaceHolderID="MainContent" Runat="Server"> <CR:CrystalReportViewer ID="CrystalReportViewer1" runat="server" AutoDataBind="True" EnableDatabaseLogonPrompt="False" EnableParameterPrompt="False" GroupTreeImagesFolderUrl="" Height="1202px" ReportSourceID="CrystalReportSource1" ToolbarImagesFolderUrl="" ToolPanelView="None" ToolPanelWidth="200px" Width="903px" BorderColor="#660033" BorderStyle="Solid" BorderWidth="1px" HasCrystalLogo="False" /> <CR:CrystalReportSource ID="CrystalReportSource1" runat="server"> <Report FileName="CrDiscProjManHoursActVsEst.rpt"> </Report> </CR:CrystalReportSource> </asp:Content> aspxdotvb codes Imports CrystalDecisions.CrystalReports.Engine Imports CrystalDecisions.Shared Imports CrystalDecisions.Enterprise Imports CrystalDecisions.ReportSource Imports CrystalDecisions.Web Imports CrystalDecisions.Windows.Forms Imports MySql Imports MySql.Data Imports MySql.Data.MySqlClient Imports System.Collections Imports System.Collections.Generic Imports System.Text Imports CrystalDecisions Imports CrystalDecisions.CrystalReports Imports CrystalReportsReportDefModelLib Partial Class ManHourCostExpenditure Inherits System.Web.UI.Page Dim CrRpt As New CrystalDecisions.CrystalReports.Engine.ReportDocument Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load Dim StrConn As String = "SERVER=localhost;DATABASE=fluor;UID=root; PWD=root;" Dim Conn As New MySqlConnection(StrConn) Conn.Open() Dim CrRpt As New CrystalDecisions.CrystalReports.Engine.ReportDocument 'Session.Add("REPORT_KEY", CrRpt) CrRpt.Load(Server.MapPath("CrManHourCostExpenditure.rpt")) CrRpt.PrintOptions.PaperOrientation = PaperOrientation.Landscape 'If IsPostBack Then ' CrRpt = CType(Session.Item("REPORT_KEY"), Group) ' CrystalReportViewer1.ReportSource = CrRpt 'End If CrystalReportViewer1.ReportSource = CrRpt 'CrystalReportViewer1.DataBind() CrystalReportViewer1.RefreshReport() Conn.Close() 'CrRpt.Close() 'CrRpt.Dispose() End Sub Protected Sub Page_Unload(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Unload 'CrystalReportViewer1.ReportSource.Close() CrRpt.Close() CrRpt.Dispose() End Sub 'Protected Sub CrystalReportViewer1_Unload(ByVal sender As Object, ByVal e As System.EventArgs) Handles CrystalReportViewer1.Unload ' CrRpt.Close() ' CrRpt.Dispose() 'End Sub End Class please help me. thanks in advance.... yasir

    Read the article

  • C#, weird optimization

    - by Snake
    Hi, I'm trying to read my compiled C# code. this is my code: using(OleDbCommand insertCommand = new OleDbCommand("...", connection)) { // do super stuff } But! We all know that a using gets translated to this: { OleDbCommand insertCommand = new OleDbCommand("...", connection) try { //do super stuff } finally { if(insertCommand != null) ((IDisposable)insertCommand).Dispose(); } } (since OleDbCommand is a reference type). But when I decompile my assembly (compiled with .NET 2.0) I get this in Resharper: try { insertCommand = new OleDbCommand("", connection); Label_0017: try { //do super stuff } finally { Label_0111: if ((insertCommand == null) != null) { goto Label_0122; } insertCommand.Dispose(); Label_0122:; } I'm talking about this line: if ((insertCommand == null) != null). True is not null, it never is, nor is false. So how is my object disposed properly? WTF? Thanks! -Kristof

    Read the article

  • How to determine whether a .NET exception is being handled?

    - by romkyns
    We're investigating a coding pattern in C# in which we'd like to use a "using" clause with a special class, whose Dispose() method does different things depending on whether the "using" body was exited normally or with an exception. To the best of my understanding, the CLR keeps track of the current exception being handled until it's been consumed by a "catch" handler. However it's not entirely clear whether this information is exposed in any way for the code to access. Do you know whether it is, and if so, how to access it? For example: using (var x = new MyObject()) { x.DoSomething(); x.DoMoreThings(); } class MyObject : IDisposable { public void Dispose() { if (ExceptionIsBeingHandled) Rollback(); else Commit(); } } This looks almost like System.Transactions.TransactionScope, except that success/failure is not determined by a call to x.Complete(), but rather based on whether the using body was exited normally.

    Read the article

  • extend web server to serve static files

    - by Turtle
    Hello, I want to extend a web server which is only able to handle RPC handling now. The web server is written in C#. It provides a abstract handler function like following: public string owsHandler(string request, string path, string param, OSHttpRequest httpRequest, OSHttpResponse httpResponse) And I wrote following code to handle image files: Bitmap queryImg = new Bitmap(path); System.IO.MemoryStream stream = new System.IO.MemoryStream(); queryImg.Save(stream, System.Drawing.Imaging.ImageFormat.Bmp); queryImg.Dispose(); byte[] byteImage = stream.ToArray(); stream.Dispose(); return Convert.ToBase64String(byteImage); And I test it in the browser, the image is returned but the image dimension info is missed. Shall I add something more to the code? Or is any general way to server static files? I do not want to serve it in a ASP.net server. Thanks

    Read the article

  • Can't Use Generic C# Class in Using Statement

    - by Eric J.
    I'm trying to use a generic class in a using statement but the compiler can't seem to treat it as implementing IDisposable. using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Data.Objects; namespace Sandbox { public sealed class UnitOfWorkScope<T> where T : ObjectContext, IDisposable, new() { public void Dispose() { } } public class MyObjectContext : ObjectContext, IDisposable { public MyObjectContext() : base("DummyConnectionString") { } #region IDisposable Members void IDisposable.Dispose() { throw new NotImplementedException(); } #endregion } public class Consumer { public void DoSomething() { using (new UnitOfWorkScope<MyObjectContext>()) { } } } } Compiler error is: Error 1 'Sandbox.UnitOfWorkScope<Sandbox.MyObjectContext>': type used in a using statement must be implicitly convertible to 'System.IDisposable' I implemented IDisposable on UnitOfWorkScope (and to see if that was the problem, also on MyObjectContext). What am I missing?

    Read the article

  • Is it OK to pass SQLCommand as a parameter?

    - by TooFat
    I have a Business Layer that passes a Conn string and a SQLCommand to a Data Layer like so public void PopulateLocalData() { System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand(); cmd.CommandType = System.Data.CommandType.StoredProcedure; cmd.CommandText = "usp_PopulateServiceSurveyLocal"; DataLayer.DataProvider.ExecSQL(ConnString, cmd); } The DataLayer then just executes the sql like so public static int ExecSQL(string sqlConnString, System.Data.SqlClient.SqlCommand cmd) { int rowsAffected; using (SqlConnection conn = new SqlConnection(sqlConnString)) { conn.Open(); cmd.Connection = conn; rowsAffected = cmd.ExecuteNonQuery(); cmd.Dispose(); } return rowsAffected; } Is it OK for me to pass the SQLCommand as a parameter like this or is there a better more accepted way of doing it. One of my concerns is if an error occurs when executing the query the cmd.dispose line will never execute. Does that mean it will continue to use up memory that will never be released?

    Read the article

  • Sharepoint: How to obtain the current site/web/list properly

    - by driAn
    Hi all What is the best way to obtain the current site/web/list ? Option 1 - Reusing existing objects SPSite site = SPContext.Current.Site; SPweb web = SPContext.Current.Web; SPList list = SPContext.Current.List; Option 2 - Creating new objects SPSite site = new SPSite(SPContext.Current.Site.ID); // dispose me SPweb web = site.OpenWeb(SPContext.Current.Web.ID); // dispose me SPList list = web.Lists[SPContext.Current.List.ID]; I experienced problems when using option 1 in some situations. Since then I chose the 2nd option and it worked fine so far. What is your opinion on this? I is generally better to go with option 2? Other suggestions?

    Read the article

  • How can i return dataset perfectly from sql?

    - by Phsika
    i try to write a winform application: i dislike below codes: DataTable dt = new DataTable(); dt.Load(dr); ds = new DataSet(); ds.Tables.Add(dt); Above part of codes looks unsufficient.How can i best loading dataset? public class LoadDataset { public DataSet GetAllData(string sp) { return LoadSQL(sp); } private DataSet LoadSQL(string sp) { SqlConnection con = new SqlConnection(ConfigurationSettings.AppSettings["ConnectionString"].ToString()); SqlCommand cmd = new SqlCommand(sp, con); DataSet ds; try { con.Open(); cmd.CommandType = CommandType.StoredProcedure; SqlDataReader dr = cmd.ExecuteReader(); DataTable dt = new DataTable(); dt.Load(dr); ds = new DataSet(); ds.Tables.Add(dt); return ds; } finally { con.Dispose(); cmd.Dispose(); } } }

    Read the article

  • The ultimate .NET file and directory utility library?

    - by Serge van den Oever
    I find myself writing file and directory utility functions all the time, and I was wondering if there is good file and directory library that already implements a more extensive set than available by default in System.IO. The kind of functions I'm looking for is things like: public static void GetTemporaryDirectory() { string tempDirectory = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName()); Directory.CreateDirectory(tempDirectory); return tempDirectory; } public static void CreateEmptyFile(string filename) { File.Create(filename).Dispose(); } public static void CreateEmptyFile(string path, string filename) { File.Create(Path.Combine(path, filename)).Dispose(); } public static void CreateDirectory(string path) { Directory.CreateDirectory(path); } public static void CreateDirectory(string path, string childpath) { Directory.CreateDirectory(Path.Combine(path, childpath)); }

    Read the article

  • Can't draw to a pictureBox in a loop

    - by Jason94
    I have a List<Point> where Point contains X and Y. What i want is to loop a list like that and draw a line point to point, i do so by: foreach (List<Point> wps in map.waypoints) { System.Drawing.Pen myPen; myPen = new System.Drawing.Pen(System.Drawing.Color.Black); System.Drawing.Graphics formGraphics = this.pictureBox1.CreateGraphics(); Point startPos = new Point(wps[0].X, wps[0].Y); foreach (Point p in wps) { formGraphics.DrawLine(myPen, startPos.X, startPos.Y, p.X, p.Y); startPos = p; } myPen.Dispose(); formGraphics.Dispose(); } BUT nothing gets drawn! I did the same with the on_click event to the pictureBox but instead if a looping some Points ive just used mouse X and Y. I have verified the lists of points that they dont contain rubish :D

    Read the article

  • wcf possible to override the dipose of proxy

    - by pdiddy
    I'd like to override the Dispose method of generated proxy (ClientBase) because of the fact that disposing of a proxy calls Close and can throw an exception when the channel is faulted. The only way I came up was to create a partial class to my generatedproxy, make it inherit from IDisposable. : public partial class MyServiceProxy : IDisposable { #region IDisposable Members public void Dispose() { if (State != System.ServiceModel.CommunicationState.Faulted) Close(); else Abort(); } #endregion } I did some test and my Dipose method is indeed called. Do you see any issue with this strategy? Also, I don't like the fact that I'll have to create this partial class for every generated proxy. It be nice if I was able to make my proxy inherit from a base class...

    Read the article

  • C# + Disposing DbConnection and DbCommand and catching error

    - by Eatdoku
    Hi, I am trying to understand DbConnection and DbCommand, and the proper way to dispose those objects after use. Following is the code snippet I have. By using "using statement" on DbConnection and DbCommand, would it be sufficient? I am trying to prevent possible memory leak. 2nd question, Do I have to Dispose DbCommand object? thanks a lot DbProviderFactory fac = DbProviderFactories.GetFactory(this.DatabaseProviderName); using (DbConnection dbConn = fac.CreateConnection()) { dbConn.ConnectionString = this.ConnectionString; using (DbCommand comm = fac.CreateCommand()) { comm.CommandText = "select * from aTable"; comm.Connection = dbConn; DataTable targetTable = new DataTable(); DbDataAdapter facDA = fac.CreateDataAdapter(); facDA.SelectCommand = comm; facDA.Fill(targetTable); //assuming Adapter would open / close connection (right assumption?) //do something with the datatable } }

    Read the article

  • Why is this simple Mobile Form not closed when using the player

    - by ajhvdb
    Hi, I created this simple sample Form with the close button. Everything is working as expected when NOT using the Interop.WMPLib.dll I've seen other applications using this without problems but why isn't the Form process closed when I just add the line: SoundPlayer myPlayer = new SoundPlayer(); and of course dispose it: if (myPlayer != null) { myPlayer.Dispose(); myPlayer = null; } The Form closes but the debugger VS2008 is still active. The Form project and the dll are still active. If you send me an email to [email protected], I can send you the zipped project. Below is the class for the dll: using System; using System.Collections.Generic; using System.Text; using System.Threading; using System.Runtime.InteropServices; using WMPLib; namespace WindowsMobile.Utilities { public delegate void SoundPlayerStateChanged(SoundPlayer sender, SoundPlayerState newState); public enum SoundPlayerState { Stopped, Playing, Paused, } public class SoundPlayer : IDisposable { [DllImport("coredll")] public extern static int waveOutSetVolume(int hwo, uint dwVolume); [DllImport("coredll")] public extern static int waveOutGetVolume(int hwo, out uint dwVolume); WindowsMediaPlayer myPlayer = new WindowsMediaPlayer(); public SoundPlayer() { myPlayer.uiMode = "invisible"; myPlayer.settings.volume = 100; } string mySoundLocation = string.Empty; public string SoundLocation { get { return mySoundLocation; } set { mySoundLocation = value; } } public void Pause() { myPlayer.controls.pause(); } public void PlayLooping() { Stop(); myPlayer.URL = mySoundLocation; myPlayer.settings.setMode("loop", true); } public int Volume { get { return myPlayer.settings.volume; } set { myPlayer.settings.volume = value; } } public void Play() { Stop(); myPlayer.URL = mySoundLocation; myPlayer.controls.play(); } public void Stop() { myPlayer.controls.stop(); myPlayer.close(); } #region IDisposable Members public void Dispose() { try { Stop(); } catch (Exception) { } // need this otherwise the process won't exit?! try { int ret = Marshal.FinalReleaseComObject(myPlayer); } catch (Exception) { } myPlayer = null; GC.Collect(); } #endregion } }

    Read the article

  • check if directory exists c#

    - by Ant
    I am trying to see if a directory exists based on an input field from the user. When the user types in the path, I want to check if the path actually exists. I have some c# code already. It returns 1 for any local path, but always returns 0 when I am checking a network path. static string checkValidPath(string path) { //Insert your code that runs under the security context of the authenticating user here. using (ImpersonateUser user = new ImpersonateUser(user, "", password)) { //DirectoryInfo d = new DirectoryInfo(quotelessPath); bool doesExist = Directory.Exists(path); //if (d.Exists) if(doesExist) { user.Dispose(); return "1"; } else { user.Dispose(); return "0"; } } } public class ImpersonateUser : IDisposable { [DllImport("advapi32.dll", SetLastError = true)] private static extern bool LogonUser(string lpszUsername, string lpszDomain, string lpszPassword, int dwLogonType, int dwLogonProvider, out IntPtr phToken); [DllImport("kernel32", SetLastError = true)] private static extern bool CloseHandle(IntPtr hObject); private IntPtr userHandle = IntPtr.Zero; private WindowsImpersonationContext impersonationContext; public ImpersonateUser(string user, string domain, string password) { if (!string.IsNullOrEmpty(user)) { // Call LogonUser to get a token for the user bool loggedOn = LogonUser(user, domain, password, 9 /*(int)LogonType.LOGON32_LOGON_NEW_CREDENTIALS*/, 3 /*(int)LogonProvider.LOGON32_PROVIDER_WINNT50*/, out userHandle); if (!loggedOn) throw new Win32Exception(Marshal.GetLastWin32Error()); // Begin impersonating the user impersonationContext = WindowsIdentity.Impersonate(userHandle); } } public void Dispose() { if (userHandle != IntPtr.Zero) CloseHandle(userHandle); if (impersonationContext != null) impersonationContext.Undo(); } } Any help is appreciated. Thanks! EDIT 3: updated code to use BrokenGlass's impersonation functions. However, I need to initialize "password" to something... EDIT 2: I updated the code to try and use impersonation as suggested below. It still fails everytime. I assume I am using impersonation improperly... EDIT: As requested by ChrisF, here is the function that calls the checkValidPath function. Frontend aspx file... $.get('processor.ashx', { a: '7', path: x }, function(o) { alert(o); if (o=="0") { $("#outputPathDivValid").dialog({ title: 'Output Path is not valid! Please enter a path that exists!', width: 500, modal: true, resizable: false, buttons: { 'Close': function() { $(this).dialog('close'); } } }); } }); Backend ashx file... public void ProcessRequest (HttpContext context) { context.Response.Cache.SetExpires(DateTime.Now); string sSid = context.Request["sid"]; switch (context.Request["a"]) {//a bunch of case statements here... case "7": context.Response.Write(checkValidPath(context.Request["path"].ToString())); break;

    Read the article

< Previous Page | 7 8 9 10 11 12 13 14 15 16 17 18  | Next Page >