Friday, May 6, 2011

What exactly is CPU Time in task manager?

I have some WCF services that are hosted in a windows service. Yesterday I looked at Task Manager and noticed that the CPU time for my windows service process was over 5 hours, while the majority of all other processes were at 0.

What does that mean?

Should I be concerned that the CPU Time was 5+ hours?

From stackoverflow
  • CPU Time is a reflection of how much time your program spends executing instructions in the CPU vs waiting for IO or other resources. Should you be concerned with it being 5+ hours?

    I would guess not, some things to consider are:

    1. How long has this process been running?

    2. Do you have any issues with the performance of the process or other processes on the box that this might be stealing CPU from?

    3. What other processes do you have? Are these active processes that you'd expect to use the CPU? For reference of the 80 processes I have about 20 have over 1 second of CPU time used.

    Edit

    It is possible that the WCF service is stealing CPU from the other services, you need to monitor them making sure their performance is what you expect. You can also get a sense based on Total CPU usage. If you for example you only see 25% of your CPU used, then your other services should not be affected; however, if your running above 75% then they might be affected.

    When it comes to monitoring be sure to monitor over time so you can see how the performance trends, and it will help you isolate problems. For example you service is running fine but then after a deploy it slowly starts to take more and more CPU (Assume 10% a week). Unless your trending your CPU usage you might one day wake up and see your service running slowly which could be weeks after a deploy.

    Grant Wagner : You had 5 hours of CPU time on a process that has been running 504 hours (3 weeks * 7 days/week * 24 hours/day). So simplistically, on average, your process has been using 1% of the CPU the entire time. In reality of course, that isn't the case, there are times your service is using near 0% CPU and other times it is using considerably more. I would say it is nothing to worry about, but if you are concerned, you should use 'perfmon' to track your processes CPU usage over time to determine if you have a problem.
  • CPU time is an indication of how much processing time that the process has used since the process has started (in Windows: link to a Technet article.)

    It is basically calculated by:

    CPU Time of Process = Process Uptime * CPU Utilization of Process
    

    For example, if the process has been running for 5 hours and the CPU time is 5 hours, then that means that the process has been utilizing 100% of the resources of the CPU. This may either be a good or bad thing depending on whether you want to keep resource consumption low, or want to utilize the entire power of the system.

    If the process was using 50% of the CPU's resource and running for 10 hours, then the CPU time will be 5 hours.

  • If you are concerned about how much CPU time your process is using, you should use perfmon to track your processes' CPU usage over an extended period of time to determine if you have a problem.

How to integrate FxCop and VS 2008?

If this is duplicated question, please point me to the proper link and I'll delete this question.

I know that in VS Team System I can use Code Analysis but I'm using VS Professional.

Can you tell me how I can integrate FxCop and Visual Studio? I don't want to add FxCopCmd.exe to my Post-build events to run FxCop with every compilation. I want to be able to run FxCop when I choose by right clicking on the project in Solution Explorer.

Thanks for your help.

From stackoverflow
  • How about setting up FxCop as an external tool in Visual Studio? Here's the link:

    http://msdn.microsoft.com/en-us/library/bb429389(VS.80).aspx

    Vadim : +1 for giving the link. The information in the link doesn't work but it gave me an idea how to solve this problem. Thanks.
  • It took awhile by I finally figure it out. It's not ideal but it works.

    Update: I create a post with step by step instructions:

    Thanks to aamit, who provided the link that put me on the right track even that solution in MSDN article doesn't work. Give him +1; he deserves it.

    1.) In FxCop GUI save your project.

    IMPORTANT:

    • a. Save project in the same directory where your solution is.
    • b. Give the FxCop project name the same as your solution name and include the .sln extension.

    For example: If your solution name is MySolution.sln, the FxCop project name is going to be MySolution.sln.FxCop.

    2.) In Visual Studio select Tools -> External Toos

    3.) Enter following information in External Tools dialog box:

    • Title: FxCop
    • Command: C:\Program Files\Microsoft FxCop 1.36\FxCopCmd.exe
    • Arguments: /c /p:"$(SolutionDir)\$(SolutionFileName).fxcop" /cXsl:"C:\Program Files\Microsoft FxCop 1.36\Xml\VSConsoleOutput.xsl"
    • Initial directory: C:\Program Files\Microsoft FxCop 1.36

    Make sure that "Use Output window" checkbox is checked.

    That's it. It works for me I hope it's going to work for you.

  • I run a command very similar Vadim's as a Post-Build event for the project. That way, I get the FxCop errors as soon as I recompile. But our commands are pretty much the same; nice to know at least two people in the world reached the same conclusion!

    The errors do show up in Visual Studo's Error List pane.

    "%ProgramFiles%\Microsoft FxCop 1.36\FxCopCmd.exe"
    /file:"$(TargetPath)" 
    /console
    /dictionary:"$(SolutionDir)Res\FxCop\CustomDictionary.xml"
    /searchgac 
    /ignoregeneratedcode
    

    (You can omit the /dictionary argument; it just points to one of my custom dictionary files since FxCop flags a few variable names as Hungarian notation when they aren't. I also line-wrapped the command for readability.)

    It does make the build a little longer, but it's nice to see the errors right away and to tailor the command settings per project. Good luck!

Cannot find the right <div> with selector after loading the HTML

I hope I can find a solution to this one. Here it goes:

After I have submitted my form to add a message to the database, I create a <div> with the load method. After that I do some stuff in the callback function.

When the function to create the new <div> has finished, it returns to the calling function that is supposed to prepend the message to the last inserted <div>.

That's where the problem starts:

I use the selector to find $(someDiv : last), but it puts it in the wrong <div>. So, I know it has something to do with the async process.

I haven't really worked out what I could do to fix this, because now I am not working from a callback function.

If you wanna see a live example The sourcecode is clutterd with debug code in the form of alerts, but you can see what it is doing.

From stackoverflow
  • Probably the new div is not being inserted where you think it is. $(someDiv : last) is returning the wrong result because the new div isn't in someDiv, or it isn't at the end. This seems like the kind of thing that Firebug would make easy to debug.

    Rather than using the "last" metaclass to select the div, here's a better idea: give the new div an ID and refer to it directly. Or give it a class when you create it, use the class to select it $(".newdiv"), and then clear the class when you're done. Or simply return the new div to the calling function, so it doesn't need to use a selector at all. Sorry, I didn't entirely understand your situation, but I think at least one of these solutions will work.

  • Did you notice that the first time the value gets added to the first item, and after that it gets added to the previously last item? That might be a clue. Oh, and I got stuck in a loop which added my message 10 times. Looks like your code has timing issues.

    Edit: bringing it back to its basics would look something like this: http://kruisit.nl/so/841982/ Hope that helps.

    Jeroen : You're using IE?
  • Ajax calls are asynchronous, you should be using a callback function to select loaded data, for example:

    $('div').load(url, data, function(data, status) {
       $(someDiv:last).dosomething();
    }
    
    Nadia Alramli : I'm glad you found a way around it

Database-Generated Human-Friendly Codes

I'd like to create some human-friendly codes to identify my objects.

I'm thinking about using the following rules:

  • 6-digit random number
  • the first character is not zero
  • each code has an edit distance value of 2 or greater* from every other such code
  • maybe a checksum too

I'd like my MS SQL database to enforce that the codes I use are not only each unique, but also conform to the above criteria too.

How would I write a database check constraint to enforce rules such as these?

How could I make the database use such numbers as default values for inserted rows?

*so a single keystroke typo won't retreive a different-than-intended record

From stackoverflow
  • Use a stored procedure to check whatever constraints you would like for inserted data.

    A stored procedure can also be used to generate these things if needed.

    Although letting the database do all this for you seems like a nice thing, doing it all in code can be easier to maintain in the long run(unless you have dedicated DBAs who love maintaining this kind of stuff).

    I think your idea and algorithm is smart. If you're going to go that far with the requirements, I would say a checksum is a great thing to have. The checksum alone can catch typo errors, regardless of edit distance.

    Zack Peterson : You're right. With a simple single-digit MOD 10 checksum added to a simple unique number, I'd end up with edit distances of 2 or greater.
  • Create a stored proc that calculates your numeric value; use that stored proc as the DEFAULT() value for the column definition in your table definition. Note: I haven't tried this, so I don't know if it's completely possible.

  • How many id's do you need?

    You could declare the column as an identity, and set the start value to 100000, and the increment to 12. That would produce a six digit number, with edit distance of 2.

    Also, as a bonus, this is pretty fast. But you may run out of numbers as this isn't all that dense.

    CREATE TABLE [Items]
    (
        [id] int IDENTITY(100000,12) NOT NULL primary key,
        [Data] varchar(50) NULL
    )
    
    Zack Peterson : I'll have to think about that. I may need another digit.
    Zack Peterson : I'd also rather that the numbers are in a random order so they don't imply unintended information such as the total number of records.
  • Write a one-time-use program to populate a table of all (or many) possible valid codes in a scrambled order with an integer primary key.

    Code table:

    Id   HumanFriendlyCode
    
    1    100124
    2    991302
    3    201463
    4    157104
    ...  ...
    

    Then just relate the objects table to the rows in that codes table with an auto-incrementing integer foreign key and a unique constraint.

    Thing table:

    Id                                    CodeId  ...
    
    e9d29b14-0ea6-4cfd-a49f-44bcaa7212eb  1       ...
    91906bb7-14ed-4acc-bf23-c4bd1631797f  2       ...
    41ace075-f9f8-46b7-b114-cb17765c4e76  3       ...
    2fba1a58-7a91-4da6-a4a2-7cacef8603db  4       ...
    

    Anyone ever done something like this?

  • This check constraint will enforce a checksum in a database column:

    ALTER TABLE tblCode
    ADD CHECK (
        CAST(SUBSTRING(CAST(Code AS VARCHAR), 6, 1) AS INTEGER) =
        (
            CAST(SUBSTRING(CAST(Code AS VARCHAR), 1, 1) AS INTEGER) +
            CAST(SUBSTRING(CAST(Code AS VARCHAR), 2, 1) AS INTEGER) +
            CAST(SUBSTRING(CAST(Code AS VARCHAR), 3, 1) AS INTEGER) +
            CAST(SUBSTRING(CAST(Code AS VARCHAR), 4, 1) AS INTEGER) +
            CAST(SUBSTRING(CAST(Code AS VARCHAR), 5, 1) AS INTEGER)
        ) % 10
    )
    

    The sixth digit must be modulo 10 of the sum of the first five digits.

  • Your enemy as far as UI goes is code length. I suggest you add alphabetic characters (omitting zero, oh, one, and eye). It will cut then length substantially, and make collisions less likely, especially for transpositions.

catch odbc exception

I need to recognize in my application whether table doesn't exist or has no rows to take appropriate action. Can I catch this two errors separately ?

>>>cursor.execute("delete from TABLE")

Traceback (most recent call last):
  File "<interactive input>", line 1, in <module>
dbi.internal-error: [IBM][CLI Driver][DB2] SQL0100W  No row was found for FETCH, UPDATE or DELETE; or the result of a query is an empty table.  SQLSTATE=02000
 in EXEC

OR

Traceback (most recent call last):
  File "<interactive input>", line 1, in <module>
dbi.program-error: [IBM][CLI Driver][DB2] SQL0204N  "SK77531.TCS_EXCEPTIONS" is an undefined name.  SQLSTATE=42704
 in EXEC
From stackoverflow
  • From the Python documentation:

    A try statement may have more than one except clause, to specify handlers for different exceptions.

    For example:

    try:
        do_something_crazy
    except AttributeError:
        print 'there was an AttributeError'
    except NameError:
        print 'there was a NameError'
    except:
    print 'something else failed miserably'
    

    The last except acts as a catch-all here, and is only executed if an exception different than an AttributeError or NameError occurs.  In production code it's best to steer clear from such catch-all except clauses, because in general you'll want your code to fail whenever an error that you didn't expect occurs.

    In your specific case you'll need to import the different exceptions that can be raised from the dbi module, so you can check for them in different except clauses.

    So something like this:

    # No idea if this is the right import, but they should be somewhere in that module
    import dbi
    
    try:
        cursor.execute("delete from TABLE")
    except dbi.internal-error:
        print 'internal-error'
    except dbi.program-error:
        print 'program-error'
    

    As you'll see in the above-lined documentation page, you can opt to include additional attributed in each except clause.  Doing so will let you access the actual error object, which might be necessary for you at some point when you need to distinguish between two different exceptions of the same class.  Even if you don't need such a fine level of distinction, it's still a good idea to do a bit more checking than I outlined above to make sure you're actually dealing with the error you think you're dealing with.

    All that said and done about try/except, what I'd really recommend is to search for a method in the database library code you're using to check whether a table exist or not before you try to interact with it.  Structured try/excepts are very useful when you're dealing with outside input that needs to be checked and sanitized, but coding defensively around the tentative existence of a database table sounds like something that's going to turn around and bite you later.

    Richard : thank you very much for your response. I tried your last example and I got something like: AttributeError: 'module' object has no attribute 'internal' but i worked with dbi atributes progError and internalError, thanks

webform or winform, how to choose?

What would be the normal way to decide which way to go?

In my case, what if

  • user-base was under 10 persons
  • you have no control over CAS but can install the framework
  • needed to import/export let say excel file/pdf
  • would be intranet
  • security is really important
  • business logic is somehow complex
From stackoverflow
  • Winforms is probably slightly "richer" in that you can do more on the client (since you're running a full fledged application vs. just a browser), e.g. it's a "Rich Client"; on the other hand, the Webforms app doesn't need to be installed on each and every machine since it's a "Thin Client", so that's a bonus.

    As for the business logic, I would separate that out into its own layer/tier anyway, which could be used from either Winforms or Webforms - no deciding factor here, I think.

    So really - which ever you feel more comfortable with is probably fine. You don't really give much really good reasons to choose one over the other....

    Marc

  • Your "cases" either do not distinguish between Webforms and Winforms, or are too vague to be used to make a decision.

    A typical Webforms application connects to a server somewhere on the internet, all data and logic is stored remotely and sent to clients. A typical Winforms application has all data and logic performed on the user's machine. This should be the basis for which you use.

    Will a bunch of people be contributing to your data, with no one user owning it? Is the data not useful unless all contributions are available? Are the contributions unreliable, or should individual users be protected from possibly dangerous contributions? Webforms are the way to go.

    Or is the data the sole responsibility of one person? Does the data need to interoperate with other files, applications, or hardware used by that person? Will each user act separately from everyone else who uses the data, and do you want to isolate each user's data from others? You should use Winforms.

    Yes, you can run a Webforms app locally on one machine, and you can create collaborative internet Winforms apps, but the two technologies were created for different purposes and you will be better off using each for the purpose it was designed for.

  • This seems to be a bit of a blacksheep of a thread, but lets go for it anyways.

    Pretty much in a small distribution, a thick client ( winForms ) is easier to develop for. One of the biggest flaws is the difficult in deployment. CAS will be more of a factor with a thick client app ( as its basically a non-factor on a webform app ), but in the end, with the basics you have described, it shouldn't really become a factor. Then again, this may be a product of not having enough information.

    Where WebForms thrive is the ease of maintenance and the lack of deployment. Additionally, it is much easier to deploy a WebForm app on the Internet should that ever become a priority.

    Your actual task described, could easily be accomplished by either technology, it really all comes down to the specifics. Need a highly or easily distributed app? Go with WebForms. Need to provide easy upgrades? Again, WebForms. Need to provide a rich client experience, then go with WinForms.

    It really all comes down to many specifics you have provided and your particular skillsets, which also arent mentioned. What you have requested ( as far as we know ), can be provided using either technology.

Should I create form objects or generate them from model

I recently found out that I can generate forms from models. I've read the docs and am wondering why someone would opt not to do this in favor creating their own form objects.

From stackoverflow
  • Not all forms are directly related to a Model. While most of the time you might end up using a ModelForm, sometimes you want to create a form for something that is better expressed as an individual form and then you can patch the data together in the view. In my experience this isn't often, but it happens sometimes.

  • Riffing off of Paolo's answer, if you are collecting data from the user to store in your database, you will probably already have a model set up with fields for the information that needs to be collected. In this case, use a ModelForm. On the other hand, sometimes you have scenarios where instead of collecting data from the user, you're using their input to perform some action on data already in the database, perhaps, say, generating a view that's a mashup of information from multiple models. In this case, you will want to use Form. The Form will still allow you to perform validation on the user input comparatively easily.

Using WinDDK test utilities with Visual Studio 2005

I'm currently trying to run the NdisProt driver given by WinDDK 2003. I've build and installed the driver successfully.

It comes with a test utility named uiotest

When I build the utility with make it runs correctly.

When I create a blank win32 application solution with Visual Studio 2005 it cannot connect to the driver during CreateFile( "\\.\\NdisProt" [...])`. The call always returns an invalid handle. I suspect that my project is not built exactly the same as with make. Here is the content of the "sources" file used by make

TARGETNAME=uiotest
TARGETPATH=obj
TARGETTYPE=PROGRAM

C_DEFINES=$(C_DEFINES) -D_WIN32WIN_

# MSC_WARNING_LEVEL=/W4

UMTYPE=console
USE_MSVCRT=1

TARGETLIBS=\
    $(SDK_LIB_PATH)\user32.lib

INCLUDES=..\sys

SOURCES=\
    uiotest.c

I've added the lib path and include path to my project

here is what make returns from the ddk environement

cl -nologo -Ii386\ -I. -ID:\WINDDK\3790~1.183\inc\mfc42 -I..\sys -Iobjfre_wxp_x8
6\i386 -ID:\WINDDK\3790~1.183\inc\wxp -ID:\WINDDK\3790~1.183\inc\wxp -ID:\WINDDK
\3790~1.183\inc\crt -D_X86_=1 -Di386=1  -DSTD_CALL -DCONDITION_HANDLING=1   -DNT
_INST=0 -DWIN32=100 -D_NT1X_=100 -DWINNT=1 -D_WIN32_WINNT=0x0501 /DWINVER=0x0501
 -D_WIN32_IE=0x0603    -DWIN32_LEAN_AND_MEAN=1 -DDEVL=1 -D__BUILDMACHINE__=WinDD
K -DFPO=0  -DNDEBUG -D_DLL=1 -D_MT=1  -D_WIN32WIN_     /c /Zl /Zp8 /Gy /Gm-  /W3
 /WX /Gz  /GX-  /GR- /GF /GS /G6 /Ze /Gi- /QIfdiv- /hotpatch -Z7 /Oxs  /Oy-   -F
ID:\WINDDK\3790~1.183\inc\wxp\warning.h   .\uiotest.c
uiotest.c
        link -out:objfre_wxp_x86\i386\uiotest.exe -machine:ix86 @C:\Temp\nm88BE.
tmp
Microsoft (R) Incremental Linker Version 7.10.4035
Copyright (C) Microsoft Corporation.  All rights reserved.

-MERGE:_PAGE=PAGE
-MERGE:_TEXT=.text
-SECTION:INIT,d
-OPT:REF
-OPT:ICF
-IGNORE:4198,4010,4037,4039,4065,4070,4078,4087,4089,4221
-INCREMENTAL:NO
-FULLBUILD
/release
-NODEFAULTLIB
/WX
-debug
-debugtype:cv
-version:5.1
-osversion:5.1
/functionpadmin:5
/safeseh
/opt:nowin98
-merge:.rdata=.text
/pdbcompress
-STACK:0x40000,0x2000
/tsaware
-subsystem:console,4.00
-base:@D:\WINDDK\3790~1.183\bin\coffbase.txt,usermode
-entry:mainCRTStartup
objfre_wxp_x86\i386\uiotest.obj
D:\WINDDK\3790~1.183\lib\wxp\i386\BufferOverflowU.lib
D:\WINDDK\3790~1.183\lib\crt\i386\msvcrt.lib
D:\WINDDK\3790~1.183\lib\wxp\i386\advapi32.lib
D:\WINDDK\3790~1.183\lib\wxp\i386\kernel32.lib
D:\WINDDK\3790~1.183\lib\wxp\i386\user32.lib
D:\WINDDK\3790~1.183\lib\wxp\i386\sehupd.lib

I'm not too sure about what to check to know what's going on so any help would be appreciable. The new project compiles and run, but the CreateFile() fails with INVALID_HANDLE_VALUE

From stackoverflow
  • It may not be the whole problem, but one thing that leaps out from the code quoted is the call CreateFile("\\.\\NdisProt",...). The correct path name of an object in the kernel name space begins with two backslashes, each of which needs to be doubled in a C string. I've had problems with the markup language used at SO being confused by backslashes in the past, so I took the liberty of editing your question to make sure I was seeing the name you intended to present, and to fix the markup to preserve that intent.

    So, the name used to create a handle to the device object should look like

    CreateFile("\\\\.\\NdisProt",...)
    

    to address the device object named

    \\.\NdisProt
    

    I have no idea if there are any other issues, or even if that is the correct name exported by that driver.

    The DDK samples are generally written to be free of dependencies on things like MFC, ATL, WTL, and the like. This results in a kind of stilted style in the code, but it has the benefit that the samples can be built with the tool chain that originally shipped with the DDK itself and are relatively independent of the choice of toolchain used.

    Note that if you end up trying to really debug a driver, you might need to track a call from the user mode code through the kernel and into the relevant bits of the driver. Doing that with the kernel debugger is easier if the user mode code is as simple as possible. This might also explain the style used in the sample code.

    Edit: If there is also a Unicode vs. ANSI issue floating, then you should review your code for places where narrow strings are passed to APIs that expect wide strings and fix them.

    One fix that is easy would be to switch to an ANSI compile for all Windows APIs. Of course, now you have problems with file names that include national characters not in your current code page since there is no way to guarantee that the Unicode file name can be correctly translated to and from ANSI.

    One fix that might be "good enough" is to make string constants wide by writing them L"...". However, now your code is guaranteed not to be portable back to an ANSI compile, so be sure to use a compile-time assertion to verify that UNICODE is defined so that you get a good error message then.

    The party line at Microsoft seems to be to never use either char or wchar_t but to instead use TCHAR. The header <tchar.h> supplies mapping macros that allow strings to be declared and used in the Windows API and in the C runtime libraries by choosing the wide or narrow API at compile time. Arguably, this is the correct thing to do in a Windows application since it is already not very portable to other platforms.

    However, getting the macro magic right to deal with translating TCHARs to a known representation is a pain.

    Regardless of which technique you choose, I don't see any way out of doing a careful and complete code review for string handling and character representation assumptions.

  • Half soved :

    CreateFile is referencing CreateFileW which waits for a unicode string. When I force CreateFileA it works.

    bk1e : Passing a narrow string to CreateFileW would probably generate a compiler warning when you compile the program. What other compiler warnings are you not telling us about?

IIS 7, ASP.NET: AccessViolationException

What can be the reason of the following exception in ASP.NET application under IIS 7? It is an unhandled exception that restarts the whole application.

Exception: System.AccessViolationException

Message: Attempted to read or write protected memory. This is often an indication that other memory has been corrupted.

StackTrace:

   in System.Web.Hosting.UnsafeIISMethods.MgdIsLastNotification(IntPtr pRequestContext, RequestNotificationStatus dwStatus)
   in System.Web.HttpRuntime.FinishRequestNotification(IIS7WorkerRequest wr, HttpContext context, RequestNotificationStatus& status)
   in System.Web.HttpRuntime.OnRequestNotificationCompletionHelper(IAsyncResult ar)
   in System.Web.HttpRuntime.OnRequestNotificationCompletion(IAsyncResult ar)
   in System.Web.HttpAsyncResult.Complete(Boolean synchronous, Object result, Exception error, RequestNotificationStatus status)
   in System.Web.HttpApplication.PipelineStepManager.ResumeSteps(Exception error)
   in System.Web.HttpApplication.ResumeStepsWaitCallback(Object error)
   in System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
   in System.Threading._ThreadPoolWaitCallback.PerformWaitCallbackInternal(_ThreadPoolWaitCallback tpWaitCallBack)
   in System.Threading._ThreadPoolWaitCallback.PerformWaitCallback(Object state)

[UPD]

System: Windows Web Server 2008 64-bit.

Application details: ASP.NET application that doesn't use pages architecture. It process requests using custom http sync and async handlers. There are also parallel threads from ThreadPool or created by Thread class are running.

From stackoverflow
  • A third-party ISAPI filter may cause this problem.

    alexey : Thanks for your answer. I don't use any third-party filter. Pure ASP.NET application.
  • A hardware error is occasionally the unexpected culprit in such cases. Everything may work perfectly, except one little method in one obscure DLL.

    Or does this happen on multiple machines, as well? Try a different one.

Disable a button on click

I have a button control. Once the user clicks on it, the click event should fire and then the button should get disabled. How can I do this? I have the option to use JQuery or JavaScript or both.

Here is my button declaration:

<asp:Button 
  ID="Button1" 
  runat="server" 
  Text="Click Me" 
  onclick="Button1_Click"
/> 

On the button click code behind, I have added a Response.Write(). That should get executed and then the button should be disabled

From stackoverflow
  • add an OnClientClick="this.disabled = true;" to your button.

    If you are using Asp.net Ajax you might want to look at using PostBack Ritalin.

    Pavel Chuchuva : You also need UseSubmitBehavior="false". See http://stackoverflow.com/questions/400616/why-doesnt-my-form-post-when-i-disable-the-submit-button-to-prevent-double-click
  • You need to be careful that the postback occurs before you disable the button through client script. This is a common gotcha with ajax and input boxes. Disabling an input box prevents the data from being sent from the browser, even if you can see text within it while it is disabled. The answer is that you need to use jquery for this to ensure the server-side code runs first before it is disabled.

    -Oisin

    Hitz : I did it..I ran this code but the code behind never executed $('input[type=submit]').click(function() { this.disabled = true; });
  • you can disable it server side

    Button1.Enabled = false;
    
    Paul U : @op: "On the button click code behind, I have added a Response.Write(). That should get executed and then the button should be disabled" The onClientCLick would disable the button before the server response. In any case, I would appreciate a reason for the down vote.
  • // to disable
    this.setAttribute('disabled', true); 
    // to enable
    this.removeAttribute('disabled');
    

    this is a cross browser solution

  • Short answer:

    The trick to disabling a Button control during a postback is to use UseSubmitBehavior=false.

    Long answer:

    For whatever reason, the HTML spec dictates that disabled elements should not be included in POST requests. So, if you use JavaScript to disable the HTML element in the client-side onclick event, the input element will be disabled when the browser assembles the POST request, the server won't be properly notified which element raised the postback, and it won't fire server-side click event handlers.

    When you set the UseSubmitBehavior property to false, ASP.NET renders an input element of type button instead of the regular input of type submit that the ASP.NET Button control normally generates. This is important because clicking a button element does not trigger the browser's form submit event.

    Instead of relying on a browser form submission, ASP.NET will render a client-side call to __doPostBack() within that button element's onclick handler. __doPostBack will raise the postback explicitly, regardless of what POST data comes through in the request.

    With the postback being raised independent of the browser submit event, you're freed of the previously mentioned HTML quirk. Then, you can set an OnClientClick of "this.disabled = true;", which will render as "this.disabled = true; __doPostBack('Button1', '');", and things will work as intended.

  • There is really cool event for body tag "<"body onBeforeunload="buttonId.disabled = true;" ">"

    This event triggers right before form submits, in other words your data will be submitted correctly.

  • When using the "this.disabled = true" method make sure you check if the page is valid before disabling the control if you have validators on the page. If validation fails you won't be able to re-enable the control without reloading the page.

    if (Page_IsValid) this.disabled = true;
    
  • Don't use directly disable. Because you may have validation controls on the form to validate before you send request to server. So, you need to check whether you have passed validations or not and then only you can disable and process request.

    Here is the exact solution for it. http://praveenbattula.blogspot.com/2010/01/disable-button-in-onclick-and-process.html

Qt: adapting signals / binding arguments to slots?

Is there any way to bind arguments to slots ala boost::bind?

Here's a for-instance. I have a window with a tree view, and I want to allow the user to hide a column from a context menu. I end up doing something like:

void MyWindow::contextMenuEvent (QContextMenuEvent* event) {
   m_column = view->columnAt (event->x());
   QMenu menu;
   menu.addAction (tr ("Hide Column"), this, SLOT (hideColumn ()));
   // .. run the menu, etc
}

I need to capture the index of the column over which the context menu was activated and store it in a member variable that is used by my window's hideColumn slot:

void MyWindow::hideColumn () {
    view->setColumnHidden (m_column, true);
}

What I'd really like is to be able to bind the column number to my slot when I create the menu so I don't need this member variable. Basically the Qt equivalent of:

menu.addAction (tr ("Hide Column"),
                boost::bind (&MyWindow::hideColumn, this,
                             event->columnAt (event->x()));

Or even better yet adapting the QAction::triggered signal and attaching it to the QTreeView::hideColumn slot, which takes the column index as an argument:

menu.addAction (tr ("Hide Column"),
                boost::bind (&QTreeView::hideColumn, view,
                             event->columnAt (event->x())));

Is any of this do-able?

From stackoverflow
  • AFAIK the only way is to create a QSignalMapper object to do this. It's like an extra level of indirection that can be used to generate a new signal providing the column index. It's a little bit clumsy IME, you can end up with lots of QSignalMapper objects hanging around all the time, but seems to be the best way at this time. (Ideally, IMO, you would be able to just supply any value such as the column index to connect() which would get passed as an argument to the slot, but you can't.)

    Marcus Lindblom : Yup. The QT signals are pretty low-level (in the current version at least, there might be hope in the far future ;). Actually they're text-based (just look inside a moc_xx.cpp file or how the SLOT/SIGNAL macros are defined.)
  • LibQxt makes this possible through QxtBoundFunction and QxtMetaObject (the former does not show up in their documentation for some reason). It's an Open Source project, so you can grab the source if you're interested in the implementation. It uses the following syntax:

    connect(
        button,
        SIGNAL(clicked()),
        QxtMetaObject::bind(
            lineEdit,
            SLOT(setText(QString)),
            Q_ARG(QString, "Hello World!)
            )
        );
    

    LibQxt has some other very useful features like the ability to emit signals over a QIODevice, such as network connection.

CSS Selectors

What is the difference between these two CSS statements:

h1 em { color:#ddd; }

and

h1 > em { color:#ddd; }

As far as I can tell they do exactly the same thing (though according to what I've read at W3C in the first case em is considered a 'descendant' where as in the second it is considered a 'child', though I have no idea how that is actually different). Can anyone explain how these are different and why you would choose to use one syntax over the other. I've always just used the first method, but every now and again I run across the second style in other people's code.

From stackoverflow
  • This one:

    h1 em { color:#ddd; }
    

    matches any em that's within an h1, whether it's a child, grandchild, great-grandchild, etc. For instance:

    <h1><strong><em>This matches</em></strong></h1>
    

    This one:

    h1 > em { color:#ddd; }
    

    matches only an em that's a direct child of an h1. So:

    <h1><strong><em>This doesn't match</em></strong></h1>
    <h1><em>But this does</em></h1>
    
    Sander Marechal : Note that the > selector is not supported in Internet Explorer 6. It is supported in IE7 and IE8.
    Paul D. Waite : And just to confirm the terminology, the first is the descendant selector, the second is the child selector. For the difference between “descendant” and “child”, you want dictionary.com.
    AmbroseChapel : "For the difference between “descendant” and “child”, you want dictionary.com" Well said Paul. Is the OP's first language not English? Even if it isn't, they know enough English to write the question, they should know enough to look up two words.
    Paul D. Waite : Well, it’s not always easy to switch between reading English and reading code, I think they’re different mindsets (which I think is why [Jeff and others find pseudocode hard](http://www.codinghorror.com/blog/archives/001264.html)). But hopefully getting those concepts into your head will help with understanding HTML and CSS.
  • Probably not the best example that you've given but I'll run with it:

    <h1>Stuff here    
      <em>Something
        <p>More stuff</p>
        <p>Something <em>here</em></p>
      </em>
    <h1>
    

    h1 em will match both em in my example.

    h1>em will only match the em that is a direct descendant of the h1 not the second inner em.

  • h1 em { color:#ddd; }
    

    means: "em within h1"

    h1 > em { color:#ddd; }
    

    means: "em with parent h1"

  • A descendant is any element that appears below the containing element at any point in the DOM tree (a child, grand-child type relationship). A child is an element that is directly below the containing element in the DOM.

    The real world implications in using this are that the child selector, alongside the sibling selector, are not support by IE6.

  • Just fyi, there are still a lot of browser compatibility issues with using > and it is a case where I would use jQuery or at least test in all your target browsers before deploying.

  • The child selector in this the > symbol lets you select only those em tags that are direct descendants of an h1 tag.

    Example is the easiest way to explain it:

    <h1>H1 Tag <em id="first">child selector<em id="second">not a direct child descendant</em></em> </h1>
    

    In this case the first em tag will have the h1 > em style and the h1 em style applied, however the second em tag or the non direct child will not have h1 > em style applied since it is not a direct child or descendant of the h1.

    You can see the doctree spec here: http://www.w3.org/TR/CSS2/conform.html#doctree

Passing Custom event arguments to timer_TICK event

I have class

//Create GroupFieldArgs as an EventArgs
    public class GroupFieldArgs : EventArgs
    {
        private string groupName = string.Empty;
        private int aggregateValue = 0;
        //Get the fieldName
        public string GroupName
        {
            set { groupName = value; }
            get { return groupName; }
        }
        //Get the aggregate value
        public int AggregateValue
        {
            set { aggregateValue = value; }
            get { return aggregateValue; }
        }
    }

I have another class that creates a event handler

public class Groupby
{
 public event EventHandler eh;
}

Finally I have Timer on my form that has Timer_TICK event. I want to pass GroupFieldArgs in Timer_TICK event. What is the best way to do it?

From stackoverflow
  • I am not sure what you are trying to achieve. The Timer.Tick event always returns plain EventArgs, because it is driven from within the .Net framework. Do you want to return GroupFieldArgs from the event you defined in Groupby class?

  • You could subclass the standard timer class and add a property where you can inject your custom event args. Your new class could handle the Elapsed event internally, and expose a new event which would carry your EventArgs.

    namespace Test
    {
    class MyTimer : System.Timers.Timer
     {
     public EventArgs MyEventArgs { get; set; }
     public MyTimer()
      {
      this.Elapsed += new System.Timers.ElapsedEventHandler(MyTimer_Elapsed);
      }
     void MyTimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
      {
      if (MyEventArgs != null)
       OnMyTimerElapsed(MyEventArgs);
      else
       OnMyTimerElapsed(e);
      }
     protected virtual void OnMyTimerElapsed(EventArgs ea)
      {
      if (MyTimerElapsed != null)
       {
       MyTimerElapsed(this, ea);
       }
      }
     public event EventHandler MyTimerElapsed;
     }
    }
    
  • As Grzenio pointed out, it's always going to generate the same kind of event.

    That said, you can create an object that "bounces" the event to its intended recipients...

    public class GroupFieldArgSender
    {
      public string GroupName  { get; set; }
      public int AggregateValue { get; set; }
    
      public void RebroadcastEventWithRequiredData(object sender, EventArgs e)
      {
        if (GroupFieldEvent != null)
        {
          GroupFieldEvent(sender, new GroupFieldEvent
            { GroupName = GroupName, AggregateValue = AggregateValue });
        }
      }
    
      public event EventHandler<GroupFieldEventArgs> GroupFieldEvent;
    }
    

    Then wire the timer tick event to the RebroadcastEventWithRequiredData method.

Can't get JQuery to work in Master Page

I have a sample jquery in a form with no master page, and it works fine. I am trying to use the same function inside my master page but it does not work, I am using ASP.NET. Here is my code for both:

WebForm (This works):

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm3.aspx.cs" Inherits="Surfitlocal.WebForm3" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title></title>
    <script src="scripts/jquery-1.3.2.js" type="text/javascript"></script>
    <script type="text/javascript">
        $(document).ready(function() {
            $('#pHeader').click(function() {
                $('#pBody').slideToggle('slow');
            });
        });
    </script>
    <style type="text/css">
        .cpHeader
        {
            color: white;
            background-color: #719DDB;
            font: bold 11px auto "Trebuchet MS", Verdana;
            font-size: 12px;
            cursor: pointer;
            width:450px;
            height:18px;
            padding: 4px;           
        }
        .cpBody
        {
            background-color: #DCE4F9;
            font: normal 11px auto Verdana, Arial;
            border: 1px gray;               
            width:450px;
            padding: 4px;
            padding-top: 7px;
        }      
    </style>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:Panel ID="pHeader" runat="server" CssClass="cpHeader">
            <asp:Label ID="lblText" runat="server" />
        </asp:Panel>

        <asp:Panel ID="pBody" runat="server" CssClass="cpBody">
            Lorem ipsum dolor sit amet, consectetur adipisicing elit,
            sed do eiusmod tempor incididunt ut labore et dolore magna
            aliqua. Ut enim ad minim veniam, quis nostrud exercitation
            ullamco laboris nisi ut aliquip ex ea commodo consequat.
            Duis aute irure dolor in reprehenderit in voluptate velit
            esse cillum dolore eu fugiat nulla pariatur
        </asp:Panel>
    </div>
    </form>
</body>
</html>

MasterPage (This does NOT work):

<%@ Master Language="C#" AutoEventWireup="true" CodeBehind="Biz.Master.cs" Inherits="Surfitlocal.Site1" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title></title>
    <script src="scripts/jquery-1.3.2.js" type="text/javascript"></script> 
    <script type="text/javascript">
        $(document).ready(function() {
            $('#pHeader').click(function() {
                $('#pBody').slideToggle('slow');
            });
        });
    </script>     
    <style type="text/css">
        .cpHeader
        {
            color: white;
            background-color: #719DDB;
            font: bold 11px auto "Trebuchet MS", Verdana;
            font-size: 12px;
            cursor: pointer;
            width:450px;
            height:18px;
            padding: 4px;           
        }
        .cpBody
        {
            background-color: #DCE4F9;
            font: normal 11px auto Verdana, Arial;
            border: 1px gray;               
            width:450px;
            padding: 4px;
            padding-top: 7px;
        }      
    </style>
    <asp:ContentPlaceHolder ID="head" runat="server"></asp:ContentPlaceHolder>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:Panel ID="pHeader" runat="server" CssClass="cpHeader">
            <asp:Label ID="lblText" runat="server" />
        </asp:Panel>

        <asp:Panel ID="pBody" runat="server" CssClass="cpBody">
            Lorem ipsum dolor sit amet, consectetur adipisicing elit,
            sed do eiusmod tempor incididunt ut labore et dolore magna
            aliqua. Ut enim ad minim veniam, quis nostrud exercitation
            ullamco laboris nisi ut aliquip ex ea commodo consequat.
            Duis aute irure dolor in reprehenderit in voluptate velit
            esse cillum dolore eu fugiat nulla pariatur
        </asp:Panel>    

        <asp:ContentPlaceHolder ID="ContentPlaceHolder1" runat="server">
</asp:ContentPlaceHolder>


    </div>
    </form>
</body>
</html>
From stackoverflow
  • The problem is that when you add the MasterPage you get ClientID mangling.

    $("#pBody")  =>   $(".pBody")
    

    You can't use ID with the MasterPage, you wont have access to the mangled clientID. You need to have a custom css class on the element.

    Of course, now you are expecting that every page that uses that MasterPage have a pBody. Better to keep that code in the page, not the master page.

    Sam Hasler : I've fixed the formatting so the examples are visible.
    : Thanks Chris, that worked. Also thanks for fixing the formatting on my question. :) Louis
    STW : it's worth noting that .NET 4 finally introduces a baked-in option to disable the ClientID generation--and with earlier versions you could disable it by inheriting from `ContentPlaceHolder` and `Content` and returning String.Empty for calls to retrieve the ClientID (and one other ID which escapes me)
  • I can see you are using CssClass but in your function you use "#" indicating its an ID.

    Therefore

    $('#pBody')
    

    Should be

    $(".pBody')
    

    If you still want to use IDs, you should be using:

    $("#<%= pBody.ClientID %>")
    
    : Meep, thanks for answering. It works like a charm now.
  • hi
    for solve this problem in asp.net you can use script manager:
    <asp:ScriptManager ID="ScriptManager1" runat="server">
         <Scripts>
    //put your js file in script reference tag:
            //<asp:ScriptReference Path="~/scripts/jquery-1.3.2.js" />
            //<asp:ScriptReference Path="~/scripts/PWDMenuMaker.js" />
        </Scripts>
    </asp:ScriptManager>
    //Movafagh bashid

    STW : This might be acceptible *if* you're already using ASP.NET AJAX extensions--but it is a very poor solution if you aren't using UpdatePanels or other such controls. In testing, a bare-nekkid `ScriptManager` generates ~20k of extra Javascript to push to the client (and to be clear, this ScriptManager doesn't even references a script--it's 20KB of 100% unused waste)

NetBeans 6.7 Beta - Why does it think certain tables have no primary key?

I am using NetBeans 6.7 Beta to create entity classes from a MySQL (version '5.0.45-log') database. NetBeans accepts most tables, but rejects certain ones consistently (I can't see a pattern), saying they have "no primary key". All tables are using the InnoDB engine. All tables have primary keys of one or more columns. The MySQL query browser and NetBeans' internal database navigator both agree that all tables do, in fact, have a primary key. What's up?

Here is the script snippet generating the bad tables:

-- -----------------------------------------------------
-- Table `beamline`.`rq_requests`
-- -----------------------------------------------------
CREATE  TABLE IF NOT EXISTS `beamline`.`rq_requests` (
  `id` INT NOT NULL AUTO_INCREMENT ,
  `facility_id` INT NOT NULL ,
  `schedule_id` INT NOT NULL ,
  `experiment_id` INT NOT NULL ,
  `person_id` INT NOT NULL ,
  `shift_per_block` INT NOT NULL ,
  `block_count` INT NOT NULL ,
  `other_requirment` VARCHAR(1023) NULL ,
  `submitted` BOOLEAN NOT NULL ,
  `date_modified` DATETIME NOT NULL ,
  `date_created` DATETIME NOT NULL ,
  PRIMARY KEY (`id`) ,
  INDEX `fk_rq_requests_xa_facilities` (`facility_id` ASC) ,
  INDEX `fk_rq_requests_xa_schedules` (`schedule_id` ASC) ,
  INDEX `fk_rq_requests_eec_exp_toc` (`experiment_id` ASC)
# ,INDEX `fk_rq_requests_eec_members` (`person_id` ASC)
 ,CONSTRAINT `fk_rq_requests_xa_facilities`
    FOREIGN KEY (`facility_id` )
    REFERENCES `beamline`.`xa_facilities` (`id` )
    ON DELETE NO ACTION
    ON UPDATE NO ACTION
 ,CONSTRAINT `fk_rq_requests_xa_schedules`
    FOREIGN KEY (`schedule_id` )
    REFERENCES `beamline`.`xa_schedules` (`id` )
    ON DELETE NO ACTION
    ON UPDATE NO ACTION
 ,CONSTRAINT `fk_rq_requests_eec_exp_toc`
    FOREIGN KEY (`experiment_id` )
    REFERENCES `beamline`.`eec_exp_toc` (`exp_id` )
    ON DELETE NO ACTION
    ON UPDATE NO ACTION
# ,CONSTRAINT `fk_rq_requests_eec_members`
#    FOREIGN KEY (`person_id` )
#    REFERENCES `beamline`.`rq_questions` (`admin_uid` )
#    ON DELETE NO ACTION
#   ON UPDATE NO ACTION
)
ENGINE = InnoDB;

-- -----------------------------------------------------
-- Table `beamline`.`rq_questions_facilities`
-- -----------------------------------------------------
CREATE  TABLE IF NOT EXISTS `beamline`.`rq_questions_facilities` (
  `facility_id` INT NOT NULL ,
  `question_id` INT NOT NULL ,
  PRIMARY KEY (`facility_id`, `question_id`) ,
  INDEX `fk_req_faciliy_current_question_req_question` (`question_id` ASC) ,
  INDEX `fk_rq_questions_facilities_xa_facilities` (`facility_id` ASC),
  CONSTRAINT `fk_req_faciliy_current_question_req_question`
    FOREIGN KEY (`question_id` )
    REFERENCES `beamline`.`rq_questions` (`id` )
    ON DELETE CASCADE
    ON UPDATE CASCADE,
  CONSTRAINT `fk_rq_questions_facilities_xa_facilities`
    FOREIGN KEY (`facility_id` )
    REFERENCES `beamline`.`xa_facilities` (`id` )
    ON DELETE NO ACTION
    ON UPDATE NO ACTION
 )
ENGINE = InnoDB;


-- -----------------------------------------------------
-- Table `beamline`.`rq_questions_supressed`
-- -----------------------------------------------------
CREATE  TABLE IF NOT EXISTS `beamline`.`rq_questions_suppressed` (
  `facility_id` INT NOT NULL ,
  `question_id` INT NOT NULL ,
  PRIMARY KEY (`facility_id`, `question_id`) ,
  INDEX `fk_req_facility_suppressed_question_req_question` (`question_id` ASC) ,
  INDEX `fk_rq_questions_suppressed_xa_facilities` (`facility_id` ASC),
  CONSTRAINT `fk_req_facility_suppressed_question_req_question`
    FOREIGN KEY (`question_id` )
    REFERENCES `beamline`.`rq_questions` (`id` )
    ON DELETE CASCADE
    ON UPDATE CASCADE,
  CONSTRAINT `fk_rq_questions_suppressed_xa_facilities`
    FOREIGN KEY (`facility_id` )
    REFERENCES `beamline`.`xa_facilities` (`id` )
    ON DELETE NO ACTION
    ON UPDATE NO ACTION)
ENGINE = InnoDB;

What gives? Thanks in advance.

From stackoverflow
  • Problem solved; the foreign key to xa_facilities was an INT(11), while xa_facilities' primary key was an INT(4). Duh!

  • I've tried running your queries (NB6.5.1) any they seem to be working fine. I did have to comment out all the foreign key constraints, so it's not an exact reproduction.

    Given that, could it be possible that you didn't create all the referenced tables (xa_facilities, rq_questions etc)? Are they properly structured?

    I recommend, for the future, to separate relational constraints into separate scripts so that you're always sure you're creating them after all your tables are there.

How do I use reflection to get the nested property

I am writing a TwoWay Binding control for ASP.NET. I finally got things working. I'm rebinding using the following code:

private void RebindData()
{
    // return if the DataValue wasn't loaded from ViewState
    if (DataValue == null)
        return;
    // extract the values from the two-way binding template
    IOrderedDictionary values = new OrderedDictionary();
    IBindableTemplate itemTemplate = DataTemplate as IBindableTemplate;
    if (itemTemplate != null)
    {
        foreach (DictionaryEntry entry in itemTemplate.ExtractValues(this))
        {
            values[entry.Key] = entry.Value;
        }
    }

    // use reflection to push the bound fields back to the datavalue
    foreach(var key in values.Keys)
    {
        var type = typeof(T);
        var pi = type.GetProperty(key.ToString());
        if (pi != null)
        {
            pi.SetValue(DataValue, values[key], null);
        }
    }
}

This works for the simple cases like this:

<%# Bind("Name") %>

The reflection technique I'm using isn't working when I have a nested binding statement like this:

<%# Bind("Customer.Name") %>

Is there an easy way to use reflection for nested properties like this? Should I use a recursive function for this, or just a loop?

From stackoverflow
  • Why not use ASP.NET DataBinder that already supports this?

    bendewey : I've research many different approaches to using the builtin ASP.NET two-way binding, my approach is very similar to the FormView, but I want the DataSource to be a single item, not an IEnumerable.
    Paul Alexander : Sorry...wasn't clear. I was thinking about using the built in DataBinder.Eval method which already supports the sub property naming convention. However to address the IEnumerable issue - you don't have to bind directly to a collection. You can an object directly and then bind to the properties of the object by name.

.Net 3.5 - Best way to communicate with another .Net Process?

Hello, I have a library that interacts with our phone system, ie, Hey phone, call this number for me. This library is used in one of our in house products. I would like to put this instead in a service, so that any of our in house products can send the service a message to place a phone call. So basically I want to communicate from a program built in .Net 3.5 with a service running on the same machine also built in the 3.5 framework. I have done some work with WCF and was considering using this but thought I would ask what others have done or would do.

From stackoverflow
  • There are many ways. WCF is a good one. Depending on the circumstance, you might want to consider named pipes, IpcChannel, sockets and other methods.

  • I think WCF is perfectly suited to this.. It allows you to separate your plumbing from your application code, and the configuration allows you to easily change transports(http, tcp, named pipes), add security, throttling, etc., without writing more code.

  • Doh, dont know why i Didnt find this link before, more or less what I want to do. My previous work was using a TCP connection, this one uses named pipes: http://stackoverflow.com/questions/184878/expose-a-wcf-service-through-a-named-pipes-binding

  • I find WCF overcomplicated. I would use MSMQ either directly or via Spring.Framework Messaging

    Serapth : Ironically, I actually find your suggest the more complicated one. I find WCF actually completely simple and easy to start with. That said, I will describe it as problematic and will honestly admit you will spend way more time solving WCF problems than you ever did implementing solutions. Overall though, I do recommend the technology.

Regular expressions C# - is it possible to extract matches while matching?

Say, I have a string that I need to verify the correct format of; e.g. RR1234566-001 (2 letters, 7 digits, dash, 1 or more digits). I use something like:

        Regex regex = new Regex(patternString);
        if (regex.IsMatch(stringToMatch))
        {
            return true;
        }
        else
        {
            return false;
        }

This works to tell me whether the stringToMatch follows the pattern defined by patternString. What I need though (and I end up extracting these later) are: 123456 and 001 -- i.e. portions of the stringToMatch.

Please note that this is NOT a question about how to construct regular expressions. What I am asking is: "Is there a way to match and extract values simultaneously without having to use a split function later?"

From stackoverflow
  • You can use regex groups to accomplish that. For example, this regex:

    (\d\d\d)-(\d\d\d\d\d\d\d)
    

    Let's match a telephone number with this regex:

    var regex = new Regex(@"(\d\d\d)-(\d\d\d\d\d\d\d)");
    var match = regex.Match("123-4567890");
    if (match.Success)
        ....
    

    If it matches, you will find the first three digits in:

    match.Groups[1].Value
    

    And the second 7 digits in:

    match.Groups[2].Value
    

    P.S. In C#, you can use a @"" style string to avoid escaping backslashes. For example, @"\hi\" equals "\\hi\\". Useful for regular expressions and paths.

    P.S.2. The first group is stored in Group[1], not Group[0] as you would expect. That's because Group[0] contains the entire matched string.

    Neil Williams : +1 Very thorough! I'd add one thing though, the reason that you start on match.Groups[1] and not [0] is because [0] contains the entire matched string.
  • Use grouping and Matches instead.

    I.e.:

    // NOTE: pseudocode.
    Regex re = new Regex("(\\d+)-(\\d+)");
    Match m = regex.Match(stringToMatch))
    if (m.success) {
      String part1 = m.Groups[1].Value;
      String part2 = m.Groups[2].Value;
      return true;
    } 
    else {
      return false;
    }
    

    You can also name the matches, like this:

    Regex re = new REgex("(?<Part1>\\d+)-(?<Part2>\\d+)");
    

    and access like this

      String part1 = m.Groups["Part1"].Value;
      String part2 = m.Groups["Part2"].Value;
    
    gnomixa : very useful tip!
    Rob Fonseca-Ensor : +1 for named groups
  • You can use parentheses to capture groups of characters:

    string test = "RR1234566-001";
    
    // capture 2 letters, then 7 digits, then a hyphen, then 1 or more digits
    string rx = @"^([A-Za-z]{2})(\d{7})(\-)(\d+)$";
    
    Match m = Regex.Match(test, rx, RegexOptions.IgnoreCase);
    
    if (m.Success)
    {
        Console.WriteLine(m.Groups[1].Value);    // RR
        Console.WriteLine(m.Groups[2].Value);    // 1234566
        Console.WriteLine(m.Groups[3].Value);    // -
        Console.WriteLine(m.Groups[4].Value);    // 001
        return true;
    }
    else
    {
        return false;
    }
    
    Andomar : +1 for the right regex... btw if you use IgnoreCase, you can use [a-z] instead of [A-Za-z].