qid
int64 1
3.11M
| question
stringlengths 10
32.1k
| date
stringlengths 10
10
| metadata
sequence | response_j
stringlengths 0
33.7k
| response_k
stringlengths 3
34.7k
|
---|---|---|---|---|---|
2,284,860 | I've been poring through .NET disassemblies and the GCC source code, but can't seem to find anywhere the actual implementation of `sin()` and other math functions... they always seem to be referencing something else.
Can anyone help me find them? I feel like it's unlikely that ALL hardware that C will run on supports trig functions in hardware, so there must be a software algorithm *somewhere*, right?
---
I'm aware of several ways that functions *can* be calculated, and have written my own routines to compute functions using taylor series for fun. I'm curious about how real, production languages do it, since all of my implementations are always several orders of magnitude slower, even though I think my algorithms are pretty clever (obviously they're not). | 2010/02/17 | [
"https://Stackoverflow.com/questions/2284860",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/172387/"
] | For `sin` specifically, using Taylor expansion would give you:
sin(x) := x - x^3/3! + x^5/5! - x^7/7! + ... (1)
you would keep adding terms until either the difference between them is lower than an accepted tolerance level or just for a finite amount of steps (faster, but less precise). An example would be something like:
```
float sin(float x)
{
float res=0, pow=x, fact=1;
for(int i=0; i<5; ++i)
{
res+=pow/fact;
pow*=-1*x*x;
fact*=(2*(i+1))*(2*(i+1)+1);
}
return res;
}
```
Note: (1) works because of the aproximation sin(x)=x for small angles. For bigger angles you need to calculate more and more terms to get acceptable results.
You can use a while argument and continue for a certain accuracy:
```
double sin (double x){
int i = 1;
double cur = x;
double acc = 1;
double fact= 1;
double pow = x;
while (fabs(acc) > .00000001 && i < 100){
fact *= ((2*i)*(2*i+1));
pow *= -1 * x*x;
acc = pow / fact;
cur += acc;
i++;
}
return cur;
}
``` | if you want `sin` then
```
__asm__ __volatile__("fsin" : "=t"(vsin) : "0"(xrads));
```
if you want `cos` then
```
__asm__ __volatile__("fcos" : "=t"(vcos) : "0"(xrads));
```
if you want `sqrt` then
```
__asm__ __volatile__("fsqrt" : "=t"(vsqrt) : "0"(value));
```
so why use inaccurate code when the machine instructions will do? |
2,284,860 | I've been poring through .NET disassemblies and the GCC source code, but can't seem to find anywhere the actual implementation of `sin()` and other math functions... they always seem to be referencing something else.
Can anyone help me find them? I feel like it's unlikely that ALL hardware that C will run on supports trig functions in hardware, so there must be a software algorithm *somewhere*, right?
---
I'm aware of several ways that functions *can* be calculated, and have written my own routines to compute functions using taylor series for fun. I'm curious about how real, production languages do it, since all of my implementations are always several orders of magnitude slower, even though I think my algorithms are pretty clever (obviously they're not). | 2010/02/17 | [
"https://Stackoverflow.com/questions/2284860",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/172387/"
] | Concerning trigonometric function like `sin()`, `cos()`,`tan()` there has been no mention, after 5 years, of an important aspect of high quality trig functions: **Range reduction**.
An early step in any of these functions is to reduce the angle, in radians, to a range of a 2\*π interval. But π is irrational so simple reductions like `x = remainder(x, 2*M_PI)` introduce error as `M_PI`, or machine pi, is an approximation of π. So, how to do `x = remainder(x, 2*π)`?
Early libraries used extended precision or crafted programming to give quality results but still over a limited range of `double`. When a large value was requested like `sin(pow(2,30))`, the results were meaningless or `0.0` and maybe with an [error flag](http://web.mit.edu/pilot/build/sgi_53/prc-tools/libmf.0.1.1/mtherr.c) set to something like `TLOSS` total loss of precision or `PLOSS` partial loss of precision.
Good range reduction of large values to an interval like -π to π is a challenging problem that rivals the challenges of the basic trig function, like `sin()`, itself.
A good report is [Argument reduction for huge arguments: Good to the last bit](http://www.csee.umbc.edu/%7Ephatak/645/supl/Ng-ArgReduction.pdf) (1992). It covers the issue well: discusses the need and how things were on various platforms (SPARC, PC, HP, 30+ other) and provides a solution algorithm the gives quality results for *all* `double` from `-DBL_MAX` to `DBL_MAX`.
---
**If the original arguments are in degrees**, yet may be of a large value, use `fmod()` first for improved precision. A good `fmod()` will introduce [no error](https://stackoverflow.com/a/20929050/2410359) and so provide excellent range reduction.
```
// sin(degrees2radians(x))
sin(degrees2radians(fmod(x, 360.0))); // -360.0 < fmod(x,360) < +360.0
```
Various trig identities and `remquo()` offer even more improvement. Sample: [sind()](https://stackoverflow.com/a/31525208/2410359) | If you want an implementation in software, not hardware, the place to look for a definitive answer to this question is Chapter 5 of [Numerical Recipes](http://www.nr.com/). My copy is in a box, so I can't give details, but the short version (if I remember this right) is that you take `tan(theta/2)` as your primitive operation and compute the others from there. The computation is done with a series approximation, but it's something that converges *much* more quickly than a Taylor series.
Sorry I can't rembember more without getting my hand on the book. |
2,284,860 | I've been poring through .NET disassemblies and the GCC source code, but can't seem to find anywhere the actual implementation of `sin()` and other math functions... they always seem to be referencing something else.
Can anyone help me find them? I feel like it's unlikely that ALL hardware that C will run on supports trig functions in hardware, so there must be a software algorithm *somewhere*, right?
---
I'm aware of several ways that functions *can* be calculated, and have written my own routines to compute functions using taylor series for fun. I'm curious about how real, production languages do it, since all of my implementations are always several orders of magnitude slower, even though I think my algorithms are pretty clever (obviously they're not). | 2010/02/17 | [
"https://Stackoverflow.com/questions/2284860",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/172387/"
] | There's nothing like hitting the source and seeing how someone has actually done it in a library in common use; let's look at one C library implementation in particular. I chose uLibC.
Here's the sin function:
<http://git.uclibc.org/uClibc/tree/libm/s_sin.c>
which looks like it handles a few special cases, and then carries out some argument reduction to map the input to the range [-pi/4,pi/4], (splitting the argument into two parts, a big part and a tail) before calling
<http://git.uclibc.org/uClibc/tree/libm/k_sin.c>
which then operates on those two parts.
If there is no tail, an approximate answer is generated using a polynomial of degree 13.
If there is a tail, you get a small corrective addition based on the principle that `sin(x+y) = sin(x) + sin'(x')y` | I'll try to answer for the case of `sin()` in a C program, compiled with GCC's C compiler on a current x86 processor (let's say a Intel Core 2 Duo).
In the C language the Standard C Library includes common math functions, not included in the language itself (e.g. `pow`, `sin` and `cos` for power, sine, and cosine respectively). The headers of which are included in [math.h](http://www.opengroup.org/onlinepubs/007908799/xsh/math.h.html).
Now on a GNU/Linux system, these libraries functions are provided by glibc (GNU libc or GNU C Library). But the GCC compiler wants you to link to the [math library](http://www.gnu.org/software/libc/manual/html_node/Mathematics.html#Mathematics) (`libm.so`) using the `-lm` compiler flag to enable usage of these math functions. ~~I'm not sure why it isn't part of the standard C library.~~ These would be a software version of the floating point functions, or "soft-float".
**Aside:** The reason for having the math functions separate is historic, and was merely intended to reduce the size of executable programs in *very* old Unix systems, possibly before shared libraries were available, as far as I know.
Now the compiler may optimize the standard C library function `sin()` (provided by `libm.so`) to be replaced with an call to a native instruction to your CPU/FPU's built-in sin() function, which exists as an FPU instruction (`FSIN` for x86/x87) on newer processors like the Core 2 series (this is correct pretty much as far back as the i486DX). This would depend on optimization flags passed to the gcc compiler. If the compiler was told to write code that would execute on any i386 or newer processor, it would not make such an optimization. The `-mcpu=486` flag would inform the compiler that it was safe to make such an optimization.
Now if the program executed the software version of the sin() function, it would do so based on a [CORDIC](https://stackoverflow.com/questions/345085/how-do-trigonometric-functions-work/345117#345117) (COordinate Rotation DIgital Computer) or [BKM algorithm](http://en.wikipedia.org/wiki/BKM_algorithm), or *more* likely a table or power-series calculation which is commonly used now to calculate such transcendental functions. [Src: <http://en.wikipedia.org/wiki/Cordic#Application]>
Any recent (since 2.9x approx.) version of gcc also offers a built-in version of sin, `__builtin_sin()` that it will used to replace the standard call to the C library version, as an optimization.
I'm sure that is as clear as mud, but hopefully gives you more information than you were expecting, and lots of jumping off points to learn more yourself. |
2,284,860 | I've been poring through .NET disassemblies and the GCC source code, but can't seem to find anywhere the actual implementation of `sin()` and other math functions... they always seem to be referencing something else.
Can anyone help me find them? I feel like it's unlikely that ALL hardware that C will run on supports trig functions in hardware, so there must be a software algorithm *somewhere*, right?
---
I'm aware of several ways that functions *can* be calculated, and have written my own routines to compute functions using taylor series for fun. I'm curious about how real, production languages do it, since all of my implementations are always several orders of magnitude slower, even though I think my algorithms are pretty clever (obviously they're not). | 2010/02/17 | [
"https://Stackoverflow.com/questions/2284860",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/172387/"
] | The actual implementation of library functions is up to the specific compiler and/or library provider. Whether it's done in hardware or software, whether it's a Taylor expansion or not, etc., will vary.
I realize that's absolutely no help. | Don't use Taylor series. Chebyshev polynomials are both faster and more accurate, as pointed out by a couple of people above. Here is an implementation (originally from the ZX Spectrum ROM): <https://albertveli.wordpress.com/2015/01/10/zx-sine/> |
2,284,860 | I've been poring through .NET disassemblies and the GCC source code, but can't seem to find anywhere the actual implementation of `sin()` and other math functions... they always seem to be referencing something else.
Can anyone help me find them? I feel like it's unlikely that ALL hardware that C will run on supports trig functions in hardware, so there must be a software algorithm *somewhere*, right?
---
I'm aware of several ways that functions *can* be calculated, and have written my own routines to compute functions using taylor series for fun. I'm curious about how real, production languages do it, since all of my implementations are always several orders of magnitude slower, even though I think my algorithms are pretty clever (obviously they're not). | 2010/02/17 | [
"https://Stackoverflow.com/questions/2284860",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/172387/"
] | OK kiddies, time for the pros....
This is one of my biggest complaints with inexperienced software engineers. They come in calculating transcendental functions from scratch (using Taylor's series) as if nobody had ever done these calculations before in their lives. Not true. This is a well defined problem and has been approached thousands of times by very clever software and hardware engineers and has a well defined solution.
Basically, most of the transcendental functions use Chebyshev Polynomials to calculate them. As to which polynomials are used depends on the circumstances. First, the bible on this matter is a book called "Computer Approximations" by Hart and Cheney. In that book, you can decide if you have a hardware adder, multiplier, divider, etc, and decide which operations are fastest. e.g. If you had a really fast divider, the fastest way to calculate sine might be P1(x)/P2(x) where P1, P2 are Chebyshev polynomials. Without the fast divider, it might be just P(x), where P has much more terms than P1 or P2....so it'd be slower. So, first step is to determine your hardware and what it can do. Then you choose the appropriate combination of Chebyshev polynomials (is usually of the form cos(ax) = aP(x) for cosine for example, again where P is a Chebyshev polynomial). Then you decide what decimal precision you want. e.g. if you want 7 digits precision, you look that up in the appropriate table in the book I mentioned, and it will give you (for precision = 7.33) a number N = 4 and a polynomial number 3502. N is the order of the polynomial (so it's p4.x^4 + p3.x^3 + p2.x^2 + p1.x + p0), because N=4. Then you look up the actual value of the p4,p3,p2,p1,p0 values in the back of the book under 3502 (they'll be in floating point). Then you implement your algorithm in software in the form:
(((p4.x + p3).x + p2).x + p1).x + p0
....and this is how you'd calculate cosine to 7 decimal places on that hardware.
Note that most hardware implementations of transcendental operations in an FPU usually involve some microcode and operations like this (depends on the hardware).
Chebyshev polynomials are used for most transcendentals but not all. e.g. Square root is faster to use a double iteration of Newton raphson method using a lookup table first.
Again, that book "Computer Approximations" will tell you that.
If you plan on implmementing these functions, I'd recommend to anyone that they get a copy of that book. It really is the bible for these kinds of algorithms.
Note that there are bunches of alternative means for calculating these values like cordics, etc, but these tend to be best for specific algorithms where you only need low precision. To guarantee the precision every time, the chebyshev polynomials are the way to go. Like I said, well defined problem. Has been solved for 50 years now.....and thats how it's done.
Now, that being said, there are techniques whereby the Chebyshev polynomials can be used to get a single precision result with a low degree polynomial (like the example for cosine above). Then, there are other techniques to interpolate between values to increase the accuracy without having to go to a much larger polynomial, such as "Gal's Accurate Tables Method". This latter technique is what the post referring to the ACM literature is referring to. But ultimately, the Chebyshev Polynomials are what are used to get 90% of the way there.
Enjoy. | The essence of how it does this lies in this excerpt from *Applied Numerical Analysis* by Gerald Wheatley:
>
> When your software program asks the computer to get a value of
> [![enter image description here](https://i.stack.imgur.com/H9tMQ.gif)](https://i.stack.imgur.com/H9tMQ.gif) or [![enter image description here](https://i.stack.imgur.com/UQuaY.gif)](https://i.stack.imgur.com/UQuaY.gif), have you wondered how it can get the
> values if the most powerful functions it can compute are polynomials?
> It doesnt look these up in tables and interpolate! Rather, the
> computer approximates every function other than polynomials from some
> polynomial that is tailored to give the values very accurately.
>
>
>
A few points to mention on the above is that some algorithms do infact interpolate from a table, albeit only for the first few iterations. Also note how it mentions that computers utilise approximating polynomials without specifying which type of approximating polynomial. As others in the thread have pointed out, Chebyshev polynomials are more efficient than Taylor polynomials in this case. |
2,284,860 | I've been poring through .NET disassemblies and the GCC source code, but can't seem to find anywhere the actual implementation of `sin()` and other math functions... they always seem to be referencing something else.
Can anyone help me find them? I feel like it's unlikely that ALL hardware that C will run on supports trig functions in hardware, so there must be a software algorithm *somewhere*, right?
---
I'm aware of several ways that functions *can* be calculated, and have written my own routines to compute functions using taylor series for fun. I'm curious about how real, production languages do it, since all of my implementations are always several orders of magnitude slower, even though I think my algorithms are pretty clever (obviously they're not). | 2010/02/17 | [
"https://Stackoverflow.com/questions/2284860",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/172387/"
] | Chebyshev polynomials, as mentioned in another answer, are the polynomials where the largest difference between the function and the polynomial is as small as possible. That is an excellent start.
In some cases, the maximum error is not what you are interested in, but the maximum relative error. For example for the sine function, the error near x = 0 should be much smaller than for larger values; you want a small *relative* error. So you would calculate the Chebyshev polynomial for sin x / x, and multiply that polynomial by x.
Next you have to figure out how to evaluate the polynomial. You want to evaluate it in such a way that the intermediate values are small and therefore rounding errors are small. Otherwise the rounding errors might become a lot larger than errors in the polynomial. And with functions like the sine function, if you are careless then it may be possible that the result that you calculate for sin x is greater than the result for sin y even when x < y. So careful choice of the calculation order and calculation of upper bounds for the rounding error are needed.
For example, sin x = x - x^3/6 + x^5 / 120 - x^7 / 5040... If you calculate naively sin x = x \* (1 - x^2/6 + x^4/120 - x^6/5040...), then that function in parentheses is decreasing, and it *will* happen that if y is the next larger number to x, then sometimes sin y will be smaller than sin x. Instead, calculate sin x = x - x^3 \* (1/6 - x^2 / 120 + x^4/5040...) where this cannot happen.
When calculating Chebyshev polynomials, you usually need to round the coefficients to double precision, for example. But while a Chebyshev polynomial is optimal, the Chebyshev polynomial with coefficients rounded to double precision is not the optimal polynomial with double precision coefficients!
For example for sin (x), where you need coefficients for x, x^3, x^5, x^7 etc. you do the following: Calculate the best approximation of sin x with a polynomial (ax + bx^3 + cx^5 + dx^7) with higher than double precision, then round a to double precision, giving A. The difference between a and A would be quite large. Now calculate the best approximation of (sin x - Ax) with a polynomial (b x^3 + cx^5 + dx^7). You get different coefficients, because they adapt to the difference between a and A. Round b to double precision B. Then approximate (sin x - Ax - Bx^3) with a polynomial cx^5 + dx^7 and so on. You will get a polynomial that is almost as good as the original Chebyshev polynomial, but much better than Chebyshev rounded to double precision.
Next you should take into account the rounding errors in the choice of polynomial. You found a polynomial with minimum error in the polynomial ignoring rounding error, but you want to optimise polynomial plus rounding error. Once you have the Chebyshev polynomial, you can calculate bounds for the rounding error. Say f (x) is your function, P (x) is the polynomial, and E (x) is the rounding error. You don't want to optimise | f (x) - P (x) |, you want to optimise | f (x) - P (x) +/- E (x) |. You will get a slightly different polynomial that tries to keep the polynomial errors down where the rounding error is large, and relaxes the polynomial errors a bit where the rounding error is small.
All this will get you easily rounding errors of at most 0.55 times the last bit, where +,-,\*,/ have rounding errors of at most 0.50 times the last bit. | Don't use Taylor series. Chebyshev polynomials are both faster and more accurate, as pointed out by a couple of people above. Here is an implementation (originally from the ZX Spectrum ROM): <https://albertveli.wordpress.com/2015/01/10/zx-sine/> |
423,896 | I am getting to grips with Windows Azure. I usually use NInject as my IoC container in web apps. However, when trying to use it within an Azure web role I get a security exception (something to do with reflection permission).
Has anyone used other IoC with Azure and had succcess? | 2009/01/08 | [
"https://Stackoverflow.com/questions/423896",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7011/"
] | I just have been prototyping with Azure services today (not Web role, though).
Autofac IoC Container for .NET has worked in this scenario. | From Ninject google group: <http://groups.google.com/group/ninject/browse_thread/thread/8d5a0aff853c6b4f/20209877f8db179a?show_docid=20209877f8db179a>
If you set the kernel option UseReflectionBasedInjection, Ninject will work
in Azure (as well as other partial trust environments):
```
var options = new KernelOptions
{
UseReflectionBasedInjection = true
};
var kernel = new StandardKernel(options, new ModuleA(), new ModuleB(), ...);
``` |
1,494,129 | I'd like to be able to write something like the following. Can someone show me how to write a clean WordReader class in C#. A word is `[a-zA-Z]+`.
```
public List<string> GetSpecialWords(string text)
{
string word;
List<string> specialWords = new List<string>();
using (WordReader wr = new WordReader(text))
{
while (true)
{
word = wr.Read();
if (word == null) break;
if (isSpecial(word)) specialWords.Add(word);
}
}
return specialWords;
}
private bool isSpecial(string word)
{
//some business logic here
}
``` | 2009/09/29 | [
"https://Stackoverflow.com/questions/1494129",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/180615/"
] | Regex.Match("[a-zA-Z]+") should return you a word in the form of a Regex.Match object. You can use Regex.Matches to get all of the matched strings, or you can just do Regex.Match("[a-zA-Z]+", indexOfLastMatch) to get the next word.
MSDN: Regex object
<http://msdn.microsoft.com/en-us/library/system.text.regularexpressions.regex.aspx>
If you're not allowed to use Regex in your homework problem, well... | I would have read your valid word characters until you his a space or punctuation. You'll want to keep track of you index in the stream, while skipping over punctuation and spaces, and also numbers, in your case. This feels like homework, so I am going to leave the implementation up to you.
You should consider the case for hyphenated words, in your case, should they count as one or two words. |
2,009,740 | There's a known problem with embedded UIWebViews that if you load data into them using loadHTMLString or loadData, the canGoBack/canGoForward properties and goBack/goForward methods don't work. These only work when using loadRequest.
Since Safari's normal app cache doesn't work in embedded UIWebViews, creating a native app that effectively caches otherwise live content becomes impossible/unusable. That is, I can cache the contents of the HTML, Javascript, images, etc. and load them via loadHTMLString or loadData, but then the back and forward buttons don't work.
I could also use loadRequest and specify a file URL, but that breaks when it comes to communicating with the live site -- even if I specify a tag (because of cookie domain issues).
I have a work around that involves basically re-implementing the app cache using local store (and not having the native app do any caching itself), which is OK, but not really ideal. Are there any other work arounds/something I missed? | 2010/01/05 | [
"https://Stackoverflow.com/questions/2009740",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/165162/"
] | So do you download the HTML yourself, then pass it to UIWebView as a string? Why so? Do you modify it on the fly or something?
Maybe a custom URL schema would help? You use loadRequest with a schema of your own, which in turn works with HTTP and then feeds the webview whatever data you want? | Could you fetch the content, save it to the local filesystem, point the webview to the local filesystem using file:// URLs, then intercept the link follows with shouldStartLoadWithRequest to fetch more to local fs, point webview at new local content, etc?
I've had good luck with UIWebView and file:/// URLs. Basically you'd be intercepting load requests, fetching stuff yourself, writing it to the local filesystem with rewritten URLs, then loading that into the browser.
There seems to be no way to load/save the browser history. |
2,009,740 | There's a known problem with embedded UIWebViews that if you load data into them using loadHTMLString or loadData, the canGoBack/canGoForward properties and goBack/goForward methods don't work. These only work when using loadRequest.
Since Safari's normal app cache doesn't work in embedded UIWebViews, creating a native app that effectively caches otherwise live content becomes impossible/unusable. That is, I can cache the contents of the HTML, Javascript, images, etc. and load them via loadHTMLString or loadData, but then the back and forward buttons don't work.
I could also use loadRequest and specify a file URL, but that breaks when it comes to communicating with the live site -- even if I specify a tag (because of cookie domain issues).
I have a work around that involves basically re-implementing the app cache using local store (and not having the native app do any caching itself), which is OK, but not really ideal. Are there any other work arounds/something I missed? | 2010/01/05 | [
"https://Stackoverflow.com/questions/2009740",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/165162/"
] | I am using the UIWebView's canGoBack to check to see if I'm at the first page of the history. If I am then I just call the little method I used to load the first page (displayLocalResource sets up the HTMLString and loads it into the webView). Here is a snippet:
```
//Implementing a back button
- (void)backOne:(id)sender{
if ([webView canGoBack]) {
// There's a valid webpage to go back to, so go there
[webView goBack];
} else {
// You've reached the end of the line, so reload your own data
[self displayLocalResource];
}
}
``` | So do you download the HTML yourself, then pass it to UIWebView as a string? Why so? Do you modify it on the fly or something?
Maybe a custom URL schema would help? You use loadRequest with a schema of your own, which in turn works with HTTP and then feeds the webview whatever data you want? |
2,009,740 | There's a known problem with embedded UIWebViews that if you load data into them using loadHTMLString or loadData, the canGoBack/canGoForward properties and goBack/goForward methods don't work. These only work when using loadRequest.
Since Safari's normal app cache doesn't work in embedded UIWebViews, creating a native app that effectively caches otherwise live content becomes impossible/unusable. That is, I can cache the contents of the HTML, Javascript, images, etc. and load them via loadHTMLString or loadData, but then the back and forward buttons don't work.
I could also use loadRequest and specify a file URL, but that breaks when it comes to communicating with the live site -- even if I specify a tag (because of cookie domain issues).
I have a work around that involves basically re-implementing the app cache using local store (and not having the native app do any caching itself), which is OK, but not really ideal. Are there any other work arounds/something I missed? | 2010/01/05 | [
"https://Stackoverflow.com/questions/2009740",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/165162/"
] | So do you download the HTML yourself, then pass it to UIWebView as a string? Why so? Do you modify it on the fly or something?
Maybe a custom URL schema would help? You use loadRequest with a schema of your own, which in turn works with HTTP and then feeds the webview whatever data you want? | Loading the string into a temp file and using that as a URL request seems to cure this. It's something about loading the string directly that causes UIWebView not to see it as the home page you can navigate back to. This code worked for me:
```
//If you load the string like this, then "webView.canGoBack" never returns YES. It's documented frequently on the web.
//Loading the string as a URL instead seems to work better.
//[self.myWebView loadHTMLString:str baseURL:nil];
//write the string to a temp file
NSString *fileName = @"homepage.html";
NSURL *fileURL = [NSURL fileURLWithPath:[NSTemporaryDirectory() stringByAppendingPathComponent:fileName]];
NSData *data = [str dataUsingEncoding:NSUTF8StringEncoding];
[data writeToURL:fileURL atomically:NO];
//open that temp file in the UIWebView
[self.myWebView loadRequest:[NSURLRequest requestWithURL:fileURL]];
```
Use this to enable/disable the back button:
```
- (void)webViewDidFinishLoad:(UIWebView *)webView{
//this is to check if we're back at the root page.
if (webView.canGoBack == YES) {
self.backButton.enabled=YES;
}
else {
self.backButton.enabled=NO;
}
}
``` |
2,009,740 | There's a known problem with embedded UIWebViews that if you load data into them using loadHTMLString or loadData, the canGoBack/canGoForward properties and goBack/goForward methods don't work. These only work when using loadRequest.
Since Safari's normal app cache doesn't work in embedded UIWebViews, creating a native app that effectively caches otherwise live content becomes impossible/unusable. That is, I can cache the contents of the HTML, Javascript, images, etc. and load them via loadHTMLString or loadData, but then the back and forward buttons don't work.
I could also use loadRequest and specify a file URL, but that breaks when it comes to communicating with the live site -- even if I specify a tag (because of cookie domain issues).
I have a work around that involves basically re-implementing the app cache using local store (and not having the native app do any caching itself), which is OK, but not really ideal. Are there any other work arounds/something I missed? | 2010/01/05 | [
"https://Stackoverflow.com/questions/2009740",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/165162/"
] | I am using the UIWebView's canGoBack to check to see if I'm at the first page of the history. If I am then I just call the little method I used to load the first page (displayLocalResource sets up the HTMLString and loads it into the webView). Here is a snippet:
```
//Implementing a back button
- (void)backOne:(id)sender{
if ([webView canGoBack]) {
// There's a valid webpage to go back to, so go there
[webView goBack];
} else {
// You've reached the end of the line, so reload your own data
[self displayLocalResource];
}
}
``` | Could you fetch the content, save it to the local filesystem, point the webview to the local filesystem using file:// URLs, then intercept the link follows with shouldStartLoadWithRequest to fetch more to local fs, point webview at new local content, etc?
I've had good luck with UIWebView and file:/// URLs. Basically you'd be intercepting load requests, fetching stuff yourself, writing it to the local filesystem with rewritten URLs, then loading that into the browser.
There seems to be no way to load/save the browser history. |
2,009,740 | There's a known problem with embedded UIWebViews that if you load data into them using loadHTMLString or loadData, the canGoBack/canGoForward properties and goBack/goForward methods don't work. These only work when using loadRequest.
Since Safari's normal app cache doesn't work in embedded UIWebViews, creating a native app that effectively caches otherwise live content becomes impossible/unusable. That is, I can cache the contents of the HTML, Javascript, images, etc. and load them via loadHTMLString or loadData, but then the back and forward buttons don't work.
I could also use loadRequest and specify a file URL, but that breaks when it comes to communicating with the live site -- even if I specify a tag (because of cookie domain issues).
I have a work around that involves basically re-implementing the app cache using local store (and not having the native app do any caching itself), which is OK, but not really ideal. Are there any other work arounds/something I missed? | 2010/01/05 | [
"https://Stackoverflow.com/questions/2009740",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/165162/"
] | I had a same problem. I tried manage the history, but it is error prone. Now I have discovered a better solution of this.
What you want to do is simply add a loadRequest to about:blank and make that as a placeholder for you before you call loadHTMLString/loadData. Then you are totally free from monitoring the history. The webview.canGoBack and canGoForward will just work. Of course, you will need a hack to handle go back to the placeholder about:blank. You can do that in webViewDidFinishLoad. Here is the code highlight:
In the function when you call loadHTMLString:
```
[weakSelf.fbWebView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"about:blank"]]];
[weakSelf.fbWebView loadHTMLString:stringResponse baseURL:url];
```
Code to handle goBack:
```
- (void)webViewDidFinishLoad:(UIWebView *)webView
{
if ([webView.request.URL.absoluteString isEqualToString:@"about:blank"]
&& ![webView canGoBack] && [webView canGoForward]) {
[weakSelf.fbWebView loadHTMLString:stringResponse baseURL:url];
}
}
```
I think it is also possible expand this solution to handle those loadHTMLString that is not the first load. Just by having a Stack to record all the string response and insert an about:blank on each loadHTMLString. And pop the stack when each time go back to about:blank. | Could you fetch the content, save it to the local filesystem, point the webview to the local filesystem using file:// URLs, then intercept the link follows with shouldStartLoadWithRequest to fetch more to local fs, point webview at new local content, etc?
I've had good luck with UIWebView and file:/// URLs. Basically you'd be intercepting load requests, fetching stuff yourself, writing it to the local filesystem with rewritten URLs, then loading that into the browser.
There seems to be no way to load/save the browser history. |
2,009,740 | There's a known problem with embedded UIWebViews that if you load data into them using loadHTMLString or loadData, the canGoBack/canGoForward properties and goBack/goForward methods don't work. These only work when using loadRequest.
Since Safari's normal app cache doesn't work in embedded UIWebViews, creating a native app that effectively caches otherwise live content becomes impossible/unusable. That is, I can cache the contents of the HTML, Javascript, images, etc. and load them via loadHTMLString or loadData, but then the back and forward buttons don't work.
I could also use loadRequest and specify a file URL, but that breaks when it comes to communicating with the live site -- even if I specify a tag (because of cookie domain issues).
I have a work around that involves basically re-implementing the app cache using local store (and not having the native app do any caching itself), which is OK, but not really ideal. Are there any other work arounds/something I missed? | 2010/01/05 | [
"https://Stackoverflow.com/questions/2009740",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/165162/"
] | I am using the UIWebView's canGoBack to check to see if I'm at the first page of the history. If I am then I just call the little method I used to load the first page (displayLocalResource sets up the HTMLString and loads it into the webView). Here is a snippet:
```
//Implementing a back button
- (void)backOne:(id)sender{
if ([webView canGoBack]) {
// There's a valid webpage to go back to, so go there
[webView goBack];
} else {
// You've reached the end of the line, so reload your own data
[self displayLocalResource];
}
}
``` | Loading the string into a temp file and using that as a URL request seems to cure this. It's something about loading the string directly that causes UIWebView not to see it as the home page you can navigate back to. This code worked for me:
```
//If you load the string like this, then "webView.canGoBack" never returns YES. It's documented frequently on the web.
//Loading the string as a URL instead seems to work better.
//[self.myWebView loadHTMLString:str baseURL:nil];
//write the string to a temp file
NSString *fileName = @"homepage.html";
NSURL *fileURL = [NSURL fileURLWithPath:[NSTemporaryDirectory() stringByAppendingPathComponent:fileName]];
NSData *data = [str dataUsingEncoding:NSUTF8StringEncoding];
[data writeToURL:fileURL atomically:NO];
//open that temp file in the UIWebView
[self.myWebView loadRequest:[NSURLRequest requestWithURL:fileURL]];
```
Use this to enable/disable the back button:
```
- (void)webViewDidFinishLoad:(UIWebView *)webView{
//this is to check if we're back at the root page.
if (webView.canGoBack == YES) {
self.backButton.enabled=YES;
}
else {
self.backButton.enabled=NO;
}
}
``` |
2,009,740 | There's a known problem with embedded UIWebViews that if you load data into them using loadHTMLString or loadData, the canGoBack/canGoForward properties and goBack/goForward methods don't work. These only work when using loadRequest.
Since Safari's normal app cache doesn't work in embedded UIWebViews, creating a native app that effectively caches otherwise live content becomes impossible/unusable. That is, I can cache the contents of the HTML, Javascript, images, etc. and load them via loadHTMLString or loadData, but then the back and forward buttons don't work.
I could also use loadRequest and specify a file URL, but that breaks when it comes to communicating with the live site -- even if I specify a tag (because of cookie domain issues).
I have a work around that involves basically re-implementing the app cache using local store (and not having the native app do any caching itself), which is OK, but not really ideal. Are there any other work arounds/something I missed? | 2010/01/05 | [
"https://Stackoverflow.com/questions/2009740",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/165162/"
] | I am using the UIWebView's canGoBack to check to see if I'm at the first page of the history. If I am then I just call the little method I used to load the first page (displayLocalResource sets up the HTMLString and loads it into the webView). Here is a snippet:
```
//Implementing a back button
- (void)backOne:(id)sender{
if ([webView canGoBack]) {
// There's a valid webpage to go back to, so go there
[webView goBack];
} else {
// You've reached the end of the line, so reload your own data
[self displayLocalResource];
}
}
``` | I had a same problem. I tried manage the history, but it is error prone. Now I have discovered a better solution of this.
What you want to do is simply add a loadRequest to about:blank and make that as a placeholder for you before you call loadHTMLString/loadData. Then you are totally free from monitoring the history. The webview.canGoBack and canGoForward will just work. Of course, you will need a hack to handle go back to the placeholder about:blank. You can do that in webViewDidFinishLoad. Here is the code highlight:
In the function when you call loadHTMLString:
```
[weakSelf.fbWebView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"about:blank"]]];
[weakSelf.fbWebView loadHTMLString:stringResponse baseURL:url];
```
Code to handle goBack:
```
- (void)webViewDidFinishLoad:(UIWebView *)webView
{
if ([webView.request.URL.absoluteString isEqualToString:@"about:blank"]
&& ![webView canGoBack] && [webView canGoForward]) {
[weakSelf.fbWebView loadHTMLString:stringResponse baseURL:url];
}
}
```
I think it is also possible expand this solution to handle those loadHTMLString that is not the first load. Just by having a Stack to record all the string response and insert an about:blank on each loadHTMLString. And pop the stack when each time go back to about:blank. |
2,009,740 | There's a known problem with embedded UIWebViews that if you load data into them using loadHTMLString or loadData, the canGoBack/canGoForward properties and goBack/goForward methods don't work. These only work when using loadRequest.
Since Safari's normal app cache doesn't work in embedded UIWebViews, creating a native app that effectively caches otherwise live content becomes impossible/unusable. That is, I can cache the contents of the HTML, Javascript, images, etc. and load them via loadHTMLString or loadData, but then the back and forward buttons don't work.
I could also use loadRequest and specify a file URL, but that breaks when it comes to communicating with the live site -- even if I specify a tag (because of cookie domain issues).
I have a work around that involves basically re-implementing the app cache using local store (and not having the native app do any caching itself), which is OK, but not really ideal. Are there any other work arounds/something I missed? | 2010/01/05 | [
"https://Stackoverflow.com/questions/2009740",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/165162/"
] | I had a same problem. I tried manage the history, but it is error prone. Now I have discovered a better solution of this.
What you want to do is simply add a loadRequest to about:blank and make that as a placeholder for you before you call loadHTMLString/loadData. Then you are totally free from monitoring the history. The webview.canGoBack and canGoForward will just work. Of course, you will need a hack to handle go back to the placeholder about:blank. You can do that in webViewDidFinishLoad. Here is the code highlight:
In the function when you call loadHTMLString:
```
[weakSelf.fbWebView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"about:blank"]]];
[weakSelf.fbWebView loadHTMLString:stringResponse baseURL:url];
```
Code to handle goBack:
```
- (void)webViewDidFinishLoad:(UIWebView *)webView
{
if ([webView.request.URL.absoluteString isEqualToString:@"about:blank"]
&& ![webView canGoBack] && [webView canGoForward]) {
[weakSelf.fbWebView loadHTMLString:stringResponse baseURL:url];
}
}
```
I think it is also possible expand this solution to handle those loadHTMLString that is not the first load. Just by having a Stack to record all the string response and insert an about:blank on each loadHTMLString. And pop the stack when each time go back to about:blank. | Loading the string into a temp file and using that as a URL request seems to cure this. It's something about loading the string directly that causes UIWebView not to see it as the home page you can navigate back to. This code worked for me:
```
//If you load the string like this, then "webView.canGoBack" never returns YES. It's documented frequently on the web.
//Loading the string as a URL instead seems to work better.
//[self.myWebView loadHTMLString:str baseURL:nil];
//write the string to a temp file
NSString *fileName = @"homepage.html";
NSURL *fileURL = [NSURL fileURLWithPath:[NSTemporaryDirectory() stringByAppendingPathComponent:fileName]];
NSData *data = [str dataUsingEncoding:NSUTF8StringEncoding];
[data writeToURL:fileURL atomically:NO];
//open that temp file in the UIWebView
[self.myWebView loadRequest:[NSURLRequest requestWithURL:fileURL]];
```
Use this to enable/disable the back button:
```
- (void)webViewDidFinishLoad:(UIWebView *)webView{
//this is to check if we're back at the root page.
if (webView.canGoBack == YES) {
self.backButton.enabled=YES;
}
else {
self.backButton.enabled=NO;
}
}
``` |
2,620,217 | Currently I am developing website in asp.net.
I wanted to include spellchecker module into my code.
It may not be fare to ask like this, but I don't have enough time to do R&D on that topic, of course I did enough study but I am unable to get the exact way to implement spell checker in my application.
Can any one suggest me how to implement spell checker and where to get source code.
Thank You. | 2010/04/12 | [
"https://Stackoverflow.com/questions/2620217",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/314264/"
] | All modern browsers come with built-in spell checkers these days, and users can customise them to their own language, locale and even add new words. Don't bother trying to implement your own. If your IE6 users complain, tell them to upgrade. | If you use javascript and jQuery, the [spellayt plugin](http://plugins.jquery.com/project/spellayt) provides spell checking in IE browsers. |
2,620,217 | Currently I am developing website in asp.net.
I wanted to include spellchecker module into my code.
It may not be fare to ask like this, but I don't have enough time to do R&D on that topic, of course I did enough study but I am unable to get the exact way to implement spell checker in my application.
Can any one suggest me how to implement spell checker and where to get source code.
Thank You. | 2010/04/12 | [
"https://Stackoverflow.com/questions/2620217",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/314264/"
] | All modern browsers come with built-in spell checkers these days, and users can customise them to their own language, locale and even add new words. Don't bother trying to implement your own. If your IE6 users complain, tell them to upgrade. | Have a look at this appliation, following the link -<http://www.spellchecker.net/> If you use FCK/CK Editor or TinyMCE, it perfectly works as a plug-in there. if not, you can embed it into your application as a SpellAsYouType functionality or spell-checking in pop-up.. |
2,620,217 | Currently I am developing website in asp.net.
I wanted to include spellchecker module into my code.
It may not be fare to ask like this, but I don't have enough time to do R&D on that topic, of course I did enough study but I am unable to get the exact way to implement spell checker in my application.
Can any one suggest me how to implement spell checker and where to get source code.
Thank You. | 2010/04/12 | [
"https://Stackoverflow.com/questions/2620217",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/314264/"
] | op said:
>
> It may not be fare to ask like this,
> but I don't have enough time to do R&D
> on that topic
>
>
>
and then commented:
>
> Actually I am new to .net. Recently I
> joined as a .net trainee. My trainer
> wants me to develop this module.
>
>
>
wow, you're making great strides!
follow the links, should do what you want...
<http://forums.karamasoft.com/ShowPost.aspx?PostID=3614> | If you use javascript and jQuery, the [spellayt plugin](http://plugins.jquery.com/project/spellayt) provides spell checking in IE browsers. |
2,620,217 | Currently I am developing website in asp.net.
I wanted to include spellchecker module into my code.
It may not be fare to ask like this, but I don't have enough time to do R&D on that topic, of course I did enough study but I am unable to get the exact way to implement spell checker in my application.
Can any one suggest me how to implement spell checker and where to get source code.
Thank You. | 2010/04/12 | [
"https://Stackoverflow.com/questions/2620217",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/314264/"
] | op said:
>
> It may not be fare to ask like this,
> but I don't have enough time to do R&D
> on that topic
>
>
>
and then commented:
>
> Actually I am new to .net. Recently I
> joined as a .net trainee. My trainer
> wants me to develop this module.
>
>
>
wow, you're making great strides!
follow the links, should do what you want...
<http://forums.karamasoft.com/ShowPost.aspx?PostID=3614> | Have a look at this appliation, following the link -<http://www.spellchecker.net/> If you use FCK/CK Editor or TinyMCE, it perfectly works as a plug-in there. if not, you can embed it into your application as a SpellAsYouType functionality or spell-checking in pop-up.. |
1,234,218 | Quite a funny question I have.
I am working now on the HTML parser and I was using vector `<HTMLTag>` for all my input purposes which seemed quite fine and fast for creating tree.
In another application I need to edit HTML structure and now inserting or reordering of the elements would be extremely painful using vector so I decided to switch to more tree-like structure.
I read a few articles on trees and their implementation and I was thinking of std::map for this purpose.
Something like this:
`std::map< element, *child_map >`
So when I thought of inserting a tag somewhere in between and having them all ordered by some key (e.g. unique integer id) I still have a problem to update all keys in a branch after insertion.
for example:
```
1:SCRIPT
2:HEAD
3:BODY
```
When I want to insert new element "SCRIPT" after the HEAD I will need to increment Body Key to 4 and have something like this:
```
1:SCRIPT
2:HEAD
3:SCRIPT
4:BODY
```
Seems a bit cumbersome to me. Am I missing something?
As an alternative I thought of doing `list<pair<>>` implementation instead. Thus sorting is not determined by a key and I can add elements anywhere without any extra updates. | 2009/08/05 | [
"https://Stackoverflow.com/questions/1234218",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/144154/"
] | I would make the child set a member of the element and use std::list:
```
class Element {
/* ... */
std::list<boost::shared_ptr<Element> > children;
/* ... */
};
```
That said, you might want to look into using an existing DOM library instead of rolling your own. For example, you could use [htmlcxx](http://htmlcxx.sourceforge.net/). | List< pair > would work well to simulate any form of tree structure such as what you're trying to do:
list< pair< "html", list > would let you store an arbitrary number of children as well as control the order of objects in the child list.
Have fun walking this tree. |
3,086,750 | I know there are plenty of questions regarding this error, but I haven't found it easy to find one exactly like mine.
Here goes.
I have a pretty small application that writes DB data to a csv file and then uploads it to a server. I have it running on my local box out of eclipse which is great, but the final version needs to be run as a cron job on a server box from command line.
I'm working on the command line call for the main java class and its giving me lots of trouble.
My dependency structure is as such:
My classes
* package=gtechReconcile
* classes= GtechReconciler.java, CSVFile.java, QueryMachine.java, FTPSender.java
My external libs
* ojdbc14.zip
* edtftpj.jar
I run the following line in the terminal in the directory above the compile source package (ie /path/to/classes where /path/to/classes/gtechReconcile/ has all the compiled class files) This path is the current directory when the command line is run :
```
java -cp /<snip>/lib/ojdbc14.zip:/<snip>/lib/edtftpj.jar:/path/to/classes gtechReconcile.GtechReconciler
```
The error then tells me it can't find java.lang.StringBuilder, even though this does not exist in my code. I use a StringBuffer, which apparently StringBuilder has replaced since Java5. Perhaps the java compiler converted this to StringBuilder, which the jvm then does not resolve?
What am I missing here?
EDIT : added error from prompt (clarified where this executes from and what is present in the package folder):
```
[gtechReconcile]$ pwd
/path/to/
[gtechReconcile]$ cd classes/gtechReconcile/
[gtechReconcile]$ ls
CSVFile.class FTPSender.class GtechReconciler.class QueryMachine.class reports
[gtechReconcile]$ cd ..
[classes]$ ls
gtechReconcile
[classes]$ java -cp .:/path/to/lib/ojdbc14.zip:/path/to/lib/edtftpj.jar gtechReconcile.GtechReconciler
Creating file
Exception in thread "main" java.lang.NoClassDefFoundError: while resolving class: gtechReconcile.CSVFile
at java.lang.VMClassLoader.resolveClass(java.lang.Class) (/usr/lib/libgcj.so.5.0.0)
at java.lang.Class.initializeClass() (/usr/lib/libgcj.so.5.0.0)
at gtechReconcile.GtechReconciler.main(java.lang.String[]) (Unknown Source)
Caused by: java.lang.ClassNotFoundException: java.lang.StringBuilder not found in [file:./, file:/opt/mms_tstt2/gtechReconcile/lib/ojdbc14.zip, file:/opt/mms_tstt2/gtechReconcile/lib/edtftpj.jar, file:/usr/share/java/libgcj-3.4.6.jar, file:./, core:/]
at java.net.URLClassLoader.findClass(java.lang.String) (/usr/lib/libgcj.so.5.0.0)
at gnu.gcj.runtime.VMClassLoader.findClass(java.lang.String) (/usr/lib/libgcj.so.5.0.0)
at java.lang.ClassLoader.loadClass(java.lang.String, boolean) (/usr/lib/libgcj.so.5.0.0)
at _Jv_FindClass(_Jv_Utf8Const, java.lang.ClassLoader) (/usr/lib/libgcj.so.5.0.0)
at java.lang.Class.forName(java.lang.String, boolean, java.lang.ClassLoader) (/usr/lib/libgcj.so.5.0.0)
at _Jv_BytecodeVerifier.verify_instructions_0() (/usr/lib/libgcj.so.5.0.0)
at _Jv_VerifyMethod(_Jv_InterpMethod) (/usr/lib/libgcj.so.5.0.0)
at _Jv_PrepareClass(java.lang.Class) (/usr/lib/libgcj.so.5.0.0)
at _Jv_WaitForState(java.lang.Class, int) (/usr/lib/libgcj.so.5.0.0)
at java.lang.VMClassLoader.linkClass0(java.lang.Class) (/usr/lib/libgcj.so.5.0.0)
at java.lang.VMClassLoader.resolveClass(java.lang.Class) (/usr/lib/libgcj.so.5.0.0)
...2 more
``` | 2010/06/21 | [
"https://Stackoverflow.com/questions/3086750",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/72401/"
] | The exception is raised when you create a new StringBuilder in your CSVFile class. Google tells me it's a frequent problem with GCJ, use an official Sun JVM. It usally resolves this kind of problem.
---
The `gtechReconcile` folder is assumed to contains all the class files in the `gtechReconcile` package.
In example, if you have `/path/to/classes/gtechReconcile/GtechReconciler.class`, you have two options.
1. Go to `/path/to/classes`, add to the classpath the current directory (`.`) and run `java` as you did before.
2. Add `/path/to/classes` to the classpath and run `java` wherever you like. | The default classpath (if you don't specify one) is the current directory (".").
However, if you specify a classpath, java will use that instead of the default, thus removing the current directory.
The solution to your problem is simple: add the "current directory" to your class path, such as:
```
java -cp .:/<snip>/lib/ojdbc14.zip:/<snip>/lib/edtftpj.jar:/<snip>/bin/ gtechReconcile.GtechReconciler
``` |
2,930,768 | I have an Sqlite database in which I want to select rows of which the value in a TIMESTAMP column is before a certain date. I would think this to be simple but I can't get it done. I have tried this:
```
SELECT * FROM logged_event WHERE logged_event.CREATED_AT < '2010-05-28 16:20:55'
```
and various variations on it, like with the date functions. I've read <http://sqlite.org/lang_datefunc.html> and <http://www.sqlite.org/datatypes.html> and I would expect that the column would be a numeric type, and that the comparison would be done on the unix timestamp value. Apparantly not. Anyone who can help? If it matters, I'm trying this out in Sqlite Expert Personal.
Edit:
Here's type table description:
```
CREATE TABLE [logged_event]
(
[id] INTEGER NOT NULL PRIMARY KEY,
[created_at] TIMESTAMP,
[name] VARCHAR(64),
[data] VARCHAR(512)
);
```
And the test data:
```
INSERT INTO table VALUES(1,'2010-05-28T15:36:56+0200','test','test');
INSERT INTO table VALUES(2,'2010-05-28T16:20:49+0200','test','test');
INSERT INTO table VALUES(3,'2010-05-28T16:20:51+0200','test','test');
INSERT INTO table VALUES(4,'2010-05-28T16:20:52+0200','test','test');
INSERT INTO table VALUES(5,'2010-05-28T16:20:53+0200','test','test');
INSERT INTO table VALUES(6,'2010-05-28T16:20:55+0200','test','test');
INSERT INTO table VALUES(7,'2010-05-28T16:20:57+0200','test','test');
``` | 2010/05/28 | [
"https://Stackoverflow.com/questions/2930768",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11449/"
] | The issue is with the way you've inserted data into your table: the `+0200` syntax doesn't match any of [SQLite's time formats](http://www.sqlite.org/lang_datefunc.html):
1. YYYY-MM-DD
2. YYYY-MM-DD HH:MM
3. YYYY-MM-DD HH:MM:SS
4. YYYY-MM-DD HH:MM:SS.SSS
5. YYYY-MM-DDTHH:MM
6. YYYY-MM-DDTHH:MM:SS
7. YYYY-MM-DDTHH:MM:SS.SSS
8. HH:MM
9. HH:MM:SS
10. HH:MM:SS.SSS
11. now
12. DDDDDDDDDD
Changing it to use the SS.SSS format works correctly:
```
sqlite> CREATE TABLE Foo (created_at TIMESTAMP);
sqlite> INSERT INTO Foo VALUES('2010-05-28T15:36:56+0200');
sqlite> SELECT * FROM Foo WHERE foo.created_at < '2010-05-28 16:20:55';
sqlite> SELECT * FROM Foo WHERE DATETIME(foo.created_at) < '2010-05-28 16:20:55';
sqlite> INSERT INTO Foo VALUES('2010-05-28T15:36:56.200');
sqlite> SELECT * FROM Foo WHERE DATETIME(foo.created_at) < '2010-05-28 16:20:55';
2010-05-28T15:36:56.200
```
If you absolutely can't change the format when it is inserted, you might have to fall back to doing something "clever" and modifying the actual string (i.e. to replace the `+` with a `.`, etc.).
---
(original answer)
You haven't described what kind of data is contained in your `CREATED_AT` column. If it indeed a datetime, it will compare correctly against a string:
```
sqlite> SELECT DATETIME('now');
2010-05-28 16:33:10
sqlite> SELECT DATETIME('now') < '2011-01-01 00:00:00';
1
```
If it is stored as a unix timestamp, you need to call `DATETIME` function with the second argument as `'unixepoch'` to compare against a string:
```
sqlite> SELECT DATETIME(0, 'unixepoch');
1970-01-01 00:00:00
sqlite> SELECT DATETIME(0, 'unixepoch') < '2010-01-01 00:00:00';
1
sqlite> SELECT DATETIME(0, 'unixepoch') == DATETIME('1970-01-01 00:00:00');
1
```
If neither of those solve your problem (and even if they do!) you should **always** post some data so that other people can reproduce your problem. You should even feel free to come up with a *subset* of your original data that still reproduces the problem. | SQLite's support for date/time types is very limited. You may have to roll-your-own method for maintaining time information. At least, that's what I did.
You can define your own stored-functions for doing comparisons using the SQLite create\_function() API. |
2,930,768 | I have an Sqlite database in which I want to select rows of which the value in a TIMESTAMP column is before a certain date. I would think this to be simple but I can't get it done. I have tried this:
```
SELECT * FROM logged_event WHERE logged_event.CREATED_AT < '2010-05-28 16:20:55'
```
and various variations on it, like with the date functions. I've read <http://sqlite.org/lang_datefunc.html> and <http://www.sqlite.org/datatypes.html> and I would expect that the column would be a numeric type, and that the comparison would be done on the unix timestamp value. Apparantly not. Anyone who can help? If it matters, I'm trying this out in Sqlite Expert Personal.
Edit:
Here's type table description:
```
CREATE TABLE [logged_event]
(
[id] INTEGER NOT NULL PRIMARY KEY,
[created_at] TIMESTAMP,
[name] VARCHAR(64),
[data] VARCHAR(512)
);
```
And the test data:
```
INSERT INTO table VALUES(1,'2010-05-28T15:36:56+0200','test','test');
INSERT INTO table VALUES(2,'2010-05-28T16:20:49+0200','test','test');
INSERT INTO table VALUES(3,'2010-05-28T16:20:51+0200','test','test');
INSERT INTO table VALUES(4,'2010-05-28T16:20:52+0200','test','test');
INSERT INTO table VALUES(5,'2010-05-28T16:20:53+0200','test','test');
INSERT INTO table VALUES(6,'2010-05-28T16:20:55+0200','test','test');
INSERT INTO table VALUES(7,'2010-05-28T16:20:57+0200','test','test');
``` | 2010/05/28 | [
"https://Stackoverflow.com/questions/2930768",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11449/"
] | SQLite's support for date/time types is very limited. You may have to roll-your-own method for maintaining time information. At least, that's what I did.
You can define your own stored-functions for doing comparisons using the SQLite create\_function() API. | As best I can tell, it's entirely reasonable to include a timezone specifier; see the text "formats 2 through 10 can . . ." at <http://www.sqlite.org/lang_datefunc.html>
However, the issue is that only the date functions interpret timestamps as dates. So for actual comparison, you need to either pass the timestamp through a date function or store things such that string comparison works.
One approach would be to code your application such that you called datetime on every value that you insert and on every literal value in a select statement.
However, simply not including the time zone as suggested by the existing answer may be easier in many applications. |
2,930,768 | I have an Sqlite database in which I want to select rows of which the value in a TIMESTAMP column is before a certain date. I would think this to be simple but I can't get it done. I have tried this:
```
SELECT * FROM logged_event WHERE logged_event.CREATED_AT < '2010-05-28 16:20:55'
```
and various variations on it, like with the date functions. I've read <http://sqlite.org/lang_datefunc.html> and <http://www.sqlite.org/datatypes.html> and I would expect that the column would be a numeric type, and that the comparison would be done on the unix timestamp value. Apparantly not. Anyone who can help? If it matters, I'm trying this out in Sqlite Expert Personal.
Edit:
Here's type table description:
```
CREATE TABLE [logged_event]
(
[id] INTEGER NOT NULL PRIMARY KEY,
[created_at] TIMESTAMP,
[name] VARCHAR(64),
[data] VARCHAR(512)
);
```
And the test data:
```
INSERT INTO table VALUES(1,'2010-05-28T15:36:56+0200','test','test');
INSERT INTO table VALUES(2,'2010-05-28T16:20:49+0200','test','test');
INSERT INTO table VALUES(3,'2010-05-28T16:20:51+0200','test','test');
INSERT INTO table VALUES(4,'2010-05-28T16:20:52+0200','test','test');
INSERT INTO table VALUES(5,'2010-05-28T16:20:53+0200','test','test');
INSERT INTO table VALUES(6,'2010-05-28T16:20:55+0200','test','test');
INSERT INTO table VALUES(7,'2010-05-28T16:20:57+0200','test','test');
``` | 2010/05/28 | [
"https://Stackoverflow.com/questions/2930768",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11449/"
] | The issue is with the way you've inserted data into your table: the `+0200` syntax doesn't match any of [SQLite's time formats](http://www.sqlite.org/lang_datefunc.html):
1. YYYY-MM-DD
2. YYYY-MM-DD HH:MM
3. YYYY-MM-DD HH:MM:SS
4. YYYY-MM-DD HH:MM:SS.SSS
5. YYYY-MM-DDTHH:MM
6. YYYY-MM-DDTHH:MM:SS
7. YYYY-MM-DDTHH:MM:SS.SSS
8. HH:MM
9. HH:MM:SS
10. HH:MM:SS.SSS
11. now
12. DDDDDDDDDD
Changing it to use the SS.SSS format works correctly:
```
sqlite> CREATE TABLE Foo (created_at TIMESTAMP);
sqlite> INSERT INTO Foo VALUES('2010-05-28T15:36:56+0200');
sqlite> SELECT * FROM Foo WHERE foo.created_at < '2010-05-28 16:20:55';
sqlite> SELECT * FROM Foo WHERE DATETIME(foo.created_at) < '2010-05-28 16:20:55';
sqlite> INSERT INTO Foo VALUES('2010-05-28T15:36:56.200');
sqlite> SELECT * FROM Foo WHERE DATETIME(foo.created_at) < '2010-05-28 16:20:55';
2010-05-28T15:36:56.200
```
If you absolutely can't change the format when it is inserted, you might have to fall back to doing something "clever" and modifying the actual string (i.e. to replace the `+` with a `.`, etc.).
---
(original answer)
You haven't described what kind of data is contained in your `CREATED_AT` column. If it indeed a datetime, it will compare correctly against a string:
```
sqlite> SELECT DATETIME('now');
2010-05-28 16:33:10
sqlite> SELECT DATETIME('now') < '2011-01-01 00:00:00';
1
```
If it is stored as a unix timestamp, you need to call `DATETIME` function with the second argument as `'unixepoch'` to compare against a string:
```
sqlite> SELECT DATETIME(0, 'unixepoch');
1970-01-01 00:00:00
sqlite> SELECT DATETIME(0, 'unixepoch') < '2010-01-01 00:00:00';
1
sqlite> SELECT DATETIME(0, 'unixepoch') == DATETIME('1970-01-01 00:00:00');
1
```
If neither of those solve your problem (and even if they do!) you should **always** post some data so that other people can reproduce your problem. You should even feel free to come up with a *subset* of your original data that still reproduces the problem. | As best I can tell, it's entirely reasonable to include a timezone specifier; see the text "formats 2 through 10 can . . ." at <http://www.sqlite.org/lang_datefunc.html>
However, the issue is that only the date functions interpret timestamps as dates. So for actual comparison, you need to either pass the timestamp through a date function or store things such that string comparison works.
One approach would be to code your application such that you called datetime on every value that you insert and on every literal value in a select statement.
However, simply not including the time zone as suggested by the existing answer may be easier in many applications. |
257,801 | Here's the scenario:
I have a textbox and a button on a web page. When the button is clicked, I want a popup window to open (using Thickbox) that will show all items that match the value entered in the textbox. I am currently using the IFrame implementation of Thickbox. The problem is that the URL to show is hardcoded into the "alt' attribute of the button. What I really need is for the "alt" attribute to pass along the value in the textbox to the popup.
Here is the code so far:
```
<input type="textbox" id="tb" />
<input alt="Search.aspx?KeepThis=true&TB_iframe=true&height=500&width=700" class="thickbox" title="Search" type="button" value="Search" />
```
Ideally, I would like to put the textbox value into the Search.aspx url but I can't seem to figure out how to do that. My current alternative is to use jQuery to set the click function of the Search button to call a web service that will set some values in the ASP.NET session. The Search.aspx page will then use the session variables to do the search. However, this is a bit flaky since it seems like there will always be the possibility that the search executes before the session variables are set. | 2008/11/03 | [
"https://Stackoverflow.com/questions/257801",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1574/"
] | Just handle the onclick of your button to run a function that calls `tb_show()`, passing the value of the text box. Something like
```
... onclick = "doSearch()" ...
function doSearch()
{
tb_show(caption, 'Search.aspx?KeepThis=true&q=\"' +
$('input#tb').val() +
'\"&TB_iframe=true&height=500&width=700');
}
``` | Here is an idea. I don't think it is very pretty but should work:
```
$('input#tb').blur(function(){
var url = $('input.thickbox').attr('alt');
var tbVal = $(this).val();
// add the textbox value into the query string here
// url = ..
$('input.thickbox').attr('alt', url);
});
```
Basically, you update the button alt tag every time the textbox loses focus. Instead, you could also listen to key strokes and update after every one.
As far as updateing the query string, I'll let you figure out the best way. I can see putting a placeholder in there like: &TB=TB\_PLACEHOLDER. Then you can just do a string replace. |
257,801 | Here's the scenario:
I have a textbox and a button on a web page. When the button is clicked, I want a popup window to open (using Thickbox) that will show all items that match the value entered in the textbox. I am currently using the IFrame implementation of Thickbox. The problem is that the URL to show is hardcoded into the "alt' attribute of the button. What I really need is for the "alt" attribute to pass along the value in the textbox to the popup.
Here is the code so far:
```
<input type="textbox" id="tb" />
<input alt="Search.aspx?KeepThis=true&TB_iframe=true&height=500&width=700" class="thickbox" title="Search" type="button" value="Search" />
```
Ideally, I would like to put the textbox value into the Search.aspx url but I can't seem to figure out how to do that. My current alternative is to use jQuery to set the click function of the Search button to call a web service that will set some values in the ASP.NET session. The Search.aspx page will then use the session variables to do the search. However, this is a bit flaky since it seems like there will always be the possibility that the search executes before the session variables are set. | 2008/11/03 | [
"https://Stackoverflow.com/questions/257801",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1574/"
] | If you read the manual, under the iframe content section, it tells you that your parameters need to go before the TB\_iframe parameter. Everything after this gets stripped off. | Here is an idea. I don't think it is very pretty but should work:
```
$('input#tb').blur(function(){
var url = $('input.thickbox').attr('alt');
var tbVal = $(this).val();
// add the textbox value into the query string here
// url = ..
$('input.thickbox').attr('alt', url);
});
```
Basically, you update the button alt tag every time the textbox loses focus. Instead, you could also listen to key strokes and update after every one.
As far as updateing the query string, I'll let you figure out the best way. I can see putting a placeholder in there like: &TB=TB\_PLACEHOLDER. Then you can just do a string replace. |
257,801 | Here's the scenario:
I have a textbox and a button on a web page. When the button is clicked, I want a popup window to open (using Thickbox) that will show all items that match the value entered in the textbox. I am currently using the IFrame implementation of Thickbox. The problem is that the URL to show is hardcoded into the "alt' attribute of the button. What I really need is for the "alt" attribute to pass along the value in the textbox to the popup.
Here is the code so far:
```
<input type="textbox" id="tb" />
<input alt="Search.aspx?KeepThis=true&TB_iframe=true&height=500&width=700" class="thickbox" title="Search" type="button" value="Search" />
```
Ideally, I would like to put the textbox value into the Search.aspx url but I can't seem to figure out how to do that. My current alternative is to use jQuery to set the click function of the Search button to call a web service that will set some values in the ASP.NET session. The Search.aspx page will then use the session variables to do the search. However, this is a bit flaky since it seems like there will always be the possibility that the search executes before the session variables are set. | 2008/11/03 | [
"https://Stackoverflow.com/questions/257801",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1574/"
] | Just handle the onclick of your button to run a function that calls `tb_show()`, passing the value of the text box. Something like
```
... onclick = "doSearch()" ...
function doSearch()
{
tb_show(caption, 'Search.aspx?KeepThis=true&q=\"' +
$('input#tb').val() +
'\"&TB_iframe=true&height=500&width=700');
}
``` | In the [code-behind](http://en.wiktionary.org/wiki/code-behind) you could also just add the alt tag progammatically,
```
button1.Attributes.Add("alt", "Search.aspx?KeepThis=true&TB_iframe=true&height=500&width=700");
``` |
257,801 | Here's the scenario:
I have a textbox and a button on a web page. When the button is clicked, I want a popup window to open (using Thickbox) that will show all items that match the value entered in the textbox. I am currently using the IFrame implementation of Thickbox. The problem is that the URL to show is hardcoded into the "alt' attribute of the button. What I really need is for the "alt" attribute to pass along the value in the textbox to the popup.
Here is the code so far:
```
<input type="textbox" id="tb" />
<input alt="Search.aspx?KeepThis=true&TB_iframe=true&height=500&width=700" class="thickbox" title="Search" type="button" value="Search" />
```
Ideally, I would like to put the textbox value into the Search.aspx url but I can't seem to figure out how to do that. My current alternative is to use jQuery to set the click function of the Search button to call a web service that will set some values in the ASP.NET session. The Search.aspx page will then use the session variables to do the search. However, this is a bit flaky since it seems like there will always be the possibility that the search executes before the session variables are set. | 2008/11/03 | [
"https://Stackoverflow.com/questions/257801",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1574/"
] | Just handle the onclick of your button to run a function that calls `tb_show()`, passing the value of the text box. Something like
```
... onclick = "doSearch()" ...
function doSearch()
{
tb_show(caption, 'Search.aspx?KeepThis=true&q=\"' +
$('input#tb').val() +
'\"&TB_iframe=true&height=500&width=700');
}
``` | If you read the manual, under the iframe content section, it tells you that your parameters need to go before the TB\_iframe parameter. Everything after this gets stripped off. |
257,801 | Here's the scenario:
I have a textbox and a button on a web page. When the button is clicked, I want a popup window to open (using Thickbox) that will show all items that match the value entered in the textbox. I am currently using the IFrame implementation of Thickbox. The problem is that the URL to show is hardcoded into the "alt' attribute of the button. What I really need is for the "alt" attribute to pass along the value in the textbox to the popup.
Here is the code so far:
```
<input type="textbox" id="tb" />
<input alt="Search.aspx?KeepThis=true&TB_iframe=true&height=500&width=700" class="thickbox" title="Search" type="button" value="Search" />
```
Ideally, I would like to put the textbox value into the Search.aspx url but I can't seem to figure out how to do that. My current alternative is to use jQuery to set the click function of the Search button to call a web service that will set some values in the ASP.NET session. The Search.aspx page will then use the session variables to do the search. However, this is a bit flaky since it seems like there will always be the possibility that the search executes before the session variables are set. | 2008/11/03 | [
"https://Stackoverflow.com/questions/257801",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1574/"
] | If you read the manual, under the iframe content section, it tells you that your parameters need to go before the TB\_iframe parameter. Everything after this gets stripped off. | In the [code-behind](http://en.wiktionary.org/wiki/code-behind) you could also just add the alt tag progammatically,
```
button1.Attributes.Add("alt", "Search.aspx?KeepThis=true&TB_iframe=true&height=500&width=700");
``` |
656,524 | I have a personal project I've been working on in my spare time. It's far from complete, but I want feedback on the UI and the functionality that has made it in so far. Where is a good location to get useful feedback without being persecuted for the post being unrelated to the site's purpose?
The project is a website. I'm not posting a link so people don't think this is spam. Will add a link if comments so request. | 2009/03/18 | [
"https://Stackoverflow.com/questions/656524",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11112/"
] | I would recommend asking for a review of your site on [Hacker News](http://news.ycombinator.com/news). This site was created and maintained by [Paul Graham](http://en.wikipedia.org/wiki/Paul_Graham) who also founded [Y Combinator](http://en.wikipedia.org/wiki/Y_Combinator), a company focused on helping startups in their early stages. As a result, Hacker News is read by a community heavily focused on anything startup-related and, therefore, are very receptive to critiquing and reviewing new sites.
When you [submit your review request](http://news.ycombinator.com/submit), you probably should word the title of your post as such:
>
> Ask HN: please review my site [my
> site]
>
>
>
and describe a bit of its intent.
(Here is a recent example: [Ask HN: Review my newest site](http://news.ycombinator.com/item?id=491556)) | I think the Business of Software forums are a good place for this.
[Joel on Software discussions](http://discuss.joelonsoftware.com/?biz) |
656,524 | I have a personal project I've been working on in my spare time. It's far from complete, but I want feedback on the UI and the functionality that has made it in so far. Where is a good location to get useful feedback without being persecuted for the post being unrelated to the site's purpose?
The project is a website. I'm not posting a link so people don't think this is spam. Will add a link if comments so request. | 2009/03/18 | [
"https://Stackoverflow.com/questions/656524",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11112/"
] | I think the Business of Software forums are a good place for this.
[Joel on Software discussions](http://discuss.joelonsoftware.com/?biz) | I would also suggest you to add a [feedback form](http://userthought.com/information/fully_customizable_feedback_form) with content highlighting feature to your website.
All the functionality requires a change of only 1 line of HTML.
**Content Highlighting** feature will allow your users to select exactly what they want to describe or point to against a feedback message.
**Rich Feedback Analytics** will help you to understand what your users want from your service.
Hope this helps. |
656,524 | I have a personal project I've been working on in my spare time. It's far from complete, but I want feedback on the UI and the functionality that has made it in so far. Where is a good location to get useful feedback without being persecuted for the post being unrelated to the site's purpose?
The project is a website. I'm not posting a link so people don't think this is spam. Will add a link if comments so request. | 2009/03/18 | [
"https://Stackoverflow.com/questions/656524",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11112/"
] | I would recommend asking for a review of your site on [Hacker News](http://news.ycombinator.com/news). This site was created and maintained by [Paul Graham](http://en.wikipedia.org/wiki/Paul_Graham) who also founded [Y Combinator](http://en.wikipedia.org/wiki/Y_Combinator), a company focused on helping startups in their early stages. As a result, Hacker News is read by a community heavily focused on anything startup-related and, therefore, are very receptive to critiquing and reviewing new sites.
When you [submit your review request](http://news.ycombinator.com/submit), you probably should word the title of your post as such:
>
> Ask HN: please review my site [my
> site]
>
>
>
and describe a bit of its intent.
(Here is a recent example: [Ask HN: Review my newest site](http://news.ycombinator.com/item?id=491556)) | I would also suggest you to add a [feedback form](http://userthought.com/information/fully_customizable_feedback_form) with content highlighting feature to your website.
All the functionality requires a change of only 1 line of HTML.
**Content Highlighting** feature will allow your users to select exactly what they want to describe or point to against a feedback message.
**Rich Feedback Analytics** will help you to understand what your users want from your service.
Hope this helps. |
807,892 | I need to create a block of unique lines to test a different project I am working on.
So I created a simple program to generate a random string of X length.
The issue is that if I call it once, I get a random string, if I call it again (in a for loop for example) I get the same string for the entire execution of the loop.
I have a feeling that it's being cached or something but I didn't know .net did that and I am just confused at this point.
**calling code:**
```
StreamWriter SW = new StreamWriter("c:\\test.txt");
int x = 100;
while (x >0)
{
SW.WriteLine(RandomString(20));
x--;
}
```
**here is the method:**
```
private static string RandomString(int Length)
{
StringBuilder sb = new StringBuilder();
Random randomNumber = new Random();
for (int i = 0; i <= Length; ++i)
{
int x = randomNumber.Next(65, 122);
sb.Append(Convert.ToChar(x));
}
return sb.ToString();
}
```
**and here is the output:**
```
"VEWMCQ`Fw]TvSFQawYnoB
VEWMCQ`Fw]TvSFQawYnoB
VEWMCQ`Fw]TvSFQawYnoB
VEWMCQ`Fw]TvSFQawYnoB
VEWMCQ`Fw]TvSFQawYnoB
VEWMCQ`Fw]TvSFQawYnoB
..................
VEWMCQ`Fw]TvSFQawYnoB
VEWMCQ`Fw]TvSFQawYnoB
VEWMCQ`Fw]TvSFQawYnoB
VEWMCQ`Fw]TvSFQawYnoB
VEWMCQ`Fw]TvSFQawYnoB"
```
So what gives i thought Random.next() would always return a new random number? | 2009/04/30 | [
"https://Stackoverflow.com/questions/807892",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/72136/"
] | Similar question, lots of answers:
[random string generation - two generated one after another give same results](https://stackoverflow.com/questions/376344/random-string-generation-two-generated-one-after-another-give-same-results) | the seed for the random numbers are all the same due to the short amount of time it takes, in effect you recreate the random generator with the same seed every time, so the Next() call returns the same random value. |
807,892 | I need to create a block of unique lines to test a different project I am working on.
So I created a simple program to generate a random string of X length.
The issue is that if I call it once, I get a random string, if I call it again (in a for loop for example) I get the same string for the entire execution of the loop.
I have a feeling that it's being cached or something but I didn't know .net did that and I am just confused at this point.
**calling code:**
```
StreamWriter SW = new StreamWriter("c:\\test.txt");
int x = 100;
while (x >0)
{
SW.WriteLine(RandomString(20));
x--;
}
```
**here is the method:**
```
private static string RandomString(int Length)
{
StringBuilder sb = new StringBuilder();
Random randomNumber = new Random();
for (int i = 0; i <= Length; ++i)
{
int x = randomNumber.Next(65, 122);
sb.Append(Convert.ToChar(x));
}
return sb.ToString();
}
```
**and here is the output:**
```
"VEWMCQ`Fw]TvSFQawYnoB
VEWMCQ`Fw]TvSFQawYnoB
VEWMCQ`Fw]TvSFQawYnoB
VEWMCQ`Fw]TvSFQawYnoB
VEWMCQ`Fw]TvSFQawYnoB
VEWMCQ`Fw]TvSFQawYnoB
..................
VEWMCQ`Fw]TvSFQawYnoB
VEWMCQ`Fw]TvSFQawYnoB
VEWMCQ`Fw]TvSFQawYnoB
VEWMCQ`Fw]TvSFQawYnoB
VEWMCQ`Fw]TvSFQawYnoB"
```
So what gives i thought Random.next() would always return a new random number? | 2009/04/30 | [
"https://Stackoverflow.com/questions/807892",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/72136/"
] | Because you create a new Random object in each call.
Simply move the randomNumber out of the method and make it a class member.
```
private Random randomNumber = new Random();
private static string RandomString(int Length)
{
StringBuilder sb = new StringBuilder();
//...
}
```
All software Random generators are 'pseudo random' , they produce a sequence of numbers bases on a (starting) seed. With the same seed they produce the same sequence. Sometimes this is usefull. If you want to produce your program to produce the same sequence on each run, you can use `new Random(0)`.
Edit: apparently the .Net Random class is auto-seeding, I didn't know that. So it is a timing problem, as others have pointed out. | the seed for the random numbers are all the same due to the short amount of time it takes, in effect you recreate the random generator with the same seed every time, so the Next() call returns the same random value. |
807,892 | I need to create a block of unique lines to test a different project I am working on.
So I created a simple program to generate a random string of X length.
The issue is that if I call it once, I get a random string, if I call it again (in a for loop for example) I get the same string for the entire execution of the loop.
I have a feeling that it's being cached or something but I didn't know .net did that and I am just confused at this point.
**calling code:**
```
StreamWriter SW = new StreamWriter("c:\\test.txt");
int x = 100;
while (x >0)
{
SW.WriteLine(RandomString(20));
x--;
}
```
**here is the method:**
```
private static string RandomString(int Length)
{
StringBuilder sb = new StringBuilder();
Random randomNumber = new Random();
for (int i = 0; i <= Length; ++i)
{
int x = randomNumber.Next(65, 122);
sb.Append(Convert.ToChar(x));
}
return sb.ToString();
}
```
**and here is the output:**
```
"VEWMCQ`Fw]TvSFQawYnoB
VEWMCQ`Fw]TvSFQawYnoB
VEWMCQ`Fw]TvSFQawYnoB
VEWMCQ`Fw]TvSFQawYnoB
VEWMCQ`Fw]TvSFQawYnoB
VEWMCQ`Fw]TvSFQawYnoB
..................
VEWMCQ`Fw]TvSFQawYnoB
VEWMCQ`Fw]TvSFQawYnoB
VEWMCQ`Fw]TvSFQawYnoB
VEWMCQ`Fw]TvSFQawYnoB
VEWMCQ`Fw]TvSFQawYnoB"
```
So what gives i thought Random.next() would always return a new random number? | 2009/04/30 | [
"https://Stackoverflow.com/questions/807892",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/72136/"
] | You are creating the `Random` instances too close in time. Each instance is initialised using the system clock, and as the clock haven't changed you get the same sequence of random numbers over and over.
Create a single instance of the `Random` class and use it over and over.
Use the `using` keyword so that the `StreamWriter` is closed and disposed when you are done with it. The code for a loop is easier to recognise if you use the `for` keyword.
```
using (StreamWriter SW = new StreamWriter("c:\\test.txt")) {
Random rnd = new Random();
for (int x = 100; x > 0; x--) {
SW.WriteLine(RandomString(rnd, 20));
}
}
```
The method takes the `Random` object as a parameter.
Also, use the length to initialise the StringBuilder with the correct capacity, so that it doesn't have to reallocate during the loop. Use the < operator instead of <= in the loop, otherwise you will create a string that is one character longer than the `length` parameter specifies.
```
private static string RandomString(Random rnd, int length) {
StringBuilder sb = new StringBuilder(length);
for (int i = 0; i < length; i++) {
int x = rnd.Next(65, 122);
sb.Append((char)x);
}
return sb.ToString();
}
``` | Similar question, lots of answers:
[random string generation - two generated one after another give same results](https://stackoverflow.com/questions/376344/random-string-generation-two-generated-one-after-another-give-same-results) |
807,892 | I need to create a block of unique lines to test a different project I am working on.
So I created a simple program to generate a random string of X length.
The issue is that if I call it once, I get a random string, if I call it again (in a for loop for example) I get the same string for the entire execution of the loop.
I have a feeling that it's being cached or something but I didn't know .net did that and I am just confused at this point.
**calling code:**
```
StreamWriter SW = new StreamWriter("c:\\test.txt");
int x = 100;
while (x >0)
{
SW.WriteLine(RandomString(20));
x--;
}
```
**here is the method:**
```
private static string RandomString(int Length)
{
StringBuilder sb = new StringBuilder();
Random randomNumber = new Random();
for (int i = 0; i <= Length; ++i)
{
int x = randomNumber.Next(65, 122);
sb.Append(Convert.ToChar(x));
}
return sb.ToString();
}
```
**and here is the output:**
```
"VEWMCQ`Fw]TvSFQawYnoB
VEWMCQ`Fw]TvSFQawYnoB
VEWMCQ`Fw]TvSFQawYnoB
VEWMCQ`Fw]TvSFQawYnoB
VEWMCQ`Fw]TvSFQawYnoB
VEWMCQ`Fw]TvSFQawYnoB
..................
VEWMCQ`Fw]TvSFQawYnoB
VEWMCQ`Fw]TvSFQawYnoB
VEWMCQ`Fw]TvSFQawYnoB
VEWMCQ`Fw]TvSFQawYnoB
VEWMCQ`Fw]TvSFQawYnoB"
```
So what gives i thought Random.next() would always return a new random number? | 2009/04/30 | [
"https://Stackoverflow.com/questions/807892",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/72136/"
] | You are creating the `Random` instances too close in time. Each instance is initialised using the system clock, and as the clock haven't changed you get the same sequence of random numbers over and over.
Create a single instance of the `Random` class and use it over and over.
Use the `using` keyword so that the `StreamWriter` is closed and disposed when you are done with it. The code for a loop is easier to recognise if you use the `for` keyword.
```
using (StreamWriter SW = new StreamWriter("c:\\test.txt")) {
Random rnd = new Random();
for (int x = 100; x > 0; x--) {
SW.WriteLine(RandomString(rnd, 20));
}
}
```
The method takes the `Random` object as a parameter.
Also, use the length to initialise the StringBuilder with the correct capacity, so that it doesn't have to reallocate during the loop. Use the < operator instead of <= in the loop, otherwise you will create a string that is one character longer than the `length` parameter specifies.
```
private static string RandomString(Random rnd, int length) {
StringBuilder sb = new StringBuilder(length);
for (int i = 0; i < length; i++) {
int x = rnd.Next(65, 122);
sb.Append((char)x);
}
return sb.ToString();
}
``` | See [Random constructor description](http://msdn.microsoft.com/en-us/library/h343ddh9.aspx) at MSN, this part:
>
> The default seed value is derived from
> the system clock and has finite
> resolution. As a result, different
> Random objects that are created in
> close succession by a call to the
> default constructor will have
> identical default seed values and,
> therefore, will produce identical sets
> of random numbers.
>
>
>
So either call the Random() constructor only once at the beginning of your program or use the Random(int32) constructor and define a varying seed yourself. |
807,892 | I need to create a block of unique lines to test a different project I am working on.
So I created a simple program to generate a random string of X length.
The issue is that if I call it once, I get a random string, if I call it again (in a for loop for example) I get the same string for the entire execution of the loop.
I have a feeling that it's being cached or something but I didn't know .net did that and I am just confused at this point.
**calling code:**
```
StreamWriter SW = new StreamWriter("c:\\test.txt");
int x = 100;
while (x >0)
{
SW.WriteLine(RandomString(20));
x--;
}
```
**here is the method:**
```
private static string RandomString(int Length)
{
StringBuilder sb = new StringBuilder();
Random randomNumber = new Random();
for (int i = 0; i <= Length; ++i)
{
int x = randomNumber.Next(65, 122);
sb.Append(Convert.ToChar(x));
}
return sb.ToString();
}
```
**and here is the output:**
```
"VEWMCQ`Fw]TvSFQawYnoB
VEWMCQ`Fw]TvSFQawYnoB
VEWMCQ`Fw]TvSFQawYnoB
VEWMCQ`Fw]TvSFQawYnoB
VEWMCQ`Fw]TvSFQawYnoB
VEWMCQ`Fw]TvSFQawYnoB
..................
VEWMCQ`Fw]TvSFQawYnoB
VEWMCQ`Fw]TvSFQawYnoB
VEWMCQ`Fw]TvSFQawYnoB
VEWMCQ`Fw]TvSFQawYnoB
VEWMCQ`Fw]TvSFQawYnoB"
```
So what gives i thought Random.next() would always return a new random number? | 2009/04/30 | [
"https://Stackoverflow.com/questions/807892",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/72136/"
] | See [Random constructor description](http://msdn.microsoft.com/en-us/library/h343ddh9.aspx) at MSN, this part:
>
> The default seed value is derived from
> the system clock and has finite
> resolution. As a result, different
> Random objects that are created in
> close succession by a call to the
> default constructor will have
> identical default seed values and,
> therefore, will produce identical sets
> of random numbers.
>
>
>
So either call the Random() constructor only once at the beginning of your program or use the Random(int32) constructor and define a varying seed yourself. | Similar question, lots of answers:
[random string generation - two generated one after another give same results](https://stackoverflow.com/questions/376344/random-string-generation-two-generated-one-after-another-give-same-results) |
807,892 | I need to create a block of unique lines to test a different project I am working on.
So I created a simple program to generate a random string of X length.
The issue is that if I call it once, I get a random string, if I call it again (in a for loop for example) I get the same string for the entire execution of the loop.
I have a feeling that it's being cached or something but I didn't know .net did that and I am just confused at this point.
**calling code:**
```
StreamWriter SW = new StreamWriter("c:\\test.txt");
int x = 100;
while (x >0)
{
SW.WriteLine(RandomString(20));
x--;
}
```
**here is the method:**
```
private static string RandomString(int Length)
{
StringBuilder sb = new StringBuilder();
Random randomNumber = new Random();
for (int i = 0; i <= Length; ++i)
{
int x = randomNumber.Next(65, 122);
sb.Append(Convert.ToChar(x));
}
return sb.ToString();
}
```
**and here is the output:**
```
"VEWMCQ`Fw]TvSFQawYnoB
VEWMCQ`Fw]TvSFQawYnoB
VEWMCQ`Fw]TvSFQawYnoB
VEWMCQ`Fw]TvSFQawYnoB
VEWMCQ`Fw]TvSFQawYnoB
VEWMCQ`Fw]TvSFQawYnoB
..................
VEWMCQ`Fw]TvSFQawYnoB
VEWMCQ`Fw]TvSFQawYnoB
VEWMCQ`Fw]TvSFQawYnoB
VEWMCQ`Fw]TvSFQawYnoB
VEWMCQ`Fw]TvSFQawYnoB"
```
So what gives i thought Random.next() would always return a new random number? | 2009/04/30 | [
"https://Stackoverflow.com/questions/807892",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/72136/"
] | See [Random constructor description](http://msdn.microsoft.com/en-us/library/h343ddh9.aspx) at MSN, this part:
>
> The default seed value is derived from
> the system clock and has finite
> resolution. As a result, different
> Random objects that are created in
> close succession by a call to the
> default constructor will have
> identical default seed values and,
> therefore, will produce identical sets
> of random numbers.
>
>
>
So either call the Random() constructor only once at the beginning of your program or use the Random(int32) constructor and define a varying seed yourself. | only declare randomNumber once
```
public class MyClass
{
private static Random randomNumber = new Random();
private static string RandomString(int Length)
{
StringBuilder sb = new StringBuilder();
for (int i = 0; i ... Length; ++i)
{
int x = MyClass.randomNumber.Next(65, 122);
sb.Append(Convert.ToChar(x));
}
return sb.ToString();
}
}
``` |
807,892 | I need to create a block of unique lines to test a different project I am working on.
So I created a simple program to generate a random string of X length.
The issue is that if I call it once, I get a random string, if I call it again (in a for loop for example) I get the same string for the entire execution of the loop.
I have a feeling that it's being cached or something but I didn't know .net did that and I am just confused at this point.
**calling code:**
```
StreamWriter SW = new StreamWriter("c:\\test.txt");
int x = 100;
while (x >0)
{
SW.WriteLine(RandomString(20));
x--;
}
```
**here is the method:**
```
private static string RandomString(int Length)
{
StringBuilder sb = new StringBuilder();
Random randomNumber = new Random();
for (int i = 0; i <= Length; ++i)
{
int x = randomNumber.Next(65, 122);
sb.Append(Convert.ToChar(x));
}
return sb.ToString();
}
```
**and here is the output:**
```
"VEWMCQ`Fw]TvSFQawYnoB
VEWMCQ`Fw]TvSFQawYnoB
VEWMCQ`Fw]TvSFQawYnoB
VEWMCQ`Fw]TvSFQawYnoB
VEWMCQ`Fw]TvSFQawYnoB
VEWMCQ`Fw]TvSFQawYnoB
..................
VEWMCQ`Fw]TvSFQawYnoB
VEWMCQ`Fw]TvSFQawYnoB
VEWMCQ`Fw]TvSFQawYnoB
VEWMCQ`Fw]TvSFQawYnoB
VEWMCQ`Fw]TvSFQawYnoB"
```
So what gives i thought Random.next() would always return a new random number? | 2009/04/30 | [
"https://Stackoverflow.com/questions/807892",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/72136/"
] | See [Random constructor description](http://msdn.microsoft.com/en-us/library/h343ddh9.aspx) at MSN, this part:
>
> The default seed value is derived from
> the system clock and has finite
> resolution. As a result, different
> Random objects that are created in
> close succession by a call to the
> default constructor will have
> identical default seed values and,
> therefore, will produce identical sets
> of random numbers.
>
>
>
So either call the Random() constructor only once at the beginning of your program or use the Random(int32) constructor and define a varying seed yourself. | the seed for the random numbers are all the same due to the short amount of time it takes, in effect you recreate the random generator with the same seed every time, so the Next() call returns the same random value. |
807,892 | I need to create a block of unique lines to test a different project I am working on.
So I created a simple program to generate a random string of X length.
The issue is that if I call it once, I get a random string, if I call it again (in a for loop for example) I get the same string for the entire execution of the loop.
I have a feeling that it's being cached or something but I didn't know .net did that and I am just confused at this point.
**calling code:**
```
StreamWriter SW = new StreamWriter("c:\\test.txt");
int x = 100;
while (x >0)
{
SW.WriteLine(RandomString(20));
x--;
}
```
**here is the method:**
```
private static string RandomString(int Length)
{
StringBuilder sb = new StringBuilder();
Random randomNumber = new Random();
for (int i = 0; i <= Length; ++i)
{
int x = randomNumber.Next(65, 122);
sb.Append(Convert.ToChar(x));
}
return sb.ToString();
}
```
**and here is the output:**
```
"VEWMCQ`Fw]TvSFQawYnoB
VEWMCQ`Fw]TvSFQawYnoB
VEWMCQ`Fw]TvSFQawYnoB
VEWMCQ`Fw]TvSFQawYnoB
VEWMCQ`Fw]TvSFQawYnoB
VEWMCQ`Fw]TvSFQawYnoB
..................
VEWMCQ`Fw]TvSFQawYnoB
VEWMCQ`Fw]TvSFQawYnoB
VEWMCQ`Fw]TvSFQawYnoB
VEWMCQ`Fw]TvSFQawYnoB
VEWMCQ`Fw]TvSFQawYnoB"
```
So what gives i thought Random.next() would always return a new random number? | 2009/04/30 | [
"https://Stackoverflow.com/questions/807892",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/72136/"
] | You are creating the `Random` instances too close in time. Each instance is initialised using the system clock, and as the clock haven't changed you get the same sequence of random numbers over and over.
Create a single instance of the `Random` class and use it over and over.
Use the `using` keyword so that the `StreamWriter` is closed and disposed when you are done with it. The code for a loop is easier to recognise if you use the `for` keyword.
```
using (StreamWriter SW = new StreamWriter("c:\\test.txt")) {
Random rnd = new Random();
for (int x = 100; x > 0; x--) {
SW.WriteLine(RandomString(rnd, 20));
}
}
```
The method takes the `Random` object as a parameter.
Also, use the length to initialise the StringBuilder with the correct capacity, so that it doesn't have to reallocate during the loop. Use the < operator instead of <= in the loop, otherwise you will create a string that is one character longer than the `length` parameter specifies.
```
private static string RandomString(Random rnd, int length) {
StringBuilder sb = new StringBuilder(length);
for (int i = 0; i < length; i++) {
int x = rnd.Next(65, 122);
sb.Append((char)x);
}
return sb.ToString();
}
``` | only declare randomNumber once
```
public class MyClass
{
private static Random randomNumber = new Random();
private static string RandomString(int Length)
{
StringBuilder sb = new StringBuilder();
for (int i = 0; i ... Length; ++i)
{
int x = MyClass.randomNumber.Next(65, 122);
sb.Append(Convert.ToChar(x));
}
return sb.ToString();
}
}
``` |
807,892 | I need to create a block of unique lines to test a different project I am working on.
So I created a simple program to generate a random string of X length.
The issue is that if I call it once, I get a random string, if I call it again (in a for loop for example) I get the same string for the entire execution of the loop.
I have a feeling that it's being cached or something but I didn't know .net did that and I am just confused at this point.
**calling code:**
```
StreamWriter SW = new StreamWriter("c:\\test.txt");
int x = 100;
while (x >0)
{
SW.WriteLine(RandomString(20));
x--;
}
```
**here is the method:**
```
private static string RandomString(int Length)
{
StringBuilder sb = new StringBuilder();
Random randomNumber = new Random();
for (int i = 0; i <= Length; ++i)
{
int x = randomNumber.Next(65, 122);
sb.Append(Convert.ToChar(x));
}
return sb.ToString();
}
```
**and here is the output:**
```
"VEWMCQ`Fw]TvSFQawYnoB
VEWMCQ`Fw]TvSFQawYnoB
VEWMCQ`Fw]TvSFQawYnoB
VEWMCQ`Fw]TvSFQawYnoB
VEWMCQ`Fw]TvSFQawYnoB
VEWMCQ`Fw]TvSFQawYnoB
..................
VEWMCQ`Fw]TvSFQawYnoB
VEWMCQ`Fw]TvSFQawYnoB
VEWMCQ`Fw]TvSFQawYnoB
VEWMCQ`Fw]TvSFQawYnoB
VEWMCQ`Fw]TvSFQawYnoB"
```
So what gives i thought Random.next() would always return a new random number? | 2009/04/30 | [
"https://Stackoverflow.com/questions/807892",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/72136/"
] | You are creating the `Random` instances too close in time. Each instance is initialised using the system clock, and as the clock haven't changed you get the same sequence of random numbers over and over.
Create a single instance of the `Random` class and use it over and over.
Use the `using` keyword so that the `StreamWriter` is closed and disposed when you are done with it. The code for a loop is easier to recognise if you use the `for` keyword.
```
using (StreamWriter SW = new StreamWriter("c:\\test.txt")) {
Random rnd = new Random();
for (int x = 100; x > 0; x--) {
SW.WriteLine(RandomString(rnd, 20));
}
}
```
The method takes the `Random` object as a parameter.
Also, use the length to initialise the StringBuilder with the correct capacity, so that it doesn't have to reallocate during the loop. Use the < operator instead of <= in the loop, otherwise you will create a string that is one character longer than the `length` parameter specifies.
```
private static string RandomString(Random rnd, int length) {
StringBuilder sb = new StringBuilder(length);
for (int i = 0; i < length; i++) {
int x = rnd.Next(65, 122);
sb.Append((char)x);
}
return sb.ToString();
}
``` | Because you create a new Random object in each call.
Simply move the randomNumber out of the method and make it a class member.
```
private Random randomNumber = new Random();
private static string RandomString(int Length)
{
StringBuilder sb = new StringBuilder();
//...
}
```
All software Random generators are 'pseudo random' , they produce a sequence of numbers bases on a (starting) seed. With the same seed they produce the same sequence. Sometimes this is usefull. If you want to produce your program to produce the same sequence on each run, you can use `new Random(0)`.
Edit: apparently the .Net Random class is auto-seeding, I didn't know that. So it is a timing problem, as others have pointed out. |
807,892 | I need to create a block of unique lines to test a different project I am working on.
So I created a simple program to generate a random string of X length.
The issue is that if I call it once, I get a random string, if I call it again (in a for loop for example) I get the same string for the entire execution of the loop.
I have a feeling that it's being cached or something but I didn't know .net did that and I am just confused at this point.
**calling code:**
```
StreamWriter SW = new StreamWriter("c:\\test.txt");
int x = 100;
while (x >0)
{
SW.WriteLine(RandomString(20));
x--;
}
```
**here is the method:**
```
private static string RandomString(int Length)
{
StringBuilder sb = new StringBuilder();
Random randomNumber = new Random();
for (int i = 0; i <= Length; ++i)
{
int x = randomNumber.Next(65, 122);
sb.Append(Convert.ToChar(x));
}
return sb.ToString();
}
```
**and here is the output:**
```
"VEWMCQ`Fw]TvSFQawYnoB
VEWMCQ`Fw]TvSFQawYnoB
VEWMCQ`Fw]TvSFQawYnoB
VEWMCQ`Fw]TvSFQawYnoB
VEWMCQ`Fw]TvSFQawYnoB
VEWMCQ`Fw]TvSFQawYnoB
..................
VEWMCQ`Fw]TvSFQawYnoB
VEWMCQ`Fw]TvSFQawYnoB
VEWMCQ`Fw]TvSFQawYnoB
VEWMCQ`Fw]TvSFQawYnoB
VEWMCQ`Fw]TvSFQawYnoB"
```
So what gives i thought Random.next() would always return a new random number? | 2009/04/30 | [
"https://Stackoverflow.com/questions/807892",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/72136/"
] | You are creating the `Random` instances too close in time. Each instance is initialised using the system clock, and as the clock haven't changed you get the same sequence of random numbers over and over.
Create a single instance of the `Random` class and use it over and over.
Use the `using` keyword so that the `StreamWriter` is closed and disposed when you are done with it. The code for a loop is easier to recognise if you use the `for` keyword.
```
using (StreamWriter SW = new StreamWriter("c:\\test.txt")) {
Random rnd = new Random();
for (int x = 100; x > 0; x--) {
SW.WriteLine(RandomString(rnd, 20));
}
}
```
The method takes the `Random` object as a parameter.
Also, use the length to initialise the StringBuilder with the correct capacity, so that it doesn't have to reallocate during the loop. Use the < operator instead of <= in the loop, otherwise you will create a string that is one character longer than the `length` parameter specifies.
```
private static string RandomString(Random rnd, int length) {
StringBuilder sb = new StringBuilder(length);
for (int i = 0; i < length; i++) {
int x = rnd.Next(65, 122);
sb.Append((char)x);
}
return sb.ToString();
}
``` | the seed for the random numbers are all the same due to the short amount of time it takes, in effect you recreate the random generator with the same seed every time, so the Next() call returns the same random value. |
337,702 | I wonder how can I write a ***catch'em all*** exception handler in the application level which will give the user the option to resume the application flow? | 2008/12/03 | [
"https://Stackoverflow.com/questions/337702",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | If you are running a Windows Forms application: add a handler to the `Application.ThreadException` event. | It depends on what you mean by "resume". The trouble with exceptions is that unless you're *very* careful, by the time an exception happens your application state is quite possibly corrupt - you might have completed *half* an operation.
If you can isolate your operations - much like a database isolates transactions - then you can effectively let your user resume from the "last commit point". That will very much depend on the type of your application though. Could you give us more details about the kind of application you're building? |
337,702 | I wonder how can I write a ***catch'em all*** exception handler in the application level which will give the user the option to resume the application flow? | 2008/12/03 | [
"https://Stackoverflow.com/questions/337702",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | Use below code in your program.cs class. It will automatically Send mail when exception occurs.
```
using System;
using System.Windows.Forms;
using System.Net;
using System.Net.Mail;
using System.Threading;
namespace ExceptionHandlerTest
{
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.ThreadException +=
new ThreadExceptionEventHandler(Application_ThreadException);
// Your designer generated commands.
}
static void Application_ThreadException(object sender, ThreadExceptionEventArgs e)
{
var fromAddress = new MailAddress("your Gmail address", "Your name");
var toAddress = new MailAddress("email address where you want to receive reports", "Your name");
const string fromPassword = "your password";
const string subject = "exception report";
Exception exception = e.Exception;
string body = exception.Message + "\n" + exception.Data + "\n" + exception.StackTrace + "\n" + exception.Source;
var smtp = new SmtpClient
{
Host = "smtp.gmail.com",
Port = 587,
EnableSsl = true,
DeliveryMethod = SmtpDeliveryMethod.Network,
UseDefaultCredentials = false,
Credentials = new NetworkCredential(fromAddress.Address, fromPassword)
};
using (var message = new MailMessage(fromAddress, toAddress)
{
Subject = subject,
Body = body
})
{
//You can also use SendAsync method instead of Send so your application begin invoking instead of waiting for send mail to complete. SendAsync(MailMessage, Object) :- Sends the specified e-mail message to an SMTP server for delivery. This method does not block the calling thread and allows the caller to pass an object to the method that is invoked when the operation completes.
smtp.Send(message);
}
}
}
}
``` | In some versions of .NET you can actually put a catcher around the Application.Run() (you'll find this in program.cs) and this should catch all the Main Thread's exceptions however in most cases this maybe poor design and wont give you much of an opportunity to "resume".
Additionally you will *always* have to manually handle any exceptions on background threads.
You can design an app to "catch all" and display a common error message and debug info, this is fine as long as you exit afterwards. What is highly discouraged is making a "resume" available to the user as this will probably give you more problems in the long-run. |
337,702 | I wonder how can I write a ***catch'em all*** exception handler in the application level which will give the user the option to resume the application flow? | 2008/12/03 | [
"https://Stackoverflow.com/questions/337702",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | I assume you are writing a Windows application in which case, **yes**, you can do this. I will leave the rights and wrongs of whether or not you should to others. There are already enough answers which look at this and I suggest you **consider them carefully before you actually do this**.
Note, that this code will behave differently in the debugger than it does if you run the application directly (another reason not to do it perhaps). To get the application to show the messagebox and to continue on thereafter you will need to run the application from explorer, not from visual studio.
Create a new Windows forms application. The code in Program.cs looks something like this:
```
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Windows.Forms;
namespace WindowsFormsApplication2 {
static class Program {
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main() {
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Form1 form1 = new Form1();
Application.ThreadException += new ThreadExceptionEventHandler(form1.UnhandledThreadExceptionHandler);
Application.Run(form1);
}
}
}
```
Then make the code in Form1 look something like this:
```
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Windows.Forms;
namespace WindowsFormsApplication2 {
public partial class Form1 : Form {
public Form1() {
InitializeComponent();
}
public void UnhandledThreadExceptionHandler(object sender, ThreadExceptionEventArgs e) {
this.HandleUnhandledException(e.Exception);
}
public void HandleUnhandledException(Exception e) {
// do what you want here.
if (MessageBox.Show("An unexpected error has occurred. Continue?",
"My application", MessageBoxButtons.YesNo, MessageBoxIcon.Stop,
MessageBoxDefaultButton.Button2) == DialogResult.No) {
Application.Exit();
}
}
private void button1_Click(object sender, EventArgs e) {
throw new ApplicationException("Exception");
}
}
}
```
(Add button1 to the form and attach it button1\_Click.) | I don't think this is really feasible using a global error handler. You need to figure out what kind of errors are recoverable at different points in your application and write specific error handlers to address the errors as they occur -- unless you want to resort to application restart, which may or may not work depending on what the actual error is. In order to do any kind of resume, you'll need to save enough state to restart from a known good state. |
337,702 | I wonder how can I write a ***catch'em all*** exception handler in the application level which will give the user the option to resume the application flow? | 2008/12/03 | [
"https://Stackoverflow.com/questions/337702",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | I assume you are writing a Windows application in which case, **yes**, you can do this. I will leave the rights and wrongs of whether or not you should to others. There are already enough answers which look at this and I suggest you **consider them carefully before you actually do this**.
Note, that this code will behave differently in the debugger than it does if you run the application directly (another reason not to do it perhaps). To get the application to show the messagebox and to continue on thereafter you will need to run the application from explorer, not from visual studio.
Create a new Windows forms application. The code in Program.cs looks something like this:
```
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Windows.Forms;
namespace WindowsFormsApplication2 {
static class Program {
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main() {
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Form1 form1 = new Form1();
Application.ThreadException += new ThreadExceptionEventHandler(form1.UnhandledThreadExceptionHandler);
Application.Run(form1);
}
}
}
```
Then make the code in Form1 look something like this:
```
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Windows.Forms;
namespace WindowsFormsApplication2 {
public partial class Form1 : Form {
public Form1() {
InitializeComponent();
}
public void UnhandledThreadExceptionHandler(object sender, ThreadExceptionEventArgs e) {
this.HandleUnhandledException(e.Exception);
}
public void HandleUnhandledException(Exception e) {
// do what you want here.
if (MessageBox.Show("An unexpected error has occurred. Continue?",
"My application", MessageBoxButtons.YesNo, MessageBoxIcon.Stop,
MessageBoxDefaultButton.Button2) == DialogResult.No) {
Application.Exit();
}
}
private void button1_Click(object sender, EventArgs e) {
throw new ApplicationException("Exception");
}
}
}
```
(Add button1 to the form and attach it button1\_Click.) | [Microsoft Enterprise Library Exception Handling Application Block](http://msdn.microsoft.com/en-us/library/ff664698(v=pandp.50).aspx) has examples of how you can do this.
Basically you surround the code that can throw exceptions with this:
```
try
{
MyMethodThatMightThrow();
}
catch(Exception ex)
{
bool rethrow = ExceptionPolicy.HandleException(ex, "SomePolicy");
if (rethrow) throw;
}
```
Then you can configure the Policy to show a dialog to the user and ask if she wants to continue.
You still need to put try catch blocks around in your code at points where you believe you are at a consistent state. |
337,702 | I wonder how can I write a ***catch'em all*** exception handler in the application level which will give the user the option to resume the application flow? | 2008/12/03 | [
"https://Stackoverflow.com/questions/337702",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | I assume you are writing a Windows application in which case, **yes**, you can do this. I will leave the rights and wrongs of whether or not you should to others. There are already enough answers which look at this and I suggest you **consider them carefully before you actually do this**.
Note, that this code will behave differently in the debugger than it does if you run the application directly (another reason not to do it perhaps). To get the application to show the messagebox and to continue on thereafter you will need to run the application from explorer, not from visual studio.
Create a new Windows forms application. The code in Program.cs looks something like this:
```
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Windows.Forms;
namespace WindowsFormsApplication2 {
static class Program {
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main() {
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Form1 form1 = new Form1();
Application.ThreadException += new ThreadExceptionEventHandler(form1.UnhandledThreadExceptionHandler);
Application.Run(form1);
}
}
}
```
Then make the code in Form1 look something like this:
```
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Windows.Forms;
namespace WindowsFormsApplication2 {
public partial class Form1 : Form {
public Form1() {
InitializeComponent();
}
public void UnhandledThreadExceptionHandler(object sender, ThreadExceptionEventArgs e) {
this.HandleUnhandledException(e.Exception);
}
public void HandleUnhandledException(Exception e) {
// do what you want here.
if (MessageBox.Show("An unexpected error has occurred. Continue?",
"My application", MessageBoxButtons.YesNo, MessageBoxIcon.Stop,
MessageBoxDefaultButton.Button2) == DialogResult.No) {
Application.Exit();
}
}
private void button1_Click(object sender, EventArgs e) {
throw new ApplicationException("Exception");
}
}
}
```
(Add button1 to the form and attach it button1\_Click.) | In some versions of .NET you can actually put a catcher around the Application.Run() (you'll find this in program.cs) and this should catch all the Main Thread's exceptions however in most cases this maybe poor design and wont give you much of an opportunity to "resume".
Additionally you will *always* have to manually handle any exceptions on background threads.
You can design an app to "catch all" and display a common error message and debug info, this is fine as long as you exit afterwards. What is highly discouraged is making a "resume" available to the user as this will probably give you more problems in the long-run. |
337,702 | I wonder how can I write a ***catch'em all*** exception handler in the application level which will give the user the option to resume the application flow? | 2008/12/03 | [
"https://Stackoverflow.com/questions/337702",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | If you are running a Windows Forms application: add a handler to the `Application.ThreadException` event. | I don't think this is really feasible using a global error handler. You need to figure out what kind of errors are recoverable at different points in your application and write specific error handlers to address the errors as they occur -- unless you want to resort to application restart, which may or may not work depending on what the actual error is. In order to do any kind of resume, you'll need to save enough state to restart from a known good state. |
337,702 | I wonder how can I write a ***catch'em all*** exception handler in the application level which will give the user the option to resume the application flow? | 2008/12/03 | [
"https://Stackoverflow.com/questions/337702",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | If you are running a Windows Forms application: add a handler to the `Application.ThreadException` event. | You should read up on all the problems associated with VB's "`On Error Resume Next`" style of error handling. It sounds like you're trying to implement this for C#.
Even if you can resume from the point of where the exception is generated, this is a broken technique for error handling. There's no way for a global handler to actually be able to handle any error/exception - it can't possibly know what's required for any arbitrary situation.
You would have to set some sort of global variable, and have the mainline code continually check it for error indications (ie., use the VB technique).
I think the best you can do to recover from an error like you're describing is to catch the exception at the application level, log the problem, inform the user (and potentially generate/send some sort of problem report for you), and restart the application. Of course, if you catch the exception closer to the problem area, that handler has a chance to do something a bit more intelligent, so you should not rely on the app-level handler as a crutch - just as a fail-safe. |
337,702 | I wonder how can I write a ***catch'em all*** exception handler in the application level which will give the user the option to resume the application flow? | 2008/12/03 | [
"https://Stackoverflow.com/questions/337702",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | I assume you are writing a Windows application in which case, **yes**, you can do this. I will leave the rights and wrongs of whether or not you should to others. There are already enough answers which look at this and I suggest you **consider them carefully before you actually do this**.
Note, that this code will behave differently in the debugger than it does if you run the application directly (another reason not to do it perhaps). To get the application to show the messagebox and to continue on thereafter you will need to run the application from explorer, not from visual studio.
Create a new Windows forms application. The code in Program.cs looks something like this:
```
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Windows.Forms;
namespace WindowsFormsApplication2 {
static class Program {
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main() {
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Form1 form1 = new Form1();
Application.ThreadException += new ThreadExceptionEventHandler(form1.UnhandledThreadExceptionHandler);
Application.Run(form1);
}
}
}
```
Then make the code in Form1 look something like this:
```
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Windows.Forms;
namespace WindowsFormsApplication2 {
public partial class Form1 : Form {
public Form1() {
InitializeComponent();
}
public void UnhandledThreadExceptionHandler(object sender, ThreadExceptionEventArgs e) {
this.HandleUnhandledException(e.Exception);
}
public void HandleUnhandledException(Exception e) {
// do what you want here.
if (MessageBox.Show("An unexpected error has occurred. Continue?",
"My application", MessageBoxButtons.YesNo, MessageBoxIcon.Stop,
MessageBoxDefaultButton.Button2) == DialogResult.No) {
Application.Exit();
}
}
private void button1_Click(object sender, EventArgs e) {
throw new ApplicationException("Exception");
}
}
}
```
(Add button1 to the form and attach it button1\_Click.) | You should read up on all the problems associated with VB's "`On Error Resume Next`" style of error handling. It sounds like you're trying to implement this for C#.
Even if you can resume from the point of where the exception is generated, this is a broken technique for error handling. There's no way for a global handler to actually be able to handle any error/exception - it can't possibly know what's required for any arbitrary situation.
You would have to set some sort of global variable, and have the mainline code continually check it for error indications (ie., use the VB technique).
I think the best you can do to recover from an error like you're describing is to catch the exception at the application level, log the problem, inform the user (and potentially generate/send some sort of problem report for you), and restart the application. Of course, if you catch the exception closer to the problem area, that handler has a chance to do something a bit more intelligent, so you should not rely on the app-level handler as a crutch - just as a fail-safe. |
337,702 | I wonder how can I write a ***catch'em all*** exception handler in the application level which will give the user the option to resume the application flow? | 2008/12/03 | [
"https://Stackoverflow.com/questions/337702",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | It depends on what you mean by "resume". The trouble with exceptions is that unless you're *very* careful, by the time an exception happens your application state is quite possibly corrupt - you might have completed *half* an operation.
If you can isolate your operations - much like a database isolates transactions - then you can effectively let your user resume from the "last commit point". That will very much depend on the type of your application though. Could you give us more details about the kind of application you're building? | I don't think this is really feasible using a global error handler. You need to figure out what kind of errors are recoverable at different points in your application and write specific error handlers to address the errors as they occur -- unless you want to resort to application restart, which may or may not work depending on what the actual error is. In order to do any kind of resume, you'll need to save enough state to restart from a known good state. |
337,702 | I wonder how can I write a ***catch'em all*** exception handler in the application level which will give the user the option to resume the application flow? | 2008/12/03 | [
"https://Stackoverflow.com/questions/337702",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | Use below code in your program.cs class. It will automatically Send mail when exception occurs.
```
using System;
using System.Windows.Forms;
using System.Net;
using System.Net.Mail;
using System.Threading;
namespace ExceptionHandlerTest
{
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.ThreadException +=
new ThreadExceptionEventHandler(Application_ThreadException);
// Your designer generated commands.
}
static void Application_ThreadException(object sender, ThreadExceptionEventArgs e)
{
var fromAddress = new MailAddress("your Gmail address", "Your name");
var toAddress = new MailAddress("email address where you want to receive reports", "Your name");
const string fromPassword = "your password";
const string subject = "exception report";
Exception exception = e.Exception;
string body = exception.Message + "\n" + exception.Data + "\n" + exception.StackTrace + "\n" + exception.Source;
var smtp = new SmtpClient
{
Host = "smtp.gmail.com",
Port = 587,
EnableSsl = true,
DeliveryMethod = SmtpDeliveryMethod.Network,
UseDefaultCredentials = false,
Credentials = new NetworkCredential(fromAddress.Address, fromPassword)
};
using (var message = new MailMessage(fromAddress, toAddress)
{
Subject = subject,
Body = body
})
{
//You can also use SendAsync method instead of Send so your application begin invoking instead of waiting for send mail to complete. SendAsync(MailMessage, Object) :- Sends the specified e-mail message to an SMTP server for delivery. This method does not block the calling thread and allows the caller to pass an object to the method that is invoked when the operation completes.
smtp.Send(message);
}
}
}
}
``` | I don't think this is really feasible using a global error handler. You need to figure out what kind of errors are recoverable at different points in your application and write specific error handlers to address the errors as they occur -- unless you want to resort to application restart, which may or may not work depending on what the actual error is. In order to do any kind of resume, you'll need to save enough state to restart from a known good state. |
2,875,279 | The related default StyleCop rules are:
1. Place `using` statements inside `namespace`.
2. Sort `using` statements alphabetically.
3. But ... `System` `using` come first (still trying to figure out if that means just `using System;` or `using System[.*];`).
So, my use case:
* I find a bug and decide that I need to at least add an intelligible Assert to make debugging less painful for the next guy. So I start typing `Debug.Assert(` and intellisense marks it in Red. I hover mouse over `Debug` and between `using System.Diagnostics;` and `System.Diagnostics.Debug` I choose the former. This inserts `using System.Diagnostics;` after all other `using` statements. It would be nice if VS2010 did not assist me in writing code that won't build due to warnings as errors.
How can I make VS2010 smarter? Is there some sort of setting, or does this require a full-fledged add-in of some sort? | 2010/05/20 | [
"https://Stackoverflow.com/questions/2875279",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/231677/"
] | For 2008, I use the [Power Commands](http://code.msdn.microsoft.com/PowerCommands) add-in. It includes a command to sort and remove unused using statements. I map that to Ctrl-O, Ctrl-R. It's not automatic, but it's very quick.
2010 has a Power Commands too, but I think the sort and order using statements stuff is now built in. You just need to set up a shortcut for it.
PS. I do not use Resharper because of the resource overhead. Every time I tell people that it thrashes my hard drive and drives memory usage through the roof, they tell me to "try the latest version - it's much better now". Suffice to say, it never has been... I do use CodeRush Xpress though. | You can make VS2010 smarter by using Resharper (www.jetbrains.com), a full-fledged add-in. It can do all of these things for you (and very much more), and is well worth the price. The Resharper add-in "StyleCop for Resharper" can even check StyleCop violations on-the-fly and underline your code the same way Visual Studio does for errors. |
2,875,279 | The related default StyleCop rules are:
1. Place `using` statements inside `namespace`.
2. Sort `using` statements alphabetically.
3. But ... `System` `using` come first (still trying to figure out if that means just `using System;` or `using System[.*];`).
So, my use case:
* I find a bug and decide that I need to at least add an intelligible Assert to make debugging less painful for the next guy. So I start typing `Debug.Assert(` and intellisense marks it in Red. I hover mouse over `Debug` and between `using System.Diagnostics;` and `System.Diagnostics.Debug` I choose the former. This inserts `using System.Diagnostics;` after all other `using` statements. It would be nice if VS2010 did not assist me in writing code that won't build due to warnings as errors.
How can I make VS2010 smarter? Is there some sort of setting, or does this require a full-fledged add-in of some sort? | 2010/05/20 | [
"https://Stackoverflow.com/questions/2875279",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/231677/"
] | With regards to your #1, you can edit the project template items by using the instructions [here](http://www.thecodinghumanist.com/Content/HowToEditVSTemplates.aspx) or [here](http://msdn.microsoft.com/en-us/library/ms185319.aspx). I've done this for VS 2K8 to make StyleCop and FxCop happy by default, but I haven't gotten around to doing it for 2010 as I find the procedure a bit tedious and there's always a likelihood that a VS service pack could overwrite them.
For instance, I edited the program.cs in the ConsoleApplication template to look like this:
```
// <copyright file="Program.cs" company="$registeredorganization$">
// Copyright (c) $year$ All Rights Reserved
// </copyright>
// <author></author>
// <email></email>
// <date>$time$</date>
// <summary></summary>
namespace $safeprojectname$
{
using System;
using System.Collections.Generic;
$if$ ($targetframeworkversion$ == 3.5)using System.Linq;
$endif$using System.Text;
/// <summary>
/// Contains the program's entry point.
/// </summary>
internal static class Program
{
/// <summary>
/// The program's entry point.
/// </summary>
/// <param name="args">The command-line arguments.</param>
private static void Main(string[] args)
{
}
}
}
```
and the assemblyinfo.cs to look like this:
```
// <copyright file="AssemblyInfo.cs" company="$registeredorganization$">
// Copyright (c) $year$ All Rights Reserved
// </copyright>
// <author></author>
// <email></email>
// <date>$time$</date>
// <summary></summary>
using System;
using System.Reflection;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("$projectname$")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("$registeredorganization$")]
[assembly: AssemblyProduct("$projectname$")]
[assembly: AssemblyCopyright("Copyright © $registeredorganization$ $year$")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
[assembly: CLSCompliant(true)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("$guid1$")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
```
I've submitted [an incident](https://connect.microsoft.com/VisualStudio/feedback/details/558675/auto-generated-code-should-conform-to-ms-recommended-style-and-not-trigger-fxcop-and-stylecop-messages) at Microsoft Connect to the effect that their tools' auto-generated code should satisfy StyleCop/FxCop and their coding guidelines documents. | You can make VS2010 smarter by using Resharper (www.jetbrains.com), a full-fledged add-in. It can do all of these things for you (and very much more), and is well worth the price. The Resharper add-in "StyleCop for Resharper" can even check StyleCop violations on-the-fly and underline your code the same way Visual Studio does for errors. |
1,039,048 | I'm working on a 4-player network game in WPF and learning WCF in the process. So far, to handle the network communication, I've followed the advice from the [YeahTrivia game on Coding4Fun](http://blogs.msdn.com/coding4fun/archive/2007/10/29/5773166.aspx) game: I use a `dualHttpBinding`, and have use a `CallbackContract` interface to send back messages to clients. It works pretty well.
However, my service is getting very large. It has methods/callbacks to handle the game itself, but also the chat system, the login/registration process, the matchmaking, the roster/player info, etc. Both the server and client are becoming hard to maintain because everything is tied into a single interface. On the client for example, I have to redirect the callbacks to either the game page, the lobby page, etc, and I find that very tedious. I'd prefer being able to handle the game callbacks on the game page, the chat callbacks on the chat window, etc.
So what's the best way to handle that? I've thought of many things, but not sure which is best: splitting the service into multiple ones, having multiple "endpoints" on my service, or is there other tricks to implement a service partially where appropriate?
Thanks | 2009/06/24 | [
"https://Stackoverflow.com/questions/1039048",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/76939/"
] | You should have multiple components, each of which should be limited to one responsibility - not necessarily one method, but handling the state for one of the objects you're dealing with. When you have everything all in one service then your service is incredibly coupled to itself. Optimally, each component should be as independent as possible.
I'd say start with splitting it up where it makes sense and things should be MUCH more manageable. | I would support Terry's response - you should definitely split up your big interface into several smaller ones.
Also, you could possibly isolate certain operations like the registration and/or login process into simpler services - not knowing anything about your game, I think this could well be a simple non-duplex service that e.g. provides a valid "player token" as its output which can then be used by the other services to authenticate the players.
Multiple smaller, leaner interfaces also give you the option to potentially create separate, dedicated front-ends (e.g. in Silverlight or something) that would target / handle just certain parts of the whole system.
Marc |
172,781 | My normal work flow to create a new repository with subversion is to create a new repos, do a checkout of the repos root, create my branches tags and trunk folders and place in the trunk my initial files. Then I do a commit of this "initial import", delete the checked out repos from my hard drive and do a checkout of the trunk. Then I can start working.
However, when dealing with a large import, think hundreds of megs, and off-site version control hosting (http based) this initial import can take quite a while to commit. What's worse, after committing I need to checkout this massive trunk all over again.
Is there a way with subversion to use the local copy of the trunk without doing a checkout all over again of data that is already there? | 2008/10/05 | [
"https://Stackoverflow.com/questions/172781",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21406/"
] | There is - it's called an "in-place import", and it's covered in the Subversion FAQ here:
<http://subversion.tigris.org/faq.html#in-place-import>
What you're really doing is creating a new empty project in the repository, checking out the empty project your local folder - which turns your folder into a working copy - and then adding all your (existing) files to that 'empty' project, so they're added to the repository when you do an svn commit. | If you've checked out a single folder, copied your files into it, run `svn add` and `svn commit`; you shouldn't need to delete the files and re-checkout.
Use the files in place: once they've been committed as you describe, they're ready to be worked on. |
172,781 | My normal work flow to create a new repository with subversion is to create a new repos, do a checkout of the repos root, create my branches tags and trunk folders and place in the trunk my initial files. Then I do a commit of this "initial import", delete the checked out repos from my hard drive and do a checkout of the trunk. Then I can start working.
However, when dealing with a large import, think hundreds of megs, and off-site version control hosting (http based) this initial import can take quite a while to commit. What's worse, after committing I need to checkout this massive trunk all over again.
Is there a way with subversion to use the local copy of the trunk without doing a checkout all over again of data that is already there? | 2008/10/05 | [
"https://Stackoverflow.com/questions/172781",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21406/"
] | I usually use "svn mkdir" to create the trunk/tags/branches directly on the server immediately after creating the repository. Then I can check out the empty trunk, move my initial files into that directory, add and commit them, and start working. | If you've checked out a single folder, copied your files into it, run `svn add` and `svn commit`; you shouldn't need to delete the files and re-checkout.
Use the files in place: once they've been committed as you describe, they're ready to be worked on. |
172,781 | My normal work flow to create a new repository with subversion is to create a new repos, do a checkout of the repos root, create my branches tags and trunk folders and place in the trunk my initial files. Then I do a commit of this "initial import", delete the checked out repos from my hard drive and do a checkout of the trunk. Then I can start working.
However, when dealing with a large import, think hundreds of megs, and off-site version control hosting (http based) this initial import can take quite a while to commit. What's worse, after committing I need to checkout this massive trunk all over again.
Is there a way with subversion to use the local copy of the trunk without doing a checkout all over again of data that is already there? | 2008/10/05 | [
"https://Stackoverflow.com/questions/172781",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21406/"
] | I agree on the "in-place import" procedure and also using a script for TTB-structure(upvoted both).
Just a small hint:
You should not import a **huge** (ten of thousands) number of files in a single commit, if you use http(s), as the time for displaying the version history *scales by the number of added entries*. The reason for this behaviour is that apache has to authenticate all added paths agains the svnaccess file(of course, only if you enabled path-based authorization). This can render your repository unusable, as all files will have to wait on a svn log for this big rev.
You should divide huge imports on directory levels | If you've checked out a single folder, copied your files into it, run `svn add` and `svn commit`; you shouldn't need to delete the files and re-checkout.
Use the files in place: once they've been committed as you describe, they're ready to be worked on. |
172,781 | My normal work flow to create a new repository with subversion is to create a new repos, do a checkout of the repos root, create my branches tags and trunk folders and place in the trunk my initial files. Then I do a commit of this "initial import", delete the checked out repos from my hard drive and do a checkout of the trunk. Then I can start working.
However, when dealing with a large import, think hundreds of megs, and off-site version control hosting (http based) this initial import can take quite a while to commit. What's worse, after committing I need to checkout this massive trunk all over again.
Is there a way with subversion to use the local copy of the trunk without doing a checkout all over again of data that is already there? | 2008/10/05 | [
"https://Stackoverflow.com/questions/172781",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21406/"
] | svn checkout --force lets you checkout a workingcopy 'over' an existing path. It keeps your old files and adds files that are only in your repository.
For creating your repository: You can perform multiple mkdir commands to a repository in a single commit using the 'svnmucc' command that is available in most Subversion distributions (e.g. [SlikSVN](http://sliksvn.com/en/download/)).
Type svnmucc without arguments for some help. | If you've checked out a single folder, copied your files into it, run `svn add` and `svn commit`; you shouldn't need to delete the files and re-checkout.
Use the files in place: once they've been committed as you describe, they're ready to be worked on. |
172,781 | My normal work flow to create a new repository with subversion is to create a new repos, do a checkout of the repos root, create my branches tags and trunk folders and place in the trunk my initial files. Then I do a commit of this "initial import", delete the checked out repos from my hard drive and do a checkout of the trunk. Then I can start working.
However, when dealing with a large import, think hundreds of megs, and off-site version control hosting (http based) this initial import can take quite a while to commit. What's worse, after committing I need to checkout this massive trunk all over again.
Is there a way with subversion to use the local copy of the trunk without doing a checkout all over again of data that is already there? | 2008/10/05 | [
"https://Stackoverflow.com/questions/172781",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21406/"
] | There is - it's called an "in-place import", and it's covered in the Subversion FAQ here:
<http://subversion.tigris.org/faq.html#in-place-import>
What you're really doing is creating a new empty project in the repository, checking out the empty project your local folder - which turns your folder into a working copy - and then adding all your (existing) files to that 'empty' project, so they're added to the repository when you do an svn commit. | I usually use "svn mkdir" to create the trunk/tags/branches directly on the server immediately after creating the repository. Then I can check out the empty trunk, move my initial files into that directory, add and commit them, and start working. |
172,781 | My normal work flow to create a new repository with subversion is to create a new repos, do a checkout of the repos root, create my branches tags and trunk folders and place in the trunk my initial files. Then I do a commit of this "initial import", delete the checked out repos from my hard drive and do a checkout of the trunk. Then I can start working.
However, when dealing with a large import, think hundreds of megs, and off-site version control hosting (http based) this initial import can take quite a while to commit. What's worse, after committing I need to checkout this massive trunk all over again.
Is there a way with subversion to use the local copy of the trunk without doing a checkout all over again of data that is already there? | 2008/10/05 | [
"https://Stackoverflow.com/questions/172781",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21406/"
] | There is - it's called an "in-place import", and it's covered in the Subversion FAQ here:
<http://subversion.tigris.org/faq.html#in-place-import>
What you're really doing is creating a new empty project in the repository, checking out the empty project your local folder - which turns your folder into a working copy - and then adding all your (existing) files to that 'empty' project, so they're added to the repository when you do an svn commit. | I agree on the "in-place import" procedure and also using a script for TTB-structure(upvoted both).
Just a small hint:
You should not import a **huge** (ten of thousands) number of files in a single commit, if you use http(s), as the time for displaying the version history *scales by the number of added entries*. The reason for this behaviour is that apache has to authenticate all added paths agains the svnaccess file(of course, only if you enabled path-based authorization). This can render your repository unusable, as all files will have to wait on a svn log for this big rev.
You should divide huge imports on directory levels |
172,781 | My normal work flow to create a new repository with subversion is to create a new repos, do a checkout of the repos root, create my branches tags and trunk folders and place in the trunk my initial files. Then I do a commit of this "initial import", delete the checked out repos from my hard drive and do a checkout of the trunk. Then I can start working.
However, when dealing with a large import, think hundreds of megs, and off-site version control hosting (http based) this initial import can take quite a while to commit. What's worse, after committing I need to checkout this massive trunk all over again.
Is there a way with subversion to use the local copy of the trunk without doing a checkout all over again of data that is already there? | 2008/10/05 | [
"https://Stackoverflow.com/questions/172781",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21406/"
] | There is - it's called an "in-place import", and it's covered in the Subversion FAQ here:
<http://subversion.tigris.org/faq.html#in-place-import>
What you're really doing is creating a new empty project in the repository, checking out the empty project your local folder - which turns your folder into a working copy - and then adding all your (existing) files to that 'empty' project, so they're added to the repository when you do an svn commit. | svn checkout --force lets you checkout a workingcopy 'over' an existing path. It keeps your old files and adds files that are only in your repository.
For creating your repository: You can perform multiple mkdir commands to a repository in a single commit using the 'svnmucc' command that is available in most Subversion distributions (e.g. [SlikSVN](http://sliksvn.com/en/download/)).
Type svnmucc without arguments for some help. |
1,083,159 | While using WPF I noticed that when I add a control to a XAML file, the default constructor is called.
Is there a way to call a parameterized constructor? | 2009/07/04 | [
"https://Stackoverflow.com/questions/1083159",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/71302/"
] | .NET 4.0 brings a new feature that challenges the answer - but apparently only for UWP applications (not WPF).
[x:Arguments Directive](https://learn.microsoft.com/en-us/dotnet/framework/xaml-services/x-arguments-directive)
```
<object ...>
<x:Arguments>
oneOrMoreObjectElements
</x:Arguments>
</object>
``` | No. Not from XAML [when using WPF]. |
1,083,159 | While using WPF I noticed that when I add a control to a XAML file, the default constructor is called.
Is there a way to call a parameterized constructor? | 2009/07/04 | [
"https://Stackoverflow.com/questions/1083159",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/71302/"
] | One of the guiding principles of XAML-friendly objects is that they should be completely usable with a default constructor, i.e., there is no behavior that is only accessible when using a non-default constructor. To fit with the declarative nature of XAML, object parameters are specified via property setters. There is also a convention that says that the order in which properties are set in XAML should not be important.
You may, however, have some special considerations that are important to your implementation but at odds with convention:
1. You may have one or more properties which *must* be set before the object can be used.
2. Two or more properties may be mutually exclusive with each other, e.g., it makes no sense to set both the `StreamSource` and `UriSource` of an image.
3. You may want to ensure that a property is *only* set during initialization.
4. One property may depend on another, which can be tricky due to the aforementioned convention of order independence when setting properties.
To make it easier to handle these cases, the `ISupportInitialize` interface is provided. When an object is read and created from XAML (i.e., parsed), objects implementing `ISupportInitialize` will be handled specially:
1. The default constructor will be called.
2. `BeginInit()` will be called.
3. Properties will be set in the order they appeared in the XAML declaration.
4. `EndInit()` is called.
By tracking calls to `BeginInit()` and `EndInit()`, you can handle whatever rules you need to impose, including the requirement that certain properties be set. This is how you should handle creation parameters; not by requiring constructor arguments.
Note that `ISupportInitializeNotification` is also provided, which extends the above interface by adding an `IsInitialized` property and `Initialized` event. I recommend using the extended version. | No. Not from XAML [when using WPF]. |
1,083,159 | While using WPF I noticed that when I add a control to a XAML file, the default constructor is called.
Is there a way to call a parameterized constructor? | 2009/07/04 | [
"https://Stackoverflow.com/questions/1083159",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/71302/"
] | .NET 4.0 brings a new feature that challenges the answer - but apparently only for UWP applications (not WPF).
[x:Arguments Directive](https://learn.microsoft.com/en-us/dotnet/framework/xaml-services/x-arguments-directive)
```
<object ...>
<x:Arguments>
oneOrMoreObjectElements
</x:Arguments>
</object>
``` | One of the guiding principles of XAML-friendly objects is that they should be completely usable with a default constructor, i.e., there is no behavior that is only accessible when using a non-default constructor. To fit with the declarative nature of XAML, object parameters are specified via property setters. There is also a convention that says that the order in which properties are set in XAML should not be important.
You may, however, have some special considerations that are important to your implementation but at odds with convention:
1. You may have one or more properties which *must* be set before the object can be used.
2. Two or more properties may be mutually exclusive with each other, e.g., it makes no sense to set both the `StreamSource` and `UriSource` of an image.
3. You may want to ensure that a property is *only* set during initialization.
4. One property may depend on another, which can be tricky due to the aforementioned convention of order independence when setting properties.
To make it easier to handle these cases, the `ISupportInitialize` interface is provided. When an object is read and created from XAML (i.e., parsed), objects implementing `ISupportInitialize` will be handled specially:
1. The default constructor will be called.
2. `BeginInit()` will be called.
3. Properties will be set in the order they appeared in the XAML declaration.
4. `EndInit()` is called.
By tracking calls to `BeginInit()` and `EndInit()`, you can handle whatever rules you need to impose, including the requirement that certain properties be set. This is how you should handle creation parameters; not by requiring constructor arguments.
Note that `ISupportInitializeNotification` is also provided, which extends the above interface by adding an `IsInitialized` property and `Initialized` event. I recommend using the extended version. |
1,083,159 | While using WPF I noticed that when I add a control to a XAML file, the default constructor is called.
Is there a way to call a parameterized constructor? | 2009/07/04 | [
"https://Stackoverflow.com/questions/1083159",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/71302/"
] | .NET 4.0 brings a new feature that challenges the answer - but apparently only for UWP applications (not WPF).
[x:Arguments Directive](https://learn.microsoft.com/en-us/dotnet/framework/xaml-services/x-arguments-directive)
```
<object ...>
<x:Arguments>
oneOrMoreObjectElements
</x:Arguments>
</object>
``` | Yes, you can do it by the `ObjectDataProvider`. It allows you to call non-default constructor, for example:
```xml
<Grid>
<Grid.Resources>
<ObjectDataProvider x:Key="myDataSource"
ObjectType="{x:Type local:Person}">
<ObjectDataProvider.ConstructorParameters>
<system:String>Joe</system:String>
</ObjectDataProvider.ConstructorParameters>
</ObjectDataProvider>
</Grid.Resources>
<Label Content="{Binding Source={StaticResource myDataSource}, Path=Name}"></Label>
</Grid>
```
assuming that Person is
```cs
public class Person
{
public Person(string Name)
{
this.Name = Name;
}
public string Name { get; set; }
}
```
Unfortunately, you cannot bind the `ConstructorParameters`. See some workaround [here](http://drwpf.com/blog/2007/09/02/supplying-an-object-reference-in-the-constructorparameters-collection-of-an-objectdataprovider/). |
1,083,159 | While using WPF I noticed that when I add a control to a XAML file, the default constructor is called.
Is there a way to call a parameterized constructor? | 2009/07/04 | [
"https://Stackoverflow.com/questions/1083159",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/71302/"
] | One of the guiding principles of XAML-friendly objects is that they should be completely usable with a default constructor, i.e., there is no behavior that is only accessible when using a non-default constructor. To fit with the declarative nature of XAML, object parameters are specified via property setters. There is also a convention that says that the order in which properties are set in XAML should not be important.
You may, however, have some special considerations that are important to your implementation but at odds with convention:
1. You may have one or more properties which *must* be set before the object can be used.
2. Two or more properties may be mutually exclusive with each other, e.g., it makes no sense to set both the `StreamSource` and `UriSource` of an image.
3. You may want to ensure that a property is *only* set during initialization.
4. One property may depend on another, which can be tricky due to the aforementioned convention of order independence when setting properties.
To make it easier to handle these cases, the `ISupportInitialize` interface is provided. When an object is read and created from XAML (i.e., parsed), objects implementing `ISupportInitialize` will be handled specially:
1. The default constructor will be called.
2. `BeginInit()` will be called.
3. Properties will be set in the order they appeared in the XAML declaration.
4. `EndInit()` is called.
By tracking calls to `BeginInit()` and `EndInit()`, you can handle whatever rules you need to impose, including the requirement that certain properties be set. This is how you should handle creation parameters; not by requiring constructor arguments.
Note that `ISupportInitializeNotification` is also provided, which extends the above interface by adding an `IsInitialized` property and `Initialized` event. I recommend using the extended version. | Yes, you can do it by the `ObjectDataProvider`. It allows you to call non-default constructor, for example:
```xml
<Grid>
<Grid.Resources>
<ObjectDataProvider x:Key="myDataSource"
ObjectType="{x:Type local:Person}">
<ObjectDataProvider.ConstructorParameters>
<system:String>Joe</system:String>
</ObjectDataProvider.ConstructorParameters>
</ObjectDataProvider>
</Grid.Resources>
<Label Content="{Binding Source={StaticResource myDataSource}, Path=Name}"></Label>
</Grid>
```
assuming that Person is
```cs
public class Person
{
public Person(string Name)
{
this.Name = Name;
}
public string Name { get; set; }
}
```
Unfortunately, you cannot bind the `ConstructorParameters`. See some workaround [here](http://drwpf.com/blog/2007/09/02/supplying-an-object-reference-in-the-constructorparameters-collection-of-an-objectdataprovider/). |
295,123 | I need to write a temporary Web-based graphical front-end for a custom server system. In this case performance and scalability aren't issues, since at most 10 people may check the system simultaneously. Also it should be PHP or Python (server) & JavaScript (client) (can't use Flex or Silverlight for very specific non-programming related issues).
So I know I could use YUI or jQuery, but was wondering if there is something even more high-level that would say allow me to write such a little project within a few hours of work, and get done with it. Basically I want to be as lazy as possible (this is throw-away code anyways) and get the job done in as little time as possible.
Any suggestions? | 2008/11/17 | [
"https://Stackoverflow.com/questions/295123",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15124/"
] | As it hasn't been mentioned yet: [jQuery.UI](http://ui.jquery.com/) | Check out [DHTMLX](http://www.dhtmlx.com/).
>
> DHTMLX Toolkit is a comprehensive set of Ajax-enabled DHTML UI components. Professionally developed grid, treegrid, treeview, tabbar, calendar, menu, toolbar, combobox, windows, items browser, color picker and file uploader empower developers to build cross-browser web applications with high interactivity and rich user experience. DHTMLX components provide the most complete set of features and allow you to bring desktop-like functionality to the web.
>
>
> |
295,123 | I need to write a temporary Web-based graphical front-end for a custom server system. In this case performance and scalability aren't issues, since at most 10 people may check the system simultaneously. Also it should be PHP or Python (server) & JavaScript (client) (can't use Flex or Silverlight for very specific non-programming related issues).
So I know I could use YUI or jQuery, but was wondering if there is something even more high-level that would say allow me to write such a little project within a few hours of work, and get done with it. Basically I want to be as lazy as possible (this is throw-away code anyways) and get the job done in as little time as possible.
Any suggestions? | 2008/11/17 | [
"https://Stackoverflow.com/questions/295123",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15124/"
] | as 2017\*
if you want to give money:
* [Kendo UI](http://www.telerik.com/kendo-ui)
* [Wijmo](http://demos.wijmo.com/5/angular/explorer/explorer/#/)
* [ExtJs](https://www.sencha.com/)
* [DHTMLX](http://dhtmlx.com/docs/products/dhtmlxGrid/)
* [Webix](http://webix.com/blog/webix-grid-1-000-000-rows-and-more/)
* [JQWidgets](http://www.jqwidgets.com/license/)
* [SmartClient](http://www.smartclient.com/#Welcome)
* [jQueryEasyUi](http://www.jeasyui.com/demo/main/index.php)
if you decide to keep your money with yourself:
* [Dojo](https://dojotoolkit.org/documentation/#widgets)
* [Foundation](http://foundation.zurb.com/)
* [jQueryUi](https://jqueryui.com/tabs/)
* [Material-UI](http://material-ui.com/#/components/appbar)
* [Ionic](http://ionicframework.com/)
* [Semantic-UI](https://semantic-ui.com/introduction/getting-started.html)
If the aims is to write very very high level UI code, the following code generator programs are just amazing to construct your whole UI of the app within minutes (for the ones who wants to use [Bootstrap](http://getbootstrap.com/)):
* [Bootstrapstudio](https://bootstrapstudio.io/)
* [Pingendo](http://pingendo.com/) | I would try application.js - less animation fluff, lots of controls and it's a window manager (someone mentioned Bindows.. not worth the money for a terrible UI).
used in this [Online Word Processor](http://shutterb.org/)
I find cappuccino confusing, and I don't want to learn yet another language tied to a single library. |
295,123 | I need to write a temporary Web-based graphical front-end for a custom server system. In this case performance and scalability aren't issues, since at most 10 people may check the system simultaneously. Also it should be PHP or Python (server) & JavaScript (client) (can't use Flex or Silverlight for very specific non-programming related issues).
So I know I could use YUI or jQuery, but was wondering if there is something even more high-level that would say allow me to write such a little project within a few hours of work, and get done with it. Basically I want to be as lazy as possible (this is throw-away code anyways) and get the job done in as little time as possible.
Any suggestions? | 2008/11/17 | [
"https://Stackoverflow.com/questions/295123",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15124/"
] | Also Dojo's UI library named [Dijit](http://dojotoolkit.org/reference-guide/dijit/index.html) is absolutely considerable! | [ExtJs](http://extjs.com/), [Bindows](http://www.bindows.net/), [YUI](http://developer.yahoo.com/yui/). First two are commercial but worth the money. |
295,123 | I need to write a temporary Web-based graphical front-end for a custom server system. In this case performance and scalability aren't issues, since at most 10 people may check the system simultaneously. Also it should be PHP or Python (server) & JavaScript (client) (can't use Flex or Silverlight for very specific non-programming related issues).
So I know I could use YUI or jQuery, but was wondering if there is something even more high-level that would say allow me to write such a little project within a few hours of work, and get done with it. Basically I want to be as lazy as possible (this is throw-away code anyways) and get the job done in as little time as possible.
Any suggestions? | 2008/11/17 | [
"https://Stackoverflow.com/questions/295123",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15124/"
] | [ShieldUI](http://www.shieldui.com) is also a good commercial framework. | The latest additions to the List would be WIJMO and KendoUI.
[**http://www.wijmo.com**](http://www.wijmo.com)
[**http://www.kendoui.com**](http://www.kendoui.com) |
295,123 | I need to write a temporary Web-based graphical front-end for a custom server system. In this case performance and scalability aren't issues, since at most 10 people may check the system simultaneously. Also it should be PHP or Python (server) & JavaScript (client) (can't use Flex or Silverlight for very specific non-programming related issues).
So I know I could use YUI or jQuery, but was wondering if there is something even more high-level that would say allow me to write such a little project within a few hours of work, and get done with it. Basically I want to be as lazy as possible (this is throw-away code anyways) and get the job done in as little time as possible.
Any suggestions? | 2008/11/17 | [
"https://Stackoverflow.com/questions/295123",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15124/"
] | Also Dojo's UI library named [Dijit](http://dojotoolkit.org/reference-guide/dijit/index.html) is absolutely considerable! | Sproutcore would be a good choice.
If you're unfamiliar with it you might find that the time required to learn the basics is too long for throw-away code but once you've got the basics down it's quite quick to develop with. |
295,123 | I need to write a temporary Web-based graphical front-end for a custom server system. In this case performance and scalability aren't issues, since at most 10 people may check the system simultaneously. Also it should be PHP or Python (server) & JavaScript (client) (can't use Flex or Silverlight for very specific non-programming related issues).
So I know I could use YUI or jQuery, but was wondering if there is something even more high-level that would say allow me to write such a little project within a few hours of work, and get done with it. Basically I want to be as lazy as possible (this is throw-away code anyways) and get the job done in as little time as possible.
Any suggestions? | 2008/11/17 | [
"https://Stackoverflow.com/questions/295123",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15124/"
] | See also this question
[What are alternatives to ExtJS?](https://stackoverflow.com/questions/200284/what-are-alternatives-to-extjs)
It's 2016
1. [Polymer](https://www.polymer-project.org/1.0/)
2. <http://angular-ui.github.io/>
Here is a few (old) ones
1. [ampleSDK](http://www.amplesdk.com/examples/) (interesting approach)
2. [DojoToolkit](http://www.dojotoolkit.org/) and their nice set of [widgets](http://download.dojotoolkit.org/release-1.5.0/dojo-release-1.5.0/dijit/themes/themeTester.html)
3. [jQuery UI](http://jqueryui.com/)
4. [Cappuccino](http://cappuccino.org/learn/demos/)
5. [rialto](http://rialto.improve-technologies.com/wiki/)
6. [Echo](http://echo.nextapp.com/site/demo)
7. Simple UI kit [UKI](http://ukijs.org/) see [demo](http://ukijs.org/examples/core-examples/wave/)
8. [vaadin](http://demo.vaadin.com/) (Requires Java)
9. [jxlib.org](http://jxlib.org/)
10. [livepipe.net](http://livepipe.net/control)
11. [dhtmlx.com](http://dhtmlx.com/index.shtml) | The latest additions to the List would be WIJMO and KendoUI.
[**http://www.wijmo.com**](http://www.wijmo.com)
[**http://www.kendoui.com**](http://www.kendoui.com) |
295,123 | I need to write a temporary Web-based graphical front-end for a custom server system. In this case performance and scalability aren't issues, since at most 10 people may check the system simultaneously. Also it should be PHP or Python (server) & JavaScript (client) (can't use Flex or Silverlight for very specific non-programming related issues).
So I know I could use YUI or jQuery, but was wondering if there is something even more high-level that would say allow me to write such a little project within a few hours of work, and get done with it. Basically I want to be as lazy as possible (this is throw-away code anyways) and get the job done in as little time as possible.
Any suggestions? | 2008/11/17 | [
"https://Stackoverflow.com/questions/295123",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15124/"
] | [ShieldUI](http://www.shieldui.com) is also a good commercial framework. | I used JQuery.UI. This is not necessarily an answer to this question(Especially since it is an old post), but thought I would share what I have, in case it helps anyone else, as I came to this Post searching for how to create a drop and drag UI.
Please note that this is for MVC.
**Please note** that there is no actual Functionality added to this yet, it is a starting point, which creates a UI that allows drop and drag items:
Layout:
```
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>jQuery UI Droppable - Default functionality</title>
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<link rel="stylesheet" href="/resources/demos/style.css">
<style>
ul.listRoles {
width: 300px;
height: auto;
padding: 5px;
margin: 5px;
list-style-type: none;
border-radius: 5px;
min-height: 70px;
}
ul.listRoles li {
padding: 5px;
margin: 10px;
background-color: #ffff99;
cursor: pointer;
border: 1px solid Black;
border-radius: 5px;
}
</style>
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<script>
$(function () {
$("#listDenyRoles, #listAllowRoles, #listAllowMoreRoles").sortable({
connectWith: ".listRoles"
}).disableSelection();
});
function submitNewRoles() {
//Generate List of new allow roles
var outputList = $("#listAllowRoles li").map(function () { return $(this).html(); }).get().join(',');
$("#GrantRoles").val(outputList);
$("#formAssignRoles").submit();
}
</script>
</head>
<body>
<div class="container body-content">
@RenderBody()
<hr />
<footer>
<p>© @DateTime.Now.Year - My ASP.NET Application</p>
</footer>
</div>
}
</body>
</html>
```
Index Page(I replaced the Home Index with this code):
```
@{
ViewBag.Title = "Home Page";
}
<p>
To GRANT a user a role, click and drag a role from the left Red box to the right Green box.<br />
To DENY a user a role, click and drag a role from the right Green box to the left Red box.
</p>
@using (Html.BeginForm("AssignRoles", "UserAdmin", FormMethod.Post, new { id = "formAssignRoles" }))
{
String[] AllRoles = ViewBag.AllRoles;
String[] AllowRoles = ViewBag.AllowRoles;
if (AllRoles == null) { AllRoles = new String[] { "Test1","Test2","Test3","Test4", "Test5", "Test6", "Test7", "Test8", "Test9", "Test10", "Test11", "Test12", "Test13" }; }
if (AllowRoles == null) { AllowRoles = new String[] { }; }
@Html.ValidationSummary(true)
<div class="jumbotron">
<fieldset>
<legend>Drag and Drop Roles as required;</legend>
@Html.Hidden("Username", "Username")
@Html.Hidden("GrantRoles", "")
<table>
<tr>
<th style="text-align: center">
Deny Roles
</th>
<th style="text-align: center">
Allow Roles
</th>
</tr>
<tr>
<td style="vertical-align: top">
<ul id="listDenyRoles" class="listRoles" style="background-color: #cc0000;">
@foreach (String role in AllRoles)
{
if (!AllowRoles.Contains(role))
{
<li>@role</li>
}
}
</ul>
</td>
<td style="vertical-align: top">
<ul id="listAllowRoles" class="listRoles" style="background-color: #00cc00;">
@foreach (String hasRole in AllowRoles)
{
<li>@hasRole</li>
}
</ul>
</td>
<td style="vertical-align: top">
<ul id="listAllowMoreRoles" class="listRoles" style="background-color: #000000;">
@foreach (String hasRole in AllowRoles)
{
<li>@hasRole</li>
}
</ul>
</td>
</tr>
</table>
<p><input type="button" onClick="submitNewRoles()" value="Assign Roles" /></p>
</fieldset>
</div>
}
```
Hopefully this can help someone else in the right direction. |
295,123 | I need to write a temporary Web-based graphical front-end for a custom server system. In this case performance and scalability aren't issues, since at most 10 people may check the system simultaneously. Also it should be PHP or Python (server) & JavaScript (client) (can't use Flex or Silverlight for very specific non-programming related issues).
So I know I could use YUI or jQuery, but was wondering if there is something even more high-level that would say allow me to write such a little project within a few hours of work, and get done with it. Basically I want to be as lazy as possible (this is throw-away code anyways) and get the job done in as little time as possible.
Any suggestions? | 2008/11/17 | [
"https://Stackoverflow.com/questions/295123",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15124/"
] | Am I I missing something, isn't [bootstrap](http://getbootstrap.com/) the defacto go to choice ?
Also, and rather cooler, google's polymer yet ... based on web components :
<https://www.polymer-project.org/1.0/> | YUI seems to be good while Extjs also comes very close.
There is little difference between YUI and Extjs, though YUI is free has a much larger community support and is backed by a giant like Yahoo.
for cappuccino u will have to spend time learning heir Objective-J, once learnt that you need not write a single line of HTML,CSS and Dom manupulation.But if you are comfortable with all these why spend time learning objective-J ?
Bindows again is a good framework very similar to YUI and Extjs, what I like about it is that it has many ready made themes that makes it more attractive and simple to design your own custom theme.
But say 2 years down the line I personally feel that YUI would have gone much farther than all these. |
295,123 | I need to write a temporary Web-based graphical front-end for a custom server system. In this case performance and scalability aren't issues, since at most 10 people may check the system simultaneously. Also it should be PHP or Python (server) & JavaScript (client) (can't use Flex or Silverlight for very specific non-programming related issues).
So I know I could use YUI or jQuery, but was wondering if there is something even more high-level that would say allow me to write such a little project within a few hours of work, and get done with it. Basically I want to be as lazy as possible (this is throw-away code anyways) and get the job done in as little time as possible.
Any suggestions? | 2008/11/17 | [
"https://Stackoverflow.com/questions/295123",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15124/"
] | Also Dojo's UI library named [Dijit](http://dojotoolkit.org/reference-guide/dijit/index.html) is absolutely considerable! | Am I I missing something, isn't [bootstrap](http://getbootstrap.com/) the defacto go to choice ?
Also, and rather cooler, google's polymer yet ... based on web components :
<https://www.polymer-project.org/1.0/> |
295,123 | I need to write a temporary Web-based graphical front-end for a custom server system. In this case performance and scalability aren't issues, since at most 10 people may check the system simultaneously. Also it should be PHP or Python (server) & JavaScript (client) (can't use Flex or Silverlight for very specific non-programming related issues).
So I know I could use YUI or jQuery, but was wondering if there is something even more high-level that would say allow me to write such a little project within a few hours of work, and get done with it. Basically I want to be as lazy as possible (this is throw-away code anyways) and get the job done in as little time as possible.
Any suggestions? | 2008/11/17 | [
"https://Stackoverflow.com/questions/295123",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15124/"
] | Out of all the JS frameworks out there, JQuery and YUI are my favorites. They accomplish a lot of the same but in very different ways.
For your request (lazy, easy, and powerful) I would vote JQuery. If this is something that will be more long term and more of an application that is very verbose and code heavy, I would vote YUI.
I really don't think there is anything out there that is better than these two frameworks. Either choice is a good one. | Qooxdoo is phenomenal. You can do mobile, web, and desktops with it. It abstracts away all the html and css. It's well-documented and OO. You can also use the same objects server- and client-side.
<http://qooxdoo.org/demos> |
1,377,052 | Is it possible in PHP to instantiate an object from the name of a class, if the class name is stored in a string? | 2009/09/04 | [
"https://Stackoverflow.com/questions/1377052",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/135295/"
] | Yep, definitely.
```
$className = 'MyClass';
$object = new $className;
``` | **[Yes it is](http://www.php.net/manual/en/language.oop5.php#89296)**:
```
<?php
$type = 'cc';
$obj = new $type; // outputs "hi!"
class cc {
function __construct() {
echo 'hi!';
}
}
?>
``` |
1,377,052 | Is it possible in PHP to instantiate an object from the name of a class, if the class name is stored in a string? | 2009/09/04 | [
"https://Stackoverflow.com/questions/1377052",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/135295/"
] | Yep, definitely.
```
$className = 'MyClass';
$object = new $className;
``` | Static too:
```
$class = 'foo';
return $class::getId();
``` |
1,377,052 | Is it possible in PHP to instantiate an object from the name of a class, if the class name is stored in a string? | 2009/09/04 | [
"https://Stackoverflow.com/questions/1377052",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/135295/"
] | Yep, definitely.
```
$className = 'MyClass';
$object = new $className;
``` | You can do some dynamic invocation by storing your classname(s) / methods in a storage such as a database.
Assuming that the class is resilient for errors.
```
sample table my_table
classNameCol | methodNameCol | dynamic_sql
class1 | method1 | 'select * tablex where .... '
class1 | method2 | 'select * complex_query where .... '
class2 | method1 | empty use default implementation
```
etc..
Then in your code using the strings returned by the database for classes and methods names. you can even store sql queries for your classes, the level of automation if up to your imagination.
```
$myRecordSet = $wpdb->get_results('select * from my my_table')
if ($myRecordSet) {
foreach ($myRecordSet as $currentRecord) {
$obj = new $currentRecord->classNameCol;
$obj->sql_txt = $currentRecord->dynamic_sql;
$obj->{currentRecord->methodNameCol}();
}
}
```
I use this method to create REST web services. |
1,377,052 | Is it possible in PHP to instantiate an object from the name of a class, if the class name is stored in a string? | 2009/09/04 | [
"https://Stackoverflow.com/questions/1377052",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/135295/"
] | Yep, definitely.
```
$className = 'MyClass';
$object = new $className;
``` | if your class need **arguments** you should do this:
```
class Foo
{
public function __construct($bar)
{
echo $bar;
}
}
$name = 'Foo';
$args = 'bar';
$ref = new ReflectionClass($name);
$obj = $ref->newInstanceArgs(array($args));
``` |
1,377,052 | Is it possible in PHP to instantiate an object from the name of a class, if the class name is stored in a string? | 2009/09/04 | [
"https://Stackoverflow.com/questions/1377052",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/135295/"
] | **[Yes it is](http://www.php.net/manual/en/language.oop5.php#89296)**:
```
<?php
$type = 'cc';
$obj = new $type; // outputs "hi!"
class cc {
function __construct() {
echo 'hi!';
}
}
?>
``` | You can do some dynamic invocation by storing your classname(s) / methods in a storage such as a database.
Assuming that the class is resilient for errors.
```
sample table my_table
classNameCol | methodNameCol | dynamic_sql
class1 | method1 | 'select * tablex where .... '
class1 | method2 | 'select * complex_query where .... '
class2 | method1 | empty use default implementation
```
etc..
Then in your code using the strings returned by the database for classes and methods names. you can even store sql queries for your classes, the level of automation if up to your imagination.
```
$myRecordSet = $wpdb->get_results('select * from my my_table')
if ($myRecordSet) {
foreach ($myRecordSet as $currentRecord) {
$obj = new $currentRecord->classNameCol;
$obj->sql_txt = $currentRecord->dynamic_sql;
$obj->{currentRecord->methodNameCol}();
}
}
```
I use this method to create REST web services. |
1,377,052 | Is it possible in PHP to instantiate an object from the name of a class, if the class name is stored in a string? | 2009/09/04 | [
"https://Stackoverflow.com/questions/1377052",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/135295/"
] | Static too:
```
$class = 'foo';
return $class::getId();
``` | You can do some dynamic invocation by storing your classname(s) / methods in a storage such as a database.
Assuming that the class is resilient for errors.
```
sample table my_table
classNameCol | methodNameCol | dynamic_sql
class1 | method1 | 'select * tablex where .... '
class1 | method2 | 'select * complex_query where .... '
class2 | method1 | empty use default implementation
```
etc..
Then in your code using the strings returned by the database for classes and methods names. you can even store sql queries for your classes, the level of automation if up to your imagination.
```
$myRecordSet = $wpdb->get_results('select * from my my_table')
if ($myRecordSet) {
foreach ($myRecordSet as $currentRecord) {
$obj = new $currentRecord->classNameCol;
$obj->sql_txt = $currentRecord->dynamic_sql;
$obj->{currentRecord->methodNameCol}();
}
}
```
I use this method to create REST web services. |
1,377,052 | Is it possible in PHP to instantiate an object from the name of a class, if the class name is stored in a string? | 2009/09/04 | [
"https://Stackoverflow.com/questions/1377052",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/135295/"
] | if your class need **arguments** you should do this:
```
class Foo
{
public function __construct($bar)
{
echo $bar;
}
}
$name = 'Foo';
$args = 'bar';
$ref = new ReflectionClass($name);
$obj = $ref->newInstanceArgs(array($args));
``` | You can do some dynamic invocation by storing your classname(s) / methods in a storage such as a database.
Assuming that the class is resilient for errors.
```
sample table my_table
classNameCol | methodNameCol | dynamic_sql
class1 | method1 | 'select * tablex where .... '
class1 | method2 | 'select * complex_query where .... '
class2 | method1 | empty use default implementation
```
etc..
Then in your code using the strings returned by the database for classes and methods names. you can even store sql queries for your classes, the level of automation if up to your imagination.
```
$myRecordSet = $wpdb->get_results('select * from my my_table')
if ($myRecordSet) {
foreach ($myRecordSet as $currentRecord) {
$obj = new $currentRecord->classNameCol;
$obj->sql_txt = $currentRecord->dynamic_sql;
$obj->{currentRecord->methodNameCol}();
}
}
```
I use this method to create REST web services. |
182,440 | This question is a follow-up from [How to indicate that a method was unsuccessful](https://stackoverflow.com/questions/161822/how-to-indicate-that-a-method-was-unsuccessful). The xxx() Tryxxx() pattern is something that can be very useful in many libraries. I am wondering what is the best way to offer both implementations without duplicating my code.
What is best:
```
public int DoSomething(string a)
{
// might throw an exception
}
public bool TrySomething(string a, out result)
{
try
{
result = DoSomething(a)
return true;
}
catch (Exception)
{
return false;
}
```
or
```
public int DoSomething(string a)
{
int result;
if (TrySomething(a, out result))
{
return result;
}
else
{
throw Exception(); // which exception?
}
}
public bool TrySomething(string a, out result)
{
//...
}
```
I'd instinctively assume that the first example is more correct (you know exactly which exception happened), but couldn't the try/catch be too expensive? Is there a way to catch the exception in the second example? | 2008/10/08 | [
"https://Stackoverflow.com/questions/182440",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5789/"
] | I usually use this pattern. Depends on how the Internal method is implemented as to whether or not this makes any sense. If you have to use conditional catch blocks it can get a bit nasty...
```
public object DoSomething(object input){
return DoSomethingInternal(input, true);
}
public bool TryDoSomething(object input, out object result){
result = DoSomethingInternal(input, false);
return result != null;
}
private object DoSomethingInternal(object input, bool throwOnError){
/* do your work here; only throw if you cannot proceed and throwOnError is true */
}
``` | The first example is correct if you are just going to catch the exception and not do anything but return false with it.
You could change TrySomething to look like below.
```
public bool TrySomething(string a, out result, bool throwException)
{
try
{
// Whatever
}
catch
{
if(throwException)
{
throw;
}
else
{
return false;
}
}
}
public bool TrySomething(string a, out result)
{
return TrySomething(a, out result, false);
}
```
So DoSomething would look like
```
public int DoSomething(string a)
{
int result;
// This will throw the execption or
// change to false to not, or don't use the overloaded one.
TrySomething(a, out result, true)
return result;
}
```
If you did not want TrySomething with throwException exposed to the public you can make it a private member.
Exceptions could get expensive and you could do some RegEx checking on the string to prevent one from being thrown. It depends on what you are trying to do. |
182,440 | This question is a follow-up from [How to indicate that a method was unsuccessful](https://stackoverflow.com/questions/161822/how-to-indicate-that-a-method-was-unsuccessful). The xxx() Tryxxx() pattern is something that can be very useful in many libraries. I am wondering what is the best way to offer both implementations without duplicating my code.
What is best:
```
public int DoSomething(string a)
{
// might throw an exception
}
public bool TrySomething(string a, out result)
{
try
{
result = DoSomething(a)
return true;
}
catch (Exception)
{
return false;
}
```
or
```
public int DoSomething(string a)
{
int result;
if (TrySomething(a, out result))
{
return result;
}
else
{
throw Exception(); // which exception?
}
}
public bool TrySomething(string a, out result)
{
//...
}
```
I'd instinctively assume that the first example is more correct (you know exactly which exception happened), but couldn't the try/catch be too expensive? Is there a way to catch the exception in the second example? | 2008/10/08 | [
"https://Stackoverflow.com/questions/182440",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5789/"
] | Making TrySomething just catch and swallow the exception is a really bad idea. Half the point of the TryXXX pattern is to avoid the performance hit of exceptions.
If you don't need much information in the exception, you could make the DoSomething method just call TrySomething and throw an exception if it fails. If you need details in the exception, you may need something more elaborate. I haven't timed where the bulk of the performance hit of exceptions is - if it's the throwing rather than the creating, you could write a private method which had a similar signature to TrySomething, but which returned an exception or null:
```
public int DoSomething(string input)
{
int ret;
Exception exception = DoSomethingImpl(input, out ret);
if (exception != null)
{
// Note that you'll lose stack trace accuracy here
throw exception;
}
return ret;
}
public bool TrySomething(string input, out int ret)
{
Exception exception = DoSomethingImpl(input, out ret);
return exception == null;
}
private Exception DoSomethingImpl(string input, out int ret)
{
ret = 0;
if (input != "bad")
{
ret = 5;
return null;
}
else
{
return new ArgumentException("Some details");
}
}
```
Time this before you commit to it though! | The first example is correct if you are just going to catch the exception and not do anything but return false with it.
You could change TrySomething to look like below.
```
public bool TrySomething(string a, out result, bool throwException)
{
try
{
// Whatever
}
catch
{
if(throwException)
{
throw;
}
else
{
return false;
}
}
}
public bool TrySomething(string a, out result)
{
return TrySomething(a, out result, false);
}
```
So DoSomething would look like
```
public int DoSomething(string a)
{
int result;
// This will throw the execption or
// change to false to not, or don't use the overloaded one.
TrySomething(a, out result, true)
return result;
}
```
If you did not want TrySomething with throwException exposed to the public you can make it a private member.
Exceptions could get expensive and you could do some RegEx checking on the string to prevent one from being thrown. It depends on what you are trying to do. |
182,440 | This question is a follow-up from [How to indicate that a method was unsuccessful](https://stackoverflow.com/questions/161822/how-to-indicate-that-a-method-was-unsuccessful). The xxx() Tryxxx() pattern is something that can be very useful in many libraries. I am wondering what is the best way to offer both implementations without duplicating my code.
What is best:
```
public int DoSomething(string a)
{
// might throw an exception
}
public bool TrySomething(string a, out result)
{
try
{
result = DoSomething(a)
return true;
}
catch (Exception)
{
return false;
}
```
or
```
public int DoSomething(string a)
{
int result;
if (TrySomething(a, out result))
{
return result;
}
else
{
throw Exception(); // which exception?
}
}
public bool TrySomething(string a, out result)
{
//...
}
```
I'd instinctively assume that the first example is more correct (you know exactly which exception happened), but couldn't the try/catch be too expensive? Is there a way to catch the exception in the second example? | 2008/10/08 | [
"https://Stackoverflow.com/questions/182440",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5789/"
] | I usually use this pattern. Depends on how the Internal method is implemented as to whether or not this makes any sense. If you have to use conditional catch blocks it can get a bit nasty...
```
public object DoSomething(object input){
return DoSomethingInternal(input, true);
}
public bool TryDoSomething(object input, out object result){
result = DoSomethingInternal(input, false);
return result != null;
}
private object DoSomethingInternal(object input, bool throwOnError){
/* do your work here; only throw if you cannot proceed and throwOnError is true */
}
``` | Assuming this is C#, I would say the second example
```
public bool TrySomething(string a, out result)
{
try
{
result = DoSomething(a)
return true;
}
catch (Exception)
{
return false;
}
}
```
It mimics the built in `int.TryParse(string s, out int result)`, and in my opinion its best to stay consistent with the language/environment. |
182,440 | This question is a follow-up from [How to indicate that a method was unsuccessful](https://stackoverflow.com/questions/161822/how-to-indicate-that-a-method-was-unsuccessful). The xxx() Tryxxx() pattern is something that can be very useful in many libraries. I am wondering what is the best way to offer both implementations without duplicating my code.
What is best:
```
public int DoSomething(string a)
{
// might throw an exception
}
public bool TrySomething(string a, out result)
{
try
{
result = DoSomething(a)
return true;
}
catch (Exception)
{
return false;
}
```
or
```
public int DoSomething(string a)
{
int result;
if (TrySomething(a, out result))
{
return result;
}
else
{
throw Exception(); // which exception?
}
}
public bool TrySomething(string a, out result)
{
//...
}
```
I'd instinctively assume that the first example is more correct (you know exactly which exception happened), but couldn't the try/catch be too expensive? Is there a way to catch the exception in the second example? | 2008/10/08 | [
"https://Stackoverflow.com/questions/182440",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5789/"
] | Making TrySomething just catch and swallow the exception is a really bad idea. Half the point of the TryXXX pattern is to avoid the performance hit of exceptions.
If you don't need much information in the exception, you could make the DoSomething method just call TrySomething and throw an exception if it fails. If you need details in the exception, you may need something more elaborate. I haven't timed where the bulk of the performance hit of exceptions is - if it's the throwing rather than the creating, you could write a private method which had a similar signature to TrySomething, but which returned an exception or null:
```
public int DoSomething(string input)
{
int ret;
Exception exception = DoSomethingImpl(input, out ret);
if (exception != null)
{
// Note that you'll lose stack trace accuracy here
throw exception;
}
return ret;
}
public bool TrySomething(string input, out int ret)
{
Exception exception = DoSomethingImpl(input, out ret);
return exception == null;
}
private Exception DoSomethingImpl(string input, out int ret)
{
ret = 0;
if (input != "bad")
{
ret = 5;
return null;
}
else
{
return new ArgumentException("Some details");
}
}
```
Time this before you commit to it though! | Assuming this is C#, I would say the second example
```
public bool TrySomething(string a, out result)
{
try
{
result = DoSomething(a)
return true;
}
catch (Exception)
{
return false;
}
}
```
It mimics the built in `int.TryParse(string s, out int result)`, and in my opinion its best to stay consistent with the language/environment. |
182,440 | This question is a follow-up from [How to indicate that a method was unsuccessful](https://stackoverflow.com/questions/161822/how-to-indicate-that-a-method-was-unsuccessful). The xxx() Tryxxx() pattern is something that can be very useful in many libraries. I am wondering what is the best way to offer both implementations without duplicating my code.
What is best:
```
public int DoSomething(string a)
{
// might throw an exception
}
public bool TrySomething(string a, out result)
{
try
{
result = DoSomething(a)
return true;
}
catch (Exception)
{
return false;
}
```
or
```
public int DoSomething(string a)
{
int result;
if (TrySomething(a, out result))
{
return result;
}
else
{
throw Exception(); // which exception?
}
}
public bool TrySomething(string a, out result)
{
//...
}
```
I'd instinctively assume that the first example is more correct (you know exactly which exception happened), but couldn't the try/catch be too expensive? Is there a way to catch the exception in the second example? | 2008/10/08 | [
"https://Stackoverflow.com/questions/182440",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5789/"
] | Making TrySomething just catch and swallow the exception is a really bad idea. Half the point of the TryXXX pattern is to avoid the performance hit of exceptions.
If you don't need much information in the exception, you could make the DoSomething method just call TrySomething and throw an exception if it fails. If you need details in the exception, you may need something more elaborate. I haven't timed where the bulk of the performance hit of exceptions is - if it's the throwing rather than the creating, you could write a private method which had a similar signature to TrySomething, but which returned an exception or null:
```
public int DoSomething(string input)
{
int ret;
Exception exception = DoSomethingImpl(input, out ret);
if (exception != null)
{
// Note that you'll lose stack trace accuracy here
throw exception;
}
return ret;
}
public bool TrySomething(string input, out int ret)
{
Exception exception = DoSomethingImpl(input, out ret);
return exception == null;
}
private Exception DoSomethingImpl(string input, out int ret)
{
ret = 0;
if (input != "bad")
{
ret = 5;
return null;
}
else
{
return new ArgumentException("Some details");
}
}
```
Time this before you commit to it though! | I usually use this pattern. Depends on how the Internal method is implemented as to whether or not this makes any sense. If you have to use conditional catch blocks it can get a bit nasty...
```
public object DoSomething(object input){
return DoSomethingInternal(input, true);
}
public bool TryDoSomething(object input, out object result){
result = DoSomethingInternal(input, false);
return result != null;
}
private object DoSomethingInternal(object input, bool throwOnError){
/* do your work here; only throw if you cannot proceed and throwOnError is true */
}
``` |
1,867,045 | Does someone here know if it is possible to backup only the part of a
subversion reposiotory that has changed since the last backup (that is:
the delta)?
Practically, that could be something like doing a full backup every
midnight, and a delta every hour. If then a crash occured say at 11:07,
one would have to use last midnights full backup and apply all deltas
on it, thus only seven minutes would be lost.
Also, if this should be possible, can that be made in a "hot-backup"
mode (if that is the correct term for it), that is, while other users
are operating, especially checking in, on the repository. | 2009/12/08 | [
"https://Stackoverflow.com/questions/1867045",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/180275/"
] | This is certainly possible. You can do an `svnadmin dump -r(from_rev) --incremental` to dump all changes from revision *(from\_rev)* onwards (if you omit the `--incremental`, the contents of the *(from\_rev)* revision will be dumped fully). All commits are atomic, so you can do a hot-backup this way - commits that are still in progress will not be in this dump but in the next one. | It is simpler and probably almost as efficient to use rsync. rsync also has the benefit that it can do more things, other than the repository. |
50,995 | I'm a C# developer who's fumbling in the first VB code he's written since VB6, so if I am asking a rather obvious question, please forgive me.
I decided to experiment with XML Literals to generate some XML code for me, instead of using XMLDocument
I have 2 questions, the second regarding a workaround due to my inability to figure out the first.
1: Ideal solution
I have a Dictionary of ElementName, ElementValue whose KeyValue pairs I was looping over in the hope of generating the values dynamically, but the following syntax dies a horrible death
```
Dim xConnections As XElement
For Each connection As Connection In connections.AsList
For Each kvp As KeyValuePair(Of String, String) In connection.DecompiledElements
xConnections = <Connections> <<%= kvp.Key %>><%= kvp.Value %><\<%=kvp.Key %>> </Connections>
Next
Next
```
I have vague memories of the T4 syntax (the <%=%> syntax) being able to handle more complex operations (rather than direct assignment to the <%= ) and a 'Response.Write' like object to write output to, but I can't remember the details.
2: Cludgy workaround
Instead I thought of building a StringBuilder object and assigning its .ToString to the XElement, but that also failed with a conversion error.
I would prefer to continue using my key value pair concept in example one above, as I feel cludging together a string as in example 2 above is rather nasty, and I really should go back to using XMLDocument if instead.
Any thoughts or assistance greatly appreciated | 2008/09/09 | [
"https://Stackoverflow.com/questions/50995",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5302/"
] | If I understand correctly what you are trying to do, you can use the StringBuilder. Use the StringBuilder.Append method and append the XmlElement 'OuterXml' property.
For example:
sb.Append(xmlElement.OuterXml) | We would all be remiss not to mention that dynamic XML element names are generally a bad idea. The whole point of XML is to create a store a data structure in a form that is readily:
1. Verifiable
2. Extendable
Dynamic element names fail that first condition. Why not simply use a standard XML format for storing key/value pairs like [plists](http://developer.apple.com/documentation/Cocoa/Conceptual/PropertyLists/Articles/XMLPListsConcept.html)?
```
<dict>
<key>Author</key>
<string>William Shakespeare</string>
<key>Title</key>
<string>Romeo et</string>
<key>ISBN</key>
<string>?????</string>
</dict>
``` |
50,995 | I'm a C# developer who's fumbling in the first VB code he's written since VB6, so if I am asking a rather obvious question, please forgive me.
I decided to experiment with XML Literals to generate some XML code for me, instead of using XMLDocument
I have 2 questions, the second regarding a workaround due to my inability to figure out the first.
1: Ideal solution
I have a Dictionary of ElementName, ElementValue whose KeyValue pairs I was looping over in the hope of generating the values dynamically, but the following syntax dies a horrible death
```
Dim xConnections As XElement
For Each connection As Connection In connections.AsList
For Each kvp As KeyValuePair(Of String, String) In connection.DecompiledElements
xConnections = <Connections> <<%= kvp.Key %>><%= kvp.Value %><\<%=kvp.Key %>> </Connections>
Next
Next
```
I have vague memories of the T4 syntax (the <%=%> syntax) being able to handle more complex operations (rather than direct assignment to the <%= ) and a 'Response.Write' like object to write output to, but I can't remember the details.
2: Cludgy workaround
Instead I thought of building a StringBuilder object and assigning its .ToString to the XElement, but that also failed with a conversion error.
I would prefer to continue using my key value pair concept in example one above, as I feel cludging together a string as in example 2 above is rather nasty, and I really should go back to using XMLDocument if instead.
Any thoughts or assistance greatly appreciated | 2008/09/09 | [
"https://Stackoverflow.com/questions/50995",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5302/"
] | VB.NET XML Literals are very powerful, but most often adding some LINQ to them makes them truly awesome. This code should do exactly what you're trying to do.
```
Dim Elements = New Dictionary(Of String, String)
Elements.Add("Key1", "Value1")
Elements.Add("Key2", "Value2")
Elements.Add("Key3", "Value3")
Dim xConnections = <Connections>
<%= From elem In Elements _
Select <<%= elem.Key %>><%= elem.Value %></> %>
</Connections>
```
The empty closing tag `</>` is all that is needed for the vb compiler to properly construct an xml element whose name is generated from a value within a `<%= %>` block.
Calling xConnections.ToString renders the following:
```
<Connections>
<Key1>Value1</Key1>
<Key2>Value2</Key2>
<Key3>Value3</Key3>
</Connections>
``` | If I understand correctly what you are trying to do, you can use the StringBuilder. Use the StringBuilder.Append method and append the XmlElement 'OuterXml' property.
For example:
sb.Append(xmlElement.OuterXml) |
50,995 | I'm a C# developer who's fumbling in the first VB code he's written since VB6, so if I am asking a rather obvious question, please forgive me.
I decided to experiment with XML Literals to generate some XML code for me, instead of using XMLDocument
I have 2 questions, the second regarding a workaround due to my inability to figure out the first.
1: Ideal solution
I have a Dictionary of ElementName, ElementValue whose KeyValue pairs I was looping over in the hope of generating the values dynamically, but the following syntax dies a horrible death
```
Dim xConnections As XElement
For Each connection As Connection In connections.AsList
For Each kvp As KeyValuePair(Of String, String) In connection.DecompiledElements
xConnections = <Connections> <<%= kvp.Key %>><%= kvp.Value %><\<%=kvp.Key %>> </Connections>
Next
Next
```
I have vague memories of the T4 syntax (the <%=%> syntax) being able to handle more complex operations (rather than direct assignment to the <%= ) and a 'Response.Write' like object to write output to, but I can't remember the details.
2: Cludgy workaround
Instead I thought of building a StringBuilder object and assigning its .ToString to the XElement, but that also failed with a conversion error.
I would prefer to continue using my key value pair concept in example one above, as I feel cludging together a string as in example 2 above is rather nasty, and I really should go back to using XMLDocument if instead.
Any thoughts or assistance greatly appreciated | 2008/09/09 | [
"https://Stackoverflow.com/questions/50995",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5302/"
] | If I understand correctly what you are trying to do, you can use the StringBuilder. Use the StringBuilder.Append method and append the XmlElement 'OuterXml' property.
For example:
sb.Append(xmlElement.OuterXml) | To answer this more completely...
When injecting Strings into an XML Literal, it will not work properly unless you use XElement.Parse when injecting an XElement (this is because special characters are escaped)
So your ideal solution is more like this:
```
Dim conns = connections.AsList()
If conns IsNot Nothing AndAlso conns.length > 0 Then
Dim index = 0
Dim xConnections = _
<Connections>
<%= From kvp As KeyValuePair(Of String, String) In conns (System.Threading.Interlocked.Increment(index)).DecompiledElements() _
Select XElement.Parse("<" & <%= kvp.Key %> & ">" & <%= kvp.Value %> & "</" & <%= kvp.Key %> & ">") _
%>
</Connections>
Return xConnections.ToString()
End If
```
ToString will return the OuterXML Properly as a String (Value will not...)
of course, just drop the ToString() if you want to return an XElement of
Since I don't know what AsList() does, nor do I know what DecompiledElements do, set your error trapping accordingly. There are other ways to do the loops as well, this is just one solution. |
50,995 | I'm a C# developer who's fumbling in the first VB code he's written since VB6, so if I am asking a rather obvious question, please forgive me.
I decided to experiment with XML Literals to generate some XML code for me, instead of using XMLDocument
I have 2 questions, the second regarding a workaround due to my inability to figure out the first.
1: Ideal solution
I have a Dictionary of ElementName, ElementValue whose KeyValue pairs I was looping over in the hope of generating the values dynamically, but the following syntax dies a horrible death
```
Dim xConnections As XElement
For Each connection As Connection In connections.AsList
For Each kvp As KeyValuePair(Of String, String) In connection.DecompiledElements
xConnections = <Connections> <<%= kvp.Key %>><%= kvp.Value %><\<%=kvp.Key %>> </Connections>
Next
Next
```
I have vague memories of the T4 syntax (the <%=%> syntax) being able to handle more complex operations (rather than direct assignment to the <%= ) and a 'Response.Write' like object to write output to, but I can't remember the details.
2: Cludgy workaround
Instead I thought of building a StringBuilder object and assigning its .ToString to the XElement, but that also failed with a conversion error.
I would prefer to continue using my key value pair concept in example one above, as I feel cludging together a string as in example 2 above is rather nasty, and I really should go back to using XMLDocument if instead.
Any thoughts or assistance greatly appreciated | 2008/09/09 | [
"https://Stackoverflow.com/questions/50995",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5302/"
] | VB.NET XML Literals are very powerful, but most often adding some LINQ to them makes them truly awesome. This code should do exactly what you're trying to do.
```
Dim Elements = New Dictionary(Of String, String)
Elements.Add("Key1", "Value1")
Elements.Add("Key2", "Value2")
Elements.Add("Key3", "Value3")
Dim xConnections = <Connections>
<%= From elem In Elements _
Select <<%= elem.Key %>><%= elem.Value %></> %>
</Connections>
```
The empty closing tag `</>` is all that is needed for the vb compiler to properly construct an xml element whose name is generated from a value within a `<%= %>` block.
Calling xConnections.ToString renders the following:
```
<Connections>
<Key1>Value1</Key1>
<Key2>Value2</Key2>
<Key3>Value3</Key3>
</Connections>
``` | We would all be remiss not to mention that dynamic XML element names are generally a bad idea. The whole point of XML is to create a store a data structure in a form that is readily:
1. Verifiable
2. Extendable
Dynamic element names fail that first condition. Why not simply use a standard XML format for storing key/value pairs like [plists](http://developer.apple.com/documentation/Cocoa/Conceptual/PropertyLists/Articles/XMLPListsConcept.html)?
```
<dict>
<key>Author</key>
<string>William Shakespeare</string>
<key>Title</key>
<string>Romeo et</string>
<key>ISBN</key>
<string>?????</string>
</dict>
``` |
50,995 | I'm a C# developer who's fumbling in the first VB code he's written since VB6, so if I am asking a rather obvious question, please forgive me.
I decided to experiment with XML Literals to generate some XML code for me, instead of using XMLDocument
I have 2 questions, the second regarding a workaround due to my inability to figure out the first.
1: Ideal solution
I have a Dictionary of ElementName, ElementValue whose KeyValue pairs I was looping over in the hope of generating the values dynamically, but the following syntax dies a horrible death
```
Dim xConnections As XElement
For Each connection As Connection In connections.AsList
For Each kvp As KeyValuePair(Of String, String) In connection.DecompiledElements
xConnections = <Connections> <<%= kvp.Key %>><%= kvp.Value %><\<%=kvp.Key %>> </Connections>
Next
Next
```
I have vague memories of the T4 syntax (the <%=%> syntax) being able to handle more complex operations (rather than direct assignment to the <%= ) and a 'Response.Write' like object to write output to, but I can't remember the details.
2: Cludgy workaround
Instead I thought of building a StringBuilder object and assigning its .ToString to the XElement, but that also failed with a conversion error.
I would prefer to continue using my key value pair concept in example one above, as I feel cludging together a string as in example 2 above is rather nasty, and I really should go back to using XMLDocument if instead.
Any thoughts or assistance greatly appreciated | 2008/09/09 | [
"https://Stackoverflow.com/questions/50995",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5302/"
] | To answer this more completely...
When injecting Strings into an XML Literal, it will not work properly unless you use XElement.Parse when injecting an XElement (this is because special characters are escaped)
So your ideal solution is more like this:
```
Dim conns = connections.AsList()
If conns IsNot Nothing AndAlso conns.length > 0 Then
Dim index = 0
Dim xConnections = _
<Connections>
<%= From kvp As KeyValuePair(Of String, String) In conns (System.Threading.Interlocked.Increment(index)).DecompiledElements() _
Select XElement.Parse("<" & <%= kvp.Key %> & ">" & <%= kvp.Value %> & "</" & <%= kvp.Key %> & ">") _
%>
</Connections>
Return xConnections.ToString()
End If
```
ToString will return the OuterXML Properly as a String (Value will not...)
of course, just drop the ToString() if you want to return an XElement of
Since I don't know what AsList() does, nor do I know what DecompiledElements do, set your error trapping accordingly. There are other ways to do the loops as well, this is just one solution. | We would all be remiss not to mention that dynamic XML element names are generally a bad idea. The whole point of XML is to create a store a data structure in a form that is readily:
1. Verifiable
2. Extendable
Dynamic element names fail that first condition. Why not simply use a standard XML format for storing key/value pairs like [plists](http://developer.apple.com/documentation/Cocoa/Conceptual/PropertyLists/Articles/XMLPListsConcept.html)?
```
<dict>
<key>Author</key>
<string>William Shakespeare</string>
<key>Title</key>
<string>Romeo et</string>
<key>ISBN</key>
<string>?????</string>
</dict>
``` |
50,995 | I'm a C# developer who's fumbling in the first VB code he's written since VB6, so if I am asking a rather obvious question, please forgive me.
I decided to experiment with XML Literals to generate some XML code for me, instead of using XMLDocument
I have 2 questions, the second regarding a workaround due to my inability to figure out the first.
1: Ideal solution
I have a Dictionary of ElementName, ElementValue whose KeyValue pairs I was looping over in the hope of generating the values dynamically, but the following syntax dies a horrible death
```
Dim xConnections As XElement
For Each connection As Connection In connections.AsList
For Each kvp As KeyValuePair(Of String, String) In connection.DecompiledElements
xConnections = <Connections> <<%= kvp.Key %>><%= kvp.Value %><\<%=kvp.Key %>> </Connections>
Next
Next
```
I have vague memories of the T4 syntax (the <%=%> syntax) being able to handle more complex operations (rather than direct assignment to the <%= ) and a 'Response.Write' like object to write output to, but I can't remember the details.
2: Cludgy workaround
Instead I thought of building a StringBuilder object and assigning its .ToString to the XElement, but that also failed with a conversion error.
I would prefer to continue using my key value pair concept in example one above, as I feel cludging together a string as in example 2 above is rather nasty, and I really should go back to using XMLDocument if instead.
Any thoughts or assistance greatly appreciated | 2008/09/09 | [
"https://Stackoverflow.com/questions/50995",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5302/"
] | VB.NET XML Literals are very powerful, but most often adding some LINQ to them makes them truly awesome. This code should do exactly what you're trying to do.
```
Dim Elements = New Dictionary(Of String, String)
Elements.Add("Key1", "Value1")
Elements.Add("Key2", "Value2")
Elements.Add("Key3", "Value3")
Dim xConnections = <Connections>
<%= From elem In Elements _
Select <<%= elem.Key %>><%= elem.Value %></> %>
</Connections>
```
The empty closing tag `</>` is all that is needed for the vb compiler to properly construct an xml element whose name is generated from a value within a `<%= %>` block.
Calling xConnections.ToString renders the following:
```
<Connections>
<Key1>Value1</Key1>
<Key2>Value2</Key2>
<Key3>Value3</Key3>
</Connections>
``` | To answer this more completely...
When injecting Strings into an XML Literal, it will not work properly unless you use XElement.Parse when injecting an XElement (this is because special characters are escaped)
So your ideal solution is more like this:
```
Dim conns = connections.AsList()
If conns IsNot Nothing AndAlso conns.length > 0 Then
Dim index = 0
Dim xConnections = _
<Connections>
<%= From kvp As KeyValuePair(Of String, String) In conns (System.Threading.Interlocked.Increment(index)).DecompiledElements() _
Select XElement.Parse("<" & <%= kvp.Key %> & ">" & <%= kvp.Value %> & "</" & <%= kvp.Key %> & ">") _
%>
</Connections>
Return xConnections.ToString()
End If
```
ToString will return the OuterXML Properly as a String (Value will not...)
of course, just drop the ToString() if you want to return an XElement of
Since I don't know what AsList() does, nor do I know what DecompiledElements do, set your error trapping accordingly. There are other ways to do the loops as well, this is just one solution. |