instruction
stringlengths
0
30k
It's because the set of integer values does not equal the set of float values for the 'int' and 'float' types. For example, the float value 0.5 has no equal in the integer set and the integer value 4519245367 might not exist in the set of values a float can store. So, the checker flags this as an issue to be checked by the programmer. Skizz
On *nix: $ dig -t a <domain name>
Selecting X words from a text field in MySQL
|mysql|
I'm building a basic search functionality, using LIKE (I'd be using fulltext but can't at the moment) and I'm wondering if MySQL can, on searching for a keyword (e.g. WHERE field LIKE '%word%') return 20 words either side of the keyword, as well?
Because floats can't store an exact int value, so if you have two variables, int i and float f, even if you assign "i = f;", the comparison "if (i == f)" probably won't return true.
C++: How to extract a string from rapidxml
|c++|xml|rapidxml|
In my C++ program I want to parse a small piece of XML, insert some nodes, then extract the new XML (preferably as a std::string) RapidXML ([http://rapidxml.sourceforge.net/][1]) has been recommended to me, but I can't see how to retrieve the XML back as a text string. (I could iterate over the nodes and attributes and build it myself, but surely there's a build in function that I am missing) Thank you [1]: http://rapidxml.sourceforge.net/
How can I get the DateTime for the Start of the Week?
|c#|datetime|
How do I find the Start of the week (Both Sunday and Monday) knowing just the current time in C#.NET Something like: DateTime.Now.StartWeek(Monday);
You can see whether a string has been interned by calling `String.IsInterned`. The call will return a new string that is either a reference to an interned string equal to the string that was passed as an argument, or `null` if the string was not interned.
We use ClickOnce where I work; in terms of comparison to a web release I would base the case around the need for providing users with a rich client app, otherwise it might well actually be better to use web applications. In terms of releasing a rich client app ClickOnce is fantastic; you can set it up to enforce updates on startup thus enforcing a version throughout the network. You can make the case that ClickOnce gives you the same benefit of having a single deployment point that web deployment possesses. Personally I've found ClickOnce to be unbelievably useful. If you're developing rich client .net apps (in Windows, though let's face it the vast majority of real .net development *is* in Windows) and want to deploy it across a network nothing else compares.
I have a custom installer action that updates the PATH environment, and creates an additional environment variable. Appending a directory to the existing path variable is working fine, but for some reason my attempts to create a new environment variable have been unsuccessful. The code I am using is: using (RegistryKey reg = Registry.LocalMachine.OpenSubKey(@"SYSTEM\CurrentControlSet\Control\Session Manager\Environment", true)) { reg.SetValue("MYVAR", "SomeVal", RegistryValueKind.ExpandString); }
I have a custom installer action that updates the PATH environment, and creates an additional environment variable. Appending a directory to the existing path variable is working fine, but for some reason my attempts to create a new environment variable have been unsuccessful. The code I am using is: using (RegistryKey reg = Registry.LocalMachine.OpenSubKey(@"SYSTEM\CurrentControlSet\Control\Session Manager\Environment", true)) { reg.SetValue("MYVAR", "SomeVal", RegistryValueKind.ExpandString); } Edit: The OS is 32-bit XP, and as far as I can tell it is failing silently.
You can try a plain old batchfile. @echo off for /f " delims==" %%i in (counter.txt) do set /A temp_counter= %%i+1 echo %temp_counter% > counter.txt assuming the count.bat and counter.txt are located in the same directory.
Many of the standard paths require a user to be logged in, especially the SH* functions as those are provided by the "shell", that is, Explorer. I suspect the only way you're going to get the right path is through the registry like you already mentioned.
Not that I know of, typically you'll develop apps on a desktop machine (PC/MAC whatever) and download/control the application on the phone. Also I don't think Java is available on a standard (non-cracked) iPhone.
I recently did a web application that just referenced the files (about 90 in total) from one web application (aspx, master and ascx) without too much of an issue. That said I was using a heavily modified version of the [MVP pattern][1], a lot of interfaces and conventions to keep the complexity down, the same middle tier and one site was a subset of the other. Big issues: 1. Master pages (and in turn designers and html view formatting) don’t work on a referenced file so you loose a lot of functionality. A pre-build step and a lot of svn:ignore entries was my hack around this. It was also a pain to get CruiseControl.NET to get the pre-build task to execute in the right folders. 2. Shared pages/controls need to be extremely aware of what they touch and reference as to avoid bringing in extra dependencies. 3. Both sites are locked together for deployment. 4. I now have to pray that the maintainer reads my pokey little document about the mess I made. It’s so far outside of what I’ve seen in ASP.NET projects. I was under a massive time pressure to get it to work, it does and now both apps are in production. I wouldn’t recommend it but if you’re interested start at: > *Add Existing Item*, select some files, click on the *Add* button’s arrow and say *Add as a Link*. [1]: http://polymorphicpodcast.com/shows/mv-patterns/
In SQL server it is as easy as SELECT * INTO NewTablenNmeHere FROM OPENROWSET( 'Microsoft.Jet.OLEDB.4.0', 'Excel 8.0;Database=C:\testing.xls','SELECT * FROM [Sheet1$]')
Does anybody know of existing code to read a mork file (Thunderbird Address Book)?
|.net|mork|thunderbird|file-format|
I have the need to read the Thunderbird address book on the fly. It is stored in a file format called Mork. Not a pleasant file format to read. I found a 1999 article explaining the file format. I would love to know if someone already has gone through this process and could make the code available. I found mork.pl by Jamie Zawinski, but I was hoping for a .NET solution. I'm hoping StackOverflow will come to the rescue, because this just seems like a waste of my time to write something to read this file format when it should be so simple. I love the comments that Jamie put in his [perl script][1]. Here is my favorite part: # Let me make it clear that McCusker is a complete barking lunatic. # This is just about the stupidest file format I've ever seen. [1]: http://www.jwz.org/hacks/mork.pl
|.net|file-format|thunderbird|mork|
I have the need to read the Thunderbird address book on the fly. It is stored in a file format called Mork. Not a pleasant file format to read. I found a 1999 article explaining the file format. I would love to know if someone already has gone through this process and could make the code available. I found mork.pl by [Jamie Zawinski][1] (he worked on Netscape Navigator), but I was hoping for a .NET solution. I'm hoping StackOverflow will come to the rescue, because this just seems like a waste of my time to write something to read this file format when it should be so simple. I love the comments that Jamie put in his [perl script][2]. Here is my favorite part: # Let me make it clear that McCusker is a complete barking lunatic. # This is just about the stupidest file format I've ever seen. [1]: http://en.wikipedia.org/wiki/Jamie_Zawinski [2]: http://www.jwz.org/hacks/mork.pl
BULK INSERT CSVTest FROM 'c:\csvtest.txt' WITH ( FIELDTERMINATOR = ',', ROWTERMINATOR = '\n' )
Parametized SQL or SPROC...doesn't matter from a performance stand point...you can query optimize either one. For me the last remaining benefit of a SPROC is that I can eliminate a lot SQL rights management by only granting my login rights to execute sprocs...if you use Parametized SQL the login withing your connection string has a lot more rights (writing ANY kind of select statement on one of the tables they have access too for example). I still prefer Parametized SQL though...
You can always use tab completion to type "s[TAB]" and press ENTER and that will execute it.
All these code samples that these good people have posted look fine. There is one thing to be aware of. Starting with Office 2007, Excel actually has up to 16,384 columns. That translates to XFD (the old max of 256 colums was IV). You will have to modify these methods somewhat to make them work for three characters. Shouldn't be that hard...
You can use double-braces to set up the data. You still call add, or put, but it's less ugly: private static final Hashtable<String,Integer> MYHASH = new Hashtable<String,Integer>() {{ put("foo", 1); put("bar", 256); put("data", 3); put("moredata", 27); put("hello", 32); put("world", 65536); }};
You can have a service implement all the service contracts you want. I mean, I don't know if there is a limit, but I don't think there is. That's a neat way to separate operations that will be implemented by the same service in several conceptually different service contract interfaces.
You are missing the reference to System.Configuration.
Newer phones come with WAP2 which uses HTML Mobile Profile (XHTML MP), which is quite similar to normal HTML. Older phones use Wireless Markup Language (WML). Depending on your audience I would consider making a mobile phone friendly version of the site using XHTML MP and drop WML completely. By mobile phone friendly I mean light graphics, little JavaScript and simple navigation. To check capabilities of different hand phones, take look at [WURFL][1]. Also, you might want to take a look at [Mobile Web Best Practices][2] from w3c. [1]: http://wurfl.sourceforge.net/ "Wireless Universal Resource File" [2]: http://www.w3.org/TR/2008/REC-mobile-bp-20080729/ "Mobile Web Best Practices"
How many ServiceContracts can a WCF Service have?
|web-services|wcf|
Specifically, since a ServiceContract is an Attribute to an Interface, how many interfaces can I code into one WCF web service? Is it a one-to-one?
Specifically, since a ServiceContract is an Attribute to an Interface, how many interfaces can I code into one WCF web service? Is it a one-to-one? Does it make sense to separate the contracts across multiple web services?
@jdiaz Of course you should strive to have very different business matters in different services, but consider the case in which you want that, for example, all your services implement a GetVersion() operation. You could have a service contract just for that operation and have every service implement it, instead of adding the GetVersion() operation to the contract of all your services.
A service can theoretically have any number of Endpoints, and each Endpoint is bound to a particular contract, or interface, so it is possible for a single conceptual (and configured) service to host multiple interfaces via multiple endpoints or alternatively for several endpoints to host the same interface. If you are using the ServiceHost class to host your service, though, instead of IIS, you can only associate a single interface per ServiceHost. I'm not sure why this is the case, but it is.
WCF services can have multiple endpoints, each of which can implement a different service contract. For example, you could have a service declared as follows: [ServiceBehavior(Namespace = "DemoService")] public class DemoService : IDemoService, IDoNothingService Which would have configuration along these lines: <service name="DemoService" behaviorConfiguration="Debugging"> <host> <baseAddresses> <add baseAddress = "http://localhost/DemoService.svc" /> </baseAddresses> </host> <endpoint address ="" binding="customBinding" bindingConfiguration="InsecureCustom" bindingNamespace="http://schemas.com/Demo" contract="IDemoService"/> <endpoint address ="" binding="customBinding" bindingConfiguration="InsecureCustom" bindingNamespace="http://schemas.com/Demo" contract="IDoNothingService"/> </service> Hope that helps, but if you were after the theoretical maximum interfaces you can have for a service I suspect it's some crazily large multiple of 2.
I hacked this together with the ActiveSupport gem: require 'active_support' def string_to_date(date_string) parts = date_string.split return parts[0].to_i.send(parts[1]) end sinces = ['1 hour', '1 day', '3 days'] sinces.each do |since| puts "#{since} ago: #{string_to_date(since).ago(Time.now)}" end
I hacked this together with the ActiveSupport gem: require 'active_support' def string_to_date(date_string) parts = date_string.split return parts[0].to_i.send(parts[1]) end sinces = ['1 hour', '1 day', '3 days'] sinces.each do |since| puts "#{since} ago: #{string_to_date(since).ago(Time.now)}" end [edit] To answer your question, you might try it like that: :conditions => ['Date)event_date) >= ?', (string_to_date(since).ago(Time.now))]
I did some research and came across this article that seems to have a solution to your question. **Ajax Control Toolkit with ASP.NET MVC#** source: jimzimmerman **ARTICLE LINK** [http://www.ajaxprojects.com/ajax/tutorialdetails.php?itemid=330][1] **QUOTE** > So basically if you put the class name > TextboxWatermark on any textbox input > with the title you like to show as the > watermark like this: > > <input type="text" class"TextboxWatermark" name="username" id="username" title="Must be at least 6 chars" /> > > or > > <%= Html.TextBox("username", new { @class = "TextboxWatermark", @title = "Must be at least 6 chars" }) %> > > What is nice about the second option > is that you get the added benefit of > getting the View Engine to fill out > the value of the textbox if there is > an item in ViewData of the > ViewData.Model that has a var named > 'username'. [1]: http://www.ajaxprojects.com/ajax/tutorialdetails.php?itemid=330
There are several differences between HashMap and Hashtable in Java: 1. [Hashtable](http://java.sun.com/javase/6/docs/api/java/util/Hashtable.html) is synchronized, whereas [HashMap](http://java.sun.com/javase/6/docs/api/java/util/HashMap.html) is not. This makes HashMap better for non-threaded applications, as unsynchronized Objects typically perform better than synchronized ones. 2. Hashtable does not allow null keys or values. HashMap allows one null key and any number of null values. 3. One of HashMap's subclasses is [LinkedHashMap](http://java.sun.com/javase/6/docs/api/java/util/LinkedHashMap.html), so in the event that you'd want predictable iteration order (which is insertion order by default), you could easily swap out the HashMap for a LinkedHashMap. This wouldn't be as easy if you were using Hashtable. Since synchronization is not an issue for you, I'd recommend HashMap.
An out-of-the-box idea, but could you use a "replace" function to strip out any instances of "(", "-" and " ", and then use an "isnumeric" function to test whether the resulting string is a number? Then you could do the same to the phone number string you're searching for and compare them as integers. Of course, this won't work for numbers like 1800-MATT-ROCKS. :)
Sometimes I use this, if I don't want it to be actually set and persisted in my db: class Person { private string _name; public string Name { get { return string.IsNullOrEmpty(_name) ? "Default Name" : _name; } set { _name = value; } } } Obviously if it's not a string then I might make the object nullable ( double?, int? ) and check if it's null, return a default, or return the value it's set to. Then I can make a check in my repository to see if it's my default and not persist, or make a backdoor check in to see the true status of the backing value, before saving. Hope that helps!
Console.WriteLine and generic List
|c#|list|generics|console|
I frequently find myself writing code like this: List<int> list = new List<int> { 1, 3, 5 }; foreach (int i in list) { Console.Write("{0}\t", i.ToString()); } Console.WriteLine(); Better would be something like this: List<int> list = new List<int> { 1, 3, 5 }; Console.WriteLine("{0}\t", list); I suspect there's some clever way of doing this, but I don't see it. Does anybody have a better solution than the first block?
|c#|generics|console|list|
Gathering OS and tool version numbers for build archive purposes
|version|archive|build-automation|
Our automated build machine needs to archive the version numbers of the OS plus various tools used during each build. (In case we ever need to replicate exactly the same build later on, perhaps when the machine is long dead.) I see the command "msinfo32.exe" can be used to dump a whole load of system version information, which we might as well archive. Does anyone know of a way to easily archive the version numbers of the Visual Studio tools? What mechanisms do other developers use to gather this kind of information for archive purposes?
|build-automation|version|archive|
Our automated build machine needs to archive the version numbers of the OS plus various tools used during each build. (In case we ever need to replicate exactly the same build later on, perhaps when the machine is long dead.) I see the command "msinfo32.exe" can be used to dump a whole load of system version information, which we might as well archive. Does anyone know of a way to easily archive the version numbers of the Visual Studio tools? What mechanisms do other developers use to gather this kind of information for archive purposes? --- Extra information for Fabio Gomes. I agree with you that in 5 years time it'll probably be impossible to recreate the exact OS and tool configuration (down to the nearest security update). Unfortunately this really comes from a contractual requirement. As part of our deliverable to a customer we must provide a copy of all source code and clear instructions on exactly how to replicate the build. It's probably impossible for us to meet this requirement perfectly. So - I'll just mark your answer as correct (I agree with you that it's practically impossible), and get on with playing with the rest of stack overflow. :) PS. It would be really great if stack overflow supported replies to answers instead of having to edit the original question.. But I see it has [already been denied][1]. [1]: http://stackoverflow.uservoice.com/pages/general/suggestions/14403
|build-automation|versions|archive|
|build-automation|versions|archive|
How do you tackle web application performance improvement?
|performance|oracle-database|web-application|
If a good name doesn't spring to mind, I would probably question whether there is a deeper problem - is the class serving a good purpose? If it is, naming it should be pretty straightforward.
If you need to get around this (you have a legitimate reason and are happy none of the issues mentioned in the other answers are an issue for you) then just cast from one type to another.
You'll want the SOA (Start of Authority) record for a given name, and this is how you accomplish it using the nslookup tool available on Windows and Unix-derived systems: $ nslookup > set querytype=soa > stackoverflow.com Server: 217.30.180.230 Address: 217.30.180.230#53 Non-authoritative answer: stackoverflow.com origin = ns51.domaincontrol.com mail addr = dns.jomax.net serial = 2008041300 refresh = 28800 retry = 7200 expire = 604800 minimum = 86400 Authoritative answers can be found from: stackoverflow.com nameserver = ns52.domaincontrol.com. stackoverflow.com nameserver = ns51.domaincontrol.com. The `origin = ns51.domaincontrol.com` tells you that **ns51.domaincontrol** is the main name server for **stackoverflow.com**. At the end of output all authoritative servers, including backup servers for the given domain, are listed.
You'll want the SOA (Start of Authority) record for a given domain name, and this is how you accomplish it using the universally available **nslookup** command line tool: command line> nslookup > set querytype=soa > stackoverflow.com Server: 217.30.180.230 Address: 217.30.180.230#53 Non-authoritative answer: stackoverflow.com origin = ns51.domaincontrol.com # ("primary name server" on Windows) mail addr = dns.jomax.net # ("responsible mail addr" on Windows) serial = 2008041300 refresh = 28800 retry = 7200 expire = 604800 minimum = 86400 Authoritative answers can be found from: stackoverflow.com nameserver = ns52.domaincontrol.com. stackoverflow.com nameserver = ns51.domaincontrol.com. The **origin** (or **primary name server** on Windows) line tells you that **ns51.domaincontrol** is the main name server for **stackoverflow.com**. At the end of output all authoritative servers, including backup servers for the given domain, are listed.
Using the "Callback" model of SampleGrabber may give you better results. See the example in Samples\C++\DirectShow\Editing\GrabBitmaps. There's also a lot of info in Samples\C++\DirectShow\Filters\Grabber2\grabber_text.txt and readme.txt.
Always go for MyClassA, MyClassB - It allows for a nice alpha sort.. **I'm kidding!** This is a good question, and something I experienced not too long ago. I was reorganising my codebase at work and was having problems of where to put what, and what to call it.. The **real** problem? I had classes doing too much. If you try to adhere to the [single responsibility principle](http://en.wikipedia.org/wiki/Single_responsibility_principle) it will make everything all come together much nicer.. Rather than one monolithic _PrintHandler_ class, you could break it down into _PageHandler_ , _PageFormatter_ (and so on) and then have a master _Printer_ class which brings it all together. In my re-org, it took me time, but I ended up binning a lot of duplicate code, got my codebase much more logical and learned a hell of a lot when it comes to thinking before throwing an extra method in a class :D I would **not** however recommend putting things like pattern names into the class name. The classes interface should make that obvious (like hiding the constructor for a singleton). There is nothing wrong with the generic name, if the class is serving a generic purpose. Good luck!
UPDATE table1, table2 SET table1.col1='value', table2.col1='value' WHERE table1.col3='567' AND table2.col6='567' This should work for ya. Here is a reference in he MySQL manual -> http://dev.mysql.com/doc/refman/5.0/en/update.html There is an example for multiple tables.
[e-texteditor](http://e-texteditor.com) seems to be growing as the editor of choice for rails development on ruby. Too bad it isn't free. Aside from that, the [RailsOnWindows](http://wiki.rubyonrails.org/rails/pages/RailsOnWindows) guide works fine. And Sqlite is by far your best choice for development: [RailsWithSqlite](http://wiki.rubyonrails.org/rails/pages/HowtoUseSQLite)
Are you just looking for an IDE, or a full stack (IDE, source control, database, web server)? If just an IDE, I would recommend [RadRails][1]. It has syntax highlighting, code help, support for Rails projects, code completion, and basically everything else you would expect to find in a full-featured IDE. It is also completely free. If a full stack, I would recommend Subversion, MySql, and Mongrel. These three are all very simple and well-supported in Windows. [1]: http://www.aptana.com/rails
Are you just looking for an IDE, or a full stack (IDE, source control, database, web server)? If just an IDE, I would recommend [NetBeans][1] or [RadRails][2]. Both have syntax highlighting, code help, support for Rails projects, code completion, and basically everything else you would expect to find in a full-featured IDE. Both are also completely free. Of course, both suffer from the "bulky" problem that you identify. If a full stack, I would recommend Subversion, MySql, and Mongrel. These three are all very simple and well-supported in Windows. [1]: http://www.netbeans.org/ [2]: http://www.aptana.com/rails
The following will update all rows in one table Update Table Set Column1 = 'New Value' The next one will update all rows where the value of Column2 is more than 5 Update Table Set Column1 = 'New Value' Where Column2 > 5 There is all [Unkwntech][1]'s example of updating more than one table UPDATE table1, table2 SET table1.col1 = 'value', table2.col1 = 'value' WHERE table1.col3 = '567' AND table2.col6='567' [1]: http://stackoverflow.com/questions/3432/multiple-updates-in-mysql#3439
Multiple Updates in MySQL
|untagged|
I know that you can insert multiple rows at once, is there a way to update multiple rows at once (as in, in one query) in MySQL?
I know that you can insert multiple rows at once, is there a way to update multiple rows at once (as in, in one query) in MySQL? Edit: For example I have the following Name id Col1 Col2 Row1 1 6 1 Row2 2 2 3 Row3 3 9 5 Row4 4 16 8 I want to combine all the following Updates into one query UPDATE table SET Col1 = 1 WHERE id = 1; UPDATE table SET Col1 = 2 WHERE id = 2; UPDATE table SET Col2 = 3 WHERE id = 3; UPDATE table SET Col1 = 10 WHERE id = 4; UPDATE table SET Col2 = 12 WHERE id = 4;
You could use the [BinaryFormatter][1] class to serialize your object to a binary format, then save the resulting string in your database. [1]: http://msdn.microsoft.com/en-us/library/system.runtime.serialization.formatters.binary.binaryformatter.aspx
By the way, using a PowerShell [here-string](http://blogs.msdn.com/powershell/archive/2006/07/15/Variable-expansion-in-strings-and-herestrings.aspx) might make your function a little easier to read as well, since you won't need to double up all the `"`-marks: function CreateAppPoolScript([string]$AppPoolName, [string]$AppPoolUser, [string]$AppPoolPass) { # Command to create an IIS application pool return @" cscript adsutil.vbs CREATE "w3svc/AppPools/$AppPoolName" IIsApplicationPool cscript adsutil.vbs SET "w3svc/AppPools/$AppPoolName/WamUserName" "$AppPoolUser" cscript adsutil.vbs SET "w3svc/AppPools/$AppPoolName/WamUserPass" "$AppPoolPass" cscript adsutil.vbs SET "w3svc/AppPools/$AppPoolName/AppPoolIdentityType" 3 "@ }
You can use [serialization][1] - it allows you to store your object at least in 3 forms: binary (suitable for BLOBs), XML (take advantage of MSSQL's XML data type) or just plain text (store in varchar or text column) [1]: http://msdn.microsoft.com/en-us/library/ms973893.aspx
HashMap: An implementation of the Map interface that uses a lookup table of hashcodes to locate keys. HashTable: Hi, 1998 called. They want their collections API back. Seriously though, you're better off staying away from Hashtable altogether. For single-threaded apps, you don't need the extra overhead of syncrhonisation. For highly concurrent apps, the paranoid synchronisation might lead to starvation and deadlocks, especially during garbage collection. Like Tim Howland pointed out, you might use ConcurrentHashMap instead.
This is a problem with Mysql - the regex function only match but cant replace. [See this post][1] for a possible solution. [1]: http://forums.mysql.com/read.php?10,137433,137465
I'd suggest just appending the current datetime of the build to a log file. date >> builddates.txt That way you get a build count via the # of lines, and you may also get some interesting statistics if you can be bothered analysing the dates and times later on. The extra size & time to count the number of lines in the file will be insignificant unless you are doing seriously fast project iterations!
Is it possible to run a query to reformat the data to match a desired format and then just run a simple query? That way even if the initial reformatting is slow you it doesn't really matter.
@Unsliced I think the problem he is getting at is when you take a crystal report someone developed against another database, and you bring it up in Crystal Reports XI, you have to do a Change Datasource for each field, including those in subreports. If you just change source on the top level of the report, it often errors. (I think that is a known issue in Crystal Reports).
> MySQL can search based on regular expressions. Sure, but given the arbitrary formatting, if my haystack contained `"(027) 123 456"` (bear in mind position of spaces can change, it could just as easily be `027 12 3456` and I wanted to match it with `027123456`, would my regex therefore need to be this? "^[\D]+0[\D]+2[\D]+7[\D]+1[\D]+2[\D]+3[\D]+4[\D]+5[\D]+6$" (actually it'd be worse as the mysql manual doesn't seem to indicate it supports `\D`) If that is the case, isn't it more or less the same as my %%%%% idea?
This would give you the preceding Sunday (I think): DateTime t = DateTime.Now; t -= new TimeSpan ((int) t.DayOfWeek, 0, 0, 0); Skizz
First up, you should use placeholders in your query instead of interpolating the variables directly. PDO/MySQLi allow you to write your queries like: SELECT * FROM sometable WHERE iUser = ? The API will safely substitute the values into the query. I also prefer to have my queries in the code instead of the database. It's a lot easier to work with an RCS when the queries are with your code. I have a rule of thumb when working with ORM's: if I'm working with one entity at a time, I'll use the interface. If I'm reporting/working with records in aggregate, I typically write SQL queries to do it. This means there's very few queries in my code.
If you're stuck with a name, sometimes just giving it <a href="http://lbrandy.com/blog/2008/08/developer-timesink-name-paralysis/"><i>any</i></a> half-sensible name with commitment to revising it later is a good strategy. Don't get naming paralysis. Yes, names are very important but they're not important enough to waste huge amounts of time on. If you can't think up a good name in 10 minutes, move on.
In some cases (financial market data and process control for example) you might need to use a real-time database rather than a RDBMS. See [wiki link][1] [1]: http://en.wikipedia.org/wiki/Real_time_database
It must be noted that the text editor/IDE that you use determines how good a font will look. I love UltraEdit, but the only font it renders properly is Courier New. It blurs out about all other useful monospace fonts. However, Visual Studio does a great job rendering any font accurately. Currently, I will vote Consolas. Though, I will try some of the others listed in the responses. Thank you. Btw, *please post links to download!*
This may be a bit of a hack, but you can cast the .DayOfWeek property to an int (it's an enum and since its not had its underlying data type changed it defaults to int) and use that to determine the previous start of the week. It appears the week specified in the DayOfWeek enum starts on Sunday, so if we subtract 1 from this value that'll be equal to how many days the Monday is before the current date. We also need to map the Sunday (0) to equal 7 so given 1 - 7 = -6 the Sunday will map to the previous Monday:- DateTime now = DateTime.Now; int dayOfWeek = (int)now.DayOfWeek; dayOfWeek = dayOfWeek == 0 ? 7 : dayOfWeek; DateTime startOfWeek = now.AddDays(1 - (int)now.DayOfWeek); The code for the previous Sunday is simpler as we don't have to make this adjustment:- DateTime now = DateTime.Now; int dayOfWeek = (int)now.DayOfWeek; DateTime startOfWeek = now.AddDays(-(int)now.DayOfWeek);
You could determine the start of the week for Sunday with: DateTime.Now.AddDays((double)DateTime.Now.DayOfWeek * -1);
The following method should return the DateTime that you want. Pass in true for Sunday being the first day of the week, false for Monday: private DateTime getStartOfWeek(bool useSunday) { DateTime now = DateTime.Now; int dayOfWeek = (int)now.DayOfWeek; if(!useSunday) dayOfWeek--; if(dayOfWeek < 0) {// day of week is Sunday and we want to use Monday as the start of the week // Sunday is now the seventh day of the week dayOfWeek = 6; } return now.AddDays(-1 * (double)dayOfWeek); }
Unfortunately I'm using an SQLEngine for embedded systems so it does not support BULK INSERT or OLEDB datasources, which is why I was thinking of taking the sql statement generation approach.
Does the Fox app use .CDX indexes? If so, you might be able to improve performance by adding indexes without needing to change any program code. If it uses .IDX indexes, though, the change would have to be done in the actual app.
In my experience writing mostly WinForms Client/Server apps these are the simple conclusions I've come to: **Use Stored Procedures:** 1. For any complex data work. If you're going to be doing something truly requiring a cursor or temp tables it's usually fastest to it within SQL Server. 2. When you need to lock down access to the data. If you don't give table access to users (or role or whatever) you can be sure that the only way to interact with the data is through the SP's you create. **Use ad-hoc queries:** 1. For CRUD when you don't need to restrict data access (or are doing so in another manner). 2. For simple searches. Creating SP's for a bunch of search criteria is a pain and difficult to maintain. If you can generate a reasonably fast search query use that. In most of my applications I've used both SP's and ad-hoc sql, though I find I'm using SP's less and less as they end up being code just like C#, only harder to version control, test, and maintain. I would recommend using ad-hoc sql unless you can find a specific reason not to.
Some things to think about here: [Who Needs Stored Procedures, Anyways?][1] Clearly it's a matter of your own needs and preferences, but one very important thing to think about when using ad hoc queries in a public-facing environment is security. Always parameterize them and watch out for the typical vulnerabilities like [SQL-injection attacks][2]. [1]: http://www.codinghorror.com/blog/archives/000117.html [2]: http://en.wikipedia.org/wiki/SQL_injection
I second Kristopher's recommendation of K&R for C. I've found the "Essential Actionscript 2.0" book quite useful for AS coding (there's an AS3 version out now I believe). I've found that having real books to thumb through is more helpful than an online reference in some cases. Not really sure why though.
Detecting if SQL server is running
|c#|sql-server|
I'm looking for a way to poll different servers and check that SQL server is up and running. I'm writing my code in C#. I don't particularly care about individual databases, just that SQL server is running and responsive. Any ideas?