Friday, May 6, 2011

Dragged div change places with destination

Hi.

Maybe a bit complex to explain. I have a grid with 9 images 100 x 100 px like this (each number symbolize a picture):

1 2 3
4 5 6
7 8 9

What I want is that the user can drag and drop e.g. 9 over 1 and they change places like this:

9 2 3
4 5 6
7 8 1

Sortables from jquery UI will not work since their solution is using floats. That will "push" all the boxes to the right or left e.g.:

9 1 2
3 4 5
6 7 8

thanks in advance.

From stackoverflow
  • take a look at this plugin:

    http://github.com/brandonaaron/jquery-swap/tree/master

  • This uses both Draggable and Droppable. The Draggable reverts to it's original position on drop. When dragging starts, the Draggable creates a function to specify where to insert the Droppable that the item gets dropped on. When the item is dropped the drop function inserts the dragged item after the item it was dropped on and invokes the insert function on the dropped item to move the Droppable to the correct position.

    $(function() {
      $('.item').draggable( {
         containment: 'parent',
         revert: true,
         revertDuration: 0,
         start: function() {
             var that = $(this);
             var previous = that.prev( '.item:last' );
             var next = that.next( '.item:first' );
             that.data( 'insert' , function(elem) {
                 if (previous.size() > 0) {
                    $(elem).insertAfter(previous);
                 }
                 else if (next.size() > 0) {
                    $(elem).insertBefore(next);
                 }
             });
         }
      });
      $('.item').droppable( {
        accept: '.item',
        drop: function(event, ui) {
           var elem = $(this);
           if (elem.siblings('.item').size() > 1) {
         ui.draggable.insertAfter(elem);
         var insert = ui.draggable.data('insert');
         insert(elem);
           }
           else { // case where there are only two elements, swap
               var parent = elem.closest('.container');
               var first = parent.children( '.item:first' );
               var last = parent.children( '.item:last' );
               last.insertBefore( first );
           }
        }
      });
    });
    
    <div id="container">
        <span class="item">1</span>
        <span class="item">2</span>
        <span class="item">3</span>
        <span class="item">4</span>
        <span class="item">5</span>
    </div>
    
  • Thanks for the fast replies!

    Your solutions looks good but the first one throws some errors when changing position 1 and 2. The second one is not quite there. But they help alot!

    I have tried to make some code that I think is a step in the right direction. What do you think?

    <!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" lang="en" xml:lang="en">
    <head>
        <meta http-equiv="Content-type" content="text/html; charset=iso-8859-1" />
        <title>Drag drop 1</title>
        <script type="text/javascript" src="js/jquery-1.3.2.min.js"></script>
        <script type="text/javascript" src="js/jquery-ui-1.7.1.custom.min.js"></script>
        <script type="text/javascript">
        $(document).ready(function() {
         $(".item").draggable({
          // Elements cannot go outside #container
          containment: 'parent',
          // Make sure the element can only be dropped in a grid
          grid: [150,150],
          start: function(event, ui) {
           // Make sure picture always are on top when dragged (z-index)
           $(this).css({'z-index' : '100'});
           // Show start dragged position
           var Startpos = $(this).position();
           $("div#start").text("START: \nLeft: "+ Startpos.left + "\nTop: " + Startpos.top);
          },
          stop: function(event, ui) {
           // Revert to default layer position when dropped (z-index)
           $(this).css({'z-index' : '10'});
           // Show dropped position
           var Stoppos = $(this).position();
           $("div#stop").text("STOP: \nLeft: "+ Stoppos.left + "\nTop: " + Stoppos.top);
          }
         });
        });
        </script>
        <style>
        #container {
         width:480px;
         border:1px solid #000;
        }
        .item {
         position:relative;
         width:150px;
         height:150px;
         z-index:10;
        }
        </style>
    </head>
    <body>
        <div id="container">
         <img id="productid_1" src="images/pic1.jpg" class="item" alt="" title="" /><img id="productid_2" src="images/pic2.jpg" class="item" alt="" title="" /><img id="productid_3" src="images/pic3.jpg" class="item" alt="" title="" /><img id="productid_4" src="images/pic4.jpg" class="item" alt="" title="" /><img id="productid_5" src="images/pic5.jpg" class="item" alt="" title="" /><img id="productid_6" src="images/pic6.jpg" class="item" alt="" title="" /><img id="productid_7" src="images/pic7.jpg" class="item" alt="" title="" /><img id="productid_8" src="images/pic8.jpg" class="item" alt="" title="" /><img id="productid_9" src="images/pic9.jpg" class="item" alt="" title="" />
        </div>
        <div style="clear:both;"></div>
        <div id="start">Waiting...</div>
        <div id="stop">Waiting...</div>
    </body>
    </html>
    

Using a .net compiled dll inside native c++

Hi, as i understand that any .NET program gets compiled to MSIL which is fed to the CLR which compiles it to the assembly code and along with the help of JIT it executes it.

I was wondering, as .NET is a wrapper around the win32 api and the CLR ultimately converts the MSIL to assembly program. Isn't it possible for me to write some functionality in C#, make to a dll and then i use a tool which makes it a complete .net independent file for me to use inside unmanaged code like in C or C++.

Am i talking about Interops and COM? Isn't this idea different from it? My aim is to run a .NET dll on machine not having .NET framework.

From stackoverflow
  • It's not a supported way and many features (like Reflection) rely on metadata provided at a higher level than raw machine code. There are some programs (called .NET linkers) that might help, but they are not 100% reliable.

  • You can use the Native Image Generator (Ngen.exe) to compile a MSIL DLL to a native code DLL, but this will not allow you to run it on a system without the .NET Framework. You will still have references to other DLLs of the framework and even if you include these DLLs, it will not work on a system without the .NET framework, because the framework is more than just a collection of DLLs.

    Mehrdad Afshari : Indeed, ngen cannot remove the need to the actual assembly. An assembly is more than IL code. It contains metadata which is still needed to run.
  • If you poke around on the web, I think there are a number of tools to 'compile' .NET assemblies/code to remove their need of the framework. Not sure how well they work....

  • This KB article explains a way to call managed methods from native code. However, you still need to have the .NET framework.

Why does my Jnlp program not working with log4j ?

Hello there. I have the following problem: I've deployed in Tomcat a JNLP and an executable JAR files. JNLP file should automatically download the JAR file and execute it. The JAR file is signed and verified. This is done (the downloading part). But when to execute the JAR main class (specified in the JNLP file), a problem occurs: A part of the main class code is executed. Afterwards, when it tries to load a class that has a static final org.apache.log4j.Logger instance declared, it says an error.

Below are the representative parts of the JNLP file, the code and the error.

JNLP

<?xml version='1.0' encoding='UTF-8'?>
<jnlp spec="1.5+" codebase="http://localhost:8080/examples" href="DemoInstaller.jnlp" download="eager" main="true">
    <information>
        <title>Demo Installer</title>
        <vendor>Codemart [www.codemart.ro]</vendor>
        <homepage>https://sourceforge.net/projects/cminstall/</homepage>
        <description>This is a demo installer built using Codemart Installer framework with JavaFX</description>
        <description kind="tooltip">Codemart Demo Installer</description>
        <offline-allowed />
        <shortcut online="true">
            <desktop />
        </shortcut>
    </information>

<security>
    <all-permissions />
</security>

<update check="background" />

<resources>
    <j2se href="http://java.sun.com/products/autodl/j2se" version="1.6+" />
   <jar href="DemoInstaller.jar" main="true" download="eager" />
</resources>

<application-desc main-class="ro.codemart.installer.packer.ant.impl.nestedjar.Main" />

The main class:

public class Main {
 public static void main(String[] args) throws Exception {
     final Main main = new Main();
     //this is the problem class !
     Class clazz = Class.forName("WizardRunner");
     Method m = clazz.getMethod("main", new Class[]{args.getClass()});
     m.invoke(null, new Object[]{args});      
    ...
   }
}

And the problem class:

public class WizardRunner{

    private final static Logger log = Logger.getLogger(WizardRunner.class);
...
}

And the error:

log4j:ERROR Could not find [log4j.dtd]. Used [sun.misc.Launcher$AppClassLoader@d9f9c3] class loader in the search. log4j:ERROR Could not parse url [jar:http://localhost:8080/examples/DemoJar.jar!/log4j.xml]. java.io.FileNotFoundException: JAR entry log4j.dtd not found in at com.sun.jnlp.JNLPCachedJarURLConnection.connect(Unknown Source) at com.sun.jnlp.JNLPCachedJarURLConnection.getInputStream(Unknown Source) at com.sun.org.apache.xerces.internal.impl.XMLEntityManager.setupCurrentEntity(Unknown Source) at com.sun.org.apache.xerces.internal.impl.XMLEntityManager.startEntity(Unknown Source) at com.sun.org.apache.xerces.internal.impl.XMLEntityManager.startDTDEntity(Unknown Source) at com.sun.org.apache.xerces.internal.impl.XMLDTDScannerImpl.setInputSource(Unknown Source) at com.sun.org.apache.xerces.internal.impl.XMLDocumentScannerImpl$DTDDriver.dispatch(Unknown Source) at com.sun.org.apache.xerces.internal.impl.XMLDocumentScannerImpl$DTDDriver.next(Unknown Source) at com.sun.org.apache.xerces.internal.impl.XMLDocumentScannerImpl$PrologDriver.next(Unknown Source) at com.sun.org.apache.xerces.internal.impl.XMLDocumentScannerImpl.next(Unknown Source) at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl.scanDocument(Unknown Source) at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(Unknown Source) at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(Unknown Source) at com.sun.org.apache.xerces.internal.parsers.XMLParser.parse(Unknown Source) at com.sun.org.apache.xerces.internal.parsers.DOMParser.parse(Unknown Source) at com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderImpl.parse(Unknown Source) at javax.xml.parsers.DocumentBuilder.parse(Unknown Source) at org.apache.log4j.xml.DOMConfigurator$2.parse(DOMConfigurator.java:612) at org.apache.log4j.xml.DOMConfigurator.doConfigure(DOMConfigurator.java:711) at org.apache.log4j.xml.DOMConfigurator.doConfigure(DOMConfigurator.java:618) at org.apache.log4j.helpers.OptionConverter.selectAndConfigure(OptionConverter.java:470) at org.apache.log4j.LogManager.(LogManager.java:122) at org.apache.log4j.Logger.getLogger(Logger.java:117) at ro.codemart.installer.wizard.WizardRunner.(WizardRunner.java:38) at java.lang.Class.forName0(Native Method) at java.lang.Class.forName(Unknown Source) at ro.codemart.installer.packer.ant.impl.nestedjar.Main.executeApplicationMainClass(Main.java:216) at ro.codemart.installer.packer.ant.impl.nestedjar.Main.main(Main.java:290) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) at java.lang.reflect.Method.invoke(Unknown Source) at com.sun.javaws.Launcher.executeApplication(Unknown Source) at com.sun.javaws.Launcher.executeMainClass(Unknown Source) at com.sun.javaws.Launcher.doLaunchApp(Unknown Source) at com.sun.javaws.Launcher.run(Unknown Source) at java.lang.Thread.run(Unknown Source) log4j:WARN No appenders could be found for logger (WizardRunner). log4j:WARN Please initialize the log4j system properly.

Thank you!

From stackoverflow
  • If you look in your stack trace the cause of the error is a FileNotFoundException for log4j.dtd. Look at how the DTD is referenced from your log4j.xml. Is the DTD included in your jar file? It needs to be in a place where the JVM can load it.

  • Yes, the log4j.dtd file comes embedded with log4j-1.2.12.jar. Also this log4j jar is in the classpath.

    Mark : So you need to investigate why it cannot be loaded. Is the log4j jar within DemoInstaller.jar as it is not listed in the JNLP file.
  • I think the problem is missing log4j.jar - it's not specified or loaded by the .jnlp file. You mentioned in the previous answer that it's in your classpath, but how if you're running via WebStart? I believe your classpath is limited to what's defined in the .jnlp file.

    Try adding

    <jar href="log4j.jar" main="true" download="eager" />
    

    to

    <resources>
    

Monitor.Wait/Pulse race condition in a multithreaded server

I'm having a problem with interlocked Monitor.Wait and Monitor.Pulse in a multi-threaded TCP server. To demonstrate my issues, here is my server code:

public class Server
{
    TcpListener listener;
    Object sync;
    IHandler handler;
    bool running;

    public Server(IHandler handler, int port)
    {
        this.handler = handler;
        IPAddress address = Dns.GetHostEntry(Dns.GetHostName()).AddressList[0];
        listener = new TcpListener(address, port);
        sync = new Object();
        running = false;
    }

    public void Start()
    {
        Thread thread = new Thread(ThreadStart);
        thread.Start();
    }

    public void Stop()
    {
        lock (sync)
        {
            listener.Stop();
            running = false;
            Monitor.Pulse(sync);
        }
    }

    void ThreadStart()
    {
        if (!running)
        {
            listener.Start();
            running = true;
            lock (sync)
            {
                while (running)
                {
                    try
                    {
                        listener.BeginAcceptTcpClient(new AsyncCallback(Accept), listener);
                        Monitor.Wait(sync);  // Release lock and wait for a pulse
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine(e.Message);
                    }
                }
            }
        }
    }

    void Accept(IAsyncResult result)
    {
        // Let the server continue listening
        lock (sync)
        {
            Monitor.Pulse(sync);
        } 

        if (running)
        {
            TcpListener listener = (TcpListener)result.AsyncState;
            using (TcpClient client = listener.EndAcceptTcpClient(result))
            {
                handler.Handle(client.GetStream());
            }
        }
    }
}

And here is my client code:

class Client
{
    class EchoHandler : IHandler
    {
        public void Handle(Stream stream)
        {
            System.Console.Out.Write("Echo Handler: ");
            StringBuilder sb = new StringBuilder();
            byte[] buffer = new byte[1024];
            int count = 0;
            while ((count = stream.Read(buffer, 0, 1024)) > 0)
            {
                sb.Append(Encoding.ASCII.GetString(buffer, 0, count));
            }
            System.Console.Out.WriteLine(sb.ToString());
            System.Console.Out.Flush();
        }
    }

    static IPAddress localhost = Dns.GetHostEntry(Dns.GetHostName()).AddressList[0];

    public static int Main()
    {
        Server server1 = new Server(new EchoHandler(), 1000);
        Server server2 = new Server(new EchoHandler(), 1001);

        server1.Start();
        server2.Start();

        Console.WriteLine("Press return to test...");
        Console.ReadLine();

        // Note interleaved ports
        SendMsg("Test1", 1000);
        SendMsg("Test2", 1001);
        SendMsg("Test3", 1000);
        SendMsg("Test4", 1001);
        SendMsg("Test5", 1000);
        SendMsg("Test6", 1001);
        SendMsg("Test7", 1000);

        Console.WriteLine("Press return to terminate...");
        Console.ReadLine();

        server1.Stop();
        server2.Stop();

        return 0;
    }

    public static void SendMsg(String msg, int port)
    {
        IPEndPoint endPoint = new IPEndPoint(localhost, port);

        byte[] buffer = Encoding.ASCII.GetBytes(msg);
        using (Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
        {
            s.Connect(endPoint);
            s.Send(buffer);
        }
    }
}

The client sends seven messages, but the server only prints four:

Press return to test...

Press return to terminate...
Echo Handler: Test1
Echo Handler: Test3
Echo Handler: Test2
Echo Handler: Test4

I suspect the monitor is getting confused by allowing the Pulse to occur (in the server's Accept method) before the Wait occurs (in the ThreadStart method), even though the ThreadStart should still have the lock on the sync object until it calls Monitor.Wait(), and then the Accept method can acquire the lock and send its Pulse. If you comment out these two lines in the server's Stop() method:

//listener.Stop();
//running = false;

The remaining messages appear when the server's Stop() method is called (i.e. waking up the server's sync object causes it to dispatch the remaining incoming messages). It seems to me this can only occur in a race condition between the ThreadStart and Accept methods, but the lock around the sync object should prevent this.

Any ideas?

Many thanks, Simon.

ps. Note that I'm aware that the output appears out-of-order etc., I'm specifically asking about a race condition between locks and the Monitor. Cheers, SH.

From stackoverflow
  • The problem is that you are using Pulse/Wait as a signal. A proper signal, such as a AutoResetEvent has a state such that it stays signalled until a thread has called WaitOne(). Calling Pulse without any threads waiting on it will become a noop.

    This is combined with the fact that a lock can be taken many times by the same thread. Since you are using Async programming the Accept callback can be called by the same thread that did the BeginAcceptTcpClient.

    Let me illustrate. I commented out the second server, and changed some code on your server.

    void ThreadStart()
    {
        if (!running)
        {
            listener.Start();
            running = true;
            lock (sync)
            {
                while (running)
                {
                    try
                    {
                        Console.WriteLine("BeginAccept [{0}]", 
                            Thread.CurrentThread.ManagedThreadId);
                        listener.BeginAcceptTcpClient(new AsyncCallback(Accept), listener);
                        Console.WriteLine("Wait [{0}]", 
                            Thread.CurrentThread.ManagedThreadId);
                        Monitor.Wait(sync);  // Release lock and wait for a pulse
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine(e.Message);
                    }
                }
            }
        }
    }
    
    void Accept(IAsyncResult result)
    {
        // Let the server continue listening
        lock (sync)
        {
            Console.WriteLine("Pulse [{0}]", 
                Thread.CurrentThread.ManagedThreadId);
            Monitor.Pulse(sync);
        }
        if (running)
        {
            TcpListener localListener = (TcpListener)result.AsyncState;
            using (TcpClient client = localListener.EndAcceptTcpClient(result))
            {
                handler.Handle(client.GetStream());
            }
        }
    }
    

    The output from my run shown below. If you run this code yourself the values will differ, but it will be the same in general.

    Press return to test...
    BeginAccept [3]
    Wait [3]
    
    Press return to terminate...
    Pulse [5]
    BeginAccept [3]
    Pulse [3]
    Echo Handler: Test1
    Echo Handler: Test3
    Wait [3]
    

    As you can see there are two Pulse's called, one from a separate thread (the Pulse [5]) which wakes up the first Wait. Thread 3 then does another BeginAccept, but having Pending incoming connections that thread decides to call the Accept callback immediately. Since the Accept is called by the same thread, the Lock(sync) doesn't block but Pulse [3] immediately on an empty thread queue.

    Two handlers are invoked and handles the two messages.

    Everything is fine, and the ThreadStart start to run again and goes to Wait indefinitely.

    Now, the underlying issue here is that you are trying to use a monitor as a signal. Since it doesn't remember the state the second Pulse get's lost.

    But there is an easy solution for this. Use AutoResetEvents, which is a proper signal and it will remember its state.

    public Server(IHandler handler, int port)
    {
        this.handler = handler;
        IPAddress address = Dns.GetHostEntry(Dns.GetHostName()).AddressList[0];
        listener = new TcpListener(address, port);
        running = false;
        _event = new AutoResetEvent(false);
    }
    
    public void Start()
    {
        Thread thread = new Thread(ThreadStart);
        thread.Start();
    }
    
    public void Stop()
    {
        listener.Stop();
        running = false;
        _event.Set();
    }
    
    void ThreadStart()
    {
        if (!running)
        {
            listener.Start();
            running = true;
            while (running)
            {
                try
                {
                    listener.BeginAcceptTcpClient(new AsyncCallback(Accept), listener);
                    _event.WaitOne();
                }
                catch (Exception e)
                {
                    Console.WriteLine(e.Message);
                }
            }
        }
    }
    
    void Accept(IAsyncResult result)
    {
        // Let the server continue listening
        _event.Set();
        if (running)
        {
            TcpListener localListener = (TcpListener) result.AsyncState;
            using (TcpClient client = localListener.EndAcceptTcpClient(result))
            {
                handler.Handle(client.GetStream());
            }
        }
    }
    

Multiply defined symbols

Hi, If I declare a global variable in a header file and include it in two .cpp files, the linker gives an error saying the symbol is multiply defined. My question is, why does this happen for only certain types of object (eg. int) and not others (eg. enum)?

The test code I used is given below:

test.h

#ifndef TEST_HEADER
#define TEST_HEADER

namespace test
{           
        int i_Test1 = -1;
        int i_Test2 = -1;
};

#endif // TEST_HEADER

class1.h

#ifndef CLASS_1_HEADER
#define CLASS_1_HEADER

class class1
{
public:
        void count();
};

#endif //CLASS_1_HEADER

class1.cpp

#include <iostream>
#include "class1.h"
#include "test.h"

void class1::count()
{
        std::cout << test::i_Test1 << std::endl;
}

class2.h

#ifndef CLASS_2_HEADER
#define CLASS_2_HEADER

class class2
{
public:
        void count();
};

#endif //CLASS_2_HEADER

class2.cpp

#include "class2.h"
#include <iostream>
#include "test.h"

void class2::count()
{
        std::cout << test::i_Test2 << std::endl;
}

main.cpp

#include "class1.h"
#include "class2.h"

int main(int argc, char** argv)
{
        class1 c1;
        class2 c2;
        c1.count();
        c2.count();
        return -1;
}

Building this code with:

g++ main.cpp class1.cpp class2.cpp -o a

produces the following output:

ld: fatal: symbol test::i_Test1' is multiply-defined: (file /var/tmp//ccwWLyrM.o type=OBJT; file /var/tmp//ccOemftz.o type=OBJT); ld: fatal: symbol test::i_Test2' is multiply-defined: (file /var/tmp//ccwWLyrM.o type=OBJT; file /var/tmp//ccOemftz.o type=OBJT); ld: fatal: File processing errors. No output written to a collect2: ld returned 1 exit status

If I change the test.h file as given below:

test.h (with enum)

#ifndef TEST_HEADER
#define TEST_HEADER

namespace test
{
        enum val
        {
                i_Test1 = 5,
                i_Test2
        };
        //int i_Test1 = -1;
        //int i_Test2 = -1;
};

#endif // TEST_HEADER

I don't get the "multiply defined" error and the program gives the desired output:

5
6
From stackoverflow
  • That's because enumerations are not objects - they are types. Class types (class,struct,union) and enumerations can be defined multiple times throughout the program, provided all definitions satisfy some restrictions (summed up by the so-called One Definition Rule (ODR)). The two most important ones are

    • All definitions have the same token sequence (textual identical)
    • Names used must have the same meaning (resolve to the same things) in all definitions. (this is a requirement on the context of the definition)

    Your enumeration definition satisfies all conditions of the ODR. Therefor, that is valid and no reason for the linker / compiler to moan (actually, for a violation of the ODR the compiler is not required to issue a message either - most of it falls under the so-called no diagnostic required rule, some violations also result in undefined behavior).

    However, for every non-inline function and object, these must be only defined one time. Multiply defining those result in spurious errors, like in your case. To solve it, put only a declaration into the header file (using "extern" without an initializer) and put one definition into one of those .cpp files (omitting the "extern" then, or putting an initializer. If it is a const object, you still need the "extern", since per default const variables have internal linkage, and the symbol would not be exported otherwise).

SharePoint Approval Workflow

I have a custom content type in SharePoint which has an approval workflow associated with it. The content type contains several Choice Site Columns. There is now a requirement to change the values of the choice columns AND update the existing content to reflect the new values.

Eg,

Existing Choices:
Choice 1
Choice 2
Choice 3

New Choices
Choice 1a
Choice 2a
Choice 3

So, some of the choices are being renamed.

As far as i can tell, whilst changing the choice column is straight forward, the existing list items won't automatically pick up the new values i.e. a list item with Choice 1 selected will still show Choice 1 until the list item is physically edited. But editing the item will require re-approval of the workflow. There are a few thousand items spread over several lists which will be affected by this change.

So, my question: Is it possible to suspend or detach the workflow whilst the changes are made and then re-attach / re-activate after the changes have been made, thus avoiding the need to re-approve everything? Or am i best to look at automating the re-approval?

Any help much appreciated

From stackoverflow
  • Hi,

    You could update the values using the object model, the SPListItem.SystemUpdate method that optionally allows you to prevent that a new version is created.

    You could use SPSiteDataQuery to find all items using your content type and then update them using the method mentioned above.

    Regards, Daniel Karlsson

    Temple : Excellent. Does exactly what I need. Thanks

Store form data in MySQL with jQuery.ajax

Edit: I found the soluton for getting the correct URL. Se the solution in this thread.

Hi, I'm having problems prosessing a form so that I can save it's data in my MySQL database. I'm using Wordpress as CMS.

I've used this example: http://www.ryancoughlin.com/2008/11/04/use-jquery-to-submit-form

I'm pretty sure that the source of my problem, is that I'm using the wrong url: in the javascript. The error message only returns 'undefined' and Firebug reports a page not found 404 error.

So what would be the correct url? Any help would be greatly appreciated.

This is my site structure:

Mywebsite (folder)      
  sl_register.tpl.php   
  includes    (folder)    
  storelocator (folder)
    process_frm_store.php
    frm_store.php
  js (folder)
    myscripts.js

And this is the logic of my site build up:

sl_register.tpl.php:

<?php
/*
  Template Name: SL - Register Store
*/  
  get_header();
  include_once 'includes/storeLocator/frm_store.php';
  get_footer();
?>

frm_store.php:

<form id="store_data_form" class="appnitro"  method="post" action="">
  <input id="store_active" name="store_active" type="hidden" value="pending" />
  <input id="store_name" name="store_name" type="text" value=""/> 
  <input id="store_street1" name="store_street1" type="text" value="" />
  <input id="saveForm" class="submitButton" type="submit" name="save" value="Save" />
</form>

process_frm_store.php:

<?php
  $myDB = new DAL(); 
  $myDB->connect();

  if (isset($_POST['save'])) 
  {
    $formData =  array(
      "name"=> mysql_real_escape_string($_POST['store_name']),
      "street1"=> mysql_real_escape_string($_POST['store_street1']),
      "zipcode"=> mysql_real_escape_string($_POST['store_zipcode']));

    $myDB->addNewStore($formData);
  }
?>

myscripts.js:

jQuery.processForms = function()
{
  jQuery('form#store_data_form').submit(function() 
  {
    var store_name = 'Test store'; //jQuery("input#store_name").val();
    var store_street1 = 'Sesamy street';//Set constant for testing
    var store_zipcode = '0574'; //Set constant for testing
    var dataString = 'name='+ store_name + '&street1=' + store_street1 + '&zipcode=' + store_zipcode;    
    jQuery.ajax(
    {   
      type: "POST",   
      url: "process_frm_store.php",   
      data: dataString,
      error: function(XMLHttpRequest, textStatus, errorThrown) 
      { 
        alert(errorThrown); // Just for debugging
        jQuery('#suggestNewStore div.error').fadeIn(); 
      },
      success: function() 
      {
        alert('It works!');
        jQuery('#suggestNewStore div.success').fadeIn();   
      }   
    });   
    return false;      
  });
}
From stackoverflow
  • It it simpler to user the absolute path like http://www.yourwebsite.com/storelocator/process_frm_store.php to be on the safe-side.

    Otherwise the url param of the .ajax method should be storelocator/process_frm_store.php because your ..js file is included and executed in your base path, outside the js or storelocator folders

    Steven : Thanks for your answer Bogdan. I don't think that will work though, since I'm using Wordpress CMS with user friendly URL's. The URL for my page / form is: http://localhost/mysite/store-locator/register-store-label The logical URL is: http://localhost/mysite/sl_register.tpl.php Firebugs reports he following error: POST (url) 404 Not Found Where url is whatever i put in my javascript file.
  • You have <?php tags wrapped around your include_once in sl_register.tpl.php when it is already inside of <?php tags ...unless you're doing something that I don't understand this is probably breaking something.

    Steven : Oh sorry... that's just a typo from my cut and paste. In my full code, that line is outside PHP tags. I'll edit and fix this.
  • I've currently given up trying to get this to work. I'll get back to this once I've solved some other issues which are related.

    Stuart Branham : Rather than posting this as an answer, it's better for these types of comments to be edits in your question or a comment on your question.
    Steven : I'm marking this as correct answer, since I can't mark my first post. And since I can only comment, and not post, a new answer to my own problem, take a look at my Edit at the top.

How to handle cookies in JavaScript ?

I am working on a project where it requires to check cookie and tell whether it is 20 minutes old or not. So I have written once code which is like this. This is only javascript code I have pasted.

function checkcookie()
{
    var difftime= getcookie();
    // further operation comes here
}

var cookieminutes;

function getcookie()
{
    var start = document.cookie.indexOf("expires");
    var cookiedate;

    if(start==-1)
    {
        cookiedate = new Date();
        document.write("Start equal to -1");
        document.cookie="expires="+cookiedate+",path=0,domain=0";
        cookieminutes= cookiedate.getMinutes();
    }
    else
    {
        document.write("Start not equal to -1");

        var date =  new Date();
        var minutes = date.getMinutes();

        document.write("The difference is "+minutes);
        document.write("<br />Cookie minutes is "+cookieminutes);
        return (minutes-cookieminutes);

    }
}

In function getcookie the variable cookieminutes is coming as undefined. But as I know since it is a global variable it should have the value.

Can anybody please tell what is the solution for this.?

From stackoverflow
  • If you want to use global variables (generally bad design) set and access them explicitly with window. E.g.:

    window.cookieminutes = cookiedate.getMinutes();
    

    and later:

    document.write("Cookie minutes is "+window.cookieminutes);
    

    And drop the var cookieminutes;

    As I said in my comment, it looks like if getcookie is being called for the first time on a given page load, and the cookie exists (start != -1), cookieminutes is never set. You need to make sure you don't use undefined variables.

    Steve Harrison : Can you provide a link that supports this point of view? I haven't come across this before.
    Matthew Flaschen : Which point of view are you referring to? Global variables are a well-known code smell.
    stefpet : I assume it is the point of view of using globals by explicitly setting/getting them using the window object (instead of not explicitly using window).
    Steve Harrison : Yes, I know that global variables should be avoided if possible. I'm curious about your statement "set and access them explicitly with window". I know that implied globals are bad, but why should you always use "window" when referring to or setting global variables in JavaScript?
    Matthew Flaschen : I never said you always had to. I just think it's better to be explicit in this case.
  • Please refer to this similar SO post:
    what-is-the-best-way-to-get-and-set-a-single-cookie-value-using-javascript

  • You're only setting a value for cookieminutes in the top section of the if statement, so any references in the else section will be null.

    Try this:

    function getcookie()
    {
        var start = document.cookie.indexOf("expires");
        var cookiedate;
    
        cookiedate = new Date();
        cookieminutes = cookiedate.getMinutes();
    
        if(start==-1)
        {    
            document.write("Start equal to -1");
            document.cookie="expires="+cookiedate+",path=0,domain=0";    
        }
        else
        {
            document.write("Start not equal to -1");
    
            var date =  new Date();
            var minutes = date.getMinutes();
    
            document.write("The difference is "+minutes);
            document.write("<br />Cookie minutes is "+cookieminutes);
            return (minutes-cookieminutes);
    
        }
    }
    
    Chaithra : Ur code is working... But if I use that cookieminutes and minutes both will be same value. I have to get a 20 mins differnece between the 2 because of my project requirement. so can u pls post some other solution thank u ..
    Matthew Flaschen : I don't understand the reference to 20 minutes. As jim0thy and I said, your original code was using cookieminutes before setting it. You need to initialize it properly, probably by reading the cookie. If you don't know how to read cookies see http://www.quirksmode.org/js/cookies.html
    jim0thy : Ok, after looking into this a bit, it would seem that the expiration date of a cookie is write-only, so JS can't read it. document.cookie.indexOf("expires") looks for a cookie NAMES "expires", and does not retrieve the expiration date. It looks like the only way around this is to create a 2nd cookie, and set it's value to the expiration date of the 1st cookie. Sorry.

How to 'transform' a String object (containing XML) to an element on an existing JSP page

Currently I have a String object that contains XML elements:

String carsInGarage = garage.getCars();

I now want to pass this String as an input/stream source (or some kind of source), but am unsure which one to choose and how to implement it.

Most of the solutions I have looked at import the package: javax.xml.transform and accept a XML file (stylerXML.xml) and output to a HTML file (outputFile.html) (See code below).

try 
{
    TransformerFactory tFactory = TransformerFactory.newInstance();
    Transformer transformer = tFactory.newTransformer 
        (new javax.xml.transform.stream.StreamSource("styler.xsl"));

    transformer.transform (
        new javax.xml.transform.stream.StreamSource ("stylerXML.xml"),
        new javax.xml.transform.stream.StreamResult (
            new FileOutputStream("outputFile.html")));
}
catch (Exception e)
{
e.printStackTrace();
}

I want to accept a String object and output (using XSL) to a element within an existing JSP page. I just don't know how to implement this, even having looked at the code above.

Can someone please advise/assist. I have searched high and low for a solution, but I just can't pull anything out.

Thankyou, Lucas

From stackoverflow
  • Use a StringReader and a StringWriter:

     try {
      StringReader reader = new StringReader("<xml>blabla</xml>");
      StringWriter writer = new StringWriter();
      TransformerFactory tFactory = TransformerFactory.newInstance();
      Transformer transformer = tFactory.newTransformer(
        new javax.xml.transform.stream.StreamSource("styler.xsl"));
    
      transformer.transform(
        new javax.xml.transform.stream.StreamSource(reader), 
        new javax.xml.transform.stream.StreamResult(writer));
    
      String result = writer.toString();
     } catch (Exception e) {
      e.printStackTrace();
     }
    
    Lycana : Hi Bruno, Thank you for that excellent answer. It is compiling properly now :) However, I still am unable to print it to the screen. I am currently trying: out.println(writer); but this is failing.
    bruno conde : Maybe there was an error with the transform ... how exactly is it failing?
    Lycana : It fails as nothing is printed to the browser. At the bottom of my try block I have: String result = writer.toString(); out.print("
    " + result + "
    "); I also just installed a tool called Firebug to inspect the content of my HTML body. Nothing again.
    Lycana : I don't know if this has anything to do with it, but I can out.print() a random string outside of the TRY-block. But I cannot out.print() the same random string when it is inside the TRY-block.
    Lycana : Hi Bruno, I have managed to get the transformed/styled XML output to screen. I must thank you for your assistance. You are amazing :) I do have one question left though :P Did you expect the original string AS WELL as the transformed/styled XML to output together? Or did you just expect the transformed/styled only to show?
    bruno conde : No. Only the transformed/styled result is in the writer. If your getting strange results check your XSL.
  • If at some point you want the source to contain more than just a single string, or you don't want to generate the XML wrapper element manually, create a DOM document that contains your source and pass it to the transformer using a DOMSource.

  • Hey Jordan, I am having the same problem as you had with the browser display being blank. I was just wondering how you got the result to appear on the screen? Thanks

Why is java secure coding important?

I'm having trouble understanding why java secure coding is important. For example, why is it important to declare variables private? I mean I get that it will make it impossible to access those variables from outside the class, but I could simply decompile the class to get the value. Similarly, defining a class as final will make it impossible to subclass this class. When would subclassing a class be dangerous for security? Again if necessary, I could decompile the original class and reimplement it with whatever malicious code I could want. Does the problem come when applications are "trusted" by the user? And people could then abuse this trust somehow? Basically what I'm looking for is a good example as to why secure coding guidelines should be followed.

From stackoverflow
  • Programming is hard.

    If you define strict APIs, that don't expose variables that are not supposed to be exposed (we like to call this encapsulation), you help users of your APIs, and thus make programming easier. This is considered a good thing.

    The reasons are not primarily "security", as in keeping secret things secret, as much as clarity, simplicity, and understandability.

    As a bonus, it's far easier to make things work correctly if you can know that the user of the API is not changing "your" variables behind your back, of course.

  • It is "secure" meaning that a class internal working are hidden to whoever uses it.

    The term secure is not used as in "securing a server" is used to intend the fact that a user of one class does not have to worry about how the class will perform the task he wants it to.

    Taking your example:

    Exposing variables of a class would let the user of your class know of their existance, which is something you don't want, for example: you just press a button to turn on the light, you don't need to now that inside there is copper or whater it needs to perform the task.

  • Just to add to what others have already said: Some of these features can also simply be viewed as a way to state intend. If I make a member private I make it "impossible" for others to access it (it is possible, but that's besides the point here), but more importantly I tell the users that this is an implementation detail, that they should not rely upon.

  • There are two issues here.

    The first when declaring variables as protected or private, they won't become part of your public API. Other classes may depend on your class in the future, and it is important that you are free to change as much as possible if you want to include new features, improve performance, etc. If all of your values are public than all of your internal values and mechanisms are public. Changing them may break other classes which depend on yours.

    The second, is that when exposing variables it allows other classes to change your values. If they change your internal values if may break your program, and create strange unexpected behavior. If you create a system which relies on the accurate performance of one your classes, and the internal values are changed, than you can no longer rely on that system. Subclassing makes this more complicated. Your system may rely on a class of a certain type to perform expected actions. By subclassing it is possible to create a new class that appears to be the same type but does not perform the expected actions.

    For example, if you have a class square with a protected function getArea(), you expect to to return the area of a square. However, a new class can be made which extends square, say class rectangle extends square. Now rectange can override getArea(), but it is still of type square, which may break something which depends on that functionality of square. By making your class final you are asserting that this can never occur in your system.

    This type of "secure coding" will not prevent someone from seeing your source code, but it helps to make your code more reliable and usable in the future.

    Tom Hawtin - tackline : protected variables are part of the public API. Use private or, if you must, some "package private" default access variables.
  • Java is an object-oriented programming langauge, and one of the key concepts in object-oriented programming is encapsulation.

    The idea behind encapsulation is to "hide away" the implementation details such as internal variables which hold the state of the object and the internal workings such as algorithms, and only provide an interface that other objects can use in order to perform functions with the object.

    Using that concept, one would like to hide internal states by using private variables to prevent other objects from directly affecting the internal states. In Java, it is common to see getters and setters (e.g. getColor and setColor) in order to work with objects.

    Also, encapsulation can increase the robustness of code as well.

    For example, by restricting access to the internal states, it would be possible to perform some sanity checks before an object is altered.

    As a solid example, say there was a Score object that was to have a percent value between 0 and 100. By providing a setPercent(int) method which validates that the specified value was within the permissible range, it would prevent the Score object from being set into an unacceptable state.

    So, trying to directly manipulate the internal state by writing a statement like score.percent = 150 could be prevented, if the setPercent method causes an error or throws an Exception if the specified value is unacceptable.

  • just imagine if your object has internal property which is not private (hidden) and your code accessing this property happen to be run in multithreading environment, so N threads would start to access it simultaneously, 5 threads would like to change this property, 4 to read. There is no way you make sure things will run neatly, neither thread will know which data it holds in the moment and did it successfully changed property of that object.

    You will have to program special piece of code which will be responsible to handle synchronous access and still that will no be guarrantee your code will work right since you still have to check rest of 680 classes in your program accessing that property not to access it directly.

    In short, you are in a huge problem, and debugging is a nightmare since you do not know when the data was chagned, which thread did that, from where it happend etc.

    Just one scenario of what is happening if you do not encapsulate...

    Good thing, your code runs 1% faster, there is less load on stack, you've achieved probably negligible performance gains which you will pay with periodic crashes of system and minor chances for successfull debugging.

  • The term "secure coding" refers to construction of software that clearly attempts to avoid security vulnerabilities, whether in C, Java, Ruby, assembly language, or anything else. Perhaps the most central part of that, after selecting a secure language system, is to keep to good programming practices. If a program is unclear, then you have little chance of it being worthy of any confidence.

    For Java there are two notable guides:

    In Java there are two distinct modes of secure coding.

    In one you are dealing with code that may not have all the privileges that your code does. For instance if you are writing a library or signing code you need to be doing this. It should be impossible for malicious code to take advantage of your permissions in unintended ways. This is difficult!

    More commonly you are dealing with programs that are dealing with only untrusted data. For instance, web servers (think XSS and SQL injection) and desktop application programs dealing with untrusted files (usually the problem is with C code having buffer overflows - genuine C++ is better). In some situations denial of service (DoS) can be a severe issue.

    There is some overlap. For instance interpreters run with the permissions of the interpreter code and may be quite "powerful".

Delegate methods of NSTextField using NSNotification

I have an NSTokenField in a window. I am using it to store tags related to a Core Data object. Right now I have it set up such that I can add tags to the objects, but I cannot delete them. I need a delegate method on the NSTokenField that can let me know when the user has moved the focus out of the NSTokenField. Since NSTokenField is a subclass of NSTextField I figured that I could use its delegate methods. It has two that I think could be useful:

- (void)textDidChange:(NSNotification *)aNotification
- (void)textDidEndEditing:(NSNotification *)aNotification

I set my controller class as the delegate of my NSTokenField and put both of these methods into my controller class. I put a basic NSLog into each of them and neither is triggered when I interact with the NSTokenField. I am guessing it has something to do with NSNotification. How do I activate these methods?

From stackoverflow
  • The NSTokenField invokes the controlTextDidChange: and the controlTextDidEndEditing: notifications; change the two methods above, implementing them as:

    - (void)controlTextDidChange:(NSNotification*)aNotification
    {
        //Code here..
    }
    
    - (void)controlTextDidEndEditing:(NSNotification *)aNotification
    {
        //Code here..
    }
    
  • hi can you help me?

    • (void)textDidChange:(NSNotification *)aNotification

    {

    the code?

    }

Are LEFT JOIN subquery table arguments evaluated more than once?

Hello. I have a query that looks like this:

SELECT  *
FROM    employees e
LEFT JOIN
        (
        SELECT  *
        FROM    timereports
        WHERE   date = '2009-05-04'
        ) t
ON      e.id = t.employee_id

As you can see, my LEFT JOIN second table parameter is generated by a a subquery.

Does the db evaluate this subquery only once, or multiple times?

thanks. matti

From stackoverflow
  • This depends on the RDBMS.

    In most of them, a HASH OUTER JOIN will be employed, in which case the subquery will be evaluated once.

    MySQL, on the other hand, isn't capable of making HASH JOIN's, that's why it will most probably push the predicate into the subquery and will issue this query:

    SELECT  *
    FROM    timereports t
    WHERE   t.employee_id = e.id
            AND date = '2009-05-04'
    

    in a nested loop. If you have an index on timereports (employee_id, date), this will also be efficient.

  • If you are using SQL Server, you can take a look at the Execution Plan of the query. The SQL Server query optimizer will optimize the query so that it takes the least time in execution. Best time will be based on some conditions viz. indexing and the like.

  • You have to ask the database to show the plan. The algorithm for doing this is chosen dynamically (at query time) based on many factors. Some databases use statistics of the key distribution to decide which algorithm to use. Other databases have relatively fixed rules.

    Further, each database has a menu of different algorithms. The database could use a sort-merge algorithm, or nested loops. In this case, there may be a query flattening strategy.

    You need to use your database's unique "Explain Plan" feature to look at the query execution plan.

    You also need to know if your database uses hints (usually comments embedded in the SQL) to pick an algorithm.

    You also need to know if your database uses statistics (sometimes called a "cost-based query optimizer) to pick an algorithm.

    One you know all that, you'll know how your query is executed and if an inner query is evaluated multiple times or flattened into the parent query or evaluated once to create a temporary result that's used by the parent query.

  • What do you mean by evaluated?

    The database has a couple of different options how to perform a join, the two most common ones being

    • Nested loops, in which case each row in one table will be looped through and the corresponding row in the other table will be looked up, and
    • Hash join, which means that both tables will be scanned once and the results are then merged using some hash algorithm.

    Which of those two options is chosen depends on the database, the size of the table and the available indexes (and perhaps other things as well).

jquery and RegExp‬

I build a function thar replace a keyword in the HTML to a link. The problem is that when the keyword is in a link then it will replaced it.

$(document).ready( function () {
 $("#content").highlight( "example", "<a href=\"http://www.example.com\">$1</a>" );});

jQuery.fn.highlight = function (text, o) {
return this.each( function(){
 var replace = o;
 $(this).html( $(this).html().replace( new RegExp('('+text+'(?![\\w\\s?&.\\/;#~%"=-]*>))', "ig"), replace) );
});}

and my HTML

<div id="content">
 <h2>the word "example" replaced by the link</h2>
 <p>this is an example</p>

 <p>this is an example number 2</p>
 <p><a href="http://www.wrong.com">this is an example</a></p>
</div>
From stackoverflow
  • Hi!

    I would check each element in the loop to see if it's a anchor tag before doing the replace.

    if( !$(this).is('a') ) {
      // Replace Code here
    }
    
    eyalb : i don't go over the text in a loop. i replace it with the replace function, so i cant check every replace.

Loading a view on a background thread

Is it possible to load a view on a background thread?

I am using buffering to render views into a buffer off screen so they can be scrolled into view later. I want to make the UI more response and it seems to be the off screen buffering that is the culprit, and am wondering if I can load up the buffered view on a background thread as I don't need it available immediately. The problem with doing this seems to be that the thread has its own auto release pool, which then gets cleared when the thread exits. Is it possible for the background thread and the ui thread to share memory or a pool?

From stackoverflow
  • Secondary thread should have it's own autorelease pool. Which should be released if the secondary thread exists.

    When you pass data between threads the sender should retain it and the receiver thread should release/autorelease it. But in most cases this is done "automatically", if you're using properties or performSelectorOnMainThread for example.

    Roger Nolan : ...and note that all UI updates should be performed on the main thread.
    Ian1971 : Interesting comment Roger. Could you go into more detail? Is it possible for me to load the view at all on the secondary thread?
    Ian1971 : performSelectorOnMainThread was what I needed

Firefox back button works only the first time, not the second time

Hi,

I have a website where you can search on stuff with dates and more. When I post the form I get to a result-page, when I hit the back button I go back to my search-page and will refill the values. This works in IE and FF.

however, whatever I do, when I search and go back again the second time, the values are lost in Firefox, while IE and other browsers still remember the filled-in values. whatever I do on the search-page, it doesn't rememeber the new state, but only the original first-state. Even when I check teh form-values before posting it, it shows the correct-values, but when returning it is lost.

From stackoverflow
  • Ok,

    I made a clean testcase without all the extra stuff I have and came to the simple conclusion it the # that caused the confusion and my problem.

    when you do

    <a href="#" onclick="DoSomethingFirstBeforeSubmittingTheForm()">Go!</a>
    

    Firefox goes back to the .html variant of the page, while IE goes back to the .html# variant of the page.

    while when you do

    <a href="javascript:DoSomethingFirstBeforeSubmittingTheForm()">Go!</a>
    

    both FF and IE go back to the html-page, and using the correct-cache.

    Mike Robinson : Add "return false;" to the end of your function, it'll stop the link from performing it's action

WHERE Clause to find all records in a specific month

I want to be able to give a stored procedure a Month and Year and have it return everything that happens in that month, how do I do this as I can't compare between as some months have different numbers of days etc?

What's the best way to do this? Can I just ask to compare based on the year and month?

Thanks.

From stackoverflow
  • If you're using SQL Server, look into DATEPART.

    http://msdn.microsoft.com/en-us/library/ms174420(SQL.90).aspx

    DATEPART(mm, [THE DATE YOU'RE LOOKING AT])

    You can then use normal integer logic with it. Same for year, just use yy instead of mm.

  • Can I just ask to compare based on the year and month?

    You can. Here's a simple example using the AdventureWorks sample database...

    DECLARE @Year    INT
    DECLARE @Month   INT
    
    SET @Year = 2002
    SET @Month = 6
    
    SELECT 
        [pch].* 
    FROM 
        [Production].[ProductCostHistory] pch
    WHERE
        YEAR([pch].[ModifiedDate]) = @Year
    AND MONTH([pch].[ModifiedDate]) = @Month
    
  • I think the function you're looking for is MONTH(date). You'll probably want to use 'YEAR' too.

    Let's assume you have a table named things that looks something like this:

    id happend_at
    -- ----------------
    1  2009-01-01 12:08
    2  2009-02-01 12:00
    3  2009-01-12 09:40
    4  2009-01-29 17:55
    

    And let's say you want to execute to find all the records that have a happened_at during the month 2009/01 (January 2009). The SQL query would be:

    SELECT id FROM things 
       WHERE MONTH(happened_at) = 1 AND YEAR(happened_at) = 2009
    

    Which would return:

    id
    ---
    1
    3
    4
    
    Tarks : Indeed ! For anyone that's interested "The DAY, MONTH, and YEAR functions are synonyms for DATEPART(dd, date), DATEPART(mm, date), and DATEPART(yy, date), respectively."
  • Something like this should do it:

    select * from yourtable where datepart(month,field) = @month and datepart(year,field) = @year
    

    Alternatively you could split month and year out into their own columns when creating the record and then select against them.

    Iain

  • One way would be to create a variable that represents the first of the month (ie 5/1/2009), either pass it into the proc or build it (concatenate month/1/year). Then use the DateDiff function.

    WHERE DateDiff(m,@Date,DateField) = 0
    

    This will return anything with a matching month and year.

  • As an alternative to the MONTH and YEAR functions, a regular WHERE clause will work too:

    select *
    from yourtable
    where '2009-01-01' <= datecolumn and datecolumn < '2009-02-01'
    
  • Using the MONTH and YEAR functions as suggested in most of the responses has the disadvantage that SQL Server will not be able to use any index there may be on your date column. This can kill performance on a large table.

    I would be inclined to pass a DATETIME value (e.g. @StartDate) to the stored procedure which represents the first day of the month you are interested in.

    You can then use

    SELECT ... FROM ...
    WHERE DateColumn >= @StartDate 
    AND DateColumn < DATEADD(month, 1, @StartDate)
    

    If you must pass the month and year as separate parameters to the stored procedure, you can generate a DATETIME representing the first day of the month using CAST and CONVERT then proceed as above. If you do this I would recommend writing a function that generates a DATETIME from integer year, month, day values, e.g. the following from a SQL Server blog.

    create function Date(@Year int, @Month int, @Day int)
    returns datetime
    as
        begin
        return dateadd(month,((@Year-1900)*12)+@Month-1,@Day-1)
        end
    go
    

    The query then becomes:

    SELECT ... FROM ...
    WHERE DateColumn >= Date(@Year,@Month,1)
    AND DateColumn < DATEADD(month, 1, Date(@Year,@Month,1))
    
    Raghav Khunger : Ya I agree with @joe "Using the MONTH and YEAR functions as suggested in most of the responses has the disadvantage that SQL Server will not be able to use any index there may be on your date column. This can kill performance on a large table."
  • I find it easier to pass a value as a temporal data type (e.g. DATETIME) then use temporal functionality, specifically DATEADD and DATEPART, to find the start and end dates for the period, in this case the month e.g. this finds the start date and end date pair for the current month, just substitute CURRENT_TIMESTAMP for you parameter of of type DATETIME (note the 1990-01-01 value is entirely arbitrary):

    SELECT DATEADD(M, 
              DATEDIFF(M, '1990-01-01T00:00:00.000', CURRENT_TIMESTAMP), 
              '1990-01-01T00:00:00.000'), 
           DATEADD(M, 
              DATEDIFF(M, '1990-01-01T00:00:00.000', CURRENT_TIMESTAMP), 
              '1990-01-31T23:59:59.997')