Saturday, February 12, 2011

How to keep business support team motivated?

In the course of my career I've noticed that developers working on new functionality are, as a rule, more cheerful than these assigned to troubleshooting and fixing bugs.

Good tips on keeping business support a happy? Organising business support in the way that team's morale isn’t hurt?

  • I have seen this too. There are few approaches that I can think of:

    1. Give some thought to selection process.

    Not everyone have same career aspirations. While some people are always dying to work for the latest technology and challenging projects, there are others who are content at a stable work environment. Picking the person with right KSA (Knowledge, Skills, Attitude) is always central to good person-job match. In this case, you just need to put more stress on the Attitude part.

    2. Choose the right lead

    Team leads play crucial role in controlling the motivation and morale of the team. There must be an open and frank channel of communication with team lead and upper management. Ideally a person from the senior management should be made the owner of the team in formal organization chart. Team lead should actively try to foster a team-culture that suites the nature of the team.

    3. Rewards

    Rewards off course are key tool for managing motivational issues. Just make sure the person receiving the rewards understand that the nature of job was also taken into consideration in decision to reward. If this point is not addressed, it is likely that the person will not take this factor into account when perceiving internal equity.

  • If we start with the assumption that the reason for new function developers being happier is that they get to feel proactive or in control and the troubleshooters are reactive and pushed around by the users one answer comes to mind:

    Create a model for those doing troubleshooting to fixes to generalise these from point fixes into broad, consistent fixes for a class of problem. This puts them in the situation of creating new code, even if not new functionality, and they get to think a problem through and anticipate and avoid problems rather than playing whack-a-mole.

    In fast moving environments it may also be possible to rotate people through the job descriptions by have them follow their feature from new development into fix and realease and hopefully into version 2 of the feature.

    que que : This answer is incredibly well thought out and so well put! I wish I could give this 10 up votes.
    MarkJ : Let them refactor.
    From Bell
  • Our organisation has a substantial amount of support work and we've got hit with this problem really hard. The motivation on support teams could dropping down exponentially over the time if you don't do it right.

    The principles which worked for us were:

    1. Choose the right people. Some people are happier doing new stuff. Some people are actually much more suited to a steady no-nonsense job. It means that you should have two teams - one for development and one for support. Developers only stay on a completed project until they pass their knowledge to the supporters.
    2. Choose the right leader. Good organisation is make or break here. A good leader would help to organise good relationship with the product users and at the same time will care for his team.
    3. Rotate. We try to keep the support people on the project for a period of less then 2 years and then move them to something new. This helps maintaining proper morale and ensure that their skills don't rust.
    4. Relationship with the customer. Make sure that the support team know how valuable they are. The customers/users should occasionally visit the team or the team should go on-site to have a face-to-face session with the users (a friendly dinner or lunch will also help)
    Totophil : Ilya, whilst I strongly agree with many of your answers I am not sure that splitting developers into development and support groups is the best approach. Then you get a tendency for project teams to push things, hoping that they will get fixed as support by a different group. To be cont.
    Totophil : Secondly, dedicated support team often would fail into the trap of looking for quick fixes and not having the influence on the big picture. Their motivation is usually to keep their job (more issues), faster response times (i.e. curing symptoms, not root cause), higher throughput
    Totophil : that can be achieved throught solving repetitive issues they already know to fix. Thirdly, dividing development and support functions you pretty much shield the developers from actual feedback and pain of the real-world software needs.
  • Following Bell's suggestion, consider letting new or junior developers cut their teeth on fixes. Promote them from maintenance to the feature team based on their performance and ability.

    Healthy competition is also a good motivator, but it must be managed to remain a positive influence.

    From Adam Liss

C#/.NET: Detect whether program is being run as a service or a console application.

I have a C#/.NET program that can run both as a console application and as a service. Currently I give it a command-line option to start as a console application, but I would like to avoid that.

Is it possible to programmatically detect whether my program is being started as a service?

If it was pure Win32, I could try starting as a service with StartServiceCtrlDispatcher and fall back to console if it returned ERROR_FAILED_SERVICE_CONTROLLER_CONNECT, but System.ServiceProcess.ServiceBase.Run() pops up an errordialog if it fails and then just returns without signaling an error to the program.

Any ideas?

  • I haven't tried it, but it's possible that Process.GetCurrentProcess will help - under console mode the process name would be the same as the executable, whereas I'd expect (and again, please check!) that when running as a service it would be different.

    Marc Gravell : I thought that the process was still (usually) the same exe itself, unless you go out of your way to rehost via svchost.exe or similar...
    Jon Skeet : Could be - hard to test from my current desk :(
    Arne Claassen : At least under mono, the process name does change to the executing entity (i.e. if run with mono-service the process is now called mono-service). Haven't tried as a windows service
    From Jon Skeet
  • Rasmus, this is the earlier question.

    From the answers it seems the most popular way is to use a simple command line option, or try accessing the Console object in a try catch block (in a Service the Console is not attached to the process and trying to access it throws an exception).

    Or if you're having trouble testing/debugging the service, move code into a separate dll assembly and create a seprate test harness (winforms/console etc).

    (Just noticed that Jonathan has added his solution to the end of the question.)

    From Ash
  • Environment.UserInteractive will do the magic.

    taspeotis : What if the service is running on Windows XP with "Allow this service to interact with the desktop" set?
    Ishmaeel : It will stop doing magic, that's what :)
  • I don't know if this will work, but you may want to try using PInvoke with this code and checking if the parent is "services.exe".

    From taspeotis

nHibernate, can I map to a table that doesn't have an row-per-object mapping?

I have a database that contains a table that looks a bit like this:

PropertyId, EntityId, Value

PropertyId and EntityId are a combined primary key. Every Entity is spread over a couple of rows where every row contains a single property of the entity. I have no control over this database so I'll have to work with it.

Is it possible to use NHibernate to map entities from this table to single objects? I only have to read from this table, this might make things a bit easier. Or would I be better off just using DataReaders and do the mapping myself?

  • Hi,

    Not quite done that, but you could use a custom SQL query to define your entities (distinct entityid, plus any entity level attributes), see here .

    Although I can see you might want the property/values mapped to attributes of the entity object. Which might mean further queries to populate them by hand - which may mean your data reader route is best.

    If your happy for them to be a collection of the entity then that should be no problem.

    Mendelt : Thanks. I'll try it out. I can store the properties in a list and make them available to the outside world through individual property getters that look up the right property in the list. Not ideal but workable :-)
  • I can't remember the exact syntax, but a map would do it:

    <map name='Values' table='EntityPropertyValue'>
      <key column='EntityId'  />
      <index-many-to-many class='Person' column='PersonId' />
      <element column='Value' type='object' />
    </map>
    
    From David Kemp

Can you recommend a Shockwave Flash (SWF) to "movie" converter for OS X?

I've Googled this in various ways, and there's no shortage of software to do it. Since this is something I'm unlikely ever to do again, I'd prefer a free solution, but I'm also willing to pay if the best solution requires it.

I'm a fairly skilled software developer in multiple languages, so if anyone knows of a library that will do it (and is available for OS X), I have no problem "rolling my own".

I have a large number of SWF files for a training course I'm taking, and I want to convert them to H.264 for use on my Apple TV so I can watch them on my television more easily. This must be Mac OS X software, compatible with an Intel Leopard machine.

I don't mind having to convert to an intermediate format, but it sure would be nice to go directly to H.264.

Thanks in advance for your help!

  • You should have a look at ffmpegx which I am use fairly often and which works perfect for my needs.

    But it looks like it cant convert .swf - but to be sure you should try it. It's free software.

    greets

    From
  • As Flash is an interactive, code driven format (i.e. not linear like a video) you cannot normally just convert to a video format. Even if your swf is a linear animation, there may still be ActionScript code controlling the animation.

    What this means for you is that you just need to make a good video/audio capture of the swf, for which you can use a whichever free screen capture software you choose (you'll probably need a fast computer).

    From Iain
  • I don't know such a swf converter for mac os. But I use iwisoft swf converter to convert .swf to .mov video. good one.

  • FlashVideo Converter.

    From mcandre
  • Handbrake takes FLV files as source and can convert to h264. It is free, relies on VLC (which is again available in 64 bit on Mac so you can use Handbrake 64) and can manage a processing queue.

  • If you go the screen capture route, iShowU HD on Mac is the absolute king and will easily grab just the pixels you want.

    Be careful of the TV exclusion zone if you're watching computer video off DVD for example. You'll lose 10% of the picture round the edge.

    From radbourn3

Getting The Full Result from "ps"

Hi,

How do I get the full width result for the *nix command "ps"?
I know we can specify something like "--cols 1000" but is there anyway I can the columns and just print out everything?

  • Try ps -w -w aux. The -w option sets the output to wide, and doing it twice makes the width unlimited. The "aux" part makes it show more information, and is (afaik) pretty standard mode to use. This is of course platform-dependant, the above works with procps version 3.2.7 on Linux.

    Chris Jester-Young : There's nothing magical about "aux"; they're simply the 'a', 'u', and 'x' options specified together. So, you can merge the two 'w' options in too. :-)
    unwind : Ah, yes, true of course. I guess it's just my standard incantation, to treat "aux" as an argument more than an option. Thanks, though.
    From unwind
  • Specify the w option twice, if you're using BSD-style ps. e.g., ps auwwx. A different set of options apply when using System V ps.

    Max Howell : This is a comment, not an answer, surely.
    Chris Jester-Young : It's an answer now!
  • There are two different option syntaxes for ps; the standard POSIX one based on SysV, and the BSD one. GNU ps, as used on linux, supports both, which it can do because the POSIX options have dashes in front and the BSD ones don't, as well as some of it's own options in the normal GNU --long-option-name style.

    Anyway, to get all processes in POSIX style is -e, in BSD it's ax (a includes other user's processes, x includes processes without a controlling terminal i.e. daemons).

    There is no single option that will make it include all the columns. There are a huge number of possible columns. The POSIX options -f, -F and -L all cause it to show different sets of extra columns, as does the BSD option u (hence the "ps aux" mentioned in another answer is a very common command).

    If you really want more columns than that you have to name explicitly which ones you want, using the -o (or o) option. See the man page for a list. There's about a hundred different names you can use, but some of them are duplicates, and others display the same info in different ways.

    ephemient : Accurate but answering the wrong question...
    Mark Baker : I read the bit about "printing out everything" to mean they wanted all the possible columns in the output, so I answered that. I agree the bit about getting all processes was the wrong question.
    From Mark Baker

Changing the BG Color of a selected link.

I have a menu that I am using and it will change the background color when I hover using a:hover but I want to know how to change the class= line so that it sticks.

So from the home if they click contacts the home pages

from (a href="#" class="clr") to (a href="#")

and Contacts would change

from (a href="#") to (a href="#" class="clr")

any help?

JD

  • The way to change class (I assume you're talking of the DOM), in javascript is:

    document.getElementById("element").className='myClass';
    

    Hope this helps.

    From friol
  • I believe you are wanting to highlight the navigational item that you're on. My answer here is fairly valid in this question as well, I believe:

    It's a better semantic match and likely an easier variable to set to keep the navigation using the same classes or ids everywhere and only alter the body element's id to match:

    <li id="homeNav">home</li>
    <li id="blogNav">blog</li>
    

    and then on each page...

    <body id="home">
    <body id="blog">
    

    And in the css:

    #home #homeNav {background-image:url(homeNav-on.jpg);}
    #blog #blogNav {background-image:url(blogNav-on.jpg);}
    
    From davebug
  • This may not apply to you, but it may lead you down the right path. If you are using PHP, stick this in your head before the doctype declaration or the (x)html tag:

    <?php
      // Get current page file name
      $url = Explode('/', $_SERVER["PHP_SELF"]);
      $page = $parts[count($url) - 1];
    ?>
    

    Then, in your menu item where you would like the class designation, place the following, but change "index.php" to the name of the page:

    <?php if ($page == "index.php") echo ' class="current"' ?>
    

    So ultimately your menu should look similar to this:

    <div id="navigation">
      <ul>
        <li><a href="index.php"<?php if ($page == "index.php") echo ' class="current"' ?>>Home</a></li>
        <li><a href="page1.php"<?php if ($page == "page1.php") echo ' class="current"' ?>>Resume</a></li>
        <li><a href="page2.php"<?php if ($page == "page2.php") echo ' class="current"' ?>>Photography</a></li>
      </ul>
    </div>
    

    Last step is adding the CSS:

    #navigation ul li a.current {
      background-color: #FFF;
    }
    

    Hope this helps.

    From PHLAK
  • Hi John,

    The mechanism we use frequently is by having a few generic event listeners on the body and have all required events bubble up. Once caught, we check for a certain className (or className pattern) on the triggering element. If such a className is found, we consider it a state identifier, and we trigger behavior based on such states.

    For instance, we have defined className pairs (such as "selected" and "unselected") with the default behavior of toggling. Or make them exclusive by giving the parent element the className "exclusive-selected".

    A simple mechanism like that can be extended to your liking and can be very powerful.

    Allow me to post a simple demonstration. Non-generic, but it is just to illustrate the inner workings of such a mechanism. For this example I consider the className pair "selected" and "unselected" to be exclusive.

    <html>
      <head>
        <script>
          document.onclick = function(evt) {
            var el = window.event? event.srcElement : evt.target;
            if (el && el.className == "unselected") {
              el.className = "selected";
              var siblings = el.parentNode.childNodes;
              for (var i = 0, l = siblings.length; i < l; i++) {
                var sib = siblings[i];
                if (sib != el && sib.className == "selected")
                  sib.className = "unselected";
              }
            }
          }
        </script>
        <style>
          .selected { background: #f00; }
        </style>
      </head>
      <body>
        <a href="#" class="selected">One</a> 
        <a href="#" class="unselected">Two</a> 
        <a href="#" class="unselected">Three</a>
      </body>
    </html>
    

    It ought to work on IE, Firefox and other browsers. Of course this mechanism can be made generic and have all kinds of className states and behaviors implemented.

  • You may want to check out jQuery (jquery.com).

    Using jQuery, you would change the class (and stick it) like this:

    $('#link-id').addClass('your-class');
    

    You could bind the code to the links like this:

    $('#link-id').mouseover(
       function(){
          $(this).addClass('your-class');
       }
    );
    

    http://docs.jquery.com/Attributes

    From Eli

Hooking up GUI interface with asynchronous (s)ftp operation

Trying to implement a progress dialog window for file uploads that look like a cross between IE download dialog and Firefox download dialog with a python GUI library on Windows.

  1. What asynchronous (S)FTP libraries are there for python? Ideally I should be able to do file upload resumes and track the progress of each parallel file uploads.
  2. If I'm running each file upload in a separate process each, how would I get the upload status and display it in a progress bar dialog?
  • "ftplib" is the standard ftp library built in to Python. In Python 2.6, it had a callback parameter added to the method used for uploading.

    That callback is a function you provide to the library; it is called once for every block that is completed.

    Your function can send a message to the GUI (perhaps on a different thread/process, using standard inter-thread or inter-process communications) to tell it to update its progress bar.

    Reference

    TheObserver : Let's say I can't use a python version greater than 2.5, what are my options then for passing a callback parameter?
    Oddthinking : Not so good. IIRC, the callback for *download* was added in 2.5.2 (perhaps earlier?) but wasn't added to the *upload* until 2.6. (See also separate answer for ckftp2.)
  • If you want a complete example of how to use threads and events to update your GUI with long running tasks using WxPython have a look at this page. This tutorial is quite useful and helped me perform a similar program than yours.

    From Mapad
  • If you data transfer runs in a separate thread from the GUI, you can use wx.CallAfter() whenever you have to update you progress bar from the data transfer thread.

    First, using CallAfter() is mandatory as wxPython function cannot be called from child threads.

    Second, this will decouple the execution of the data transfer from the GUI in the main thread.

    Note that CallAfter() only works for threads, not for separate processes. In that case, using the multiprocessing package should help.

    From Ber
  • If you can't use Python 2.6's ftplib, there is a company offering a commercial solution.

    Chilkat's CKFTP2 costs several hundreds of dollars, but promises to work with Python 2.5, and offers a function call get_AsyncBytesSent() which returns the information you need. (I didn't see a callback, but it may offer that too.)

    I haven't used this product.

    Also consider that if FTP proves to be too hard/expensive, you could always switch to HTTP uploads instead. Chilkat have a free HTTP/HTTPS upload library.

Best Practice for Loading Object from Serialized XML in C#

Greetings,

I have a particular object which can be constructed from a file, as such:

public class ConfigObj
{
     public ConfigObj(string loadPath)
     {
          //load object using .Net's supplied Serialization library
          //resulting in a ConfigObj object
          ConfigObj deserializedObj = VoodooLoadFunction(loadpath); 

          //the line below won't compile
          this = thisIsMyObj; 
     }
}

I want to, in essense, say "ok, and now this object we've just deserialized, this is the object that we in fact are." There are a few ways of doing this, and I'm wondering which is considered a best-practice. My ideas are:

  • Build a copy-into-me function which copies the object field by field. This is the current implementation and I'm pretty sure its a horrible idea since whenever a new member is added to the object I need to also remember to add it to the 'copy-into-me' function, and there's no way that's maintainable.
  • Build a static method for the ConfigObj class which acts as a de-facto constructor for loading the object. This sounds much better but not very best-practice-y.

I'm not entirely happy with either of the two, though. What is the acknowledged best practice here?

  • I always go with the static method. Usually it's kind of a hierarchy which is loaded, and therefore only the root object needs the method. And it's not really an unusual approach in the .NET framework (e.g. Graphics.FromImage), so it should be fine with users of your class.

  • Your second option is what is called a factory method and is a common design technique. If you do use this technique, you may find that you need to know the type of class you will load before you actually load the class. If you run into this situation, you can use a higher level type of factory that looks at the stream and calls the factory method for the appropriate type of class.

    AlexeyMK : Thank you. Is it considered acceptable to (at least in limited cases where I'm only loading this particular type) create a Factory method inside the same class as the method being loaded? For whatever reason, I was under the impression factories usually had their own classes.
    Greg Hewgill : Certainly, you can create a static factory method within the class itself. You only need the higher level factory abstraction if you have a whole tree of potential objects to deal with. For your situation, just make a static method that returns a newly allocated instance of your class.
  • There's nothing wrong with having a static method instead of a constructor. In fact, it has a number of advantages.

    From Jon Skeet

distributed transaction between two MS SQL Server 2005

I need to make DISTRIBUTED TRANSACTION between two MS SQL Server 2005, it drops an error that NO ACTIVE TRANSACTION IS PRESENT or smth like this. DTCTESTER programs drops an error that transaction could not be done. btw 135 port is open on the firewall.

Maybe anyone knows what a problem, or have a suggestion?

  • KB 954950 looks like the problem, patch in a post SP2 hotfix

    From gbn

Importing Active Directory Users and Groups into SQL Server (possibly via c#)

I need to import all ad groups in a few OUs into a table in SQL Server 2008. Once I have those I need to import all the members of those groups to a different table. I can use c# to do the work and pass the data to SQL server or do it directly in SQL server.

Suggestions on the best way to approach this?

  • Add a Linked Server to your SQL Server and query the Active Directory via LDAP queries. This here described this quite well:

    Create a SQL Server View of your AD Users, Brendan Tompkins (MVP)

    Jeremy : I think you can only return 1000 active directory objects from within SQL server, because you can't do a paged query from SQL server.
    From Mudu
  • Mudu,

    Thanks, that has got me started. I can query users and groups from the domain that the SQL Server is in. Problem is I want to query against a different domain, ideas how I would do this.

    Also, how would I get group membership?

    Thanks in advance.

    From Arry
  • Arry,

    I don't know exactly, but found some links that may help you. I think the hottest track is this expression:

    "(&(objectCategory=Person)(memberOf=DN=GroupName, OU=Org, DC=domain,
    DC=com))"
    

    I found it in LDAP Query for group members on a ColdFusion community's site. I'm more or less sure the filter can easily be applied to your query. I'm sorry, but I cannot test it, because I have no AD around here.

    This one could also be a bit (but less) interesting:

    http://forge.novell.com/pipermail/cldap-dev/2004-April/000042.html

    Hope this helps, cheers,

    Matthias

    Eddie : The filter described in this answer is the best way to return all users within an Active Directory Security Group that I have found.
    From Mudu
  • I'm having the same issue. I need to query users from our internal domain and users from our external domain. The OUs and Groups that I use for my application are in the external domain. The SQL Server is in the internal domain. I can query the internal domain just fine but get the following error when I try the external domain from SQL Server:

    Msg 7330, Level 16, State 2, Line 1 Cannot fetch a row from OLE DB provider "ADSDSOObject" for linked server "(null)".

    I'm using OPENROWSET as follows:

    select * FROM OPENROWSET('ADSDSOObject', 'User ID=domain\User;Password=XXX;adsdatasource;', 'SELECT cn, mail, co, distinguishedName, displayName FROM ''LDAP://DC=XX,DC=XX'' where objectClass = ''User'' ')

    This works on our internal domain. Any pointers would be greatly appreciated.

    Thanks, Mike

    From

Do web service requests guarantee end of file is reached?

Hi, If I am transferring data over a web service, does it guarantee that the end of file was reached?

what about the data send, does it guarantee it wasn't corrupted somehow?

(using asp.net web services)

  • Hi,

    HTTP uses TCP for transport which includes error detection, and automatic re-send of corrupted data. The detection is quite robust but is not perfect: some errors still manage to go through.

    ASP.NET does not add any protection against data corruption on top of the one provided by TCP, so it is possible that your data gets corrupted during transfert.

    If you really need to ensure that your data has not been corrupted, you can hash your data, and send the generated hash along with the data in your request (or response). On the receiving side, hash the received data and compare the two hashes. If they differ, the data has been corrupted, and you can take appropriate measures.

    This technique is very robust: it is very, very improbable that the data and hash get corrupted in a way that they will still correspond.

Pointer question

I am new to C and i have this question. why does the following code crash:

int *a = 10;
*a = 100;
  • You need to assign the pointer to a memory location, not arbitrary value (10).

    int cell = 10;
    int *a = &cell; // a points to address of cell
    *a = 100;       // content of cell changed
    

    See my answer to another question, about being careful with C.

    From gimel
  • Because you've never allocated any memory for a. You've just allocated some stack space for a pointer to a.

    int *a = NULL;
    
    a = malloc (sizeof (int));
    
    if (a != NULL)
    {
    *a =10;
    }
    

    Will work.

    Alternatively you could give a the address of some existing variable, which would work as well.

    i.e.

    int a* = NULL;
    int b = 10;
    
    a = &b;
    

    This will now mean that doing something like

    *a = 100;
    

    will also set b to be == 100

    Check out this: http://home.netcom.com/~tjensen/ptr/pointers.pdf

    From Joeb
  • Because You declare a pointer to int, initialize the pointer to 10 (an address) and then try to assign a value to an int at this address. Since the memory at address 10 does not belong to your process, You get a crash. This should work:

    int *a;
    a = malloc(sizeof(int));
    *a = 10;
    printf("a=%i\n", *a);
    free(a);
    
    From zoul
  • Does this code even compile? 10 isn't convertible to an int *, unless you cast it like so:

    int *a = (int *) 10;
    *a = 100;
    

    In that case, you're trying to write 100 into the memory address at 10. This isn't usually a valid memory address, hence your program crashes.

    DrJokepu : Plain C isn't really concerned about type safety. Most modern compilers will generate a warning but will compile it none the less.
  • The following line,

    int *a = 10;
    

    defines a pointer to an integer a. You then point the pointer a to the memory location 10.

    The next line,

    *a = 100;
    

    Puts the value 100 in the memory location pointed to by a.

    The problem is:

    1. You don't know where a points to. (You don't know the value of memory location 10)
    2. Wherever a points to, you probably have no right changing that value. It's probably some other program/process's memory. You thief!
    zoul : It’s probably not some other process’ memory because of the memory virtualization (AFAIK). It would have been a part of some other process in DOS, for example.
    DrJokepu : I agree with Zoul, on modern architecures, each process has its own address space. On x86, this is called Protected Mode. Even though both the Linux and Windows kernels put themselves above 0xC0000000, I am sure that the first hundreds of bytes of each address space belong to the kernel too.
    moogs : i wanted to customize my answer to fit the author of the question. talking about virtual memory and protected mode might be a bit daunting for someone who still needs basic c pointer help :) both of you are right tho, any ideas how to make the "correct" yet simple to understand?
    From moogs
  • Because you are trying to write 100 to the memory location 0x0000000A which is probably not allocated to your program. That is,

    int *a = 10;
    

    does not mean that the pointer 'a' will point to a location in memory having the value of 10. It means it is pointing to address 10 (0x0000000A) in the memory. Then, you want to write something into that address, but you don't have the "rights" to do so, since it is not allocated

    You can try the following:

    int *a = malloc(sizeof(int));
    *a = 100;
    

    This would work, although horribly inefficient. If you only need a single int, you should just put it into the stack, not the heap. On a 32-bit architecure, a pointer is 32 bits long, and an int is 32 bits long too, so your pointer-to-an-int structure takes up (at least) 8 bytes of memory space this way instead of 4. And we haven't even mentioned caching issues.

    From DrJokepu
  • It's probably crashing because you are assigning the pointer to some part of memory which you don't have access to and then you're assigning some value to that memory location (which you're not allowed to do!).

    From jpoh
  • I would like to propose a slight change in the use of malloc(), for all the answers that suggest using it to allocate memory for the int. Instead of:

    a = malloc(sizeof(int));
    

    I would suggest not repeating the type of the variable, since that is known by the compiler and repeating it manually both makes the code more dense, and introduces an error risk. If you later change the declaration to e.g.

    long *a;
    

    Without changing the allocation, you would end up allocating the wrong amount of memory ( in the general case, on 32-bit machines int and long are often the same size). It's, IMO, better to use:

    a = malloc(sizeof *a);
    

    This simply means "the size of the type pointed at by a", in this case int, which is of course exactly right. If you change the type in the declaration as above, this line is still correct. There is still a risk, if you change the name of the variable on the left hand side of the assignment, but at least you no longer repeat information needlessly.

    Also note that no parenthesis are needed with sizeof when using it on actual objects (i.e. variables), only with type names, which look like cast expressions. sizeof is not a function, it's an operator.

    From unwind
  • Okay, trying to give the simplest explanation today, while trying to give you more detailed picture about it all. Lets add some parentheses shall we?

    (int*) a = 10;
    (*a) = 100;
    

    You attempt to write four bytes into the address-range [10-13]. The memory layout of your program starts usually higher, so your application does not accidentally overwrite anything from where it could and still function (from .data, .bss, and stack for instance). So it just ends up crashing instead, because the address-range has not been allocated.

    Pointer points to a memory location and C static typing defines a type for a pointer. Though you can override the pointer easily. Simply:

    (void*) v = NULL;
    

    Here we go further to things. What is a null pointer? It's simply pointer that points to address 0.

    You can also give a struct type for your pointer:

    struct Hello {
        int id;
        char* name;
    };
    
    ...
    
    struct Hello* hello_ptr = malloc(sizeof Hello);
    hello_ptr->id = 5;
    hello_ptr->name = "Cheery";
    

    Ok, what is malloc? Malloc allocates memory and returns a pointer to the allocated memory. It has a following type signature:

    void* malloc(size_t size);
    

    If you do not have a conservative garbage collector, it is likely that your memory won't end up being freed automatically. Therefore, if you want to get the memory back into use from what you just allocated, you must do:

    free(hello_ptr);
    

    Each malloc you do has a size-tag in it, so you do not need to state the size of the chunk you pointed for free -routine.

    Ok, yet one thing, what does a character string look like in memory? The one similar to "Cheery" for instance. Simple answer. It's a zero-terminated array of bytes.

    0.1.2.3.4.5. 6
    C h e e r y \0
    
    Onorio Catenacci : Interesting response but I don't think you answered the actual question.
    Cheery : Oh, I guess I was carried away. Well, I add a paragraph that answers the actual question. :)
    DrJokepu : Actually it is address range 10-13, not 10-14. Sorry for the nitpicking :)
    Cheery : Depends about how you look at it. Yes, the set of addresses that get changed: [10, 11, 12, 13] ... fixing it because the marking '-' is more correct that way.
    From Cheery
  • You could also write it as:

    int* a = 10;
    *a = 100;
    

    Note the different spacing on the first line. It's not a popular style, but I personally think it's clearer. It has exactly the same meaning to the compiler.

    Then, read it out loud:

    "Pointer-to-int 'a' becomes 10"
    "Value-pointed-to-by 'a' becomes 100"
    

    Substituting the actual value:

    "Value-pointed-to-by 10 becomes 100"
    

    ... at which you realise that 10 is unlikely to point to a piece of memory you can use.

    You would pretty much never assign to a pointer with a literal:

    int* ptr = (int*)10;  // You've guessed at a memory address, and probably got it wrong
    int* ptr = malloc(sizeof(int)); // OS gives you a memory address at runtime
    

    I guess there might be some very low level jobs where you directly specify absolute memory addresses. Kernel implementation for example?

    From slim

ASP.NET authentication mode=Forms - so why am I getting a Windows Login prompt?

I have authentication mode set to forms in my asp.net web.config but am still getting a windows login prompt when i browse to the website.

Could authentication mode be set elsewhere, in IIS for example? My site runs on IIS 6.

Thanks.

  • I have had issues where the authentication was set to forms and the directory security was set to allow anonymous, but some resources (images in my particular case) did not have the proper permissions to allow the anonymous user to read them.

    The effect is that the user was prompted to login so that the graphics could be displayed, after which the form was displayed and the user logged in (again) with the intended form.

    From DocMax
  • This could be because the permissions on the folder that is being served is not allowed to be accessed by the user running the web site

    From Andrew Cox
  • Sounds like windows permissions problem.

    Windows permissions will always override anything that you have set up in aspnet.

    I would start by looking at "anonymous access" permissions in IIS admin, then work your way through the file system.

    From seanb
  • You have configured anonymous access in IIS Administrator, but the IIS user does not have permission to access the filesystem, defaulting to the login dialog to authenticate as Windows user.

    From devio
  • As it happens a colleague updated my machine to .NET Framework 3.5 SP1 whilst I was away. So I compiled my project and released onto the server which does not have SP1 installed and the above happened.

    I've installed SP1 on the server and it's working fine now.

    Thanks for all your input.

    Just to clarify : the login popped up because the application was unable to load a file due to the problem described in the following: http://geekswithblogs.net/LessonsLeared/archive/2008/08/21/hidden-surprises-in-.net-3.5-service-pack-1.aspx

    From paulie

How to create a Silverlight control that has two content areas

I want to create a Silverlight 2 control that has two content areas. A Title and a MainContent. So the control would be:

<StackPanel>
<TextBlock Text=" CONTENT1 "/>
<Content with CONTENT2 "/>
</StackPanel>

When I use the control I should just be able to use:

<MyControl Text="somecontent">main content </MyControl>

How can I create such a control?

  • What you wanted is a Silverlight version of the WPF HeaderedContentControl You can find a try here. http://leeontech.wordpress.com/2008/03/11/headeredcontentcontrol-sample/

    From Jobi Joy
  • You can do that easily with the ContentProperty attribute.

    Then you can define your code behind as:

    [ContentProperty("Child")]
    public partial class MyControl: UserControl
    {
     public static readonly DependencyProperty ChildProperty = DependencyProperty.Register("Child", typeof(UIElement), typeof(MyControl), null);
    
     public UIElement Child
     {
      get { return (UIElement)this.GetValue(ChildProperty); }
      set
      {
       this.SetValue(ChildProperty, value);
       this.content.Content = value;
      }
     }
    

    What that will do is any default content within your tags (<MyControl Text="somecontent">main content </MyControl>) - will be set as the Child property on your class. Then once it's been set you can assign it to any control you like.

    Edit:

    You can have as many contents as you like, but you can only have 1 auto-content (which is designated via the ContentProperty attribute). If you want two you could do:

    <MyControl>
      <MyControl.Content1>Hello World</MyControl.Content1>
      <MyControl.Content2>Goodbye World</MyControl.Content2>
    </MyControl>
    

    All you have to do is make sure you have the matching dependency properties in your code. Then when the property is set, just assign it to a parent content control in your XAML.

    Peter : Perfect, can I have two contents?
    Mark Ingram : Answered in my question as I didn't have enough characters here.

Databases: Are "TEXT" fields less efficient than "varchar"?

Is it less efficient to use TEXT than varchar in an SQL database?

If so why?

If not why would you not just always use TEXT?

I'm not targetting a specific database here but oracle is probably the most relevant, although I'm testing on MySQL for the time being as part of a proof of concept.

  • From Microsoft here

    ntext, text, and image data types will be removed in a future version of Microsoft SQL Server. Avoid using these data types in new development work, and plan to modify applications that currently use them. Use nvarchar(max), varchar(max), and varbinary(max) instead.

    When you use varchar(max) over text you can use it in the WHERE clause, because they work the same as their smaller counterparts, varchar,nvarchar and varbinary. Below is a small list of what should be used as opposed what was to be used:

    • Use varchar(max) instead of text
    • Use nvarchar(max) instead of ntext
    • Use varbinary(max) instead of image
    From Galwegian
  • The short answer is: Yes, they are less efficient.

    The longer, more convoluted answer is:

    Yes, they are probably less efficient. It depends on which DBMS you are using and the size of your table, etc, etc. TEXT fields are variable width, and as such the DBMS has to do more work when trying to find records. How much this impacts on your performance is directly proportional to how efficient your DBMS is in general, how much data it stores about table rows, and whether it optimises fixed length tables.

    I know MySQL works faster with fixed length table rows, but you have to tell it that the table is able to be treated as a fixed length table first. I don't really have any practical experience with other DBMS's to be able to relate actual numbers. But on tables with lots (reads a million or more) of records, it can make a significant difference. Smaller tables will have little to no practical difference though.

    dan04 : That's `TEXT` vs. `CHAR`. The OP asked for `TEXT` vs. `VARCHAR`.
  • You need to be specific about which database you're talking about. I believe in at least some databases, TEXT is stored as a CLOB separate from the table itself (which just contains a reference). This leads to the table being smaller (good) but an extra lookup and probably cache miss when fetching (bad).

    There are probably indexing and querying implications too, but again it will depend on the particular RDBMS you're using.

    From Jon Skeet
  • PostgreSQL documentation says:

    Tip: There are no performance differences between these three types, apart from increased storage size when using the blank-padded type, and a few extra cycles to check the length when storing into a length-constrained column. While character(n) has performance advantages in some other database systems, it has no such advantages in PostgreSQL. In most situations text or character varying should be used instead.

SQL date format issue in select query

I have an ASP page which will fetch records from a SQL server DB table. The table "order_master" has a field called order_date. I want to frame a select query to fetch order date > a date entered by user(ex : 07/01/2008)

I tried with convert and cast, but both are not working. The sample data in order_date column is 4/10/2008 8:27:41 PM. Actually, I dont know what type it is (varchar/datetime).

Is there any way to do that?

  • You could create a stored procedure like this

    CREATE PROCEDURE GetOrders
        @OrderDate DATETIME
    AS
    SELECT
        *
    FROM order_master
    WHERE Order_Date > @OrderDate
    
    GO
    

    Then you can just convert the users input to a date before calling the stored procedure via your ASP code.

    Edit

    I just noticed the remark about the column type, you can run this command

    sp_help order_master
    

    to get column information to find the data type of order_date.

  • Have you tried CONVERT()'ing both values to a datetime type?

  • I'd check to make sure that the SQL datatype is a DateTime or SmallDateTime first, then I'd check to make sure that you're passing in a Date/DateTime value from the page.

    If those are both correct, then you'd probably be better off following Joel's advice and explicitly convert both values to dates before trying the comparison. Also, check the precision of the time values that you're looking at; it seems obvious, but 1/1/2008 12:00:00.001 AM will not be equal to 1/1/2008 12:00:00.000 AM. Yes, I am speaking from experience. :P

  • the 07/01/2008 date is the British/French annotation, so all you need to do is:

    SELECT myColumn FROM myTable WHERE myDateField >= convert(datetime, '07/01/2008 00:00:00', 103)

    this code will get all rows where myDateField has the date 7th of January 2008, since 00:00:00 (hh:mm:ss) so, the first second on that day... in simple words, the entire day.

    for more info, check Books online on MSDN

    From balexandre
  • Remember that when comparing dates, 4/10/2008 8:27:41 PM is not equal to 4/10/2008. SQL Server will interpret 4/10/2008 to mean 4/10/2008 12:00:00 AM, and do an exact comparison down to the second. Therefore 4/10/2008 is LESS THAN 4/10/2008 8:27:41 PM

  • I shall fileter before framing the query.but how to frame the query ? thats what i am confused

  • You state you don't know the field type. That would be the first problem to solve, find out. You can do that with:-

    SELECT DATA_TYPE
    FROM INFORMATION_SCHEMA.COLUMNS
    WHERE TABLE_NAME = 'Order_Master' AND
        COLUMN_NAME = 'Order_Date'
    

    If its not one of the datetime types it should be converted, if that isn't your responsibility then get on to someone who does have the responsibility.

    The fact that you are concerned about the 'format' of the date indicates that you may be building the SQL using concatenation. If so stop doing that. Use a command with a parameter and pass in the date as date type.

    Now your issue is one of how the date is entered at the client end and getting it into an unambigous format that can be parsed as a date in the ASP code.

    If that is not something you have solved add a comment to this answer and I'll expand this answer.

  • helow i am new here i have a table name Orde in one of the culome i have date time that the order created i want to select all the order in every mont and year

    how do i do it

  • hi, take date format in C#. I have some problem so I can't solve problem.

    code: private void dtTmeStartDate_ValueChanged(object sender, EventArgs e) { TxtClintName.Text = String.Format("{0:mm/dd/yyyy}",dtTmeStartDate.Text); }

    output should be come : 05/25/2008