Wednesday, April 20, 2011

The best way to build Dynamic LINQ query.

Hi I am looking for best method for writing Dynamic LINQ query.

I have a function like

public IQueryable<Student> FindByAllStudents(int? id, string Name, int? CourseID, bool? IsActive) // like this way, all field values are passed
    {    
        // code for compairision
        return db.Student;
    }

we can also write db.Students.where(predicate)

or

a query like

var students = from s in db.students where s.Name.Contains(Name)
    s.ID.Equals(id)
    //and so on....

So will this method works if i don't pass ID (i.e. Null)? is proper way for all the datatypes?

The point is function can have all null values as a parameter for equivalence of select * from statement.

can any one help me to build best query with sample code?

From stackoverflow
  • Okay, it's not entirely clear what you want, but if you're trying to only add where clauses for the parameters which are non-null, you could do:

    public IQueryable<Student> FindByAllStudents
        (int? id, string name, int? courseID, bool? isActive)
    {    
        IQueryable<Student> query = db.Student;
        if (id != null)
        {
            query = query.Where(student => student.ID == id.Value);
        }
        if (name != null)
        {
            query = query.Where(student => student.Name.Contains(name));
        }
        if (courseID != null)
        {
            query = query.Where(student => student.CourseID == courseID.Value);
        }
        if (isActive != null)
        {
            query = query.Where(student => student.IsActive == isActive.Value);
        }
        return query;
    }
    

    I haven't tried that, and it's possible that LINQ to SQL would get confused by the code to find the value of the nullable value types. You may need to write code like this:

        if (courseID != null)
        {
            int queryCourseID = courseID.Value;
            query = query.Where(student => student.CourseID == queryCourseID);
        }
    

    It's worth trying the simpler form first though :)

    Of course, all this gets a bit irritating. A helpful extension method could make life more concise:

    public static IQueryable<TSource> OptionalWhere<TSource, TParameter>
        (IQueryable<TSource> source,
         TParameter? parameter, 
         Func<TParameter, Expression<Func<TSource,bool>>> whereClause)
        where TParameter : struct
    {
        IQueryable<TSource> ret = source;
        if (parameter != null)
        {
            ret = ret.Where(whereClause(parameter.Value));
        }
        return ret;
    }
    

    You'd then use it like this:

    public IQueryable<Student> FindByAllStudents
        (int? id, string name, int? courseID, bool? isActive)
    {    
        IQueryable<Student> query = db.Student
            .OptionalWhere(id, x => (student => student.ID == x))
            .OptionalWhere(courseID, x => (student => student.CourseID == x))
            .OptionalWhere(isActive, x => (student => student.IsActive == x));
        if (name != null)
        {
            query = query.Where(student => student.Name.Contains(name));
        }
        return query;
    }
    

    Using a higher order function like this could get confusing if you're not really comfortable with it though, so if you're not doing very many queries like this you might want to stick with the longer but simpler code.

    Vikas : Thanks! For first solution we could also use if(id.HasValue) { than use id.Value}
    Vikas : Can you guide me to use full text search?
    Jon Skeet : Using HasValue is equivalent to using != null. I don't know about using full text search with LINQ, I'm afraid.
    Pure.Krome : Love the extension method Jon! Linq + Full Text Search discussion here: http://stackoverflow.com/questions/224475/is-it-possible-to-use-full-text-search-fts-with-linq
    RemotecUk : One slight comment on this if I may, I had problems getting this to work with strings as a string is already nullable (and as I understand it a ref type as opposed to a struct - if Ive got that correct). Just looked at the code again and I can see that you queried name separately - possibly due to this limitation?

Why can't browser send gzip request?

If webserver can send gzip response, why can't browser sent gzip request?

From stackoverflow
  • Why should it? The requests are usually so small that compression would

    1. probably enlarge it and
    2. take more time than it takes to transfer the uncompressed request.
    Yuliy : Not always. Consider a file upload.
    DisgruntledGoat : You'll find that the majority of files these days are already compressed. Aside from zip/gz themselves, which are probably the most common files uploaded, PDFs, docx, mp3s, video files etc are all compressed in some way, and trying to re-compress wastes time and could make the file bigger.
  • A client can't know in advance that a server would understand a gzipped request, but the server can know that the client will accept one.

  • Because it doesn't know that the server can accept it. An HTTP transaction has a single request sent by the client followed by a response. One of the things the client sends is what encoding/compression it can support. The server can then decide how to compress the response. The client does not have this luxury.

  • The client and server have to agree on how to communicate; part of this is whether the communication can be compressed. Http was designed as a request/response model, and the original creation was almost certainly envisioned to always have small requests and potentially large responses. Compression is not required to implement HTTP, there are both servers and clients that don't support it.

    Http compression is implemented by the client saying it can support compression, and if the server sees this in the request and it supports compression it can compress the response. To compress the request the client would have to have a "pre-request" that actually negotiated that the request would be made compressed OR it would have to require compression as a supported encoding for ALL requests.

  • OPTIONS * HTTP/1.1 Host: www.w3c.org

    HTTP/1.1 200 OK Date: Fri, 10 Apr 2009 07:23:05 GMT Server: Apache/2 Vary: Host Allow: GET,HEAD,POST,OPTIONS,TRACE Content-Length: 0 Connection: close Content-Type: application/x-httpd-cgi

    Is this ture ? "If server responce to OPTIONS request contains Accept-Encoding: gzip, client may safely upload request in gzip format."

  • It could, provided it could guarantee that the server would accept it. This might mean using an OPTIONS request.

    There are a lot of things that web browsers could do (for example, pipelining) that they don't do. Web browser developers consider the compatibility implications of a change.

    In a heterogeneous environment, there are a lot of different web servers and configurations. Making a change to the way a client works could break some of them.

    Perhaps only 1% of servers might accept gzipped requests, but perhaps some of those advertise that they do, but cannot correctly accept it - so users would be denied from uploading files to those sites.

    Historically there have been a lot of broken client / server implementations - for a long time, gzipped responses were broken in major web browsers (thankfully those are now mostly gone).

    So you'd end up with blacklists of user-agents or servers (or domain names) where those options were automatically turned off, which is nasty.

  • If you're writing a web application, I'm assuming that you're in control of what is sent to the client and what is sent back from the client.

    It would be easy enough to write a gzip implementation in javascript, that compresses the post data being sent to the server. The server could have a filter (j2ee term), that knows client data is sent compressed, this filter decompresses the data and then passes the data to the servlet (or action classes in Struts) that read the data as normal e.g. request.getParameter(...).

    This seems perfectly logical and do-able if you're in control. As other posts mention, you couldn't rely on the browser to do this automatically, but since you're writing the web pages, you can get the browser to do the compression you're after (with a little work).

    Andy.

Hibernate Tool

Hi i an using Hibernate tool with eclipse ganymede 3.4.1 . Now when i create the .hbm.xml file using the code generation of Hibernate tool,it is automatically creating a composite key. I am adding the code over here :

but i need a mapping something like

        <id name="id" type="java.lang.Integer">
            <column name="id" />
        </id>
        <key-property name="name" type="string">
            <column name="name" length="30" />
        </key-property>
        </class>

. can someone tell me how to do it.

Thanks in advance, Rima

From stackoverflow
  • The tool somehow got that your table structure has a composite primary key (id, name). If this is the table structure than the tool didn't got it wrong. Or maybe it just has a bug.

    Anyway if you to have a unique index on the "name" field you should map it like:

    <property name="name" type="string" unique="true">
        <column name="name" length="30"/>
    </property>
    

    <key-property> tag is used in <composite-id> tag to define multiple properties as identifier properties.

Copying arraylist values within itself

Consider i have ArrayLists like these,

1){int[],int,int[]}
2){int[],int[],int} And i have a count, 'n'. If n is 3 then my arrayList should be,

1){int[],int[],int[],int,int[],int[],int[]}

2){int[],int[],int[],int[],int[],int[],int}

i.e The new ArrayList should contain 'n' times the Array int[].

From stackoverflow
  • For one thing, do you really have to use an ArrayList? The fact that you're holding different types of data in one collection suggests there's probably a better way of solving your problem. Anyway, you could do something like this:

    public static ArrayList DuplicateIntArrays(ArrayList input, int copies)
    {
        ArrayList ret = new ArrayList();
        foreach (object element in input)
        {
            if (element is int[])
            {
                for (int i=0; i < copies; i++)
                {
                    ret.Add(element);
                }
            }            
            else
            {
                ret.Add(element);
            }
        }
        return ret;
    }
    

Is there ever a good reason to use Insertion Sort?

For general-purpose sorting, the answer appears to be no, as quick sort, merge sort and heap sort tend to perform better in the average- and worst-case scenarios. However, insertion sort appears to excel at incremental sorting, that is, adding elements to a list one at a time over an extended period of time while keeping the list sorted, especially if the insertion sort is implemented as a linked list (O(log n) average case vs. O(n)). However, a heap seems to be able to perform just (or nearly) as well for incremental sorting (adding or removing a single element from a heap has a worst-case scenario of O(log n)). So what exactly does insertion sort have to offer over other comparison-based sorting algorithms or heaps?

From stackoverflow
  • Most sorting procedures will use quicksort and then insertion sort for very small data sets.

  • From http://www.sorting-algorithms.com/insertion-sort:

    Although it is one of the elementary sorting algorithms with O(n2) worst-case time, insertion sort is the algorithm of choice either when the data is nearly sorted (because it is adaptive) or when the problem size is small (because it has low overhead).

    For these reasons, and because it is also stable, insertion sort is often used as the recursive base case (when the problem size is small) for higher overhead divide-and-conquer sorting algorithms, such as merge sort or quick sort.

    j_random_hacker : +1. Insertion sort's inner loop just happens to be a good fit for modern CPUs and caches -- it's a very tight loop that accesses memory in increasing order only.
    guns : Well, quicksort can be implemented as a stable sort, but since it's optimal for randomized sets, I think the efficient qsort functions randomize the data deliberately before sorting.
    sykora : Insertion sort is also good because it's useful in online situation, when you get one element at a time.
  • An important concept in analysis of algorithms is asymptotic analysis. In the case of two algorithms with different asymptotic running times, such as one O(n^2) and one O(nlogn) as is the case with insertion sort and quicksort respectively, it is not definite that one is faster than the other.

    The important distinction with this sort of analysis is that for sufficiently large N, one algorithm will be faster than another. When analyzing an algorithm down to a term like O(nlogn), you drop constants. When realistically analyzing the running of an algorithm, those constants will be important only for situations of small n.

    So what does this mean? That means for certain small n, some algorithms are faster. This article from EmbeddedGurus.net includes an interesting perspective on choosing different sorting algorithms in the case of a limited space (16k) and limited memory system. Of course, the article references only sorting a list of 20 integers, so larger orders of n is irrelevant. Shorter code and less memory consumption (as well as avoiding recursion) were ultimately more important decisions.

    Insertion sort has low overhead, it can be written fairly succinctly, and it has several two key benefits: it is stable, and it has a fairly fast running case when the input is nearly sorted.

  • If you're talking about maintaining a sorted list, there is no advantage over some kind of tree, it's just slower.

    Well, maybe it consumes less memory or is a simpler implementation.

    Inserting into a sorted list will involve a scan, which means that each insert is O(n), therefore sorting n items becomes O(n^2)

    Inserting into a container such as a balanced tree, is typically log(n), therefore the sort is O(n log(n)) which is of course better.

    But for small lists it hardly makes any difference. You might use an insert sort if you have to write it yourself without any libraries, the lists are small and/or you don't care about performance.

  • YES,

    Insertion sort is better than Quick Sort on short lists.

    In fact an optimal Quick Sort has a size threshold that it stops at, and then the entire array is sorted by insertion sort over the threshold limits.

    Also...

    For maintaining a scoreboard, Binary Insertion Sort may be as good as it gets.

    See this page: http://www.pathcom.com/~vadco/binary.html

    All the Best,

    HeavyJ

Is ASP.NET MVC 1.0 Futures beta/preview code?

I understand that the "1.0" in "ASP.NET MVC 1.0 Futures" means that it is the ASP.NET MVC Futures built against the ASP.NET MVC 1.0 RTW (final/release to web). What I'd like to know is whether the Futures code is solid enough to treat as 1.0 / gold quality?

We're about to jump into ASP.NET MVC for the first time and it came up that we should consider adding Futures to our build. Problem is, if it's alpha code I'm wondering if it would be wise; stability is going to be very important for us.

From stackoverflow
  • Stability is good anough. The only problem is that Features might be cahnged in the future. Anyway, I use them in productino websites without any problems.

  • It is the official release, not the beta. However, like any Microsoft product, 2.0 will always better if you can wait, but as far as your question concerned, it's the full release.

JQuery Autocomplete CSS not working?

I am trying to implement JQuery Autocomplete pluggi using Django. I've been able to wire the thing together and I can actually see the result back in the HTML template. My problem is that the JQuery Autocomplete CSS doesn't seem to work. The results I get are not well formatted/styled, and they have no background and you cannot even select them. What is it that am missing?

I have these three files in my media folder same folder:

autocomplete.js
dimensions.js
autocomplete.css

In my html template I have the following function:

$(function(){
    setAutoComplete("tags", "tagResults", "/taglookup/?query=");
});

My textfield looks like this;

<input type="text" name="tags" value="">

Where do I put the tagResults in my HTML template document? Every time I try to introduce a DIV with id="tagResults", JQuery throws an error.

Any ideas?

From stackoverflow
  • I'm not sure this will be of any help to you but here it goes:

    I have been learning to use the exelent jQuery pluggin Autocomplete that could be found here the last couple of days. It does not seem to be the same thing as you are using. I could not find any references what so ever to the thing you are using on the jquery homepage. If this motivates a switch from one autocomplete-library to another for you I do not know, but you got tons of examples out there on the thing I'm using so you might be helped by a switch.

    Good luck.