1. My open source project

    Date: 01/07/13     Keywords: google

    Hello.

    I want to share with you my open source project.

    The purpose of my project is to demonstrate my visual filter builder WPF control in use. FilesFilter application allows you to filter your files by many parameters applying filtering expressions. Essentially my WPF user control builds LINQ binary tree lambda expressions to select a subset of items from a list. In terms of C sharp code it can be applied to lists of elements of any given classes. If you need such a filtering expression builder, you're welcome to use my component in your projects. Any changes and improvements would be also very much appreciated.

    Please, take a look at this:
    https://code.google.com/p/filesfilter/

    I think you may find it useful and interesting.

    Source: http://csharp.livejournal.com/108985.html

  2. Any DBAs in the New York area looking for work?

    Date: 07/12/11     Keywords: sql, web

    http://jobsattmp.com/new-york/web-development/dba-sql-server-2005_2008-jobs

    Hey all, I am trying to hire a DBA in NYC that has a background in MS SQL Server 2005/2008. If you're interested or know someone who might be please pass their resume along via the link above. Thanks!

    Source: http://csharp.livejournal.com/108669.html

  3. .Net custom control help

    Date: 02/23/11     Keywords: asp, java, seo, google

    I want to use a SEO friendly link button on my page. Mind you i am sure that the page is really not all that accessible as the page I am linking to will still have javascript running on it - but thats besides the point. The correct way to do this would be to put the href thats generated by a link button into the onclick event and return void or false or whatever. And then have a SEO / accessibility friendly URL in the HREF. This seems to be what Google recommends and t seems to make sense to me.

    I found this nifty .CS file here - http://files.codes-sources.com/fichier.aspx?id=44402&f=CrawlableLinkButton.cs. Essentially it inherits a linkbutton and adds a NavigateUrl parameter to it so that I can put whatever href I want in there. Awesome. Just what I was looking for.

    Trouble is I have no idea how to include it in my code. I feel ashamed for admitting my ignorance here. I can register a control at the top of the page, but I think I need to either use a .dll (like I do with things like the AjaxToolKit) and then reference the assembly name and the namespace. Or I can register an ascx control, and set the tagname and the src. How do I reference this .cs file in the aspx page the way this dude does? I feel like I am missing something so obvious.

    For example:
    <%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="asp" %>

    And:
    <%@ Register TagPrefix="uc1" TagName="videocontrol" src="~/controls/videocontrol.ascx" %>

    Assume for the moment I have the file stored in ~/controls/CrawlableLinkButton.cs, and I want to refer to his control as he does:
    ' />

    Any help here? I am a bit thick and getting more and more tired. I know deep down I am a good .Net developer, honest - so why can I not figure out the little things?

    Source: http://csharp.livejournal.com/108052.html

  4. Socket Programming

    Date: 02/09/11     Keywords: asp, web, microsoft

    Hi,

    I have created a socket connection as described on MDSN web site:
    client: http://msdn.microsoft.com/en-us/library/bew39x2a(v=VS.85).aspx
    server: http://msdn.microsoft.com/en-us/library/fx6588te(v=VS.85).aspx

    It works fine. Events here are:
    1) Client sends request
    2) Server receives it
    3) Server sends response
    4) Server shutdown the socket
    5) Client receives response

    Then, I know, that between 2) an 3) might be a time gap. I want to send few interim responses like:
    2a) Server sends response: Still working on your request.
    The problem here is that I cannot send a response without shutting down the socket, but as I shout it down I am not able to send neither 3) nor another 2a)

    Is it possible for client to get response without closing the socket connection? Something like .flush()?


    corresponding piece of code:

    ...
       public class MathTask {
          public string inputData;
          public int MaxTryCount;
          public int DelayBetweenNotificationsSec;
          public bool complete = false;
          public MathTask(string _data, int _maxTry, int _delayBetweenNotifications) {
             inputData = _data;
             MaxTryCount = _maxTry;
             DelayBetweenNotificationsSec = _delayBetweenNotifications;
             complete = false;
          }
       }
    ...
    ...
          private static void Send(Socket handler, MathTask taskData)
          {
             // Convert the string data to byte data using ASCII encoding.
             byte[] byteData = Encoding.ASCII.GetBytes(taskData.inputData);
    
             if (taskData.complete || (taskData.MaxTryCount <= 0))
             { // final sending
                // Begin sending the data to the remote device.
                IAsyncResult res = handler.BeginSend(byteData, 0, byteData.Length, 0,
                    new AsyncCallback(SendCallback), handler);
    
             }
             else
             { // interim (notification) sending
                // Begin sending the data to the remote device.
                StateObject so = new StateObject();
                so.workSocket = handler;
                so.sb.Append(taskData.inputData);
                IAsyncResult res = handler.BeginSend(byteData, 0, byteData.Length, 0,
                    new AsyncCallback(SendInterimCallback), so);
             }
          }
    
          // after sending notification (task is running)
          private static void SendInterimCallback(IAsyncResult ar)
          {
             try
             {
                // Retrieve the socket from the state object.
                StateObject so = (StateObject)ar.AsyncState;
                int bytesSent = so.workSocket.EndSend(ar);
                
                Console.WriteLine("Sent {0} bytes to client.", bytesSent);
    
                // client receives response ONLY AFTER this statement
                so.workSocket.Shutdown(SocketShutdown.Both);
                so.workSocket.Close();
    
             }
             catch (Exception e)
             {
                Console.WriteLine(e.ToString());
             }
          }
    ...
    
    


    Thanks for response, the problem solved.

    That was not the server, but the client. Take a look at ReceiveCallback:
    private static void ReceiveCallback( IAsyncResult ar ) {
            try {
                // Retrieve the state object and the client socket 
                // from the asynchronous state object.
                StateObject state = (StateObject) ar.AsyncState;
                Socket client = state.workSocket;
    
                // Read data from the remote device.
                int bytesRead = client.EndReceive(ar);
    
                if (bytesRead > 0) {
                    // There might be more data, so store the data received so far.
                state.sb.Append(Encoding.ASCII.GetString(state.buffer,0,bytesRead));
    
                    // Get the rest of the data.
                    client.BeginReceive(state.buffer,0,StateObject.BufferSize,0,
                        new AsyncCallback(ReceiveCallback), state);
                } else {
                    // All the data has arrived; put it in response.
                    if (state.sb.Length > 1) {
                        response = state.sb.ToString();
                    }
                    // Signal that all bytes have been received.
                    receiveDone.Set();
                }
            } catch (Exception e) {
                Console.WriteLine(e.ToString());
            }
        }
    


    If client reads any bytesRead more than 0, it will store it in buffer and keep waiting for more data to come. Only when 0 bytes read it calls receiveDone.Set(); which finalize the receive process. Now I understand why it was working only after socket became closed.

    Source: http://csharp.livejournal.com/107817.html

  5. Marshaling a union with a pointer

    Date: 08/05/10     Keywords: linux

    I am using Mono on Linux, and want to marshal the following unmanaged structure to a native one:

    
    int 	type
    union {
       guint32   u
       gint32   i
       gboolean   b
       gdouble   d
       gchar *   s
    } 	value
    


    According to Mono's excellent page on native-library interop, the way to deal with unions is to use StructLayoutAttribute with LayoutKind.Explicit and specify a FieldOffsetAttribute that is the same for all union members. So you might do something similar to this:

    
    [StructLayout(LayoutKind.Explicit)]
    public struct Rpc {
     [FieldOffset(0)] public int type;
     [FieldOffset(4)] public uint value_u;
     [FieldOffset(4)] public int value_i;
     [FieldOffset(4)] public bool value_b;
     [FieldOffset(4)] public double value_d;
     [FieldOffset(4)] public string value_s;
    }
    


    The problem however is this, the Mono runtime crashes when this code is run, complaining that: "you cannot have a reference field that is the same offset as another field" in an [ExplicitLayout] structure. I assume this is referring to the last member of the union which is a pointer. Thing is, I'm not sure how else to do this.

    I thought about just having a "public object value;" member of the structure, and then casting this as appropriate in managed code, but the runtime apparently cannot marshal to a vanilla object this way.

    Thoughts?

    Source: http://csharp.livejournal.com/107180.html

  6. Help with Error Module

    Date: 07/07/10     Keywords: html, asp, web

    I posted my question here originally last night but I figured I might as well reach out to the LJ crowd to see if anyone here has answers.

    I implemented an error handling httpmodule similar to the one described here:

    http://wiki.asp.net/page.aspx/917/neater-handling-of-exceptions/

    If I run the application locally through the Visual Studio Development Server everything works as expected. If I run it through IIS with a wildcard mapping set up in the ISAPI extensions to go to the dotnet dll, and I have the checkbox to "Verify that the file exists" turned off - it works as expected for .aspx files but not for anything else.

    In my web.config I have the following:

        
          
          
        

        
          
        


    And under IIS errors I have it set up so that 404 errors go to the same 404 URL in web.config.

    The behavior I am expecting is that if I go to appliationname.com/xyz.html and the page does not exist, it is kicked into the error handling code. The error handling module is set up to log the event and I should get an email. And even failing that the 404 page should still load in IIS settings.

    The error handling code does kick in if I go to appliationname.com/xyz.aspx - a page which does not exist. But for any other file extension the 404 processing is handled by IIS. So any error logging I am doing in the HTTPModule is not getting called.

    When I run an HTML page it does get processed to some extent. The code I have in Application_BeginRequest in global.asax does get called. But at the end of that block it stops processing.

    The application I am working on is a migration of older code. I want to be alerted to every 404 that comes through the application so that I can see if we missed anything. I could potentially get this sort of information from the IIS logs or I could try to move the error logging to the code behind of the error pages instead of the HTTPModule. But I shouldn't have to should I? Why won't it process HTML? And why does it work when when running the application through Visual Studio but bot when I run it through IIS?

    Any help would be appreciated.

    Source: http://csharp.livejournal.com/106895.html

  7. Graphics.DrawString

    Date: 04/14/10     Keywords: css, web, google

    I'm getting very frustrated with trying to generate text on images in .Net. Whilst the process to do so is pretty simple, the results one gets simply aren't that satisfactory.

    I have the following code (really very simple, as you can see) in an IHttpHandler, which I call in a loop to iterate through some of the fonts on my system as a proof-of-concept:

    /// Enables processing of HTTP Web requests. /// /// An T:System.Web.HttpContext"/> object that provides references to the /// intrinsic server objects (for example, Request, Response, Session, and Server) /// used to service HTTP requests. /// /// /// Looks for a HttpRequest.QueryString"/> item named font and /// renders a 100×30px image of that font name, in that font. /// /// ArgumentNullException"> /// No querystring element font was found. ///
    public void ProcessRequest(HttpContext context) { context.Response.ContentType = "image/png"; string fontName = context.Request.QueryString["font"]; Image img = new Bitmap(Width, Height); using (Graphics graphic = Graphics.FromImage(img)) { graphic.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality; graphic.DrawString( fontName, new Font(fontName, FontSize), new SolidBrush(Color.Black), new PointF(0, 0) ); } img.Save(context.Response.OutputStream, System.Drawing.Imaging.ImageFormat.Png); }

    So far so good. It does almost exactly what I'd expect it to. But the images it generates are, frankly, shit. The following image is a screengrab of me running this locally (in Google Chrome, not that that matters), with the images on the left and the font name on the right (using CSS to cause it to be in the same size and font as the image):

    Screengrab of results

    So why is GDI+ generating the text bolder (darker) than it should be. I understand that it won't necessarily be as beautiful as the ClearType-rendered text, but the weight of the font is just damn wrong!

    So how do I get GDI+ to play ball? Anyone?

    If you don't want to leave thoughts as a comment on here, feel free to email me (owen dot blacker at iris hyphen digital dot com). Cross-posted to owenblacker and ms_dot_net.

    Source: http://csharp.livejournal.com/106659.html

  8. Custom validator in a custom control

    Date: 01/21/10     Keywords: programming, java

    I am programming a control that will have a custom validator in it. The control will be called on a page inside a repeater. I was hoping to have client validation on this custom validator. If I do this, when the page is rendered, won't the javascript function names be repeated and won't that cause an error? Is there a way around this and does anyone have any example code I can look at?

    Source: http://csharp.livejournal.com/106272.html

  9. LINQ beginner

    Date: 12/12/09     Keywords: no keywords

    I have a pair of LINQ "group" statements, each outputs a IEnumerable>. Call these results a and b. I want to create four collections of ints, The ones that correspond to "a.Key && b.Key", "a.Key && !b.Key", "!a.Key && b.Key", "!a.Key && !b.Key".

    I can convert a and b to Dictionaries with the ToDictionary extension method and have code like...

    var foo = from aa in aMap[true] join bb in bMap[true] on aa equals bb select aa;

    ...but then I need to check the dictionary keys exists, which is not a huge overhead but I can't help thinking there must be some way of "join"ing a and b directly...?

    Source: http://csharp.livejournal.com/105845.html

  10. NMock2 question

    Date: 11/18/09     Keywords: no keywords

    Is it possible in NMock2 to expect one of two different methods, A() or B(), on a mock to be called?

    If there was a way to check how many times a given method had already been called, I could just

    Expect.Once.On.(myMock).Method("A");
    Expect.Once.On.(myMock).Method("B");
    test(myMock);

    ..and then test to see if one of them had been called and forcibly call the other so the expectations would be met. Ugly but good enough, but I don't think NMock2 mocks expose any interface that allows that the number of calls to be tested?

    Source: http://csharp.livejournal.com/105589.html

  11. Нужна помощь с DevExpress GridControl

    Date: 10/06/09     Keywords: no keywords

    Привет!
    Работал ли кто-нибудь с GridControl.AdvBandedGridView? Мне нужно, чтобы в band я мог поместить другой band на один уровень с column. А компонент позволяет в band'е держать или другие band'ы или column'ы, но не то и другое одновременно. Подскажите, как можно обойти это или же сделать визуальную симуляцию такого размещения band и column?

    Source: http://csharp.livejournal.com/105374.html

  12. Application stops owing to callback from unmanaged DLL

    Date: 09/16/09     Keywords: asp, microsoft

    Why does my c# application stop after receiving a callback from unmanaged DLL?

    I've just encountered this very strange problem. And wonder why it could happen.

    The similar situation is described by someone on MSDN-site.
    http://social.msdn.microsoft.com/Forums/en-US/clr/thread/25bd7c1d-373f-4ef7-a64b-a101897b6b9a/

    But nobody there brought a clear explanation of that yet.

    This little article described how to deal with callbacks from unmanaged code.
    http://www.codeproject.com/KB/cs/win32_to_net.aspx
    I think I did everything properly so that the program works well. But it doesn't.
    If necessary, I could share snippets of my code.

    Thank you.

    Source: http://csharp.livejournal.com/105163.html

  13. Beginner's "-=" question

    Date: 09/03/09     Keywords: java

    There are several ways to listen to an event with "+=". As a primarily-Java programmer I'm particulally drawn to the anonymous delegate. But if you want to subsequently remove the listener with -=, how can you identify the object? I guess it is not possible with the anonymous case, but even when you specify

    MyEvent += MyInstanceMethod

    a delegate for the MyInstanceMethod is being created... so will -= MyInstanceMethod remove the same object from the event's colection of listeners? Or do I have to create an explicit "new" instance of a delegate type, keep it on a field and "-=" the field?

    Source: http://csharp.livejournal.com/104768.html

  14. Application.Exit() not exiting!

    Date: 08/18/09     Keywords: no keywords

    I have the following:
                    if (userDlg.ShowDialog(this) == DialogResult.Cancel)
                    {
                        Application.Exit();
                    }
    But when I run the code, the application is not exiting when I click the cancel button on the userDlg dialog. Stepping through in the debugger it's hitting the Application.Exit(); line ok, but just carrying on!

    So how can I get the program to terminate (neatly!) at this point?

    Thanks in advance,

    Tim

    Source: http://csharp.livejournal.com/104596.html

  15. NMock2 question

    Date: 07/08/09     Keywords: no keywords



    Is there a way to change what a mock returns from its faked methods or properies after it has been initialised?

    For instance if I am testing myContainer to see if it supports repeated attempts to Add the same Foo instance regardless of the value of the Foo's boolean Bar property I want to do something like

    myMockery = new Mockery();
    myFoo = myMockery.NewMock();
    Stub.On(myFoo).GetProperty("Bar").Will(Return.Value(false));
    myCollection.Add( myFoo );
    Stub.On(myFoo).GetProperty("Bar").Will(Return.Value(true));
    myCollection.Add( myFoo );
    Assert something about myCollection


    But it seems that once you use "Stub.On" any subsequent Stub.On the same object has no effect?

    Source: http://csharp.livejournal.com/104068.html

  16. IIS Application config wildcards

    Date: 06/10/09     Keywords: css

    I have an application in IIS where I set up a wildcard so that all file extensions are processed via the .net dll. I did this so that I can process some URL rewriting. I see at the top of the configuration screen where I can specify which extensions should be processed by what processors. What I am wondering is if there is a way to specify an extension that should not be processed by the wildcard. Specifically I know that .jpg, .gif, .css, .png and .js extensions should not go through it. Is there a way to tell IIS to just serve them normally?



    cross posted to a few communities.

    Source: http://csharp.livejournal.com/103725.html

  17. Photo album component.

    Date: 05/08/09     Keywords: no keywords

    Is there a .net photo album component similar to facebook's photo album? Its a cheap gimmick to be sure but I do like the way the next set of photos preloads and scrolls left. I imagine similar functionality could be used to display any grid data. Any suggestions?

    Source: http://csharp.livejournal.com/103000.html

  18. Client-side validation

    Date: 02/27/09     Keywords: html, xml, java, web

    I’m having some “fun” with client-side validation on a roll-my-own BaseValidator subclass.

    My validator is to validate email format and includes the following code (with XMLdoc removed for brevity):

    using System;
    using System.Text.RegularExpressions;
    
    namespace IrisDigital.WebControls.Validation
    {
       [System.Web.UI.ToolboxData("<{0}:EmailValidator runat='server'/>")]
       public class EmailValidator : BaseValidator
       {
          protected override void AddAttributesToRender(System.Web.UI.HtmlTextWriter writer)
          {
             base.AddAttributesToRender(writer);
    
             if (base.RenderUplevel)
             {
                writer.AddAttribute("evaluationfunction", "CheckEmailFormat");
                writer.AddAttribute("controltovalidate", this.GetControlRenderID(this.ControlToValidate));
             }
          }
    
          protected override bool EvaluateIsValid()
          {
             // ...
          }
    
          protected override void OnPreRender(EventArgs e)
          {
             base.OnPreRender(e);
    
             if (base.RenderUplevel)
             {
                if (!Page.ClientScript.IsClientScriptBlockRegistered("IrisDigital.WebControls.Validation.EmailValidator"))
                {
                   Page.ClientScript.RegisterClientScriptInclude("IrisDigital.WebControls.Validation.EmailValidator",
                      Page.ClientScript.GetWebResourceUrl(this.GetType(), "IrisDigital.WebControls.Validation.EmailValidator.js"));
                }
                this.ClientValidationFunction = "CheckEmailFormat";
             }
          }
    

    Most of the rationale for doing things this way is from an article on CodeProject: RequiredIfValidator — Extending from the BaseValidator class, which does it precisely this way.

    The validator works wonderfully. But the client-side validation never fires.

    The WebResource correctly gets added to the page as a script include (for which I need to have the following line in my AssemblyInfo.cs, in case you were wondering):

    [assembly: System.Web.UI.WebResource("IrisDigital.WebControls.Validation.EmailValidator.js", "text/javascript")]

    , but it just never gets called.

    Anyone got any ideas why?

    Cross-posted to '[info]'ms_dot_net and '[info]'owenblacker.

    Source: http://community.livejournal.com/csharp/102003.html

  19. Client-side validation

    Date: 02/27/09     Keywords: html, xml, java, web

    I’m having some “fun” with client-side validation on a roll-my-own BaseValidator subclass.

    My validator is to validate email format and includes the following code (with XMLdoc removed for brevity):

    using System;
    using System.Text.RegularExpressions;
    
    namespace IrisDigital.WebControls.Validation
    {
       [System.Web.UI.ToolboxData("<{0}:EmailValidator runat='server'/>")]
       public class EmailValidator : BaseValidator
       {
          protected override void AddAttributesToRender(System.Web.UI.HtmlTextWriter writer)
          {
             base.AddAttributesToRender(writer);
    
             if (base.RenderUplevel)
             {
                writer.AddAttribute("evaluationfunction", "CheckEmailFormat");
                writer.AddAttribute("controltovalidate", this.GetControlRenderID(this.ControlToValidate));
             }
          }
    
          protected override bool EvaluateIsValid()
          {
             // ...
          }
    
          protected override void OnPreRender(EventArgs e)
          {
             base.OnPreRender(e);
    
             if (base.RenderUplevel)
             {
                if (!Page.ClientScript.IsClientScriptBlockRegistered("IrisDigital.WebControls.Validation.EmailValidator"))
                {
                   Page.ClientScript.RegisterClientScriptInclude("IrisDigital.WebControls.Validation.EmailValidator",
                      Page.ClientScript.GetWebResourceUrl(this.GetType(), "IrisDigital.WebControls.Validation.EmailValidator.js"));
                }
                this.ClientValidationFunction = "CheckEmailFormat";
             }
          }
    

    Most of the rationale for doing things this way is from an article on CodeProject: RequiredIfValidator — Extending from the BaseValidator class, which does it precisely this way.

    The validator works wonderfully. But the client-side validation never fires.

    The WebResource correctly gets added to the page as a script include (for which I need to have the following line in my AssemblyInfo.cs, in case you were wondering):

    [assembly: System.Web.UI.WebResource("IrisDigital.WebControls.Validation.EmailValidator.js", "text/javascript")]

    , but it just never gets called.

    Anyone got any ideas why?

    Cross-posted to ms_dot_net and owenblacker.

    Source: http://csharp.livejournal.com/102003.html

  20. Bundling changes together.

    Date: 02/21/09     Keywords: cms, database, sql, web

    First off, I'll state that I'm working with C# 2008 express edition, SQL Server 2008 Professional edition, and .NET 3.5.

    Second, I'll state that one of the ideas behind this project is to do it without .Net's auto-binding. If it can't be done without auto-binding, it's not going to get done at all, for reasons having to do with extreme customization of the data access code that will be happening way, way down the line. So I need an answer in code, not in designer. Thanks.

    Okay, what I'm doing seems to me to be simple and obvious, but either .Net doesn't agree with me or I'm looking in the wrong place. I have a simple form. It contains a datagridview and three buttons. One button works perfectly--it's the one that closes the form, and we don't need to discuss it here. The other two buttons, however, are giving me fits. They are labelled "save changes" and "cancel".

    The datagridview is bound to a DataTable. This is pretty standard code, I think:

    SqlConnection cnErasmus = new SqlConnection();
                //populate the datatable with the data already in the table.
                tblAuthorType = PopulateDataSet(cnErasmus);
                //Attach DataTable to datagrid.
                dgvAuthorType.DataSource = tblAuthorType;


    (note: it used to be a dataset. I forgot to change the name of the routine.)

    In case you want/need to see the actual filling of the DataTable, I'll put it

            private DataTable PopulateDataSet(SqlConnection cnErasmus)
            {
                string strAuthorTypeSelectQuery = "SELECT AuthType FROM AuthorType";
                using (cnErasmus)
                {
                    using (SqlCommand cmSelectCommand = new SqlCommand(strAuthorTypeSelectQuery, cnErasmus))
                    {
                        CreateConnectionString(cnErasmus);
                        OpenConnection(cnErasmus);
                        using (SqlDataReader theReader = cmSelectCommand.ExecuteReader())
                        {
                            tblAuthorType.Load(theReader);
                            CloseConnection(cnErasmus);
                        }
                    }
                }



    All of this is completely normal. At least, I think it is. Now, the tough part seems to be logging changes. The obvious way to do so, to me (I'm a database guy more than a programmer) is through a transaction object:

    /******************SqlTransaction trnchangeAuthorTypeData = 
           cnErasmus.BeginTransaction("Changes");
                //Must assign both transaction object and connection
                //to Command object for a pending local transaction.
                SqlCommand cmTransactionCommand = cnErasmus.CreateCommand();
                cmTransactionCommand.Connection = cnErasmus;
                cmTransactionCommand.Transaction = trnchangeAuthorTypeData;
                //Whether transaction is committed or rolled back depends
                //on which button the user presses...********************/


    These are the lines just after setting the dgv's data source.

    I've seen this done at least a dozen times in various places on the web, but in every case, the example has some sort of hardcoded INSERT or DELETE statement immediately following, and then a try/catch block with the appropriate transaction.Commit() or transaction.Rollback() statements. The important bit for me is that in every example I've found, all the statements follow one another. It's all very procedural. I want the Commit() or Rollback() to be fired based on which of those buttons gets pressed; the Cancel button will cause a Rollback() and the Save button will cause a Commit(). To me, this seems perfectly logical. My problem is that, unfortunately, trnchangeAuthorTypeData goes out of scope the second we hit the end of that block of code, and so is nowhere to be found when I get to btnSave_Click or btnCancel_Click. Setting it the normal way (trnChancgeAuthorTypeData = new SqlTransaction()) raises an error based on the protection level of SqlTransaction, so I can't declare it the way I declare every other variable. (While no resource I've consulted specifically explains this odd behavior, they all confirm that this is by design.)

    So, after all that, my question is: how do I separate BeginTransaction(), Commit(), and Rollback() into three separate routines? If that's not possible, as I have spent the last twelve hours ascertaining, is there some way other than transactions to make sure that, when the Cancel button is pressed, the system will roll back all changes since either (a) the form was opened or (b) the Save button was last pressed, and that can be done in that manner (with the transaction-analogue starting in the same routine where the datagridview is bound, and finishing in one of the button-press routines)?

    Thanks.

    Source: http://community.livejournal.com/csharp/101781.html

  ||  Next page


antivirus | apache | asp | blogging | browser | bugtracking | cms | crm | css | database | ebay | ecommerce | google | hosting | html | java | jsp | linux | microsoft | mysql | offshore | offshoring | oscommerce | php | postgresql | programming | rss | security | seo | shopping | software | spam | spyware | sql | technology | templates | tracker | virus | web | xml | yahoo | home