instruction
stringlengths
0
30k
|c#|java|python|openid|
|web-application|openid|
|web-applications|openid|
How to hide the cancel button on an ASP.NET ChangePassword control
|asp.net|webform|
I'm considering using the ChangePassword control on an ASP.NET 2.0 Webform. I don't want the 'cancel' button to show. Is there a good way to hide it without resorting to silly "width = 0" sort of games? Or perhaps there's a generic way to walk through the parts of a composite control like this and hide individual parts?
|asp.net|webforms|
How do you update your web application on the server?
@Peter Hoffmann Using generator expressions has the benefit of also producing an iterator but saves importing itertools. Furthermore, list comprehensions are generally preferred to map, thus, I'd expect generator expressions to be preferred to imap. >>> l = [1, "foo", 4 ,"bar"] >>> ",".join(str(bit) for bit in l) '1,foo,4,bar'
I don't think that you can using pure LINQ. However, if you're doing this sort of thing a lot in your code you may be able to make this work with reflection.
I've been on some of the jQuery mailing lists and from what I've read there, they most likely filter by tag name then class name (or vice versa if it was faster). They are obsessive about speed and would use anything to gain a smidgen of performance. I really wouldn't worry about it too much anyway unless you are running that selector thousands of times/sec. If you are really concerned, try doing some benchmarking and see which is faster.
This works in IE (and FF, I believe): if(document.getElementById("uploadBox").value != "") { // you have a file }
> * I must have a reasonnable number of possible combinations (let's say 1M) > * The code must be as short as possible, to avoid errors from the user Well, if you want it to have at least one million combinations, then you need at least six digits. Is that short enough?
If you can use Javascript, there are several options: navigator.appName navigator.appVersion [link][1] Or something more robust by using a library such as [jQuery][2]. Finally, you could use the [BrowserDetect][3] object from QuirksMode. Once you have the browser name and version, you can then insert HTML to link to a style sheet or include other tags. [1]: http://www.w3schools.com/js/js_browser.asp [2]: http://docs.jquery.com/Utilities/jQuery.browser [3]: http://www.quirksmode.org/js/detect.html
At the end of the day, a single alphanumeric character has at least 36 possible values. If you include punctuation, lower case, etc then you can easily pass 72 possible values. A non-colliding number that allows you to quickly compare strings would necessarily grow exponentially with the length of the string. So you *first* must decide on the longest string you are expecting to compare. Assuming it's N characters in length, and assuming you ONLY need uppercase letters and the numerals 0-9 then you need to have an integer representation that can be as high as 36^N For a string of length 25 (common name field) then you end up needing a binary number with 130 bits. If you compose that into 32 bit numbers, you'll need 4. Then you can compare each number (four integer compares should take no time, compared to walking the string). I would recommend a big number library, but for this specialized case I'm pretty sure you can write your own and get better performance. If you want to handle 72 possible values per character (uppercase, lowercase, numerals, punctuation...) and you need 10 characters, then you'll need 62 bits - two 32 bit integers (or one 64 bit if you're on a system that supports 64 bit computing) If, however, you are not able to restrict the numbers in the string (ie, could be any of the 256 letters/numbers/characters/etc) and you can't define the size of the string, then comparing the strings directly is the only way to go, but there's a shortcut. Cast the pointer of the string to a 32 bit unsigned integer array, and compare the string 4 bytes at a time (or 64 bits/8bytes at a time on a 64 bit processor). This means that a 100 character string only requires 25 compares maximum to find which is greater. You may need to re-define the character set (and convert the strings) so that the characters with higher precedence are assigned values closer to 0, and lower precedence values closer to 255 (or vice versa, depending on how you are comparing them). Good luck! -Adam
The main argument agaisnt building a pre-rocessor for C# is integration in Visual Studio: it would take a lot of efforts (if at all possible) to get intellisense and the new background compiling to work seamlessly. Alternatives are to use a Visual Studio productivity plugin like [ReSharper][1] or [CodeRush][2]. The latter has -to the best of my knowledge- an unmatched templating system and comes with an excellent [refactoring][3] tool. Another thing that could be helpful in solving the exact types of problems you are referring to is an AOP framework like [PostSharp][4]. You can then use custom attributes to add common functionality. [1]: http://www.jetbrains.com/resharper/ [2]: http://devexpress.com/Products/Visual_Studio_Add-in/Coding_Assistance/ [3]: http://devexpress.com/Products/Visual_Studio_Add-in/Refactoring/ [4]: http://www.postsharp.org/
I know that **Automator** in Mac OS X is not a shell but it is the best graphical tool I have ever used to do batch tasks. I think it is worth mentioning here as even I (self-titled as a power user) use it from time to time to rename files or other routines. Although these could be done in a few lines of shell script, the **Automator**'s graphical interface makes me feel like I am not working and it just works.
@Matt Hamilton Your answer works with the example above but would not work if the data set was 100, 75, 75, 50, 50 (where it would return only 3 rows). TOP WITH TIES only includes the ties of the last row returned...
**JavaScript** Using anonymous functions: var f = function(n){ if(n>1){ return arguments.callee(n-1)*n; } return 1; }
I used to use git push to publish to my web server but lately I've just been using rsync. I try to make my site as agnostic about where it's running as possible (using relative paths, etc) and so far it's worked pretty well. The only challenge is keeping databases in sync, and for that I usually use the production database as the master and make regular backups and imports into my testing database.
Crucible got it (assuming SQL 2005 is an option).
unit testing dynamic fixtures in CakePHP
|unit-testing|cakephp|fixture|
> If you are not familiar with the CakePHP framework, you can maybe still help me. CakePHP uses [SimpleTest][1] In the cakephp framework i am building tests for a behavior that is configured by adding fields to the table. This is intended to work in the same way that adding the "created" and "modified" fields will auto-populate these fields on save. To test this I *could* create dozens of fixtures/model combos to test the different setups, but it would be a hundred times better, faster and easier to just have the fixture change "shape" between test methods. Do you know how to do this? [1]: http://simletest.org
unit testing of dynamic fixtures
Is it possible to have a fixture change between test methods? If so, how can I do this? My syntax for this problem : In the cakephp framework i am building tests for a behavior that is configured by adding fields to the table. This is intended to work in the same way that adding the "created" and "modified" fields will auto-populate these fields on save. To test this I *could* create dozens of fixtures/model combos to test the different setups, but it would be a hundred times better, faster and easier to just have the fixture change "shape" between test methods. > If you are not familiar with the [CakePHP framework][1], you can maybe still help me as it uses [SimpleTest][2] *Edit: rephrased question to be more general* [1]: http://cakephp.org [2]: http://simletest.org
Is there any reason not to just use [Google Analytics][1]? It's free, and you don't have to write it yourself. I use it, and it gives you a lot of information. Sorry, I know it's not a "programming" answer ;) [1]: http://www.google.com/analytics/
The best practice is to use a finaliser in your class and always use `using` blocks. There isn't really a direct equivalent though, finalisers look like C destructors, but behave differently. You're supposed to nest `using` blocks, that's why the C# code layout defaults to putting them on the same line... using (SqlConnection con = new SqlConnection("DB con str") ) using (SqlCommand com = new SqlCommand( con, "sql query") ) { //now code is indented one level //technically we're nested twice } When you're not using `using` you can just do what it does under the hood anyway: PleaseDisposeMe a; try { a = new PleaseDisposeMe(); throw new Exception(); } catch (Exception ex) { Log(ex); } finally { //this always executes, even with the exception a.Dispose(); } With managed code C# is very very good at looking after its own memory, even when stuff is poorly disposed. If you're dealing with unmanaged resources a lot it's not so strong.
What I like to do is have a number of tables that represent the raw data, so in this case you'd have Items (ID pk, Name, <properties>) Tags (ID pk, Name) TagItems (TagID fk, ItemID fk) This works fast for the write times, and keeps everything normalized, but you may also note that for each tag, you'll need to join tables twice for every further tag you want to AND, so it's got slow read. A solution to improve read is to create a caching table on command by setting up a stored procedure that essentially creates new table that represents the data in a flattened format... CachedTagItems(ID, Name, <properties>, tag1, tag2, ... tagN) Then you can consider how often the Tagged Item table needs to be kept up to date, if it's on every insert, then call the stored procedure in a cursor insert event. If it's an hourly task, then set up an hourly job to run it. Now to get really clever in data retrieval, you'll want to create a stored procedure to get data from the tags. Rather than using nested queries in a massive case statement, you want to pass in a single parameter containing a list of tags you want to select from the database, and return a record set of Items. This would be best in binary format, using bitwise operators. In binary format, it is easy to explain. Let's say there are four tags to be assigned to an item, in binary we could represent that 0000 If all four tags are assigned to an object, the object would look like this... 1111 If just the first two... 1100 Then it's just a case of finding the binary values with the 1s and zeros in the column you want. Using SQL Server's Bitwise operators, you can check that there is a 1 in the first of the columns using very simple queries. Check this link to find out [more](http://cas.sdss.org/dr6/en/help/docs/sql_help.asp).
I second the answer of Jonathan: this is a log analyzer, meaning that you must feed it as input the logfile of the webserver and it generates a summarization of it. Given that you are on a shared host, it is improbable that you can access to that file, and even if you would access it, it is probable that it contains then entries for *all* the websites hosted on the given machine (setting up separate logging for each VirtualHost is certainly possible with Apache, but I don't know if it is a common practice). One possible workaround would be for you to write out a logfile from your pages. However this is rather difficult and can have a severe performance impact (you have to serialize the writes to the logfile for one, if you don't want to get garbage from time to time). All in all, I would suggest going with an online analytics service, like Google Analytics.
Is there a way I can have a VM gain access to my computer?
|vm|
I would like to have a VM to look at how applications appear and to develop OS-specific applications, however, I want to keep all my code on my Windows machine so if I decide to nuke a VM or anything like that, it's all still there. If it matters, I'm using VirtualBox.
Your NAME variable is being substituted like this: printf "Hello, %s\n" George W. Bush Use this: `#! /bin/sh NAME="George W. Bush" printf "Hello, %s\n" "$NAME"`
Your NAME variable is being substituted like this: printf "Hello, %s\n" George W. Bush Use this: #! /bin/sh NAME="George W. Bush" printf "Hello, %s\n" "$NAME"
There is no doubt that **filtering by tag name first is much faster** than filtering by classname. This will be the case until all browsers implement getElementsByClassName natively, as is the case with getElementsByTagName.
If you're trying to test existing code that you're reluctant or unable to change, reflection is a good choice. If the class's design is still flexible and you've got a complicated private method that you'd like to test separately, I suggest you pull it out into a separate class and test that class separately. This doesn't have to change the public interface of the original class, it can internally create an instance of the helper class and call the helper method. If you want to test difficult error conditions coming from the helper method, you can go a step further. Extract an interface from the helper class, add a public getter and setter to the original class to inject the helper class (used through its interface), and then inject a mock version of the helper class into the original class to test how the original class responds to exceptions from the helper. This approach is also helpful if you want to test the original class without also testing the helper class.
You should always be able make a normal network connection between the VM and the hosting OS, as though it were another computer on the same network. Which, in some sense, it is.
This is usually handled with network shares. Share your code folder from your host machine and access it from the VMs.
When you are creating the verification code, do you have access to the caller's phone number? If so I would use the caller's phone number and run it through some sort of hashing function so that you can guarantee that the verification code you gave to the caller in step 1 is the same one that they are entering in step 2 (to make sure they aren't using a friend's validation code or they simply made a very lucky guess). About the hashing, I'm not sure if it's possible to take a 10 digit number and come out with a hash result that would be < 10 digits (I guess you'd have to live with a certain amount of collision) but I think this would help ensure the user is who they say they are. Of course this won't work if the phone number used in step 1 is different than the one they are calling from in step 2.
Sounds like the controls aren't being databound properly after the postback. Are you databinding the first dropdown in the page or in the codebehind? If codebehind, are you doing it in on_init or on_load every time? There might be an issue of the SelectedValue of the second drop down being set to a non-existent item after the postback.
`wcstombs` doesn't get the size of the destination, so it can, in theory, buffer overflow. And why are you using `sprintf` with what I assume are constants? Just use: `EZMPPOST" " EZMPTAG "/" EZMPVER " " TYPETXT EOL` C and C++ combines string literal declarations into a single string. MSN
It's still a technology worth using. There are lots of Windows Forms and unmanaged apps around that use GDI+ that either won't be upgraded, or that will be upgraded, but that don't need more advanced rendering capabilities. GDI+ is a good bolt-on solution for older applications, and for new applications written in Windows Forsm. That's the primary reason GDI+ wasn't axed in Vista in favour of a totally DirectX solution. There's not specifically anything wrong with GDI/GDI+. True, it's not as advanced as Aero et al, but that doesn't always matter. Particularly in LOB applications (in companies that probably don't even have machines capable of running Vista - mine certainly doesn't), GDI+ is an extremely important technology. The fact that it's not supported (for drawing, at least... you CAN still use it for image manipulation) in ASP.NET is a red herring, since other drawing technologies are not supported for web applications either (plugin-based "applications" notwithstanding).
The difference between loops
|php|loops|
It's about PHP but I've no doubt many of the same comments will apply to other languages. Simply put, what are the differences in the different types of loop for PHP? Is one faster/better than the others or should I simply put in the most readable loop? for ($i = 0; $i < 10; $i++) { # code... } foreach ($array as $index => $value) { # code... } do { # code... } while ($flag == false);
Eric Z Beard: > I do store all dates in GMT. Here's the use case: something happened at 11:00 PM EST on the 1st, which is the 2nd GMT. I want to see activity for the 1st, and I am in EST so I will want to see the 11PM activity. If I just compared raw GMT datetimes, I would miss things. Each row in the report can represent an activity from a different time zone. Right, but when you say you're interested in activity for Jan 1st 2008 EST: SELECT @activityDateMidnight = '1/1/2008', @activityDateTZ = 'EST' you just need to convert *that* to GMT (I'm ignoring the complication of querying for the day before EST goes to EDT, or vice versa): Table: TimeZone Fields: TimeZone, Offset Values: EST, -4 --Multiply by -1, since we're converting EST to GMT. --Offsets are to go from GMT to EST. SELECT @activityGmtBegin = DATEADD(hh, Offset * -1, @activityDateMidnight) FROM TimeZone WHERE TimeZone = @activityDateTZ which should give you '1/1/2008 4:00 AM'. Then, you can just search in GMT: SELECT * FROM EventTable WHERE EventTime >= @activityGmtBegin --1/1/2008 4:00 AM AND EventTime < (@activityGmtBegin + 1) --1/2/2008 4:00 AM The event in question is stored with a GMT EventTime of 1/2/2008 3:00 AM. You don't even need the TimeZone in the EventTable (for this purpose, at least). Since EventTime is not in a function, this is a straight index scan - which should be pretty efficient. Make EventTime your clustered index, and it'll fly. ;) Personally, I'd have the app convert the search time into GMT before running the query.
title in command prompt window
|c|winapi|
how can i change the command prompt window every time I execute a dos-based program by double clicking it, in c language. should i used windows API? thanks
How to change the Title of the command prompt window
How can I change the title of the command prompt window every time I execute a dos-based program by double clicking it, in c language. should I used windows API?
How can I change the title of the command prompt window every time I execute a dos-based program by double clicking it, in c language. Should I use the Windows API?
If you open the .aspx file and switch between design view and html view and back it will prompt VS to check the controls and add any that are missing to the designer file. Also, according to [this blog][1], you can try to right click on the as(c/p)x and select "Convert to Web Application". When this is done you should see that you now have a *.Designer.cs file available and your controls within the Design HTML will be available for your control. PS: This should not be done in debug mode, as not everything is "recompiled" when debugging. ![alt text][2] [1]: http://blog.bdapps.com/2008/07/15/RestoreDesignercsFilesInVisualStudio.aspx [2]: http://blog.bdapps.com/content/binary/ConvertToWebApp.JPG
(The following comes from experience with VS2005.) If you edit an ASPX page while debugging, then the codebehind doesn't get updated with the new classes. So, you have to stop debugging, trivially edit the ASPX page (like add a button or something), then click Design View, then delete the button. Then, your designer files should be updated. If you are having a different issue with VS2008, then I can't help.
ASP.NET and sending SMS/making phone calls
|c#|asp.net|sms|
I have a scenario where I need to make call a telephone(landline/mobile) or send SMS to a particular set of users only using ASP.NET and C#. The web application is not a mobile application. How do I go about doing these? What typically would be the hardware requirements? I would be **extremely grateful** if you could provide me with pointers and reference websites.
I have a scenario where I need to make a call to a telephone(landline/mobile) or send SMS to a particular set of users only using ASP.NET and C#. The web application is not a mobile application. How do I go about doing these? What typically would be the hardware requirements? I would be **extremely grateful** if you could provide me with pointers and reference websites.
Well I found a solution that works, though I don't really like it. I had to delete the .designer.cs file then recreate and empty file with the same name. When I went back in and saved the aspx file again, the designer file was re-generated. Dodgy!
How do I implement a pre-commit hook script in SVN that calls dos2unix to validate checked-in file
|python|svn|dos2unix|
I was wondering if anyone here had some experience writing this type of script and if they could give me some pointers. Thanks.
Related to high availability: OpenBSD can be configured in a failover / HA way for firewalls. See [this description][1]. I've heard that they've done demos where such setups done as well (if not better) as high-end Cisco gear. [1]: http://www.countersiege.com/doc/pfsync-carp/
Well, it seems I cannot do that. What I should be doing is [subclassing NSAnimation](http://developer.apple.com/documentation/Cocoa/Conceptual/AnimationGuide/Articles/TimingAnimations.html#//apple_ref/doc/uid/TP40003581-CJBGGDAD subclassing NSAnimation). This will work on a MacOS 10.4+ app, but not on Cocoa Touch, in which I cannot find any alternatives apart from using a NSTimer.
>As fortune would have it I do have access to the log file for my site. I've been able to generate the HTML page on the server manually - I've just been looking for a way to get it to happen automatically. All I need is to execute a shell command and get the output to display as the page. Sounds like a good job for an intern. =) Call your host and see if you can work out a deal for doing a shell execute.
Something like a callback delegate function in php
|php|oop|
I would like to implement something similar to a c# delegate method in PHP. A quick word to explain what I'm trying to do overall: I am trying to implement some asynchronous functionality. Basically some resource-intensive calls that get queued, cached, and dispatched when the underlying system gets around to it. When the asynchronous call finally receives a response I would like a callback event to be raised. I am having some problems coming up with a mechanism to do callbacks in PHP. I have come up with a method that works for now but I am unhappy with it. Basically it involves passing a reference to the object and the name of the method on it that will serve as the callback (taking the response as an argument) and then use eval to call the method when need be. This is sub-optimal for a variety of reasons, is there a better way of doing this that anyone knows of?
You can use the WindowsIdentity.Impersonate method to achieve this. This method allows code to impersonate a different Windows user. Here is a link for more information on this method with a good sample: <http://msdn.microsoft.com/en-us/library/system.security.principal.windowsidentity.impersonate.aspx> Complete example: // This sample demonstrates the use of the WindowsIdentity class to impersonate a user. // IMPORTANT NOTES: // This sample can be run only on Windows XP. The default Windows 2000 security policy // prevents this sample from executing properly, and changing the policy to allow // proper execution presents a security risk. // This sample requests the user to enter a password on the console screen. // Because the console window does not support methods allowing the password to be masked, // it will be visible to anyone viewing the screen. // The sample is intended to be executed in a .NET Framework 1.1 environment. To execute // this code in a 1.0 environment you will need to use a duplicate token in the call to the // WindowsIdentity constructor. See KB article Q319615 for more information. using System; using System.Runtime.InteropServices; using System.Security.Principal; using System.Security.Permissions; using System.Windows.Forms; [assembly:SecurityPermissionAttribute(SecurityAction.RequestMinimum, UnmanagedCode=true)] [assembly:PermissionSetAttribute(SecurityAction.RequestMinimum, Name = "FullTrust")] public class ImpersonationDemo { [DllImport("advapi32.dll", SetLastError=true, CharSet = CharSet.Unicode)] public static extern bool LogonUser(String lpszUsername, String lpszDomain, String lpszPassword, int dwLogonType, int dwLogonProvider, ref IntPtr phToken); [DllImport("kernel32.dll", CharSet=System.Runtime.InteropServices.CharSet.Auto)] private unsafe static extern int FormatMessage(int dwFlags, ref IntPtr lpSource, int dwMessageId, int dwLanguageId, ref String lpBuffer, int nSize, IntPtr *Arguments); [DllImport("kernel32.dll", CharSet=CharSet.Auto)] public extern static bool CloseHandle(IntPtr handle); [DllImport("advapi32.dll", CharSet=CharSet.Auto, SetLastError=true)] public extern static bool DuplicateToken(IntPtr ExistingTokenHandle, int SECURITY_IMPERSONATION_LEVEL, ref IntPtr DuplicateTokenHandle); // Test harness. // If you incorporate this code into a DLL, be sure to demand FullTrust. [PermissionSetAttribute(SecurityAction.Demand, Name = "FullTrust")] public static void Main(string[] args) { IntPtr tokenHandle = new IntPtr(0); IntPtr dupeTokenHandle = new IntPtr(0); try { string userName, domainName; // Get the user token for the specified user, domain, and password using the // unmanaged LogonUser method. // The local machine name can be used for the domain name to impersonate a user on this machine. Console.Write("Enter the name of the domain on which to log on: "); domainName = Console.ReadLine(); Console.Write("Enter the login of a user on {0} that you wish to impersonate: ", domainName); userName = Console.ReadLine(); Console.Write("Enter the password for {0}: ", userName); const int LOGON32_PROVIDER_DEFAULT = 0; //This parameter causes LogonUser to create a primary token. const int LOGON32_LOGON_INTERACTIVE = 2; tokenHandle = IntPtr.Zero; // Call LogonUser to obtain a handle to an access token. bool returnValue = LogonUser(userName, domainName, Console.ReadLine(), LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT, ref tokenHandle); Console.WriteLine("LogonUser called."); if (false == returnValue) { int ret = Marshal.GetLastWin32Error(); Console.WriteLine("LogonUser failed with error code : {0}", ret); throw new System.ComponentModel.Win32Exception(ret); } Console.WriteLine("Did LogonUser Succeed? " + (returnValue? "Yes" : "No")); Console.WriteLine("Value of Windows NT token: " + tokenHandle); // Check the identity. Console.WriteLine("Before impersonation: " + WindowsIdentity.GetCurrent().Name); // Use the token handle returned by LogonUser. WindowsIdentity newId = new WindowsIdentity(tokenHandle); WindowsImpersonationContext impersonatedUser = newId.Impersonate(); // Check the identity. Console.WriteLine("After impersonation: " + WindowsIdentity.GetCurrent().Name); // Stop impersonating the user. impersonatedUser.Undo(); // Check the identity. Console.WriteLine("After Undo: " + WindowsIdentity.GetCurrent().Name); // Free the tokens. if (tokenHandle != IntPtr.Zero) CloseHandle(tokenHandle); } catch(Exception ex) { Console.WriteLine("Exception occurred. " + ex.Message); } } }
Definitely build. I help manage an ISP and we have two firewalls built. One is for fail over and for redundancy. We use a program called [pfsense][1]. I couldn't recommend this program more. It has a great web interface for configuring it and we actually run it off a compact flash card. [1]: http://www.pfsense.org/
Troubleshooting a NullReference exception in a service
|.net|exception|powershell|service|
I have a windows service that runs various system monitoring operations. However, when running SNMP related checks, I always get a NullReference exception. The code runs fine when run through the user interface (under my username and password), but always errors running as the service. I've tried running the service as different user accounts (including mine), with no luck. I've tried replacing the SNMP monitoring code with calling the PowerShell cmdlet get-snmp (from the /n NetCmdlets), but that yields the same error. The application I'm working with is [PolyMon][1]. Any ideas? [1]: http://codeplex.com/polymon
How to properly cast objects created through reflection
|reflection|.net|c#|
I'm trying to wrap my head around reflection, so I decided to add plugin capability to a program that I'm writing. The only way to understand a concept is to get your fingers dirty and write the code, so I went the route of creating a simple interface library consisting of the IPlugin and IHost interfaces, a plugin implementation library of classes that implement IPlugin, and a simple console project that instantiates the IHost implementation class that does simple work with the plugin objects. Using reflection, I wanted to iterate through the types contained inside my plugin implementation dll and create instances of types. I was able to sucessfully instantiate classes with this code, but I could not cast the created object to the interface. I'm using loop through assemblies loop through types in assembly // This successfully created the right object object o = Activator.CreateInstance(type); // This threw an Invalid Cast Exception or returned null for an "as" cast // even though the object implemented IPlugin IPlugin i = (IPlugin) o; I made the code work with this. using System.Runtime.Remoting; ObjectHandle oh = Activator.CreateInstance(assembly.FullName, type.FullName); // This worked as I intended IPlugin i = (IPlugin) oh.Unwrap(); i.DoStuff(); Here are my questions: 1. Activator.CreateInstance(Type t) returns an object, but I couldn't cast the object to an interface that the object implemented. Why? 2. Should I have been using a different overload of CreateInstance()? 3. What are the reflection related tips and tricks? 4. Is there some crucial part of reflection that I'm just not getting?
|c#|.net|reflection|
I'm trying to wrap my head around reflection, so I decided to add plugin capability to a program that I'm writing. The only way to understand a concept is to get your fingers dirty and write the code, so I went the route of creating a simple interface library consisting of the IPlugin and IHost interfaces, a plugin implementation library of classes that implement IPlugin, and a simple console project that instantiates the IHost implementation class that does simple work with the plugin objects. Using reflection, I wanted to iterate through the types contained inside my plugin implementation dll and create instances of types. I was able to sucessfully instantiate classes with this code, but I could not cast the created object to the interface. I tried this code but I couldn't cast object o as I expected. I stepped through the process with the debugger and the proper constructor was called. Quickwatching object o showed me that it had the fields and properties that I expected to see in the implementation class. loop through assemblies loop through types in assembly // Filter out unwanted types if (!type.IsClass || type.IsNotPublic || type.IsAbstract ) continue; // This successfully created the right object object o = Activator.CreateInstance(type); // This threw an Invalid Cast Exception or returned null for an "as" cast // even though the object implemented IPlugin IPlugin i = (IPlugin) o; I made the code work with this. using System.Runtime.Remoting; ObjectHandle oh = Activator.CreateInstance(assembly.FullName, type.FullName); // This worked as I intended IPlugin i = (IPlugin) oh.Unwrap(); i.DoStuff(); Here are my questions: 1. Activator.CreateInstance(Type t) returns an object, but I couldn't cast the object to an interface that the object implemented. Why? 2. Should I have been using a different overload of CreateInstance()? 3. What are the reflection related tips and tricks? 4. Is there some crucial part of reflection that I'm just not getting?
As with most issues, it's not as simple as it sounds. There are cases where it would make sense to store the images in the database. - You are storing images that are changing dynamically, say invoices and you wanted to get an invoice as it was on 1 Jan 2007? - The government wants you to maintain 6 years of history - Images stored in the database do not require a different backup strategy. Images stored on filesystem do - It is easier to control access to the images if they are in a database. Idle admins can access any folder on disk. It takes a really determined admin to go snooping in a database to extract the images On the other hand there are problems associated - Require additional code to extract and stream the images - Latency may be slower than direct file access - Heavier load on the web server
I use the first loop when iterating over a conventional (indexed?) array and the foreach loop when dealing with an associative array. It just seems natural and helps the code flow and be more readable, in my opinion. As for do...while loops, I use those when I have to do more than just flip through an array. I'm not sure of any performance benefits, though.
Comparing effective dates in SQL
|sql|
Wondering if there is a better why in the WHERE clause of choosing records when you need to look at effective start and end dates? Currently this how I've done it in the past on MS SQL Server. Just worried about the date and not the time. I'm using SQL Server 2005. AND CAST(CONVERT( CHAR(10), ep.EffectiveStartDate, 101) AS DATETIME) <= CAST( CONVERT( CHAR(10), GETDATE(), 101) AS DATETIME) AND CAST(CONVERT( CHAR(10), ep.EffectiveEndDate, 101) AS DATETIME) >= CAST( CONVERT( CHAR(10), GETDATE(), 101) AS DATETIME)
try ep.EffectiveStartDate BETWEEN @date1 AND @date2 where you would do something like declare @date1 datetime, @date2 datetime; set @date1 = cast('10/1/2000' as datetime) set @date2 = cast('10/1/2020' as datetime)
Is there a Unix utility to prepend timestamps to lines of text?
|unix|shell|sed|
I ended up writing a quick little script for this in Python, but I was wondering if there was a utility you could feed text into which would prepend each line with some text -- in my specific case, a timestamp. Ideally, the use would be something like: $ cat somefile.txt | prepend-timestamp (Before you answer sed, I tried this: $ cat somefile.txt | sed "s/^/`date`/" but that only evaluates the date command once when sed is executed, so the same timestamp is incorrectly prepended to each line.)
|unix|shell|
|unix|shell|awk|
I ended up writing a quick little script for this in Python, but I was wondering if there was a utility you could feed text into which would prepend each line with some text -- in my specific case, a timestamp. Ideally, the use would be something like: $ cat somefile.txt | prepend-timestamp (Before you answer sed, I tried this: $ cat somefile.txt | sed "s/^/`date`/" but that only evaluates the date command once when sed is executed, so the same timestamp is incorrectly prepended to each line.) *Note on the accepted answer below:* strftime() appears to be a GNU awk extension, so if you're on Mac OS, for example, use gawk instead of awk.
Aside from network shares, another tool to use for this is a version-control system.
Does it have to be only numbers? You could create a random number between 1 and 1M (I'd suggest even higher though) and then [Base32 encode it][1]. The next thing you need to do is Hash that value (using a secret salt value) and base32 encode the hash. Then append the two strings together, perhaps separated by the dash. That way, you can verify the incoming code algorithmically. You just take the left side of the code, hash it using your secret salt, and compare that value to the right side of the code. [1]: http://www.crockford.com/wrmg/base32.html
The other thing to consider when using a GPU is the bus speed, Most Graphics cards are designed to have a higher bandwidth when transferring data from the CPU out to the GPU as that's what they do most of the time. The bandwidth from the GPU back up to the CPU, which is needed to return results etc, isn't as fast. So they work best in a pipelined mode.
The TFS 2008 power toys does come with the tf history /followbranches command. But that command doesn't expand merges. All it does is show you the change set history from A before branch B was created. What it doesn't show you is what change sets were merged from A -> B after the branch was created. In other words, what I want to see is all the change sets that were made on a source branch and then applied to a target branch as part of merge operation.
I have a tip regarding the "Track Active Item" option mentioned above, for when working with big projects. It's posted here: <http://stackoverflow.com/questions/31163/forcing-the-solution-explorer-to-select-the-file-in-the-editor-in-visual-studio#46193>
Test Driven Development in PHP
|php|unit-testing|tdd|
I am a web-developer working in PHP. I have some limited experience with using Test Driven Development in C# desktop applications. In that case we used nUnit for the unit testing framework. I would like to start using TDD in new projects but I'm really not sure where to begin. What recommendations do you have for a PHP-based unit testing framework and what are some good resources for someone who is pretty new to the TDD concept?
Passing large files to WCF service.