Monday, February 21, 2011

Why declare static classes as sealed and abstract in C#?

This MSDN article states that static classes should be declared as sealed and abstract. I was under the impression that static classes were already sealed. Why would you also need to declare a static class as sealed?

From stackoverflow
  • That may be the difference between good code and crappy code. In fact, it depends on how you're going to use your code - separate it - and what kind of security you need for each class.

  • I think the pertinent bit from that article is:

    "Do declare static classes as sealed and abstract, and add a private instance constructor, if your programming language does not have built-in support for static classes."

    Remember, the .NET framework supports a lot of different languages.

    Guy : Thanks - It was late at night and I wasn't reading properly
  • It appears to be saying that declaring a class as sealed and abstract with a private constructor is an alternative to the static class if the language does not support static classes.

  • C# v1 did not allow 'static' keyword on class. So if you have a class with only static methods, it was suggested to declare it 'sealed', 'abstract' and make constructor private. This means that no one can instantiate your class or try to inherit from it. [It doesn't make sense to inherit from a class which has only static methods.]

    C# v2 allowed the static keyword on a class so you don't have to use the above trick to enforce correct usage.

    Henk Holterman : C#1 did have a static keyword, it just wasn't allowed on class definitions
    SolutionYogi : Henk, you are right. I corrected my answer, thank you.
    • One of the effects of marking a class as abstract is that it cannot be instantiated.
    • One of the effects of marking a class as sealed is that is cannot be inherited.

    That's what a static class actually is -- a class that cannot be instantiated and that cannot be inherited.

    So the article doesn't state you should mark your static classes as abstract and sealed additionally, but this is the way how static classes are represented in IL.

    (Other languages may allow you to do this if they do not have a static keyword, although I doubt it, because an abstract sealed class doesn't make a lot of sense semantically.)

C# WinForms User/Permission management

Can anyone provide me a link of any example WinForms application that implements the concept of User authentication and authorization one the basis of Roles or Groups?

The application should allow access of users to the main-menu on the basis of their roles.

From stackoverflow
  • If you are building the menu from a database table, you can security trim it by joining it to another table or view that excludes records on the basis of the permissions set.

    The diagram below illustrates the basics of setting up role permissions for users, and contains a couple of other tables for security trimming individual controls on the form as well.

    Controls Based Security in a Windows Forms Application
    http://www.simple-talk.com/dotnet/windows-forms/controls-based-security-in-a-windows-forms-application/
    .

    alt text

AfxGetAppName() returns garbage characters

I have the following line of code in my application:

CString strAppName = AfxGetAppName();

Sometimes it fills strAppName up with garbage characters, and I can't figure out why.

Anyone have any ideas?

TIA.

From stackoverflow
  • That is possible if you change m_pszAppName manually.

    At the very beginning of application initialization, AfxWinInit calls CWinApp::SetCurrentHandles, which caches the current value of the m_pszAppName pointer as follows:
    pModuleState->m_lpszCurrentAppName = m_pszAppName;

    That is, the module state struct holds a copy of the m_pszAppName pointer. If you change m_pszAppName in InitInstance as adviced in MSDN, you still have the old pointer value in pModuleState->m_lpszCurrentAppName. The AfxGetAppName() function returns AfxGetModuleState()->m_lpszCurrentAppName.

    You could add data breakpoint on m_lpszCurrentAppName and on m_pszAppName. It is initialized in <...>\Microsoft Visual Studio 9.0\VC\atlmfc\src\mfc\appinit.cpp file. You'll see what is going on with that variable and who's trying to change it.

    Justin : My application does not change `m_pszAppName`. It changes some registry keys though, could that be the issue?
    Kirill V. Lyadvinsky : I don't think that changing registry keys could implicitly change `m_pszAppName`.

sql server Invalid object name '#temp'

Hi , i have created a procedure

create procedure testProcedure_One

as

DECLARE @Query nvarchar(4000)

begin

SET @Query = 'SELECT * into #temptest FROM Table1'

Exec sp_Executesql @query

SELECT * FROM #temptest drop table #temptest end

When i run the procedure testProcedure_One i am getting "Invalid object name '#temp' " error message

but if i use ##temp means its working.

create procedure testProcedure_two

as

DECLARE @Query nvarchar(4000)

begin

SET @Query = 'SELECT * into ##temptest FROM Table1'

Exec sp_Executesql @query

SELECT * FROM ##temptest drop table ##temptest end

testProcedure_two is working fine the What might be the issue . How can i solve it ?

Please help.

From stackoverflow
  • Presumably you have following code that SELECTs from #temp, giving you the error?

    It's down to scope. ##temp is a global temporary table, available in other sessions. #temp is "local" temporary table, only accessible by the current executing scope. sp_executesql runs under a different scope, and so it will insert the data into #temp, but if you then try to access that table outside of the sp_executesql call, it won't find it.

    e.g. This errors as #Test is created and only visible to, the sp_executesql context:

    EXECUTE sp_executesql N'SELECT 1 AS Field1 INTO #Test'
    SELECT * FROM #Test
    

    The above works with ##Test as it creates a global temporary table.

    This works, as the SELECT is part of the same scope.

    EXECUTE sp_executesql N'SELECT 1 AS Field1 INTO #Test; SELECT * FROM #Test'
    

    My questions would be:
    1) do you really need to use temp tables, can you not find a solution without them using e.g. a subquery?
    2) do you really need to execute sql like this using sp_executesql?

    Jebli : Thanks.I know it was out of scope but it didn't strike for me that i have to do the select with the same query.
  • thanks AdaTheDev had given me the right solution.

TSR Programs in C

can anybody suggest a good book (or website link)for studying TSR programs in C?? Thanks in advance..

From stackoverflow
  • What? TSR? Are you on DOS still?

    See wikipedia

  • On the assumption that you really do mean TSR as in Terminate and Stay Resident, here's a wander through ancient history:

    The long out of print The Programmer's Guide MSDOS by Dennis M. Jump (1984, ISBN 0-8359-5655-5) was a good reference to all you'd need to know. Of course, C compilers that targeted pure DOS without too much runtime burden were rare, but Borland TurboC came pretty close. I'm pretty sure I once wrote a TSR in Datalight C too, but it has been a long time since those days.

    The modern descendant of TurboC is still available, and the compiler is free. I don't think it can target classic real-mode DOS any more, however.

    True Turbo C v2.01 is available at the museum.

    The FreeDOS folk probably have useful tools as well.

  • The A to Z of C has a chapter on TSR programming.

to implement online converting engine from browser to web server

Hello im looking for common way to build the right client server architecture when my goal is : the browser submit data to the web server -> the web server response with converted pdf file based on that data now my question is this : where to implement this convention engine ( that is static lib ) as web server plug in (apache, lighthttpd,nginx)? or as separate process in different server ?

From stackoverflow
  • This sounds to me like you are wanting to dynamically generate PDFs based on the data captured from a web-based form? If so, there are many different ways to achieve this- and each person from each language discipline will promote their method as being simple.

    : i know , this is what i like to learn

Simulate keypress in a Linux C console application

Is there any way to simulate a keypress in Linux using C?

In my specific situation, I'm on Ubuntu 9.04 and need a simple app that invokes a press on the "pause" button when launched. That would get an iframe in Firefox to refresh using Javascript.

From stackoverflow
  • I assume you mean the "X11 application" - it is not entirely clear from your description what you are planning to do. The below code snippet will send the "pause" keycode to the application that currently has the keyboard input focus under X11 using XTest extension - from what I've read this is the most compatible way to "fake" the keyboard events. See if you might apply this to your scenario (no error check on whether the XOpenDisplay succeeded, to make it simpler).

    #include <X11/Xlib.h>
    #include <X11/keysym.h>
    #include <X11/extensions/XTest.h>
    ...
    Display *display;
    unsigned int keycode;
    display = XOpenDisplay(NULL);
    ...
    keycode = XKeysymToKeycode(display, XK_Pause);
    XTestFakeKeyEvent(display, keycode, True, 0);
    XTestFakeKeyEvent(display, keycode, False, 0);
    XFlush(display);
    

    You will need to link with the -lX11 -lXtst.

    Obviously the firefox would need to have focus at that time.

    However, I would be curious to know what is the bigger task that you are trying to accomplish - I suspect there should be a more elegant solution than spoofing the keypress events.

    Andrew Y : side comment about my own use case for the above code: I had it an OpenCV-powered weekend hack that allowed me to fake the arrow keypresses by moving my head in front of webcam (so I could scroll the /. posts and eat sandwich at the same time :-)
    Baversjo : I want to use a griffin powermate to reload an iframe :)
    Andrew Y : Ah, so it's pretty much the same usage as my case :)

Can JDBC connection strings specify multiple databases?

Here's my current connection string:

jdbc:amazon;moduleName=Foobar:oracle:thin:@ab1na-orasvr.db.foobar.com:42111:ab1na

But I need JDBC to access multiple databases. Can I simply append the second module name, separated by a semi-colon?

From stackoverflow

How do I assign a device level hotkey to my Blackberry App?

Blackberry devices have shortcuts to open applications. For example, if you hit the 'T' button, the tasks app will open.

(BTW, you have to have "Call from Home Screen" disabled in the Phone App Settings for this to work)

How can I assign a shortcut key to open my own application?

For clarity and in case the link dies, I'll post the instructions here:

Complete the following steps:

  1. In your Project Properties in the Integration Development Environment (IDE), click the Resources tab.
  2. Under the Title ID option, specify the Resource variable name (App_Title) which corresponds to the actual text to be displayed (myApp) on the ribbon.
  3. If you want the A in myApp to be a hotkey, insert the unicode underscore character (\u0332) after the A. Therefore, in your resource package, instead of specifying myApp as the value for the variable App_Title, specify the following:

    myA\u0332pp

From stackoverflow
  • See this knowledge base article. Of course you have to avoid collisions with other applications.

    JR Lawhorne : Effin awesome! Also, be sure to do the same thing in all languages you might have defined. Different keys could be defined for different locales.

Which language is best for this editoral and op-ed aggregator project?

I'm looking for an aggregator for the editoral and op-ed pages of a bunch of English language newspapers I want to follow. The objective is to generate an HTML that is just a collection of editorial pieces from the dozen newspapers I want to follow internationally, so that I can print them off in the morning. Since this is a very narrow requirement, I couldn't find anything already available so I'm thinking of writing one on my own.

Now, I used to be a programmer for ~8 years in my previous life (and now have been swayed to the "Dark Side" that is Wall Street after my MBA). I'm not knowledgeable enough today about programming to make a good choice on a scripting language so am unsure which the best language for this would be (performance is not a key issue, libraries for parsing HTML, text handling as well as getting data off live web pages are more important).

PS: I don't mind learning a new language (previously I worked extensively with x86 ASM, C and Visual C++/MFC) almost exclusively in Win32 environments.

From stackoverflow
  • interpreted languages do well with code generation, you should think about Perl or Ruby

  • Use Python and the excellent lxml library for scraping HTML. It supports CSS selectors, which is a huge convenience, and it's rather fast. It handles broken HTML well too.

    Wahnfrieden : Make sure you look at the lxml.html module. The documentation can be a little confusing, so just try playing around with it in an interactive Python shell - that's how I learned to use it.

How can I use a wildcard in my .htaccess but only for 1 subdomain?

I add to httpd.conf:

ServerAlias *.domain.com

Now I want only 1 subdomain: h.domain.com to load hobbies.php

Which lines do I need to add into my .htaccess file to make this happen?

From stackoverflow
  • This should work, but I can't test it at the moment. Give it a shot.

    SetEnvIfNoCase Referer "^http://h.domain.com" allow_hobbies=1
    
    <FilesMatch "hobbies.php">
      Order Deny, Allow
      Allow from env=allow_hobbies 
    </FilesMatch>
    

    Note: You should probably not rely on this for security purposes, as there are ways around it (rather simple ones at that). The Referer header can be faked.

Rewrite only a specific file using MOD_REWRITE

I have a file that can be reached using multiple paths:

http://mydomain.com/portal1/movie.swf
http://mydomain.com/portal2/movie.swf
http://mydomain.com/portal1/substep/movie.swf
etc.

I want a rewrite rule to get this specific file from the following path:

http://mydomain.com/movie.swf

How can I do that?

From stackoverflow
  • in .htaccess in your main folder:

    RewriteRule ^portal.*movie\.swf$ /movie.swf [L]
    

    (backlash before the dot added after Gumbos comment. +1)

    Scharrels : I don't want to specify a rule for every possible path. Can I rewrite alle movie.swf's to /movie.swf using 1 rule?
    Scharrels : Never mind - your solution worked. I used RewriteRule ^.*/movie.swf$ /movie.swf [L]
    Gumbo : Don’t forget to escape the `.` character.

How can I monitor the number of outgoing WCF requests?

We're trying to track down some performance issues with an application and would like to figure out how many outgoing requests are being triggered by each page load. I can find lots of counters for showing incoming WCF connections, but nothing tracking how many are going out. Any ideas short of retrofitting all of the pages with custom counters?

From stackoverflow

What is the most efficient/secure way to authenticate a web service in ASP.NET?

Background:** We have an ASP.NET web app which exposes simple ASMX web services such as:

  1. string GetOrders(string userName,string password,DateTime orderDate) : Return an XML string of customer orders based on the user (customer).

  2. void UpdateOrders(string userName, string password, Guid orderGuid, string orderXml) : Update an order's data (from the XML Payload) based on the order's GUID.

Example:

WebServiceClient proxy = new WebServiceClient();
string xmlData = proxy.GetOrders("james","password",DateTime.Today);

My question is:

  1. ALthough we use HTTPS: is this method actually save?
  2. What will be a better alternative in ASP.NET?
From stackoverflow
    1. The transmission of the credentials is safe since the connection and between the client and the server is encrypted. However, the content of the connection is not safe. If the SSL certificate were to break, or if somebody were to decrypt that traffic stream, the user name and password would essentially be in clear text.

    How safe this is for you depends on the nature of the data and what is acceptable to you.

    1. As an alternative, update the services to use WCF (Windows Communication Foundation). It has a far more robust set of ways to deal with authenticated and authorized communication for web services.
  • Here is a similar thread covering some of these issues.

    In general, even with a SSL connection, don't send passwords in clear text. A challenge response is a good way to secure your password, this is what many banks do as well. Basically send the user a timestamp or something similar that would vary depending on when you call the service. Then have the user respond with a hash of his password + the timestamp, this way even if the password hash is intercepted it cannot be used to access your service, since next time it is called the hash would need to be different.

Visual Studio Setup Project failing to add keys to registry

Hello, I'm creating a setup pacakage in Visual Studio 2008 to register a COM component and one of the actions is to add a few keys to the registry.

The odd thing about it is when I run the installer it creates the key hierarchy correctly but the last key in the hierarchy it creates has the wrong GUID... whereas its right in the installer... has anyone run into this or have any suggestions on what is going wrong?

Thanks

From stackoverflow

Why does MarshalByRefObject.InitializeLifetimeService return an object and not an ILease?

I am reading through the msdn docs for .NET Remoting and noticed that the MarshalByRefObject.InitializeLifetimeService method returns an object instead of an ILease. The documentation says that the method returns an object of type ILease and all code examples I have found casts the returned value to an ILease. But the methods signature says that it returns an object. Does anybody know why?

I'm just curious... :-)

From stackoverflow
  • Odd. Reflector shows that all the method does is:

    return LifetimeServices.GetLeaseInitial(this);
    

    which does return an ILease. So it's probably just an oversight in the library (that has to be propogated forward for compatibility issues), especially if the documentation also claims it's an ILease

Use Javascript to Load Flash SWF file automatically after other SWF finishes playing?

I basically have a series of small SWF Files. I have used SWFObject to play them, but how do I get a series of SWF videos to play sequentially even though they are separate SWF files?

From stackoverflow
  • You can listen for the enterFrame event, loading the next SWF file when the currentFrame reaches currentScene.numFrames/2 and start playing the next SWF when it reaches currentScene.numFrames-1.

    Dkong : are these events available via some sort of javascript api?

Making an element "fixed" if it's being scrolled out

So, I have an element on a webpage that is located under some other elements. This element should, whenever it hits the top of the page be fixed (ie. it shouldn't leave the view.)

I've seen this being done on the Webkit Inspector in the resources tab.

Does anyone know how to replicate this feature/effect?

From stackoverflow
  • I think that the behavior you want is similar to the desired on this question, check this example.

    henrikh : Thanks, that answered the question.

How to handle parents browser windows page features from child windows close in JS

I open a page in browser. There is a link where I click, its fade the page, by putting a layer in the Z-index. At the mean time another Pop up window is also open. When I close the pop up window, the browser remain still faded. I can’t disable the z-index layer that I put in the parents window. Enter code is done in Java Script.

From stackoverflow
  • I believe want you want to do is something like this. On your parent window/page:

    var fadeIn = function fadeIn() {
        // Code to remove added layer
    };
    

    And on your child/popup window/page:

    window.onunload = function () {
        window.opener.fadeIn();
    }
    
  • Any JavaScript that resides in the parent page can be called by the child. In your child popup your "close' button click event should have an event similar to this:

    function closePopup()
    { 
        parent.FadeOut();  // Where fadeOut() is a JS function on the parent page
    }
    
    
    //In the Parent Page
    function fadeOut()
    {
       document.getElementById('myLayer').zindex = 0; //Or similar 
    }
    
    PortageMonkey : Was this what you were looking for in terms of a workable solution?

Given a list of words - what would be a good algorithm for word completion in java? Tradeoffs: Speed/efficiency/memory footprint

I'm exploring the hardware/software requirements (ultimate goal is mobile Java app) for a potential free/paid application.

The application will start with this simple goal: Given a list of relevant words in a database, to be able to do word completion on a single string input.

In other words I already know the contents of the database - but the memory footprint/speed/search efficiency of the algorithm will determine the amount of data supported.

I have been starting at the beginning with suffix-based tree searches, but am wondering if anyone has experience with the speed/memory size tradeoffs of this simple approach vs. the more complex ones being talked about in the conferences.

Honestly the initial application only has probably less than 500 words in context so it might not matter, but ultimately the application could expand to tens of thousands or hundreds of thousands of record - thus the question about speed vs. memory footprint.

I suppose I could start with something simple and switch over later, but I hope to understand the tradeoff earlier!

From stackoverflow
  • Word completion suggests that you want to find all the words that start with a given prefix.

    Tries are good for this, and particularly good if you're adding or removing elements - other nodes do not need to be reallocated.

    If the dictionary is fairly static, and retrieval is important, consider a far simpler data structure: put your words in an ordered vector! You can do binary-search to discover a candidate starting with the correct prefix, and a linear search each side of it to discover all other candidates.

UberCart: service products and accommodation?

What is the best way to deal with "service" products. For example, let's say I'm a painter and wish to advertise these services on a site that also sells paint brushes and paint. Now, the paint brushes and paint I can easily set up as products that are sold for X and Y amount. But when creating a product called "Painting your house", it doesn't make sense to give it a price, or a quantity etc.

In other words, I need a way to generically define a "service node" so that clients can "place orders" but in actual fact, it will just send a notification to me, saying that user so and so is interested in letting me do his paint job.

I can of course, just create a node type called "service" and this could in actual fact just have all the fields on it. But what would be ideal is to have it hook into UberCart.

Also, I was wondering what is the best way to go about setting up an "accommodation" field. I.e. Instead of a product, people can book "rooms" or basically request a quotation on a night in a hotel (as prices change).

So far the only solution I have for this whole scenario is to:

  1. Let ubercart manage products (paint brushes)
  2. Create a node for "services"
  3. Find some other module or simply also create a node for "accomodation".
  4. Mimic (2) and (3) to provide a similar checkout process as UberCart

Can anybody suggest a better way that i can instead use UberCart to cater for (2) and (3)?

From stackoverflow
  • They aren't complete solutions, but two modules come to mind on this:

    The Signup integration for Ubercart module allows you to sell signups on a node and has the users fill in profile fields during checkout (like, name, e-mail etc.). This could be helpful particularly for selling the hotel rooms.

    The UC Node Checkout module is great for selling non-products that are kinda like products where you want to gather more information. There is a great Drupal Easy tutorial about it.

    greggles : Does anything seem insufficient about this answer?

What does the runtime do with XAML namespaces?

In every XAML document, there are one or more namespace declarations. ie:

<Window x:Class="WindowsApplication1.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Window1 Height="300">

The declarations are in the form of a URL, leading me to ask: Does the runtime actually retrieve information from those URLs when the application loads? What happens if no Internet connection is present?

From stackoverflow
  • This is just a standqard xml namespace and nothing special to do with XAML at all. It is really just a unique identifier for this particular xml; no data is retrieved from this url and, in fact, it doesn't even need to be a url.

    See this previous post for an explanation of what a namespace is in xml, and why the actual namespace text itself is of no real consequence.

  • No. The runtime does not dereference the URIs, they are just used as readable globally unique identifiers. The fact that they use an http protocol at all is just a convention. They follow the XML Namespace standard from W3C.

    The URIs refer to the URIs defined using the XmlnsDefinitionAttribute defintions in the WPF assemblies. The XAML reader uses these attributes to group CLR namespaces from those assemblies together into a combined XML namespace.

How can I access my View elements via x:Name from my Presenter?

My presenter defines its own view:

public SmartFormPresenter(SmartFormView view)
{
    View = view;
    View.DataContext = this;
}

In the view I have an element with x:Name="MainTabControl":

<DockPanel LastChildFill="True">
    <TabControl x:Name="MainTabControl" DockPanel.Dock="Top" ItemsSource="{Binding SmartFormAreaPresenters}">
        <TabControl.ItemContainerStyle>
            <Style TargetType="{x:Type TabItem}">
                <Setter Property="Header" Value="{Binding Title}"/>
            </Style>...

How can I access this element as I do in code behind, something like this:

PSEUDO-CODE:

View.Root.Children.MainTabControl.Visibility = Visibility.Collapsed;
From stackoverflow
  • Found it:

    TabControl mainTabControl = View.FindName("MainTabControl") as TabControl;
    mainTabControl.Visibility = Visibility.Hidden;
    
  • You can define a public property in your view that will expose the private field. Or better, don't do it and define some abstract property in your view, like "IsViewTabbed" or sth like this, that will abstract UI code out of presenter.

    Edward Tanguay : If I were doing an MVVM pattern I would *have* to abstract out a property. I understand that this is an advantage to having a Presenter instead of a ViewModel: that the Presenter intimately knows its View so you have the ability to reach in and change things manually if needed.

Integrating Haskell in non-functional projects

I have looking to Haskell questions in SO, and I recovering my university notes on funtional programming as a hobby. But I've always wondered how could something done in Haskell get outside Hugs interpreter and integrate with a C#, C++ or Java project. Has anybody done that? How?

From stackoverflow
  • Well, first of all, Haskell compiles to machine code, so you don't have to worry about the interpreter bit.

    As far as integrating with other languages, your best bet is the Foreign Function Interface.

    yeyeyerman : That's was exactly what I was looking for. Thanks.
    Harold L : Haskell compiles to machine code via more sophisticated compilers like GHC.
  • For integrating with .NET projects, there is also http://haskell.forkio.com/dotnet/

  • Python has a subset which is pretty much a functional language.

    Adam Byrtek : There are some functional features in Python, but it is definitely *not* a functional language.
  • To integrate with other code, you need to use the FFI (as was already said). Usually, you would use GHC (the Glasgow Haskell Compiler) and compile to machine code, rather than use an interpreter like Hugs. (Most "real" projects use GHC instead of Hugs.)

Regular expression for file path which doesn't allow parent directories

I'm looking to write a regex for a file path that must start with some prefix. In this case it should start with '/tank/home/'. I also want to make sure that it contains no '/..' -- no jumping up to parent directories.

I spent a while fiddling around without coming up with anything quite right. I settled on using two regexes, the first which must match and the second which must not match:

'^/tank/home/'

'/\.\.(/.*)?$'

Does this do what I think it does? Is there an easier way?

This is in a bash script, for what it's worth.

From stackoverflow
  • You could use a negative lookahead to make sure that there aren't any /.. in the string:

    ^(?!.*/\.\..*)/tank/home.*$
    
    alberge : Very close, but not quite right. That doesn't match "/tank/home/..foo".
    Amber : If it's really necessary that you be able to match ..foo, then something like this should probably work: `^(?!.*/\.\.(?:/.*|$))/tank/home.*$`
    Amber : (Basically make the look-ahead only match if it's /../ or /.. at the end of the string.)
    alberge : Thanks -- I hadn't used negative lookahead before.
  • You could use negative lookbehind too:

    \/tank\/home\/([^\/]|?(<!\/..)\/)+$

  • You can expand Dav's regex to include an extra trailing slash:

    ^(?!.*/\.\./.*)/tank/home.*$
    

    But... a better option might be to make sure that the result of the path is something that starts under /tank/home:

    FILEPATH=$(readlink -f $YOURFILE)
    [[ $FILEPATH =~ ^/tank/home/ ]] && echo "starts with /tank/home/"
    
    alberge : Aha. I was wondering if there was something that did that.
  • '^/tank/home(?!.*/\.\.(/|$))/'
    

    matches /tank/home/foo..bar but not /tank/home/.. or /tank/home/foo/../bar

What's the most efficient way to convert several win forms in VB2008 to a tabbed form?

I have developed an application inside ESRI ArcMAP that uses several forms that are raised by buttons on a toolbar. I'd like to convert these forms to a set of tabs on a single form. Is there a way to bind the forms to individual tabs or do I have to just recreate the form as controls on each tab?

From stackoverflow
  • Recreate each form as a UserControl. You should be able to mostly just copy and paste the controls and code. Once you get to that point you can easily stick each UserControl on its own tab.

How to solve problem with out of synchronization of J2EE module dependency in Eclipse?

I have two projects : my-lib and my-web.

my-lib is built using the Java compiler of Eclipse, and a short Ant task is run on some properties files, which are then modified (as explained here). This is not a pretty solution, but it works.

Now, as my-web is dependent of my-lib, I define my-lib as a Java EE Module Dependency of my-web. However, when I attach my-web to the Tomcat in Eclipse, and try to publish, I get the following exception:

'Publishing to Tomcat at localhost' has encountered a problem.
Resource is out of sync with the file system: '/my-lib/target/classes/my-app.properties'

This file is indeed one of the files modified by the Ant task.

How can I correct this problem, as I need to have the Ant task run on the my-lib.

From stackoverflow
  • If you have the Ant task run as an external builder or external task, you can configure it to refresh the project, workspace, or selected resources after execution. When specifying the task/builder click on the Refresh tab and pick the appropriate one for your needs.

    There's more information in the eclipse help.

how to create multiple objects and enumerate them in c#

my problem is as follows:

Im building a console application which asks the user for the numbers of objects it should create and 4 variables that have to be assigned for every object. The new objects name should contain a counting number starting from 1.

How would you solve this? Im thinking about a class but im unsure about how to create the objects in runtime from userinput. Is a loop the best way to go?

What kind of class, struct, list, array .... would you recommend. The variables in the object are always the same type but i need to name them properly so I can effectivly write methods to perform operations on them in a later phase of the program.

Im just learning the language and I would be very thankful for a advice on how to approach my problem.

From stackoverflow
  • Use a list or an array. List example:

    int numberOfObjects = 3;
    List<YourType> listOfObjects = new List<YourType>();
    for(int i = 0 ; i < numberOfObjects ; i++ ) 
    {
        // Get input and create object ....
        // Then add to your list
        listOfObjects.Add(element);
    }
    

    Here, listOfObjects is a Generic list that can contain a variable number of objects of the type YourType. The list will automatically resize so it can hold the number of objects you add to it. Hope this helps.

    annakata : Actually sound more like a `Dictionary` (for a custom class foo) with the "name" requirement.
    Thorarin : I'm not sure if that is an actual requirement, or just because he needs to get more confortable with the concept of arrays.
  • Why not just write the methods to use the index of the array? Or if you need some form of key/value type of functionality. You could use a dictionary class and have your method check for the key of the value you passed to it.

    A dictionary is similar to an array.

  • If I understood what you are asking you could probably do something like this:

    class Foo 
    {
       private static int count;
       public string name;
       public Foo(...){
         name = ++count + "";
       }
    }
    
    Thorarin : I've thought about that, but I thought it better to discourage such a pattern at this point. If you wanted to make absolutely sure no object has the same number / name, you could enforce it like this. Then again, you should probably add a `volatile` to your static variable in that case.
  • I'm guessing what you're trying to do here, but this is a stab in the dark. The problem I'm having is dealing with the whole "the new objects name should contain a counting number starting from 1" thing. Anyway, here's my attempt:

    public class UserInstantiatedClass
    {
       public int UserSetField1;
       public int UserSetField2;
       public int UserSetField3;
       public int UserSetField4;
       public string UserSpecifiedClassName;
    }
    
    public static class MyProgram
    {
       public static void Main(string [] args) 
       {
          // gather user input, place into variables named 
          // numInstances, className, field1, field2, field3, field4
          List<UserInstantiatedClass> instances = new List< UserInstantiatedClass>();
          UserInstantiatedClass current = null;
          for(int i=1; i<=numInstances; i++)
          {
             current = new UserInstantiatedClass();
             current.UserSpecifiedClassName = className + i.ToString(); // adds the number 1, 2, 3, etc. to the class name specified
             current.UserSetField1 = field1;
             current.UserSetField2 = field2;
             current.UserSetField3 = field3;
             current.UserSetField4 = field4;
             instances.Add(current);
          }
          // after this loop, the instances list contains the number of instances of the class UserInstantiatedClass specified by the numInstances variable.  
       }
    }
    
  • If I understand your problem correctly:

    class MyClass
    {
        public int ObjectNumber { get; set; }
        public string SomeVariable { get; set; }
        public string AnotherVariable { get; set; }
    }
    
    // You should use keyboard input value for this 
    int objectsToCreate = 10;
    
    // Create an array to hold all your objects
    MyClass[] myObjects = new MyClass[objectsToCreate];
    
    for (int i = 0; i < objectsToCreate; i++)
    {
        // Instantiate a new object, set it's number and
        // some other properties
        myObjects[i] = new MyClass()
        {
            ObjectNumber = i + 1,
            SomeVariable = "SomeValue",
            AnotherVariable = "AnotherValue"
        };
    }
    

    This doesn't quite do what you described. Add in keyboard input and stuff :) Most of this code needs to be in some kind of Main method to actually run, etc.

    In this case, I've chosen a class to hold your 4 variables. I have only implemented 3 though, and I've implemented them as properties, rather than fields. I'm not sure this is necessary for your assignment, but it is generally a good habit to not have publically accessible fields, and I don't want to be the one to teach you bad habits. See auto-implemented properties.

    You mentioned a struct, which would be an option as well, depending on what you want to store in it. Generally though, a class would be a safer bet.

    A loop would indeed be the way to go to initialize your objects. In this case, a for loop is most practical. It starts counting at 0, because we're putting the objects in an array, and array indexes in C# always start at 0. This means you have to use i + 1 to assign to the object number, or the objects would be numbered 0 - 9, just like their indexes in the array.

    I'm initializing the objects using object initializer syntax, which is new in C# 3.0. The old fashioned way would be to assign them one by one:

    myObjects[i] = new MyClass();
    myObjects[i].ObjectNumber = i + 1;
    myObjects[i].SomeVariable = "SomeValue";
    

    Alternatively, you could define a constructor for MyClass that takes 3 parameters.

    One last thing: some people here posted answers which use a generic List (List<MyClass>) instead of an array. This will work fine, but in my example I chose to use the most basic form you could use. A List does not have a fixed size, unlike an array (notice how I initialized the array). Lists are great if you want to add more items later, or if you have no idea beforehand how many items you will need to store. However, in this case, we have the keyboard input, so we know exactly how many items we'll have. Thus: array. It will implicitly tell whoever is reading your code, that you do not intend to add more items later.

    I hope this answered some questions, and raised some new ones. See just how deep the rabbit hole goes :P

fork in multi-threaded program

I've heard that mixing forking and threading in a program could be very problematic, often resulting with mysterious behavior, especially when dealing with shared resources, such as locks, pipes, file descriptors. But I never fully understand what exactly the dangers are and when those could happen. It would be great if someone with expertise in this area could explain a bit more in detail what pitfalls are and what needs to be care when programming in a such environment.

For example, if I want to write a server that collects data from various different resources, one solution I've thought is to have the server spawns a set of threads, each popen to call out another program to do the actual work, open pipes to get the data back from the child. Each of these threads responses for its own work, no data interexchange in b/w them, and when the data is collected, the main thread has a queue and these worker threads will just put the result in the queue. What could go wrong with this solution?

Please do not narrow your answer by just "answering" my example scenario. Any suggestions, alternative solutions, or experiences that are not related to the example but helpful to provide a clean design would be great! Thanks!

From stackoverflow
  • It is really quite simple. The problems with multiple threads and processes always arise from shared data. If there is not shared data then there can be no possible issues arising.

    In your example the shared data is the queue owned by the main thread - any potential contention or race conditions will arise here. Typical methods for "solving" these issues involve locking schemes - a worker thread will lock the queue before inserting any data, and the main thread will lock the queue before removing it.

    bdonlan : Does the malloc metadata count as "shared data"? :)
    1800 INFORMATION : I dunno - it could but normally your standard libraries are written in such a way as to be thread safe (sometimes you have to select thread safe versions of them). It depends on what your definition of shared data is and what the impact is.
    jimx : often, we can't avoid to have shared data. like pipes, file descriptors, etc. They always are shared across fork. Now under linux, one may set O_CLOEXEC flag so a fd can be closed when forking, (I guess what that mean is close the fd on the child's address space), though I don't know if that would help if we add threads in? e.g. what if I open pipes in one thread and fork? what if another thread also does fork? which child will be able to see the pipe?
    NVRAM : @bdonlan - no, *malloc()* only utilizes process memory. @jimx - threads within a process share FD, and while I didn't know O_CLOEXEC - the effects are the same regardless of which thread calls fork().
  • The problem with forking when you do have some threads running is that the fork only copies the CPU state of the one thread that called it. It's as if all of the other threads just died, instantly, wherever they may be.

    The result of this is locks aren't released, and shared data (such as the malloc heap) may be corrupted.

    pthread does offer a pthread_atfork function - in theory, you could take every lock in the program before forking, release them after, and maybe make it out alive - but it's risky, because you could always miss one. And, of course, the stacks of the other threads won't be freed.

    jimx : Can you elaborate a little bit what does it mean by 'locks aren't released'? From the child perspective right? So the child can never acquire a lock?
    bdonlan : Correct. The fork clones all locks while they're still in the locked state.