Saturday, February 5, 2011

Excel: How to add double quotes to strings only in CSV file

I want to create a CSV file from Excel in which string values should be in double quotes and date values should be in MM/dd/yyyy format. All the numeric and Boolean values should be without quotes.

How would I go about this?

  • The default csv file format is to use commas between each value, quotes to contain each cell (In case your cell contains a comma) and line breaks for the next row e.g.

    "A1","B1"
    "A2","B2"
    

    This is only from me toying with open office, which may vary a little from excel. But try it and see.

    John Y : That's not the default format for Excel. Excel will read CSVs with quotes around every value (and try very hard to interpret numeric-looking values as numeric, even with quotes), but it won't write CSVs like that.
    wbinford : As the previous commenter noted, this is not how Excel works by default.
    From
  • It's easier to use VBA to do this. The SaveAs method of the Workbook object only lets you choose pre-defined formats and the xlCSV one does not delimit strings with double-quotes.

    To do this in VBA:

    Dim fileOut As Integer
    
    fileOut = FreeFile
    Open "C:\foo.csv" For Output As #fileOut
    
    Write #fileOut, 14, "Stack Overflow", Date, True
    
    Close #fileOut
    

    (NB Date is a VBA statement that returns the current system date as a Variant of sub-type Date)

    If you then examine the file in Notepad:

    14,"Stack Overflow",#2009-05-12#,#TRUE#

    The string has been delimited as required, the date converted to universal format and both the date and boolean are delimited with # signs.

    To read the data back in use the Input # statement which will interpret all of the values appropriately.

    If you want to write part of a line and then finish writing it later then:

    Write #fileOut, 14, "Stack Overflow";
    Write #fileOut, Date, True
    

    produces the same result as the original program. The semi-colon at the end of the first statement prevents a new line being started

    Strings with embedded double-quotes will cause problems so you'll need to remove or replace those characters

    From barrowc
  • It's kind of scary that Excel doesn't let you specify formats. Here's a MrExcel link that might prove useful to you as well.

    http://www.mrexcel.com/forum/showthread.php?t=320531

See All Files Changed in Multiple Changesets in VSTS

Does anyone know how get a listing of all files changed in multiple changesets in Visual Studio Team System 2005? I basically want to see a listing of all files changed from the start of a development effort till the end.

  • You can use TF.exe from the command line to get at an awful lot of information very easily.

    Even if it's not possible to directly extract the info you want in one call, it would be easy to write a small program that calls TF.exe to get a list of the changesets you're interested in, and then calls it again for each changeset to retrieve the file lists.

    Start a Visual Studio Command Prompt (from your start menu) and enter tf.exe /? to get to the documentation.

  • With the power tools installed:

    # get-tfschangeset doesn't support arrays, so you have to loop
    100, 200, 300 | % { get-tfschangeset $_ } | select-tfsitem | select -unique path | sort
    
    # powershell also has a range operator...
    100..105 | % { get-tfschangeset $_ } | select-tfsitem
    

IList(Of T).Sort help

Dim classCodeDetails As List(Of ClassCodeDetail) =     
    db.ClassCodeHeaders.Single(Function(cch)
        cch.CLCH_ID = classCodeHeaderId
    ).ClassCodeDetails.ToList()

classCodeDetails.Sort(Function(c1, c2)  
    c1.Make.MAKE_English.CompareTo(c2.Make.MAKE_English)
)

My question is how can I sort on multiple attributes? I want to sort first by Make.MAKE_English, then By Model.MODL_English.

How do I implement that?

Thanks,
~ck

  • If you don't need to sort in-place, you could use the OrderBy function:

    Dim sortedList = list.OrderBy(Function(x) x.Prop1).ThenBy(Function(x) x.Prop2)
    

    Your example would be:

    Dim classCodeDetails As List(Of ClassCodeDetail) = _
       db.ClassCodeHeaders.Single(Function(cch) cch.CLCH_ID = classCodeHeaderId).ClassCodeDetails _
      .OrderBy(Function(c1) c1.Make.MAKE_English) _
      .ThenBy(Function(c1) c1.Make.MODL_English) _
      .ToList()
    

    In fact, this is the correct way to do this (seems you are using LINQ to SQL) since it'll use ORDER BY in the generated SQL statement to sort data instead of manually sorting it on the client.

Efficient modelling of an MruList in C# or Java

How would you implement a capacity-limited, generic MruList in C# or Java?

I want to have a class that represents a most-recently-used cache or list (= MruList). It should be generic, and limited to a capacity (count) specified at instantiation. I'd like the interface to be something like:

public interface IMruList<T>
{
    public T Store(T item);
    public void Clear();
    public void StoreRange(T[] range);
    public List<T> GetList();
    public T GetNext(); // cursor-based retrieval
}

Each Store() should put the item at the top (front?) of the list. The GetList() should return all items in an ordered list, ordered by most recent store. If I call Store() 20 times and my list is 10 items long, I only want to retain the 10 most-recently Stored items. The GetList and StoreRange is intended to support retrieval/save of the MruList on app start and shutdown.

This is to support a GUI app. I guess I might also want to know the timestamp on a stored item. Maybe. Not sure.

Internally, how would you implement it, and why?

(no, this is not a course assignment)

  • Couple of comments about your approach

    • Why have Store return T? I know what I just added, returning it back to me is un-necessary unless you explicitly want method chaining
    • Refactor GetNext() into a new class. It represents a different set of functionality (storage vs. cursor traversal) and should be represented by a separate interface. It also has usability concerns as what happens when two different methods active on the same stack want to traverse the structure?
    • GetList() should likely return IEnumerable<T>. Returning List<T> either forces an explicit copy up front or returns a pointer to an underlying implementation. Neither is a great choice.

    As for what is the best structure to back the interface. It seems like the best to implement is to have a data structure which is efficient at adding to one end, and removing from the other. A doubly linked list would suit this nicely.

    From JaredPar
  • I would have an internal ArrayList and have Store() delete the last element if its size exceeds the capacity established in the constructor. I think standard terminology, strangely enough, calls this an "LRU" list, because the least-recently-used item is what gets discarded. See wikipedia's entry for this.

  • You can build this up with a Collections.Generic.LinkedList<T>. When you push an item into a full list, delete the last one and insert the new one at the front. Most operations should be in O(1) which is better than a array-based implementation.

    From Dario
  • Here's a Cache class that stores objects by the time they were accessed. More recent items bubble to the end of the list. The cache operates off an indexer property that takes an object key. You could easily replace the internal dictionary to a list and reference the list from the indexer.

    BTW, you should rename the class to MRU as well :)

    class Cache
        {
            Dictionary<object, object> cache = new Dictionary<object, object>();
    
            /// <summary>
            /// Keeps up with the most recently read items.
            /// Items at the end of the list were read last. 
            /// Items at the front of the list have been the most idle.
            /// Items at the front are removed if the cache capacity is reached.
            /// </summary>
            List<object> priority = new List<object>();
            public Type Type { get; set; }
            public Cache(Type type)
            {
                this.Type = type;
    
                //TODO: register this cache with the manager 
    
            }
            public object this[object key]
            { 
                get 
                {
                    lock (this)
                    {
                        if (!cache.ContainsKey(key)) return null;
                        //move the item to the end of the list                    
                        priority.Remove(key);
                        priority.Add(key);
                        return cache[key];
                    }
                }
                set 
                {
                    lock (this)
                    {
                        if (Capacity > 0 && cache.Count == Capacity)
                        {
                            cache.Remove(priority[0]);
                            priority.RemoveAt(0);
                        }
                        cache[key] = value;
                        priority.Remove(key);
                        priority.Add(key);
    
                        if (priority.Count != cache.Count)
                            throw new Exception("Capacity mismatch.");
                    }
                }
            }
            public int Count { get { return cache.Count; } }
            public int Capacity { get; set; }
    
            public void Clear()
            {
                lock (this)
                {
                    priority.Clear();
                    cache.Clear();
                }
            }
        }
    
    From Steve
  • In Java, I'd use the LinkedHashMap, which is built for this sort of thing.

    public class MRUList<E> implements Iterable<E> {
        private final LinkedHashMap<E, Void> backing;
    
        public MRUList() {
            this(10);
        }
    
        public MRUList(final int maxSize) {
            this.backing = new LinkedHashMap<E,Void>(maxSize, maxSize, true){
               private final int MAX_SIZE = maxSize;
               @Override
               protected boolean removeEldestEntry(Map.Entry<E,Void> eldest){
                   return size() > MAX_SIZE;
               }
            };
        }
    
        public void store(E item) {
            backing.put(item, null);
        }
    
        public void clear() {
            backing.clear();
        }
    
        public void storeRange(E[] range) {
            for (E e : range) {
                backing.put(e, null);
            }
        }
    
        public List<E> getList() {
            return new ArrayList<E>(backing.keySet());
        }
    
        public Iterator<E> iterator() {
            return backing.keySet().iterator();
        }
    }
    

    However, this does iterate in exactly reverse order (i.e. LRU first, MRU last). Making it MRU-first would require basically reimplementing LinkedHashMap but inserting new elements at the front of the backing list, instead of at the end.

  • Java 6 added a new Collection type named Deque... for Double-ended Queue.

    There's one in particular that can be given a limited capacity: LinkedBlockingDeque.

    import java.util.ArrayList;
    import java.util.List;
    import java.util.concurrent.LinkedBlockingDeque;
    
    public class DequeMruList<T> implements IMruList<T> {
    
        private LinkedBlockingDeque<T> store;
    
        public DequeMruList(int capacity) {
         store = new LinkedBlockingDeque<T>(capacity);
        }
    
        @Override
        public void Clear() {
         store.clear();
        }
    
        @Override
        public List<T> GetList() {
         return new ArrayList<T>(store);
        }
    
        @Override
        public T GetNext() {
     // Get the item, but don't remove it
         return store.peek();
        }
    
        @Override
        public T Store(T item) {
         boolean stored = false;
         // Keep looping until the item is added
         while (!stored) {
          // Add if there's room
          if (store.offerFirst(item)) {
           stored = true;
          } else {
           // No room, remove the last item
           store.removeLast();
          }
         }
         return item;
        }
    
        @Override
        public void StoreRange(T[] range) {
         for (T item : range) {
          Store(item);
         }
        }
    
    }
    
    From R. Bemrose
  • Everyone enjoys rolling their own container classes.

    But in the .NET BCL there is a little gem called SortedList<T>. You can use this to implement your MRU list or any other priority-queue type list. It uses an efficient tree structure for efficient additions.

    From SortedList on MSDN:

    The elements of a SortedList object are sorted by the keys either according to a specific IComparer implementation specified when the SortedList is created or according to the IComparable implementation provided by the keys themselves. In either case, a SortedList does not allow duplicate keys.

    The index sequence is based on the sort sequence. When an element is added, it is inserted into SortedList in the correct sort order, and the indexing adjusts accordingly. When an element is removed, the indexing also adjusts accordingly. Therefore, the index of a specific key/value pair might change as elements are added or removed from the SortedList object.

    Operations on a SortedList object tend to be slower than operations on a Hashtable object because of the sorting. However, the SortedList offers more flexibility by allowing access to the values either through the associated keys or through the indexes.

    Elements in this collection can be accessed using an integer index. Indexes in this collection are zero-based.

How to integrate native applications with eclipse?

I have a couple of native applications written in C++ and C#. These are legacy applications that require data sharing between them. Currently, data sharing is through import/export of text file in some proprietary format. We are currently looking at integrating these two applications using eclipse. My questions are:

  1. How can we integrate native applications such as c++ and c# based applications into eclipse?
  2. What kind of data integration methods does eclipse provide for native applications?
  3. Is eclipse the best choice for such use?

Also, it will be very helpful if you can share your experiences about integrating native applications in eclipse.

[EDIT] I am specifically looking at integrating native applications into eclipse just the way we would integrate a eclipse plugin written in Java. For example, what does it take to write a wrapper plugin in Java which will wrap a native tool by using JNI calls that can be integrated into eclipse just as any other eclipse plugin? Is this is a preferred approach for integrating native applications or is it a good idea to rewrite my legacy native application in Java?

I am not looking at using eclipse as a launch pad for my native applications using the "External Tools" configuration.

  • There's nothing inherently specific about Eclipse here (that's not to say you can't use it as an IDE). Basically, you should look at P/Invoke, COM Interop, and MSDN's (vast) section on Managed-Unmanaged Interoperability. While you could integrate both sides with Java/SWT, and use it as the middle-man, I don't think that makes much sense.

  • If you just want to run the apps from inside eclipse use the external tools infrastructure.

    If not, please provide more details on the integration that you seek.

    Suresh Kumar : I am specifically looking at integrating native applications into eclipse just the way we would integrate a eclipse plugin written in Java. For example, what does it take to write a wrapper plugin in Java which will wrap a native tool by using JNI calls that can be integrated into eclipse just as any other eclipse plugin? Is this is a preferred approach for integrating native applications or is it a good idea to rewrite my legacy native application in Java? I am not looking at using eclipse as a launch pad for my native applications using the "External Tools" configuration.
    From lothar
  • If you can write a JNI wrapper around your C++/C# applications, then you can use them from an Eclipse plugin.

    The simplest approach is to:

    1. repackage your C++/C# applications as DLLs (if they aren't already)
    2. wrap them with a JNI layer
    3. place the DLLs in the root folder of your plugin
    4. call System.LoadLibrary() from a static initializer block in your JNI wrapper class to load required DLLs

    You might find the discussion on the Eclipse newsgroup entitled Using DLL in an Eclipse plugin helpful.

    From Ken Dyck

can we rename our Rails folders and not have any side effects?

when starting Ruby on Rails programming, I will use

rails first
rails second

and try out things in these "first" and "second" projects

but as they get more mature i want to check them into SVN and develop further, so can i rename them into

"superapp"

or

"web30"

and check into SVN and develop further without any side effects? I don't want to rename them and generate more controllers and models and do migration and one day found out that the project is messed up and caused problem when going to production / deployment.

  • Not a problem. Rails doesn't care about the name of the directory it's stored in (or the path to it).

    From Burke
  • If you have to merge, merge them first and then commit.

    Rails don't mind about project names so don't worry about that. If you need to rename something already on a svn, don't forget to use the rename function.

    From marcgg
  • I have not encountered any problems while doing such renames.

    In fact I have just created a project and verified that after the rename, the RAILS_ROOT variable is automatically updated. You can verify this using script/console.

    From gdelfino

Easy way to see SQL generated by ActiveRecord.Save()?

SubSonic 2.1

I have an ActiveRecord object. When I call its Save() method, is there an easy way for me to seen the generated SQL, say in the Visual Studio debugger? Running SQL Profiler is not an option.

Thanks.

  • You can load the subsonic source project into visual studio, and set the core project's debug target to your application and run the debugger. Or you can attach the debugger to your running application. Your application has to be built with a reference to the subsonic project's current debug output 'subsonic.dll'; I usually have both projects open in separate instances of visual studio. Then set a breakpoint about line 180 of activerecord.cs:

    QueryCommand cmd = GetSaveCommand(userName);

    Then do a watch on cmd to see the sql.

    R.L. : Thanks Paul....
    From P a u l

TextBox let '\n' be the carriage return

TextBoxes created by "CreateWindowEx(WS_EX_CLIENTEDGE, "EDIT", "", ES_MULTILINE.." require \r\n for a new line. im redirecting my stdoutput into that textbox, which uses just '\n' to indicate a new line. and im not willing to replace all '\n' with '\r\n' isn't there a way to let '\n' beeing a newline in textboxes?

thx

  • \r\n is not a new line. It is a carriage return + new line. They are different things. It probably means more to people who work in the console world though because you can go to a new line without shifting back to character position 1.

  • I'm pretty sure what you're asking is impossible (i.e. there's no magic setting to make Windows edit controls accept Unix-style newlines).

    5andr0 : alright, thanks for letting me know. so i really have to replace all the \n with \r\n :/
    From codebolt
  • Not sure what language you are using, but why not just do this (VB.NET Example):

    TextBox1.Text=TextBox1.Text.Replace("\r\n","\n")
    

    That should replace all the "\r\n" occurences with just "\n"

    From icemanind

How can I supply a table name at runtime using LINQ to SQL?

I have to use LINQ to SQL and along with it a pure SQL classic query. And this SQL query has the Table from where my data will be generated, but I will not know this Table previously. It will be known in compile time.

So how can I make LINQ understand from what Table I want to make the query?

What are some good widgets to add to a programming related blog (on blogger.com)?

I decided to start my blog recently. Anyway I put it on blogger.com and was looking at the widgets you can add. There are some 100k+ of them.

By the way, I tried to add the StackOverflow search widget and it complained it was broken.

Anyway, I'm after some suggestions on good programming related widgets worth adding.

Zipcode based search

I want to make a geographical search using US city and state or zip-code and corresponding results will be viewed. In the search we have to mention the radius distance. For example: i would like to search between 25 miles around California.

To do this, what should i do? is there any database containing us city,state,zip, latitude, longitude information?????

Please help me with this asap

with regards Tarek Mahmud Apu

SqueakMap won't work in a fresh 3.10 dev image

Hello, I just downloaded a fresh Squeak-dev image from Damien Cassou, clicked on SqueakMap, and got the error that in SqueakMap>>categories, the objects instance variable is nil, but shouldn't be. I can't be the only one with that error, am I? What should I do?

  • This fixes it:

    SMSqueakMap default loadUpdates
    

    Easy, huh?

    From nes1983

How to get the token type from a CFStringTokenizer in Cocoa?

The CFStringTokenizer documentation has two conflicting statements in CFStringTokenizerAdvanceToNextToken():

CFStringTokenizerAdvanceToNextToken

...

Return Value

The type of the token if the tokenizer succeeded in finding a token and setting it as current token. Returns kCFStringTokenizerTokenNone if the tokenizer failed to find a token. For possible values, see “Token Types.”

...

If a token is found, it is set as the current token and the function returns true; otherwise the current token is invalidates and the function returns false.

The first paragraph (returning a token type) is what I'd like to see: it lets you, for example, check if a token is made up entirely of non-alphanumeric characters. However, the second paragraph (returning true or false) seems to be what is actually happening.

Any ideas why that would be, or how to work around it?

  • The header comment doesn't mention returning true or false, and when the header and the online docs disagree it's often the header that is correct.

    In a simple test I'm able to get return values other than 0 and 1, so the problem you are seeing may be more specific; can you post sample code that's failing?

    From smorgan
  • It's possible they meant “true” and “false” in the broader sense of “non-zero” and “zero”. If it finds a token, the function returns kCFStringTokenizerTokenNormal (which is 1) or some combination of the masks (either way, non-zero/“true”). If it doesn't, the function returns kCFStringTokenizerTokenNone (which is zero/“false”).

    It's certainly vague language, though, so please file a documentation bug on the Apple Bug Reporter.

Static methods vs repository pattern with Linq2Sql

I've hit on the idea of creating static methods on the partial Linq queries such as

public partial class User
{
    public static User FindByGuid(string guid, ApplicationDataContext context)
    {
        return context.Users.Where(x => x.GUID == guid).Single();
    }
}

So, for example, I can easily find a user by doing:

using (var context = new ApplicationDataContext())
{
    var user = DataAccess.User.FindByGuid(UsersDropDown.SelectedValue, context);
}

Is this a recognised design pattern? What are the advantages/disadvantages of doing this vs the repository model?

  • While I don't see a recognized pattern in what your doing here I do see that you are using Dependency Injection by passing the applicationdatacontext into the method as a dependency. The problem here is that you are still tightly coupled to your datacontext regardless of where the dependency is initiated which makes it more difficult to unit test.

SQL query to extract text from a column and store it to a different column in the same record.

I need some help with a SQL query...

I have a SQL table that holds in a column details of a form that has been submitted. I need to get a part of the text that is stored in that column and put it into a different column on the same row. The bit of text that I need to copy is always in the same position in the column.

Any help would be appreciated guys... my mind has gone blank :">

  • UPDATE  mytable
    SET     other_column = SUBSTRING(column, begin_position, length)
    
    From Quassnoi
  • UPDATE table SET Column2 = SUBSTRING(Column1, startPos, length)

    Irfan Mulic : There is no "where" statement - meaning this will update the all records in this table.
  • You may just want to use a computed column. This way if the source string changes, your computed column is still correct. If you need to seek to this substring then you might want a persisted computed column if your db supports it.

    John Sansom : +1: For thinking outside the box :-) You could also make it a persisted computer column.
    Rob Garrison : Perfect answer. If you persist the column, you can also index it.
    From
  • What if the value you wanted to copy was in a different position in each record, but always followed the same text?

    Richard West : I would use CHARINDEX ( string_expression , target_expression) to get the starting position of text string, then use SUBSTRING to pull it out of the field.

Passwords in Emacs tramp mode editing

I'm using emacs tramp mode to remotely edit files over ssh. The problem is that every time I save the file I'm editing I have to enter my user password. I find that very annoying. How can I write my password only once / editing session?

  • Ah, from the tramp docs on password caching you can set:

    (setq password-cache-expiry nil)
    

    which requires the package password-cache.el.

    Also, in the tramp sources, it mentions reading the ssh-agent(1) man page, which shows how to set it up so that you don't have to re-enter passwords (inside, or outside of Emacs):

    There are two main ways to get an agent set up: The first is that the agent starts a new subcommand into which some environment variables are exported, eg ssh-agent xterm &. The second is that the agent prints the needed shell commands (either sh(1) or csh(1) syntax can be generated) which can be evalled in the calling shell, eg eval ssh-agent -s for Bourne-type shells such as sh(1) or ksh(1) and eval ssh-agent -c for csh(1) and derivatives.

    Török Gábor : The package name is `package-cache`.
    Trey Jackson : (belated) Credit to Török for the package name.
  • (setq password-cache-expiry nil)
    
    Jonas : Should this go into my .emacs file?
    dfa : yes, right after (require 'tramp)
    From dfa
  • In addition to Trey Jackson's solution, there are a few more ways you can choose:

  • use SSH public key authentication.

  • Using public key (RSA) authentication is more secure and much more convenient. On a GNU/Linux system (and maybe others, I don't know) you typically would unlock your private key once per login session with a password and then use it.

    From Borbus

ASP.NET Website Administration Tool With Custom Role Provider

My system uses a custom security and data model for users and roles.

However I was wondering if I implemented this using the provider model whether I could hook this up to the asp.net website administration tool.

I'm also sceptical as to whether, the asp.net website administration tool is of any real world use or if it's just a gimmock.

  • Yes, the ASP.NET Website Administration Tool should pick up on any providers you have defined in your config file (custom or otherwise).

    As for it's real world use, you could just copy the files from "C:\Windows\Microsoft.NET\Framework\v2.0.50727\ASP.NETWebAdminFiles" to your live site, although I tend to only use it in my development environment to quickly add users and roles for testing and then use my own web forms hooked into the provider on the live site (more for styling and formatting reasons than any other though).

How to "push" updates to individual cells in a (ASP.NET) web page table/grid?

I'm building something similar to a price comparison site. This will be developed in ASP.NET/WebForms/C#/.NET 3.5. The site will be used by the public, so I have no control over the client side - and the application isn't so central to their lives that they'll go out of their way to make it work.

I want to have a table/grid that displays products in rows, vendors in columns, and prices in the cells. Price updates will be arriving (at the server) continuously, and I'd like to "push" any updates to the clients' browsers - ideally only updating what has changed. So, if Vendor A changes their price on Product B, I'd want to immediately update the relevant cell in all the browsers that are viewing this information.

I don't want to use any browser plug-ins (e.g. Silverlight). Javascript is fine.

What's the best approach to take?

Presumably my options are:

1) have the client page continuously poll the server for updates, locate the correct cell and update it; or 2) have the server be able to send updates to all the open browser pages which are listening for these updates.

The first one would seem the most plausible, but I don't want to constrain the assembled wisdom of the SO community.

I'm happy to purchase any third party components (e.g. a grid) that might help with this. I already have the DevExpress grid/ajax components if they provide anything useful.

  • I didn't think you could 'poll' a browser (IE, Firefox etc) so, the only way I know of to get data is to make the page Request it.

    What about refreshing an AJAX update panel every so many seconds. This way the page won't flicker and you will be limiting the amount of data that is being sent back and forth.

    From iWeasel
  • I think your instinct is correct that the pull model is easier to construct. iWeasel mentioned Ajax, and I want point you to Dave Ward's post on jQuery, Ajax and PageMethods in Asp.Net. His blog has an excellent series that will help you achieve what you looking to do.

    For validation of Dave's approach, Rick Strahl has a great article on jQuery and Asp.net as well, and in his example he is displaying products in a grid like format.

    While I don't have experience with this jQuery plugin, you may want to investigate jQuery Timer to help with your timing intervals.

  • you can possibly look at few so-called server side push technologies like - AjaxPush, Comet or even some commercial products like kaazing gateway & lightstreamer

    David Robbins : I read about Comet on Ajaxian. Do you have direct experience with it?
    Vikram : @David, we are building a Comet based chat solution and are currently exploring different solutions for the same. We have used 2 articles from codeproject.com as the base and here are the links for the same - http://www.codeproject.com/KB/aspnet/wxv_comet.aspx , http://www.codeproject.com/KB/aspnet/AspNetComet.aspx
    From Vikram

Best way to load large amouts of data into datagrid.

I am trying to load a lot of data into a datagrid which as you would expect takes a long time to load up. This is due to the face that I am loading data from a COM object which I have wrapped up into .NET object with a custom enumerator.

I have looked into virtual loading the datagrid and it works alright but I was wondering if there was a better way of doing the same thing.

What I am after is a datagrid that shows a scroll bar for the whole amount of data but only loads the data for the first say 50 rows then after you scroll it loads the next 50 or so.

Does anyone know if this is possible, or if there is a control available that does this automatically?

  • Check out Telerik datagrid controls.

    From Galwegian
  • http://www.codeproject.com/KB/grid/DataGridView_paging.aspx

    From fuz3d
  • Is it possible to load only a part of the data from the COM object? If so, load for example 100 rows, and save the rowcount. Then in the scroll event of the grid, use the FirstDisplayedScrollingRowIndex property to see if you are getting close to 100, and load some more rows, and increment the rowcount.

    This does not however show a scrollbar for all loadable rows.

    From kaze

How do you stop RadioButtonList Label text from wrapping under the button

I have a radio button list and some of the labels are quite long so they wrap and the second line appears underneath the radio button. Ideally I would like the text to wrap with the second line starting beneath the first character of the first line.

Any ideas on how? or would I have to make my own list based control for this?

  • You can take a radio button and a seperate label and set the AssociatedControlID property of that label.

    <table>
        <tr>
            <td>
                <asp:RadioButton runat="server" ID="rdo" />
            </td>
            <td>
                <asp:Label runat="server" ID="lbl" Text="Radio Text" AssociatedControlID="rdo" />
            </td>
        </tr>
    </table>
    
    Mark Dickinson : Thanks, I was hoping to not have to do even more table layout so I'm going with the style idea.
    From Kirtan
  • This CSS actually does the trick:

    <style type="text/css">
     table.radioWithProperWrap input
     {    
          float: left;
     }
    
     table.radioWithProperWrap label
     {    
          margin-left: 25px;
          display: block;
     }
    </style>
    <asp:RadioButtonList runat="server" CssClass="radioWithProperWrap" ....>
    
    Mark Dickinson : Many thanks, I had a similar style in place that worked for IE and was just sorting which element to force to display:block when you hit the nail on the head.
  • try a negative text-indent style -20px works for IE8

    From Fred

Does SslStream use LocalCertificateSelectionCallback when acting as a server?

If I create a SslStream instance like this:

secureStream = new SslStream(stream, true, tlsRemoteCallback, tlsLocalCallback);

And then I use one of the AuthenticateAsServer or BeginAuthenticateAsServer methods, is it at all possible for the LocalCertificateSelectionCallback (tlsLocalCallback) to be invoked? And if so, how?

I'm under the impression this isn't possible, because the AuthenticateAsServer method requires an X509Certificate parameter. And if you pass null, then it throws an exception. But I want to be certain since I'm trying to write a socket API for other developers on my team to use.

  • Are you trying to have secureStream pick which certificate it uses to authenticate itself with the client?

    I don't think that is possible. Doing some Reflectoring, I see that the delegate ultimate goes to a "m_CertSelectionDelegate" in System.Net.Security.SecureChannel. A quick analysis of this variable seems to indicate that it's only using for verifying a server cert or verifying the cert the client gives to mutually authenticate itself.

    From Jeff Moser

Coverting from Datasets to stored procs and modern ORM

How much effort would it take to migrate a large existing codebase from a Strongly Typed Dataset driven data access layer to a DAL driven by stored procs and/or a more modern ORM package? Is there any shiny tool that automates a portion of this process?

The current code base has well over 100+ datasets mirroring the sql database (but haven't always been 100% in sync with changes in the DB structure). The current stance is that it would be too much time/effort to change now, but I question how much technical debt this is leaving us to pay down every week. This is to say nothing of the performance on the backend of datasets' SQL vs. an optimized sproc.

So, is that justified? Would something like that be too much of a monster to tackle in a reasonable time and get a worthwhile payoff? I know I could change the DAO-like classes they use to interfaces (should be already) and develop this on the side while still using the datasets in production until a feasibility test of some sort could be done on a small subset of the whole.

  • I would say moving on to an ORM like LINQ to SQL would be far less effort intensive compared to the stored proc driven DAL layer. few things that come straight to my mind :

    • Situation 1 - if you are using your typed datasets outside your DAL [in UI, BLL] then the effort is going to be high for sure because you will need to do an extensive impact analysis of the change and make changes pretty much everywhere you have used your typed datasets.

    • Situation 2 - if you are using your typed datasets ONLY withing your DAL and your UI, BLL dont care about the internal implementation of DAL and are oblivious of the typed dataset, then it would be far less effort intensive. You will need to change only within the DAL layer.

    • If you are in situation 2, then i think it would definitely be worthwile to move from typed data sets to ORM mapper.

    • If you intend to take the stored proc approach for DAL, then you might look at www.mygenerationsoftware.com to auto generate your procs to reduce some effort, however the effort would still be higher compared to the ORM mapper and another downside may be that you end up with umpteen simple insert / update procs in your DB. we generally use procs primarily for cascaded UPSERTS (update+insert) or complex calcualtions only and use LINQ to SQL for basic insert, update, deletes.

    hope this helps in someway !

    Drithyin : I agree that we don't need a stored proc for every CRUD op, only for things more complex than that. I'll have to read some code (I just started at this comp a couple weeks ago) to see what the impact would be. At first blush, it seems like every Dataset is behind a "DataManager" class which is 95% passthroughs to the Datasets, so I think it's not leaking out of the DAL. Sound like the hardest part will be convincing the uppers that the time would be worth it...
    From Vikram

Are cross-dll allocations ok?

If I have an app that uses at least two dlls, is it generally safe to allocate resources in one dll and free them in another?

I'm thinking specifically about calling fopen and fclose in different dlls, but I'd also like to know that it's safe for other resources (memory pointers, handles, etc...).

I think as long as everything is compiled with the same switches, it should work.

Thanks, Cory

  • As long as you're using the DLL version of the C runtime library (/MD or /MDd) then yes, it's safe.

    If you're statically linking the CRT into either DLL (/MT or /MTd) then no, it's not safe.

  • This is a Bad Thing(TM) to do for all but non-trivial projects. This works under a very stringent set of conditions like version of the dlls, threading model, memory allocators used in each and a host of others. Finally, bugs will be too hard to chase.

    From dirkgently