text
stringlengths
8
267k
meta
dict
Q: Which .Net collection for adding multiple objects at once and getting notified? Was considering the System.Collections.ObjectModel ObservableCollection<T> class. This one is strange because * *it has an Add Method which takes one item only. No AddRange or equivalent. *the Notification event arguments has a NewItems property, which is a IList (of objects.. not T) My need here is to add a batch of objects to a collection and the listener also gets the batch as part of the notification. Am I missing something with ObservableCollection ? Is there another class that meets my spec? Update: Don't want to roll my own as far as feasible. I'd have to build in add/remove/change etc.. a whole lot of stuff. Related Q: https://stackoverflow.com/questions/670577/observablecollection-doesnt-support-addrange-method-so-i-get-notified-for-each A: Well the idea is same as that of fryguybob - kinda weird that ObservableCollection is kinda half-done. The event args for this thing do not even use Generics.. making me use an IList (that's so.. yesterday :) Tested Snippet follows... using System.Collections.Generic; using System.Collections.ObjectModel; using System.Collections.Specialized; namespace MyNamespace { public class ObservableCollectionWithBatchUpdates<T> : ObservableCollection<T> { public void AddRange(ICollection<T> obNewItems) { IList<T> obAddedItems = new List<T>(); foreach (T obItem in obNewItems) { Items.Add(obItem); obAddedItems.Add(obItem); } NotifyCollectionChangedEventArgs obEvtArgs = new NotifyCollectionChangedEventArgs( NotifyCollectionChangedAction.Add, obAddedItems as System.Collections.IList); base.OnCollectionChanged(obEvtArgs); } } } A: Not only is System.Collections.ObjectModel.Collection<T> a good bet, but in the help docs there's an example of how to override its various protected methods in order to get notification. (Scroll down to Example 2.) A: If you use any of the above implementations that send an add range command and bind the observablecolletion to a listview you will get this nasty error. NotSupportedException at System.Windows.Data.ListCollectionView.ValidateCollectionChangedEventArgs(NotifyCollectionChangedEventArgs e) at System.Windows.Data.ListCollectionView.ProcessCollectionChanged(NotifyCollectionChangedEventArgs args) at System.Collections.Specialized.NotifyCollectionChangedEventHandler.Invoke(Object sender, NotifyCollectionChangedEventArgs e) at System.Collections.ObjectModel.ObservableCollection`1.OnCollectionChanged(NotifyCollectionChangedEventArgs e) The implementation I have gone with uses the Reset event that is more evenly implemented around the WPF framework: public void AddRange(IEnumerable<T> collection) { foreach (var i in collection) Items.Add(i); OnPropertyChanged("Count"); OnPropertyChanged("Item[]"); OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset)); } A: I have seen this kind of question many times, and I wonder why even Microsoft is promoting ObservableCollection everywhere where else there is a better collection already available thats.. BindingList<T> Which allows you to turn off notifications and do bulk operations and then turn on the notifications. A: It seems that the INotifyCollectionChanged interface allows for updating when multiple items were added, so I'm not sure why ObservableCollection<T> doesn't have an AddRange. You could make an extension method for AddRange, but that would cause an event for every item that is added. If that isn't acceptable you should be able to inherit from ObservableCollection<T> as follows: public class MyObservableCollection<T> : ObservableCollection<T> { // matching constructors ... bool isInAddRange = false; protected override void OnCollectionChanged(NotifyCollectionChangedEventArgs e) { // intercept this when it gets called inside the AddRange method. if (!isInAddRange) base.OnCollectionChanged(e); } public void AddRange(IEnumerable<T> items) { isInAddRange = true; foreach (T item in items) Add(item); isInAddRange = false; var e = new NotifyCollectionChangedEventArgs( NotifyCollectionChangedAction.Add, items.ToList()); base.OnCollectionChanged(e); } } A: If you're wanting to inherit from a collection of some sort, you're probably better off inheriting from System.Collections.ObjectModel.Collection because it provides virtual methods for override. You'll have to shadow methods off of List if you go that route. I'm not aware of any built-in collections that provide this functionality, though I'd welcome being corrected :) A: Another solution that is similar to the CollectionView pattern: public class DeferableObservableCollection<T> : ObservableCollection<T> { private int deferLevel; private class DeferHelper<T> : IDisposable { private DeferableObservableCollection<T> owningCollection; public DeferHelper(DeferableObservableCollection<T> owningCollection) { this.owningCollection = owningCollection; } public void Dispose() { owningCollection.EndDefer(); } } private void EndDefer() { if (--deferLevel <= 0) { deferLevel = 0; OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset)); } } public IDisposable DeferNotifications() { deferLevel++; return new DeferHelper<T>(this); } protected override void OnCollectionChanged(NotifyCollectionChangedEventArgs e) { if (deferLevel == 0) // Not in a defer just send events as normally { base.OnCollectionChanged(e); } // Else notify on EndDefer } } A: Inherit from List<T> and override the Add() and AddRange() methods to raise an event? A: Take a look at Observable collection with AddRange, RemoveRange and Replace range methods in both C# and VB. In VB: INotifyCollectionChanging implementation. A: For fast adding you could use: ((List<Person>)this.Items).AddRange(NewItems);
{ "language": "en", "url": "https://stackoverflow.com/questions/57020", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "36" }
Q: jQuery and Java applets I'm working on a project where we're using a Java applet for part of the UI (a map, specifically), but building the rest of the UI around the applet in HTML/JavaScript, communicating with the applet through LiveConnect/NPAPI. A little bizarre, I know, but let's presume that setup is not under discussion. I started out planning on using jQuery as my JavaScript framework, but I've run into two issues. Issue the first: Selecting the applet doesn't provide access to the applet's methods. Java: public class MyApplet extends JApplet { // ... public String foo() { return "foo!"; } } JavaScript: var applet = $("#applet-id"); alert(applet.foo()); Running the above JavaScript results in $("#applet-id").foo is not a function This is in contrast to Prototype, where the analogous code does work: var applet = $("applet-id"); alert(applet.foo()); So...where'd the applet methods go? Issue the second: There's a known problem with jQuery and applets in Firefox 2: http://www.pengoworks.com/workshop/jquery/bug_applet/jquery_applet_bug.htm It's a long shot, but does anybody know of a workaround? I suspect this problem isn't fixable, which will mean switching to Prototype. Thanks for the help! A: For the first issue, how about trying alert( $("#applet-id")[0].foo() ); For the second issue here is a thread with a possible workaround. Quoting the workaround // Prevent memory leaks in IE // And prevent errors on refresh with events like mouseover in other browsers // Window isn't included so as not to unbind existing unload events jQuery(window).bind("unload", function() { jQuery("*").add(document).unbind(); }); change that code to: // Window isn't included so as not to unbind existing unload events jQuery(window).bind("unload", function() { jQuery("*:not('applet, object')").add(document).unbind(); });
{ "language": "en", "url": "https://stackoverflow.com/questions/57034", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "10" }
Q: What, if any, checksum is used for TNT.com tracking numbers? I am writing some software to identify tracking numbers (in the same way that Google identifies FedEx or UPS numbers when you search for them). Most couriers use a system, such as a "weighted average mod system" which can be used to identify if a number is a valid tracking number. Does anyone know if TNT consignment numbers use such a system, and if so, what it is? I have asked TNT support, and the rep told me they do not... but I'd like to doublecheck. A: OK, so it's three months since you asked but I stumbled across this as I'm writing a similar piece of software. As far as we know TNT uses the S10 tracking number system. Which means that their numbers will be of the type AA#########AA. With the last two letters corresponding to a ISO/IATA country code. Having said that TNT uses WW which we believe must stand for worldwide. This is not quite an answer, at least it's not about checksums or algorithms, but it might be useful? Hope that helps Willow A: As far as I can tell, there isn't one. Sorry. I take it you're trying to validate the tracking number entered to make sure it was entered properly? -- Kevin Fairchild A: I believe there is a Check Digit / Checksum digit, Possibly a derivative of MOD10 but have no idea what algorithm it is, referred to as the 9th digit by TNT. Would be nice to know??? All I know it 12345678 check digit is 5 and 22345678 check digit is 8. A: It is actually MOD 11 VB.net I've written is as follows: Dim number As String = TextBox1.Text Dim A As Integer Dim B As Integer Dim C As Integer Dim check_digit As Integer A = (CInt(Mid(number, 1, 1)) * 8) + (CInt(Mid(number, 2, 1)) * 6) + (CInt(Mid(number, 3, 1)) * 4) + (CInt(Mid(number, 4, 1)) * 2) + (CInt(Mid(number, 5, 1)) * 3) + (CInt(Mid(number, 6, 1)) * 5) + (CInt(Mid(number, 7, 1)) * 9) + (CInt(Mid(number, 8, 1)) * 7) B = ((A \ 11) * 11) C = A - B If C = 0 Then check_digit = 5 End If If C = 1 Then check_digit = 0 End If If C <> 0 And C <> 1 Then check_digit = 11 - C End If MsgBox(number & check_digit)
{ "language": "en", "url": "https://stackoverflow.com/questions/57053", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to solve call ambiguity between Generic.IList.this[] and IList.this[]? I've got a collection that implements an interface that extends both IList<T> and List. public Interface IMySpecialCollection : IList<MyObject>, IList { ... } That means I have two versions of the indexer. I wish the generic implementation to be used, so I implement that one normally: public MyObject this[int index] { .... } I only need the IList version for serialization, so I implement it explicitly, to keep it hidden: object IList.this[int index] { ... } However, in my unit tests, the following MyObject foo = target[0]; results in a compiler error The call is ambiguous between the following methods or properties I'm a bit surprised at this; I believe I've done it before and it works fine. What am I missing here? How can I get IList<T> and IList to coexist within the same interface? Edit IList<T> does not implement IList, and I must implement IList for serialization. I'm not interested in workarounds, I want to know what I'm missing. Edit again: I've had to drop IList from the interface and move it on my class. I don't want to do this, as classes that implement the interface are eventually going to be serialized to Xaml, which requires collections to implement IDictionary or IList... A: You can't do this with public interface IMySpecialCollection : IList<MyObject>, IList { ... } But you can do what you want with a class, you will need to make the implementations for one of the interfaces explicit. In my example I made IList explicit. public class MySpecialCollection : IList<MyObject>, IList { ... } IList<object> myspecialcollection = new MySpecialCollection(); IList list = (IList)myspecialcollection; Have you considered having IMySpecialCollection implement ISerializable for serialization? Supporting multiple collection types seems a bit wrong to me. You may also want to look at casting yout IList to IEnumerable for serialization since IList just wraps IEnumerable and ICollection. A: This is a dupe of my question here To summarise, if you do this, it solves the problem: public Interface IMySpecialCollection : IList<MyObject>, IList { new MyObject this[int index]; ... } A: Unfortunately you can't declare two indexers with the same parameter list. The following paragraph is taken from here C# Programming Guide - Using Indexers "Remarks" section: The signature of an indexer consists of the number and types of its formal parameters. It does not include the indexer type or the names of the formal parameters. If you declare more than one indexer in the same class, they must have different signatures. You will have to declare a different set of parameters if you wish to use the second indexer. A: List<T> implies IList, so it's a bad idea to use both in the same class. A: Change your generic implementation to... T IList<T>.this[int index] { get; set; } This explicitly says which 'this' is which.
{ "language": "en", "url": "https://stackoverflow.com/questions/57054", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: Where can I find sample databases with common formatted data that I can use in multiple database engines? Does anybody know of any sample databases I could download, preferably in CSV or some similar easy to import format so that I could get more practice in working with different types of data sets? I know that the Canadian Department of Environment has historical weather data that you can download. However, it's not in a common format I can import into any other database. Moreover, you can only run queries based on the included program, which is actually quite limited in what kind of data it can provide. Does anybody know of any interesting data sets that are freely available in a common format that I could use with mySql, Sql Server, and other types of database engines? A: For Microsoft SQL Server, there is the Northwind Sample DB and AdventureWorks. A: For MySQL there are quite a few sample database at http://dev.mysql.com/doc/index-other.html * *world (world countries and cities) *sakila(video rental) *employee *menagerie A: I use generatedata.com to generate custom databases schemes with entries. To use it, you can simply register a new account, or download its sources and install it on your server. You can export generated code in SQL, XML, JSON, or even server-side scripting language like php etc. A: UnData and Swivel are both good sources for data. Any database should be able to import CSV files. A: The datawrangling blog posted a nice list a while back: http://www.datawrangling.com/some-datasets-available-on-the-web Includes financial, government data (labor, housing, etc.), and too many more to list here. A: What database engine are you importing into? That will help determine what formats you can include in your search. The Federal Energy Regulatory Commission has some sample data for download in CSV format. A: The Guardian newspaper in the UK has a data-store, http://www.guardian.co.uk/data-store, full of categorized datasets. They're all ultimately stored as Google Documents, so you can export them into csv & Excel. A: There's a whole bunch of free SQL Server sample databases on CodePlex: http://www.codeplex.com/Wikipage?ProjectName=SqlServerSamples#databases One very simple way to get sample data is use full applications. I needed some sample data to practice what I was learning with MySQL at the time and just downloaded PHPBB and used their provided database. If you need to add users etc, just use the program to do it. Think generic. You can get weather data from common sources for free, thetvdb.com has a pretty nifty set of data for TV show episodes for free, sites like last.fm have a tonne of data available for music listening habits. If you just want sample data, the easiest way to get it is not thinking in terms of "I want a database". Think "what freely available data is out there". A: For FileMaker, see Sample Database: http://www.yzysoft.com/printouts/yzy_soft___Sample_Database.html A: You can probably find the Northwind sample database for SQLServer It might be overkill but you can install OracleXE, I think it comes with some sample schemas or you can find the old Scott schema online. Also, in stephen bohlen's Summer of NHibernate screen-cast series he creates a sample database, the code comes with it in xml files and you can import it like he describes in the screencast (maybe episode 2 or 3) and just not delete it later. A: For Firebird you have employee.fdb on windows OS, it is located there C:\Program Files\Firebird\Firebird_2_1\examples\empbuild A: A lot of the data in Stack Overflow is licensed under the create commons. Every 3 months they release a data dump with all the questions, answers, comments, and votes.
{ "language": "en", "url": "https://stackoverflow.com/questions/57068", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "69" }
Q: How do I assign a keyboard shortcut to a VBA macro in Outlook 2007? How can I assign a keyboard shortcut to a VBA macro in Outlook 2007? I know how to create a tool for the macro and put it in a menu with an underscore shortcut. This solution requires me to use a shortcut of Alt + {menu key} + {tool key}. What if I want to assign it to Alt + F12 or something like that? The Visual Basic Editor is assigned to the keyboard shortcut Alt + F11 in Outlook 2007. I want to assign a keyboard shortcut like that to a macro, or if necessary a macro on a tool in either a menu or a toolbar. A: Since Outlook doesn't have the OnKey event, the easiest way is to assign a toolbar button to the macro and put an ampersand in its name somewhere. This only works if your shortcut letter doesn't conflict with an existing shortcut. You may also have luck with setting a global hotkey, but it's usually more pain then it's worth: http://www.mvps.org/vbvision/_samples/HotKey_Demo.zip A: The article Do-It-Yourself IntelliSense from MSDN provides excellent information about key bindings in VBA.
{ "language": "en", "url": "https://stackoverflow.com/questions/57075", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: How to position a DIV to fill all available space between a header DIV and a footer DIV? Let's say I have a parent DIV. Inside, there are three child DIVs: header, content and footer. Header is attached to the top of the parent and fills it horizontally. Footer is attached to the bottom of the parent and fills it horizontally too. Content is supposed to fill all the space between header and footer. The parent has to have a fixed width and height. The content DIV has to fill all available space between header and footer. When the content size of the content DIV exceeds the space between header and footer, the content DIV should display scrollbars and allow appropriate scrolling so that the footer contents should never be obscured nor the footer obscure content. Now comes the hard part: you don't know the height of the header nor footer beforehand (eg. header and footer are filled dynamically). How can content be positioned without using JavaScript? Example: <div style="position : relative; width : 200px; height : 200px; background-color : #e0e0ff; overflow : hidden;"> <div style="background-color: #80ff80; position : absolute; left : 0; right : 0; top : 0;"> header </div> <div style="background-color: #8080ff; overflow : auto; position : absolute;"> content (how to position it?) </div> <div style="background-color: #ff8080; position : absolute; bottom : 0px; left :0; right : 0;"> footer </div> </div> To clarify this event further - the target layout that I'm trying to achieve will be used in a business web application. The parent DIV will have a fixed, but unknown size (for instance, it will be exactly the size of the browser viewport, sizing itself along with sizing the browser window by the user). Let's call the parent DIV a "screen". The header will contain a set of filtering controls (like textboxes, drop down lists and a "filter" button) that should wrap to the next line if there is insufficient horizontal space (so its height can change any time to accomodate line breaking). The header should always be visible and attached to the top of the "screen". The footer will contain a set of buttons, like on a dialog window. These too can wrap to next line if there is not enough space horizontally. The footer must be attached to the bottom of the "screen" to be accessible and visible at all times. The content will contain "screen" contents, like dialog fields etc. If there are too few fields, the rest of the content will be "blank" (in this case the footer should not begin right after the content, but still be attached to the bottom of the "screen" which is fixed size). If there are too many fields, the content DIV will provide scrollbar(s) to access the hidden controls (in this case the content DIV must not extend itself below the footer, as the scrollbar would be partially hidden). I hope this clarifies the question a little bit further, as I have too low rep to enter comments to your repsonses. A: I'm going to get downmodded for this, but this sounds like a job for a table. What you're trying to do is to set the total height of three contiguous divs as a unit, and a 1x3 table with height 100% is actually a cleaner solution. A: Pure CSS Solution 1 - Flexbox: You can create a column of divs that behave in this way by using the CSS3 display: flex; property (see W3 Specs) Using a wrapper, you can align everything in a column with the flex-direction: column; declaration and then fill the vertical space with justify content: space-between; and height: 100vh;. Then all you need to do is make your content element expand with flex: 1 0 0; and give it a scrollbar with overflow-y: auto;. Note on browser support - While flexbox is supported by most modern browsers, there are still a few limitations (see: http://caniuse.com/#feat=flexbox). I would recommend using the -webkit- and -ms- prefixes. Working example: See the following snippet and this jsfiddle. body { display: -webkit-flex; /* Safari 6.1+ */ display: -ms-flex; /* IE 10 */ display: flex; -webkit-flex-direction: column; /* Safari 6.1+ */ -ms-flex-direction: column; /* IE 10 */ flex-direction: column; -webkit-justify-content: space-between; /* Safari 6.1+ */ -ms-justify-content: space-between; /* IE 10 */ justify-content: space-between; /* Header top, footer bottom */ height: 100vh; /* Fill viewport height */ } main { -webkit-flex: 1 0 0; /* Safari 6.1+ */ -ms-flex: 1 0 0; /* IE 10 */ flex: 1 0 0; /* Grow to fill space */ overflow-y: auto; /* Add scrollbar */ height: 100%; /* Needed to fill space in IE */ } header, footer { -webkit-flex: 0 0 auto; /* Safari 6.1+ */ -ms-flex: 0 0 auto; /* IE 10 */ flex: 0 0 auto; } /* Make it look a little nicer */ body { margin: 0; background-color: #8080ff; } header { background-color: #80ff80; } footer { background-color: #ff8080; } p { margin: 1.25rem; } <body> <header> <p>header</p> </header> <main> <article> <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nullam pellentesque lobortis augue, in porta arcu dapibus dapibus. Suspendisse vulputate tempus venenatis. Pellentesque ac euismod urna. Donec dui odio, ullamcorper in posuere eu, laoreet sed nisl. Sed vitae vestibulum leo. Maecenas mattis lacus eget nisl malesuada, quis semper urna ornare. Praesent id mauris nec neque aliquet dignissim.</p> <p>Morbi varius dolor at lorem aliquet lacinia. Aliquam id lacinia quam. Sed vel libero felis. Etiam et pellentesque sem. Aenean bibendum, ante quis luctus tincidunt, elit mauris volutpat nisi, et tempus lectus sapien in mauris. Aliquam condimentum nisl ut elit accumsan hendrerit. Morbi mollis turpis est, id tincidunt ipsum rhoncus eget. Fusce in feugiat lacus. Quisque vel massa magna. Mauris varius congue nisl, vitae pellentesque diam ultricies at. Sed ac nibh ac diam tristique venenatis non nec nisl. Vivamus enim eros, pretium at iaculis nec, pharetra non sem. Aenean ac imperdiet odio.</p> <p>Morbi varius dolor at lorem aliquet lacinia. Aliquam id lacinia quam. Sed vel libero felis. Etiam et pellentesque sem. Aenean bibendum, ante quis luctus tincidunt, elit mauris volutpat nisi, et tempus lectus sapien in mauris. Aliquam condimentum nisl ut elit accumsan hendrerit. Morbi mollis turpis est, id tincidunt ipsum rhoncus eget. Fusce in feugiat lacus. Quisque vel massa magna. Mauris varius congue nisl, vitae pellentesque diam ultricies at. Sed ac nibh ac diam tristique venenatis non nec nisl. Vivamus enim eros, pretium at iaculis nec, pharetra non sem. Aenean ac imperdiet odio.</p> </article> </main> <footer> <p>footer</p> </footer> </body> For more information on how to use flexbox see these guides: * *https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Flexible_boxes *https://css-tricks.com/snippets/css/a-guide-to-flexbox/ Pure CSS Solution 2 - Display Table [Old solution]: This can also be done by using the CSS display: table; property (see W3 Specs). The HTML: <div id="screen"> <div id="header"></div> <div id="content"> <div id="content_frame"> <div id="content_wrap"></div> </div> </div> <div id="footer"></div> </div> The CSS: html, body, #screen, #content, #content_frame { height: 100%; /* Make #screen viewport height and #content fill space */ } #screen { display: table; } #header, #content, #footer { display: table-row; } #content_frame { overflow-y: auto; /* Add scrollbar */ position: relative; } #content_wrap { position: absolute; /* Fix problem with overflow in FF */ } The overflow property is unreliable on css table elements and their children, so I had to nest the content. In this case I was forced to nest twice and use position: absolute; in order to make it work in Firefox. Maybe someone else can come up with a more elegant solution to avoid this 'divitis'. Here is a functioning jsfiddle. Warning: This does not appear to work in Opera 12! The content div takes up 100% of the parent's height which causes the rows to overflow the table (as they did in firefox). A: If you can get away with not having the main content scrollable, you might be better using the footerStickAlt method to make sure your footer stays at the bottom of the screen or the bottom of the content (if the content extends beyond the bottom of the screen). A: Absolute positioning is messing you up. Try something like this: HTML: <div id="wrapper"> <div id="header"> header </div> <div id="content"> content </div> <div id="footer"> footer </div> </div> CSS: #wrapper { width: 200px; height: 200px; overflow: visible; background: #e0e0ff; } #header { background: #80ff80; } #content { background: #8080ff; } #footer { background: #ff8080; } edit: perhaps I misunderstood, do you want everything to fit into the 200x200px box or do you want the box to increase its height to fit the content? A: Does the parent need to stay at a fixed height? <div style="position : relative; width : 200px; background-color : #e0e0ff; overflow : hidden;"> <div style="float: left; clear: left; background-color: #80ff80;"> header </div> <div style="float: left; clear: left; background-color: #8080ff; overflow : auto; "> content (how to position it?) <BR />taller <BR />taller <BR />taller <BR />taller <BR />taller <BR />taller <BR />taller <BR />taller </div> <div style="float: left; clear: left; background-color: #ff8080;"> footer <BR />taller </div> if the height of the parent is fixed, this is the closest I'd know how to get to it offhand -- still not exactly right if those color blocks (as opposed to just text) are truly important and weren't just for illustrating the boundaries of the DIVs: <div style="position : relative; width : 200px; height : 200px; background-color : #e0e0ff; overflow : hidden;"> <div style="float: left; clear: left; background-color: #80ff80; "> header <BR .> taller </div> <div style="float: left; clear: left; background-color: #8080ff; overflow : auto; "> content (how to position it?)<BR /> and another line </div> <div style="background-color: #ff8080; position : absolute; bottom : 0px; left :0; right : 0;"> footer <BR /> taller </div> A: Do you need to have the center div change size? If you're just trying to make sure that it appears that its background (#8080ff) appears between the header and the footer, why not just have the containing div's background be #8080ff. The header and footer background would override that, and the rest of the div's background would be correct. A: This can be solved by using different techniques. The first one is using media queries. Using them, you can define what your page should look like for each screen size. Secondly, there are several techniques for positioning your footer correctly (sticky footer). Thirdly, you can use different table styles or the flexbox approach to position your content correctly.
{ "language": "en", "url": "https://stackoverflow.com/questions/57091", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }
Q: How can I programmatically run the ASP.Net Development Server using C#? I have ASP.NET web pages for which I want to build automated tests (using WatiN & MBUnit). How do I start the ASP.Net Development Server from my code? I do not want to use IIS. A: This is what I used that worked: using System; using System.Diagnostics; using System.Web; ... // settings string PortNumber = "1162"; // arbitrary unused port # string LocalHostUrl = string.Format("http://localhost:{0}", PortNumber); string PhysicalPath = Environment.CurrentDirectory // the path of compiled web app string VirtualPath = ""; string RootUrl = LocalHostUrl + VirtualPath; // create a new process to start the ASP.NET Development Server Process process = new Process(); /// configure the web server process.StartInfo.FileName = HttpRuntime.ClrInstallDirectory + "WebDev.WebServer.exe"; process.StartInfo.Arguments = string.Format("/port:{0} /path:\"{1}\" /virtual:\"{2}\"", PortNumber, PhysicalPath, VirtualPath); process.StartInfo.CreateNoWindow = true; process.StartInfo.UseShellExecute = false; // start the web server process.Start(); // rest of code... A: From what I know, you can fire up the dev server from the command prompt with the following path/syntax: C:\Windows\Microsoft.NET\Framework\v2.0.50727\Webdev.WebServer.exe /port:[PORT NUMBER] /path: [PATH TO ROOT] ...so I could imagine you could easily use Process.Start() to launch the particulars you need through some code. Naturally you'll want to adjust that version number to whatever is most recent/desired for you. A: Building upon @Ray Vega's useful answer, and @James McLachlan's important update for VS2010, here is my implementation to cover VS2012 and fallback to VS2010 if necessary. I also chose not to select only on Environment.Is64BitOperatingSystem because it went awry on my system. That is, I have a 64-bit system but the web server was in the 32-bit folder. My code therefore looks first for the 64-bit folder and falls back to the 32-bit one if necessary. public void LaunchWebServer(string appWebDir) { var PortNumber = "1162"; // arbitrary unused port # var LocalHostUrl = string.Format("http://localhost:{0}", PortNumber); var VirtualPath = "/"; var exePath = FindLatestWebServer(); var process = new Process { StartInfo = { FileName = exePath, Arguments = string.Format( "/port:{0} /nodirlist /path:\"{1}\" /virtual:\"{2}\"", PortNumber, appWebDir, VirtualPath), CreateNoWindow = true, UseShellExecute = false } }; process.Start(); } private string FindLatestWebServer() { var exeCandidates = new List<string> { BuildCandidatePaths(11, true), // vs2012 BuildCandidatePaths(11, false), BuildCandidatePaths(10, true), // vs2010 BuildCandidatePaths(10, false) }; return exeCandidates.Where(f => File.Exists(f)).FirstOrDefault(); } private string BuildCandidatePaths(int versionNumber, bool isX64) { return Path.Combine( Environment.GetFolderPath(isX64 ? Environment.SpecialFolder.CommonProgramFiles : Environment.SpecialFolder.CommonProgramFilesX86), string.Format( @"microsoft shared\DevServer\{0}.0\WebDev.WebServer40.EXE", versionNumber)); } I am hoping that an informed reader might be able to supply the appropriate incantation for VS2013, as it apparently uses yet a different scheme... A: You can easily use Process Explorer to find complete command line options needed for manually start it. Start Process Explorer while debugging your website. For VS2012, expand 'devenv.exe' node. Right-click on 'WebDev.WebServer20.exe' and from there you can see Path and Command Line values.
{ "language": "en", "url": "https://stackoverflow.com/questions/57094", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "12" }
Q: Embedded java databases I would like to get opinions or suggestions regarding embedded databases in Java. In particular I was looking at H2, HSQLDB and Derby. Have you use any of these in a production project? Do you have comment or recommendations to select one over the others? Thanks Edit: I am currently evaluating these options to use in our internal developments, so I don't have a specific use case in mind. One of the possible uses I am evaluating them for is a desktop application that uses the database as a local repository. At some point it synchronizes with a central repository (in this case DB2). It is a store and forward architecture. Anyway, this is just a possibility to guide your answers, Basically I’m looking for your experiences using these tools.
{ "language": "en", "url": "https://stackoverflow.com/questions/57102", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "43" }
Q: Rails Binary Stream support I'm going to be starting a project soon that requires support for large-ish binary files. I'd like to use Ruby on Rails for the webapp, but I'm concerned with the BLOB support. In my experience with other languages, frameworks, and databases, BLOBs are often overlooked and thus have poor, difficult, and/or buggy functionality. Does RoR spport BLOBs adequately? Are there any gotchas that creep up once you're already committed to Rails? BTW: I want to be using PostgreSQL and/or MySQL as the backend database. Obviously, BLOB support in the underlying database is important. For the moment, I want to avoid focusing on the DB's BLOB capabilities; I'm more interested in how Rails itself reacts. Ideally, Rails should be hiding the details of the database from me, and so I should be able to switch from one to the other. If this is not the case (ie: there's some problem with using Rails with a particular DB) then please do mention it. UPDATE: Also, I'm not just talking about ActiveRecord here. I'll need to handle binary files on the HTTP side (file upload effectively). That means getting access to the appropriate HTTP headers and streams via Rails. I've updated the question title and description to reflect this. A: +1 for attachment_fu I use attachment_fu in one of my apps and MUST store files in the DB (for annoying reasons which are outside the scope of this convo). The (one?) tricky thing dealing w/BLOB's I've found is that you need a separate code path to send the data to the user -- you can't simply in-line a path on the filesystem like you would if it was a plain-Jane file. e.g. if you're storing avatar information, you can't simply do: <%= image_tag @youruser.avatar.path %> you have to write some wrapper logic and use send_data, e.g. (below is JUST an example w/attachment_fu, in practice you'd need to DRY this up) send_data(@youruser.avatar.current_data, :type => @youruser.avatar.content_type, :filename => @youruser.avatar.filename, :disposition => 'inline' ) Unfortunately, as far as I know attachment_fu (I don't have the latest version) does not do clever wrapping for you -- you've gotta write it yourself. P.S. Seeing your question edit - Attachment_fu handles all that annoying stuff that you mention -- about needing to know file paths and all that crap -- EXCEPT the one little issue when storing in the DB. Give it a try; it's the standard for rails apps. IF you insist on re-inventing the wheel, the source code for attachment_fu should document most of the gotchas, too! A: You can use the :binary type in your ActiveRecord migration and also constrain the maximum size: class BlobTest < ActiveRecord::Migration def self.up create_table :files do |t| t.column :file_data, :binary, :limit => 1.megabyte end end end ActiveRecord exposes the BLOB (or CLOB) contents as a Ruby String. A: I think your best bet is the attachment_fu plug-in: http://github.com/technoweenie/attachment_fu/tree/master UPDATE: Found some more info here http://groups.google.com/group/rubyonrails-talk/browse_thread/thread/a81beffb93708bb3 A: As for streaming, you can do it all in an (at least memory-) efficient way. On the upload side, file parameters in forms are abstracted as IO objects that you can read from; on the download side, look in to the form of render :text => that takes a Proc argument: render :content_type => 'application/octet-stream', :text => Proc.new { |response, output| # do something that reads data and writes it to output } If your stuff is in files on disk, though, the aforementioned solutions will certainly work better. A: Look into the plugin, x_send_file too. "The XSendFile plugin provides a simple interface for sending files via the X-Sendfile HTTP header. This enables your web server to serve the file directly from disk, instead of streaming it through your Rails process. This is faster and saves a lot of memory if you‘re using Mongrel. Not every web server supports this header. YMMV." I'm not sure if it's usable with Blobs, it may just be for files on the file system. But you probably need something that doesn't tie up the web server streaming large chunks of data.
{ "language": "en", "url": "https://stackoverflow.com/questions/57104", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "16" }
Q: How to detect true Windows version? I know I can call the GetVersionEx Win32 API function to retrieve Windows version. In most cases returned value reflects the version of my Windows, but sometimes that is not so. If a user runs my application under the compatibility layer, then GetVersionEx won't be reporting the real version but the version enforced by the compatibility layer. For example, if I'm running Vista and execute my program in "Windows NT 4" compatibility mode, GetVersionEx won't return version 6.0 but 4.0. Is there a way to bypass this behaviour and get true Windows version? A: Another solution: read the following registry entry: HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProductName or other keys from HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion A: real version store on PEB block of process information. Sample for Win32 app (Delphi Code) unit RealWindowsVerUnit; interface uses Windows; var //Real version Windows Win32MajorVersionReal: Integer; Win32MinorVersionReal: Integer; implementation type PPEB=^PEB; PEB = record InheritedAddressSpace: Boolean; ReadImageFileExecOptions: Boolean; BeingDebugged: Boolean; Spare: Boolean; Mutant: Cardinal; ImageBaseAddress: Pointer; LoaderData: Pointer; ProcessParameters: Pointer; //PRTL_USER_PROCESS_PARAMETERS; SubSystemData: Pointer; ProcessHeap: Pointer; FastPebLock: Pointer; FastPebLockRoutine: Pointer; FastPebUnlockRoutine: Pointer; EnvironmentUpdateCount: Cardinal; KernelCallbackTable: PPointer; EventLogSection: Pointer; EventLog: Pointer; FreeList: Pointer; //PPEB_FREE_BLOCK; TlsExpansionCounter: Cardinal; TlsBitmap: Pointer; TlsBitmapBits: array[0..1] of Cardinal; ReadOnlySharedMemoryBase: Pointer; ReadOnlySharedMemoryHeap: Pointer; ReadOnlyStaticServerData: PPointer; AnsiCodePageData: Pointer; OemCodePageData: Pointer; UnicodeCaseTableData: Pointer; NumberOfProcessors: Cardinal; NtGlobalFlag: Cardinal; Spare2: array[0..3] of Byte; CriticalSectionTimeout: LARGE_INTEGER; HeapSegmentReserve: Cardinal; HeapSegmentCommit: Cardinal; HeapDeCommitTotalFreeThreshold: Cardinal; HeapDeCommitFreeBlockThreshold: Cardinal; NumberOfHeaps: Cardinal; MaximumNumberOfHeaps: Cardinal; ProcessHeaps: Pointer; GdiSharedHandleTable: Pointer; ProcessStarterHelper: Pointer; GdiDCAttributeList: Pointer; LoaderLock: Pointer; OSMajorVersion: Cardinal; OSMinorVersion: Cardinal; OSBuildNumber: Cardinal; OSPlatformId: Cardinal; ImageSubSystem: Cardinal; ImageSubSystemMajorVersion: Cardinal; ImageSubSystemMinorVersion: Cardinal; GdiHandleBuffer: array [0..33] of Cardinal; PostProcessInitRoutine: Cardinal; TlsExpansionBitmap: Cardinal; TlsExpansionBitmapBits: array [0..127] of Byte; SessionId: Cardinal; end; //Get PEB block current win32 process function GetPDB: PPEB; stdcall; asm MOV EAX, DWORD PTR FS:[30h] end; initialization //Detect true windows wersion Win32MajorVersionReal := GetPDB^.OSMajorVersion; Win32MinorVersionReal := GetPDB^.OSMinorVersion; end. A: The following works for me in Windows 10 without the Windows 10 GUID listed in the application manifest: uses System.SysUtils, Winapi.Windows; type NET_API_STATUS = DWORD; _SERVER_INFO_101 = record sv101_platform_id: DWORD; sv101_name: LPWSTR; sv101_version_major: DWORD; sv101_version_minor: DWORD; sv101_type: DWORD; sv101_comment: LPWSTR; end; SERVER_INFO_101 = _SERVER_INFO_101; PSERVER_INFO_101 = ^SERVER_INFO_101; LPSERVER_INFO_101 = PSERVER_INFO_101; const MAJOR_VERSION_MASK = $0F; function NetServerGetInfo(servername: LPWSTR; level: DWORD; var bufptr): NET_API_STATUS; stdcall; external 'Netapi32.dll'; function NetApiBufferFree(Buffer: LPVOID): NET_API_STATUS; stdcall; external 'Netapi32.dll'; type pfnRtlGetVersion = function(var RTL_OSVERSIONINFOEXW): LONG; stdcall; var Buffer: PSERVER_INFO_101; ver: RTL_OSVERSIONINFOEXW; RtlGetVersion: pfnRtlGetVersion; begin Buffer := nil; // Win32MajorVersion and Win32MinorVersion are populated from GetVersionEx()... ShowMessage(Format('GetVersionEx: %d.%d', [Win32MajorVersion, Win32MinorVersion])); // shows 6.2, as expected per GetVersionEx() documentation @RtlGetVersion := GetProcAddress(GetModuleHandle('ntdll.dll'), 'RtlGetVersion'); if Assigned(RtlGetVersion) then begin ZeroMemory(@ver, SizeOf(ver)); ver.dwOSVersionInfoSize := SizeOf(ver); if RtlGetVersion(ver) = 0 then ShowMessage(Format('RtlGetVersion: %d.%d', [ver.dwMajorVersion, ver.dwMinorVersion])); // shows 10.0 end; if NetServerGetInfo(nil, 101, Buffer) = NO_ERROR then try ShowMessage(Format('NetServerGetInfo: %d.%d', [Buffer.sv101_version_major and MAJOR_VERSION_MASK, Buffer.sv101_version_minor])); // shows 10.0 finally NetApiBufferFree(Buffer); end; end. Update: NetWkstaGetInfo() would probably also work, similar to 'NetServerGetInfo()`, but I have not try it yet. A: The best approach I know is to check if specific API is exported from some DLL. Each new Windows version adds new functions and by checking the existance of those functions one can tell which OS the application is running on. For example, Vista exports GetLocaleInfoEx from kernel32.dll while previous Windowses didn't. To cut the long story short, here is one such list containing only exports from kernel32.dll. > *function: implemented in* > GetLocaleInfoEx: Vista > GetLargePageMinimum: Vista, Server 2003 GetDLLDirectory: Vista, Server 2003, XP SP1 GetNativeSystemInfo: Vista, Server 2003, XP SP1, XP ReplaceFile: Vista, Server 2003, XP SP1, XP, 2000 OpenThread: Vista, Server 2003, XP SP1, XP, 2000, ME GetThreadPriorityBoost: Vista, Server 2003, XP SP1, XP, 2000, NT 4 IsDebuggerPresent: Vista, Server 2003, XP SP1, XP, 2000, ME, NT 4, 98 GetDiskFreeSpaceEx: Vista, Server 2003, XP SP1, XP, 2000, ME, NT 4, 98, 95 OSR2 ConnectNamedPipe: Vista, Server 2003, XP SP1, XP, 2000, NT 4, NT 3 Beep: Vista, Server 2003, XP SP1, XP, 2000, ME, 98, 95 OSR2, 95 Writing the function to determine the real OS version is simple; just proceed from newest OS to oldest and use GetProcAddress to check exported APIs. Implementing this in any language should be trivial. The following code in Delphi was extracted from the free DSiWin32 library): TDSiWindowsVersion = (wvUnknown, wvWin31, wvWin95, wvWin95OSR2, wvWin98, wvWin98SE, wvWinME, wvWin9x, wvWinNT3, wvWinNT4, wvWin2000, wvWinXP, wvWinNT, wvWinServer2003, wvWinVista); function DSiGetWindowsVersion: TDSiWindowsVersion; var versionInfo: TOSVersionInfo; begin versionInfo.dwOSVersionInfoSize := SizeOf(versionInfo); GetVersionEx(versionInfo); Result := wvUnknown; case versionInfo.dwPlatformID of VER_PLATFORM_WIN32s: Result := wvWin31; VER_PLATFORM_WIN32_WINDOWS: case versionInfo.dwMinorVersion of 0: if Trim(versionInfo.szCSDVersion[1]) = 'B' then Result := wvWin95OSR2 else Result := wvWin95; 10: if Trim(versionInfo.szCSDVersion[1]) = 'A' then Result := wvWin98SE else Result := wvWin98; 90: if (versionInfo.dwBuildNumber = 73010104) then Result := wvWinME; else Result := wvWin9x; end; //case versionInfo.dwMinorVersion VER_PLATFORM_WIN32_NT: case versionInfo.dwMajorVersion of 3: Result := wvWinNT3; 4: Result := wvWinNT4; 5: case versionInfo.dwMinorVersion of 0: Result := wvWin2000; 1: Result := wvWinXP; 2: Result := wvWinServer2003; else Result := wvWinNT end; //case versionInfo.dwMinorVersion 6: Result := wvWinVista; end; //case versionInfo.dwMajorVersion end; //versionInfo.dwPlatformID end; { DSiGetWindowsVersion } function DSiGetTrueWindowsVersion: TDSiWindowsVersion; function ExportsAPI(module: HMODULE; const apiName: string): boolean; begin Result := GetProcAddress(module, PChar(apiName)) <> nil; end; { ExportsAPI } var hKernel32: HMODULE; begin { DSiGetTrueWindowsVersion } hKernel32 := GetModuleHandle('kernel32'); Win32Check(hKernel32 <> 0); if ExportsAPI(hKernel32, 'GetLocaleInfoEx') then Result := wvWinVista else if ExportsAPI(hKernel32, 'GetLargePageMinimum') then Result := wvWinServer2003 else if ExportsAPI(hKernel32, 'GetNativeSystemInfo') then Result := wvWinXP else if ExportsAPI(hKernel32, 'ReplaceFile') then Result := wvWin2000 else if ExportsAPI(hKernel32, 'OpenThread') then Result := wvWinME else if ExportsAPI(hKernel32, 'GetThreadPriorityBoost') then Result := wvWinNT4 else if ExportsAPI(hKernel32, 'IsDebuggerPresent') then //is also in NT4! Result := wvWin98 else if ExportsAPI(hKernel32, 'GetDiskFreeSpaceEx') then //is also in NT4! Result := wvWin95OSR2 else if ExportsAPI(hKernel32, 'ConnectNamedPipe') then Result := wvWinNT3 else if ExportsAPI(hKernel32, 'Beep') then Result := wvWin95 else // we have no idea Result := DSiGetWindowsVersion; end; { DSiGetTrueWindowsVersion } --- updated 2009-10-09 It turns out that it gets very hard to do an "undocumented" OS detection on Vista SP1 and higher. A look at the API changes shows that all Windows 2008 functions are also implemented in Vista SP1 and that all Windows 7 functions are also implemented in Windows 2008 R2. Too bad :( --- end of update FWIW, this is a problem I encountered in practice. We (the company I work for) have a program that was not really Vista-ready when Vista was released (and some weeks after that ...). It was not working under the compatibility layer either. (Some DirectX problems. Don't ask.) We didn't want too-smart-for-their-own-good users to run this app on Vista at all - compatibility mode or not - so I had to find a solution (a guy smarter than me pointed me into right direction; the stuff above is not my brainchild). Now I'm posting it for your pleasure and to help all poor souls that will have to solve this problem in the future. Google, please index this article! If you have a better solution (or an upgrade and/or fix for mine), please post an answer here ... A: WMI QUery: "Select * from Win32_OperatingSystem" EDIT: Actually better would be: "Select Version from Win32_OperatingSystem" You could implement this in Delphi like so: function OperatingSystemDisplayName: string; function GetWMIObject(const objectName: string): IDispatch; var chEaten: Integer; BindCtx: IBindCtx; Moniker: IMoniker; begin OleCheck(CreateBindCtx(0, bindCtx)); OleCheck(MkParseDisplayName(BindCtx, PChar(objectName), chEaten, Moniker)); OleCheck(Moniker.BindToObject(BindCtx, nil, IDispatch, Result)); end; function VarToString(const Value: OleVariant): string; begin if VarIsStr(Value) then begin Result := Trim(Value); end else begin Result := ''; end; end; function FullVersionString(const Item: OleVariant): string; var Caption, ServicePack, Version, Architecture: string; begin Caption := VarToString(Item.Caption); ServicePack := VarToString(Item.CSDVersion); Version := VarToString(Item.Version); Architecture := ArchitectureDisplayName(SystemArchitecture); Result := Caption; if ServicePack <> '' then begin Result := Result + ' ' + ServicePack; end; Result := Result + ', version ' + Version + ', ' + Architecture; end; var objWMIService: OleVariant; colItems: OleVariant; Item: OleVariant; oEnum: IEnumvariant; iValue: LongWord; begin Try objWMIService := GetWMIObject('winmgmts:\\localhost\root\cimv2'); colItems := objWMIService.ExecQuery('SELECT Caption, CSDVersion, Version FROM Win32_OperatingSystem', 'WQL', 0); oEnum := IUnknown(colItems._NewEnum) as IEnumVariant; if oEnum.Next(1, Item, iValue)=0 then begin Result := FullVersionString(Item); exit; end; Except // yes, I know this is nasty, but come what may I want to use the fallback code below should the WMI code fail End; (* Fallback, relies on the deprecated function GetVersionEx, reports erroneous values when manifest does not contain supportedOS matching the executing system *) Result := TOSVersion.ToString; end; A: How about obtaining the version of a system file? The best file would be kernel32.dll, located in %WINDIR%\System32\kernel32.dll. There are APIs to obtain the file version. eg: I'm using Windows XP -> "5.1.2600.5512 (xpsp.080413-2111)" A: Note: Gabr is asking about an approach that can bypass the limitations of GetVersionEx. JCL code uses GetVersionEx, and is thus subject to compatibility layer. This information is for people who don't need to bypass the compatibility layer, only. Using the Jedi JCL, you can add unit JclSysInfo, and call function GetWindowsVersion. It returns an enumerated type TWindowsVersion. Currently JCL contains all shipped windows versions, and gets changed each time Microsoft ships a new version of Windows in a box: TWindowsVersion = (wvUnknown, wvWin95, wvWin95OSR2, wvWin98, wvWin98SE, wvWinME, wvWinNT31, wvWinNT35, wvWinNT351, wvWinNT4, wvWin2000, wvWinXP, wvWin2003, wvWinXP64, wvWin2003R2, wvWinVista, wvWinServer2008, wvWin7, wvWinServer2008R2); If you want to know if you're running 64-bit windows 7 instead of 32-bit, then call JclSysInfo.IsWindows64. Note that JCL allso handles Editions, like Pro, Ultimate, etc. For that call GetWindowsEdition, and it returns one of these: TWindowsEdition = (weUnknown, weWinXPHome, weWinXPPro, weWinXPHomeN, weWinXPProN, weWinXPHomeK, weWinXPProK, weWinXPHomeKN, weWinXPProKN, weWinXPStarter, weWinXPMediaCenter, weWinXPTablet, weWinVistaStarter, weWinVistaHomeBasic, weWinVistaHomeBasicN, weWinVistaHomePremium, weWinVistaBusiness, weWinVistaBusinessN, weWinVistaEnterprise, weWinVistaUltimate, weWin7Starter, weWin7HomeBasic, weWin7HomePremium, weWin7Professional, weWin7Enterprise, weWin7Ultimate); For historical interest, you can check the NT-level edition too with the NtProductType function, it returns: TNtProductType =       (ptUnknown, ptWorkStation, ptServer, ptAdvancedServer,        ptPersonal, ptProfessional, ptDatacenterServer, ptEnterprise, ptWebEdition); Note that "N editions" are detected above. That's an EU (Europe) version of Windows, created due to EU anti-trust regulations. That's a pretty fine gradation of detection inside the JCL. Here's a sample function that will help you detect Vista, and do something special when on Vista. function IsSupported:Boolean; begin case GetWindowsVersion of wvVista: result := false; else result := true; end; end; Note that if you want to do "greater than" checking, then you should just use other techniques. Also note that version checking can often be a source of future breakage. I have usually chosen to warn users and continue, so that my binary code doesn't become the actual source of breakage in the future. Recently I tried to install an app, and the installer checked my drive free space, and would not install, because I had more than 2 gigabytes of free space. The 32 bit integer signed value in the installer became negative, breaking the installer. I had to install it into a VM to get it to work. Adding "smart code" often makes your app "stupider". Be wary. Incidentally, I found that from the command line, you can run WMIC.exe, and type path Win32_OperatingSystem (The "Select * from Win32_OperatingSystem" didn't work for me). In future perhaps JCL could be extended to use the WMI information. A: Essentially to answer duplicate Q: Getting OS major, minor, and build versions for Windows 8.1 and up in Delphi 2007 Starting with W2K you can use NetServerGetInfo. NetServerGetInfo returns the correct info on W7 and W8.1, unable to test on W10.. function GetWinVersion: string; var Buffer: PServerInfo101; begin Buffer := nil; if NetServerGetInfo(nil, 101, Pointer(Buffer)) = NO_ERROR then try Result := <Build You Version String here>( Buffer.sv101_version_major, Buffer.sv101_version_minor, VER_PLATFORM_WIN32_NT // Save since minimum support begins in W2K ); finally NetApiBufferFree(Buffer); end; end; A: One note about using NetServerGetInfo(), which does work still on Windows 10 (10240.th1_st1)... https://msdn.microsoft.com/en-us/library/windows/desktop/aa370903%28v=vs.85%29.aspx sv101_version_major The major version number and the server type. The major release version number of the operating system is specified in the least significant 4 bits. The server type is specified in the most significant 4 bits. The MAJOR_VERSION_MASK bitmask defined in the Lmserver.h header {0x0F} should be used by an application to obtain the major version number from this member. In other words, (sv101_version_major & MAJOR_VERSION_MASK).
{ "language": "en", "url": "https://stackoverflow.com/questions/57124", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "41" }
Q: 403 Forbidden error using Subversion I recently upgraded to Subversion 1.5, and now I cannot commit my code to the repository. I get an error message: "403 Forbidden in response to MKACTIVITY". I know the upgrade worked because my fellow developers are not getting this issue. What's going on? A: We run into the periodically and it is very frustrating to developers. For some reason reading from the repository seems to be case insensitive but commit cares. I understand the reason why case matters due to Subversion's roots in unix filing systems that are case sensitive, but I really wish you would get the error on the initial checkout not on the commit! A: Answering my own question: Apparently my SVN URL had the wrong case! A Google search turned up an article (no longer available online) that explained what was going on. My URL was of the form http://svn.foobar.com/foobar but the actual repository was called http://svn.foobar.com/fooBar. I use TortoiseSVN, so the fix was to use the Relocate command to correct the path to the repository. Hopefully this will help someone else. A: Another instance when this issue will rear its head is if you commit a file twice with the same name but with different capitalizations (e.g., foobar and FooBar). This is only possible, of course, on a windows system and may just be a special case of Todd's answer above. One of our developers accidentally did this and it similarly cost us many debugging hours. A: Todd is right. The stupid thing is that the repo browser accepts upper- and lowercase when checking out but the commit will fail if you used the wrong case when checking out. I checked out from https://svn.domain.com/Company/Product/trunk but couldn't commit because the correct URL was https://svn.domain.com/company/product/trunk. A: Another possible reason, within a msWin environment as client, are the proxy settings. Configuration: internet-explorer/internetOptions/connections/LAN-Settings/advanced/exceptions Put your SVN-Server within the exceptions. Names may be others, I do not use english as sys language. A: The error Access to 'foo' forbidden or 403 Forbidden indicates that your user account lacks permissions to the requested repository. As repository names and paths in repositories are case-sensitive, you should check that the URL you entered is correct and that you log on under correct credentials. Run svn auth to view stored credentials on your client computer. Normally, access control in Subversion is implemented in form of path-based authorization and fully supports Read / Write, Read Only and No Access access levels. If you implement a complex access control policy, you must understand the access control principles in Subversion. Read the article KB33: Understanding VisualSVN Server authorization for more information. While it says 'VisualSVN Server' in title, the article covers path-based authorization in general and should apply to other SVN server distributions. A: I had the same issue. I tried several answers provided above, but none worked for me. I found out that I had two versions of eclipse installed and subversion was installed on the previous version of eclipse. I've done the below steps to resolve the 403-forbidden-error: * *delete the subversion folder \AppData\Roaming\Subversion *uninstall subversion from eclipse *installed subversion A: I had credentials that were no longer used, but they were recorded in the settings. It was enough to remove these old settings that my problem was solved. Open Settings of Tortoise SVN: * *Saved Data * *Authentication data * *Clear all *Refresh repository *Login again with right credencials A: I think the thing here is that Subversion (regardless of OS platform its server is installed on) is case sensitive. However, clients' OS maybe not. And that might create a problem. In my company I have had this case and it took me about an hour to figure it out. So, one developer, who was working on mac, committed to svn file with the same name, but he changed couple of letters in its name to capital ones. For mac and subversion it is not a problem and file got in. Later another developer, who happened to work on windows laptop got an error and windows got completely confused and could not do anything. so, the solution was - I asked developers, which of two files I can delete. I did it on linux and everybody happy ever since. so, upper/low case spelling is not a subversion problem, but windows OS one. A: It happened for me and the reason being i do not have access to that folder. Once admin added my user, i was able to checkout the code. A: I had the same issue: an error occurred while accessing the repository entry(403 Forbidden) and i found a few different approaches. But for me the solution was: download the correct plugin (subclipse 1.4) version for svn installed on server which was 1.4.3 A: The user/certificate has no privileges to read the repo in svn. For that reason, you can not access the repository through the browser / tortoise. Talk with the admin to solve this problem. A: In my case the issue was that, Jenkins was going through a proxy. I had given below properties in catalina.properties file of Tomcat. http.proxyHost=proxyserver http.proxyPort=3128 In order to instruct it to avoid going through proxy I had to add http.nonProxyHosts property. Multiple hosts can be seperated by pipe (|) http.nonProxyHosts=localhost|*.companydomain.com SVN server was on the intranet. I didn't need to go through proxy. A: For me, update was working but the commit operation was giving me 403 forbidden error. I got this fixed when I did the email verification.
{ "language": "en", "url": "https://stackoverflow.com/questions/57137", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "45" }
Q: Is there any disadvantage to returning this instead of void? Say instead of returning void a method you returned a reference to the class even if it didn't make any particular semantic sense. It seems to me like it would give you more options on how the methods are called, allowing you to use it in a fluent-interface-like style and I can't really think of any disadvantages since you don't have to do anything with the return value (even store it). So suppose you're in a situation where you want to update an object and then return its current value. instead of saying myObj.Update(); var val = myObj.GetCurrentValue(); you will be able to combine the two lines to say var val = myObj.Update().GetCurrentValue(); EDIT: I asked the below on a whim, in retrospect, I agree that its likely to be unnecessary and complicating, however my question regarding returning this rather than void stands. On a related note, what do you guys think of having the language include a new bit of syntactic sugar: var val = myObj.Update()<.GetCurrentValue(); This operator would have a low order of precedence so myObj.Update() would execute first and then call GetCurrentValue() on myObj instead of the void return of Update. Essentially I'm imagining an operator that will say "call the method on the right-hand side of the operator on the first valid object on the left". Any thoughts? A: The only disadvantage I can see is that it makes the API slightly more confusing. Let's say you have some collection object with a remove() method that would normally return void. Now you want to return a reference to the collection itself. The new signature would look like: public MyCollection remove(Object someElement) Just looking at the signature, it's not clear that you're returning a reference to the same instance. Maybe MyCollection is immutable and you're returning a new instance. In some cases, like here, you would need some external documentation to clarify this. I actually like this idea, and I believe that there was some talk in retrofitting all void methods in Java7 to return a reference to 'this', but it ultimately fell through. A: Isn't this how "fluent interfaces" - like those that JQuery utilizes - are built? One benefit is supposed to be code readability (though the wikipedia entry at http://en.wikipedia.org/wiki/Fluent_interface mentions that some find it NOT readable). Another benefit is in code terseness, you lose the need to set properties in 7 lines of code and then call a method on that object in the 8th line. Martin Fowler (who coined the term here - http://martinfowler.com/bliki/FluentInterface.html) says that there is more to fluent interfaces than method chaining, however method chaining is a common technique to use with fluent interfaces. EDIT: I was actually coming back here to edit my answer and add that there is no disadvantage to returning this instead of void in any measurable way, when I saw George's comment pointing out that I did forget to discuss the point of the question. Sorry for the initial "pointless" rambling. A: Returning "self" or "this" is a common pattern, sometimes referred to as "method chaining". As for your proposed syntax sugar, I'm not so sure. I'm not a .NET guy, but it doesn't seem terribly useful to me. A: The NeXTSTEP Objective-C framework used to use this pattern. It was discontinued in that framework once distributed objects (remote procedure calls, basically) were added to the language—a function that returned self had to be a synchronous invocation, since the distributed object system saw the return type and assumed that the caller would need to know the result of the function. A: I think as a general policy, it simply doesn't make sense. Method chaining in this manner works with a properly defined interface but it's only appropriate if it makes semantic sense. Your example is a prime one where it's not appropriate, because it makes no semantic sense. Similarly, your syntactic sugar is unnecessary with a properly designed fluent interface. Fluent interfaces or method chaining can work very well, but need to be designed carefully. A: I know in Java they're actually thinking about making this standard behaviour for void methods. If you do that you don't need the extra syntactic sugar. The only downside I can think of is performance. But that's easilly measured. I'll get back to you with the results in a few minutes :-) Edit: Returning a reference is a bit slower than returning void .. what a surprise. So that's the only downside. A few more ticks when calling your function. A: At first sight it may look good, but for a consistent interface you will need that all methods return a reference to this (which has it own problems). Let say you have a class with two methods GetA which return this and GetB which return another object: Then you can call obj.GetA().GetB(), but not obj.GetB().GetA(), which at least doesn't seems consistent. With Pascal (and Visual Basic) you can call several methods of the same object. with obj .GetA(); .GetB(); end with; The problem with this feature is that you easily can write code that is harder to understand than it should be. Also adding a new operator probably make it ever harder.
{ "language": "en", "url": "https://stackoverflow.com/questions/57140", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "12" }
Q: Using Small (1-10 Items) Instance-Level Collections in Java While creating classes in Java I often find myself creating instance-level collections that I know ahead of time will be very small - less than 10 items in the collection. But I don't know the number of items ahead of time so I typically opt for a dynamic collection (ArrayList, Vector, etc). class Foo { ArrayList<Bar> bars = new ArrayList<Bar>(10); } A part of me keeps nagging at me that it's wasteful to use complex dynamic collections for something this small in size. Is there a better way of implementing something like this? Or is this the norm? Note, I'm not hit with any (noticeable) performance penalties or anything like that. This is just me wondering if there isn't a better way to do things. A: For the sake of keeping things simple, I think this is pretty much a non-issue. Your implementation is flexible enough that if the requirements change in the future, you aren't forced into a refactoring. Also, adding more logic to your code for a hybrid solution just isn't worth it taking into account your small data set and the high-quality of Java's Collection API. A: Google Collections has collections optimized for immutable/small number of elements. See Lists.asList API as an example. A: The ArrayList class in Java has only two data members, a reference to an Object[] array and a size—which you need anyway if you don't use an ArrayList. So the only advantage to not using an ArrayList is saving one object allocation, which is unlikely ever to be a big deal. If you're creating and disposing of many, many instances of your container class (and by extension your ArrayList instance) every second, you might have a slight problem with garbage collection churn—but that's something to worry about if it ever occurs. Garbage collection is typically the least of your worries. A: The overhead is very small. It is possible to write a hybrid array list that has fields for the first few items, and then falls back to using an array for longer list. You can avoid the overhead of the list object entirely by using an array. To go even further hardcore, you can declare the field as Object, and avoid the array altogether for a single item. If memory really is a problem, you might want to forget about using object instances at the low-level. Instead use a larger data structure at a larger level of granularity.
{ "language": "en", "url": "https://stackoverflow.com/questions/57145", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: What's the best way to handle one-to-one relationships in SQL? Let's say I've got Alpha things that may or may not be or be related to Bravo or Charlie things. These are one-to-one relationships: No Alpha will relate to more than one Bravo. And no Bravo will relate to more than one Alpha. I've got a few goals: * *a system that's easy to learn and maintain. *data integrity enforced within my database. *a schema that matches the real-world, logical organization of my data. *classes/objects within my programming that map well to database tables (à la Linq to SQL) *speedy read and write operations *effective use of space (few null fields) I've got three ideas… PK = primary key FK = foreign key NU = nullable One table with many nullalbe fields (flat file)… Alphas -------- PK AlphaId AlphaOne AlphaTwo AlphaThree NU BravoOne NU BravoTwo NU BravoThree NU CharlieOne NU CharlieTwo NU CharlieThree Many tables with zero nullalbe fields… Alphas -------- PK AlphaId AlphaOne AlphaTwo AlphaThree Bravos -------- FK PK AlphaId BravoOne BravoTwo BravoThree Charlies -------- FK PK AlphaId CharlieOne CharlieTwo CharlieThree Best (or worst) of both: Lots of nullalbe foreign keys to many tables… Alphas -------- PK AlphaId AlphaOne AlphaTwo AlphaThree NU FK BravoId NU FK CharlieId Bravos -------- PK BravoId BravoOne BravoTwo BravoThree Charlies -------- PK CharlieId CharlieOne CharlieTwo CharlieThree What if an Alpha must be either Bravo or Charlie, but not both? What if instead of just Bravos and Charlies, Alphas could also be any of Deltas, Echos, Foxtrots, or Golfs, etc…? EDIT: This is a portion of the question: Which is the best database schema for my navigation? A: If you want each Alpha to be related to by only one Bravo I would vote for the possibility with using a combined FK/PK: Bravos -------- FK PK AlphaId BravoOne BravoTwo BravoThree This way one and only one Bravo may refer to your Alphas. If the Bravos and Charlies have to be mutually exclusive, the simplest method would probably to create a discriminator field: Alpha -------- PK AlphaId PK AlphaType NOT NULL IN ("Bravo", "Charlie") AlphaOne AlphaTwo AlphaThree Bravos -------- FK PK AlphaId FK PK AlphaType == "Bravo" BravoOne BravoTwo BravoThree Charlies -------- FK PK AlphaId FK PK AlphaType == "Charlie" CharlieOne CharlieTwo CharlieThree This way the AlphaType field forces the records to always belong to exactly one subtype. A: I'm assuming you will be using SQL Server 2000 / 2005. I have a standard pattern for 1-to-1 relationships which I use, which is not too dissimilar to your 2nd idea, but here are the differences: * *Every entity must have its own primary key first, so your Bravo, Charlie, etc tables should define their own surrogate key, in addition to the foreign key column for the Alpha table. You are making your domain model quite inflexible by specifying that the primary key of one table must be exactly the same as the primary key of another table. The entities therefore become very tightly coupled, and one entity cannot exist without another, which is not a business rule that needs to be enforced within database design. *Add a foreign key constraint between the AlphaID columns in the Bravo and Charlie tables to the primary key column on the Alpha table. This gives you 1-to-many, and also allows you to specify whether the relationship is mandatory simply by setting the nullability of the FK column (something that isn't possible in your current design). *Add a unique key constraint to tables Bravo, Charlie, etc on the AlphaID column. This creates a 1-to-1 relationship, with the added benefit that the unique key also acts as an index which can help to speed up queries that retrieve rows based on the foreign key value. The major benefit of this approach is that change is easier: * *Want 1-to-many back? Drop the relevant unique key, or just change it to a normal index *Want Bravo to exist independently of Alpha? You've already got the surrogate key, all you do is set the AlphaID FK column to allow NULLs A: Personally, I've had lots of success with your second model, using a PK/FK on a single column. I have never had a situation where all Alphas were required to have a record in a Bravo or Charlie table. I've always dealt with 1 <-> 0..1, never 1 <-> 1. As for your last question, that's just that many more tables. A: One more approach is having 3 tables for storing the 3 entities and having a separate table for storing the relations. A: You could have a join table that specifies an Alpha and a related ID. You can then add another column specifing if it is an ID for Bravo, Charlie or whatever. Keeps the column creep down on Alpha but does add some complexity to joining queries. A: I have an example working pretty well so far that fits your model: I Have Charlie and Bravo Tables Having the Foreign Key alpha_id from Alpha. Like your first example, except alpha is not the Primary Key, bravo_id and charlie_id are. I use alpha_id on every table I need to address to those entities, so, to avoid a SQL that may cause some delay researching both Bravo and Charlie to find which one Alpha is, I created a AlphaType table and on Alpha table I have its id (alpha_type_id) as foreign key. That way I can know in a programmatic way which AlphaType I am dealing with without Joining tables that may have zillions of records. in tSQL: // For example sake lets think Id as a CHAR. // and pardon me on any mistake, I dont have the exact code here, // but you can get the idea SELECT (CASE alpha_type_id WHEN 'B' THEN '[Bravo].[Name]' WHEN 'C' THEN '[Charlie].[Name]' ELSE Null END) FROM ... A: You raise a lot of questions that make it hard to select any of your proposed solutions without a lot more clarification on the exact problem you are trying to solve. Consider not just my clarification questions, but the criteria that you will use to evaluate my questions, as an indication of the amount of detail required to solve your problem: * *a system that's easy to learn and maintain. What "System" will it be easy to learn and maintain? The source code of your app, or the app's data via it's end-user interface? * *data integrity enforced within my database. What do you mean by "enforced within my database"? Does this mean you cannot by any means control data integrity any other way, i.e. the project requires only DB-based data integrity rules? * *a schema that matches the real-world, logical organization of my data. Can you provide us the real world, logical organization to which you are referring? It's impossible to infer it from your three examples of the data you are trying to store -- i.e. suppose all three of your structures are completely wrong. How would we know that unless we know the real-world spec? * *classes/objects within my programming that map well to database tables (à la Linq to SQL) This requirement sounds like your hand is being forced to create this with linq to SQL, is that the case? * *speedy read and write operations What is "speedy"? .03 seconds? 3 seconds? 30 minutes? It's unclear because you're not specifying the data size and type of operations to which you are referring. * *effective use of space (few null fields) Effective use of space has nothing to do with the number of null fields. If you mean a normalized database structure, that will depend again on the real-world spec's and other design elements of the application that have not been provided in the question. A: I'd go with option 1 unless I had a significant reason not to. It might not cost you as much space as you think, esp. if you are using varchars in Bravo. Don't forget that splitting it will cost you for foreign keys, secondary identity and needed indexes. A place where you might run into trouble is if Bravo is unlikely to be needed (<%10) AND you need to quickly query by one of its fields so you index it. A: I would create a supertype / subtype relationship. THINGS ------ PK ThingId ALPHAS ------ FK ThingId (not null, identifying, exported from THINGS) AlphaCol1 AlphaCol2 AlphaCol3 BRAVOS ------ FK ThingId (not null, identifying, exported from THINGS) BravoCol1 BravoCol2 BravoCol3 CHARLIES -------- FK ThingId (not null, identifying, exported from THINGS) CharlieCol1 CharlieCol2 CharlieCol3 So, for example, an alpha that has a charlie but not a bravo:- insert into things values (1); insert into alphas values (1,'alpha col 1',5,'blue'); insert into charlies values (1,'charlie col 1',17,'Y'); Note, you can't create more than one charlie for the alpha, as if you tried to create a two charlies with a ThingId of 1 the second insert would get a unique index/constraint violation.
{ "language": "en", "url": "https://stackoverflow.com/questions/57152", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "10" }
Q: Problems with migrating Cardspace cards between computers Here's the scenario. I'm using myopenid for, among other things, StackOverflow. When I initially set up my openid account with myopenid, I decided to try out Cardspace because they had support. I later wanted to access Stackoverflow from another machine so I chose to back up my card. I gave it a password and a filename and successfully created a backup file. I was also to able successfully import it to my laptop. Here is where the problem comes in - I am unable to use the card that I backed up from my laptop. The original card still works great on my desktop. Additional information is that my desktop is running Windows XP SP3 (x86) while my laptop is running Windows Vista (x64). Any ideas? Am I doing something wrong? I'm seriously considering dropping Cardspace on myopenid and moving to a password solution with them instead. Thanks! A: It should work; however if you have 3.5SP1 on one machine and 3.5 or less on another there was an (unannounced) breaking change with the code to generate the unique ID from the card; which may explain why it doesn't work. I would try sending a test transaction to the SharpSTS test page with only the PPID as the claim, and examine the token sent back; if the PPIDs differ then that's your problem. A: In Cardspace, the card is locked to the computer. You can move it around by exporting/importing. The next version "Geneva" will allow you to store your cards in a directory service which is useful for those running Active Directory.
{ "language": "en", "url": "https://stackoverflow.com/questions/57154", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: How to copy a row from one SQL Server table to another I have two identical tables and need to copy rows from table to another. What is the best way to do that? (I need to programmatically copy just a few rows, I don't need to use the bulk copy utility). A: Alternative syntax: INSERT tbl (Col1, Col2, ..., ColN) SELECT Col1, Col2, ..., ColN FROM Tbl2 WHERE ... The select query can (of course) include expressions, case statements, constants/literals, etc. A: SELECT * INTO < new_table > FROM < existing_table > WHERE < clause > A: INSERT INTO DestTable SELECT * FROM SourceTable WHERE ... works in SQL Server A: Jarrett's answer creates a new table. Scott's answer inserts into an existing table with the same structure. You can also insert into a table with different structure: INSERT Table2 (columnX, columnY) SELECT column1, column2 FROM Table1 WHERE [Conditions] A: As long as there are no identity columns you can just INSERT INTO TableNew SELECT * FROM TableOld WHERE [Conditions] A: To select only few rows..This will work like charm.. SELECT TOP 10 * INTO db2.dbo.new_table FROM db1.dbo.old_table; Note : Just create a new table in the required db..We need not define its structure.
{ "language": "en", "url": "https://stackoverflow.com/questions/57168", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "109" }
Q: Oracle from .Net with a 64 bit client Has anyone had any luck of using Oracle from .Net on a 64 bit machine, and using the UDT capabilities of Oracle? I've been able to use an x64 ODP.Net client, but cannot find one with any support for UDTs. Thanks Nick [Edit] I've posted an answer below. The latest (as of December 2008) release is 11.1.0.7. This has support for 64 bit and UDT. A: You need to use 11.1.0.7 release. This has UDT support and works with 32 and 64 bit. A: UDT capability is only listed in 11g clients and the latest 64 bit client is 10.2.0.3. Not the answer you wanted, but the one that Oracle seems to be giving. Actually I'm glad you asked this question. We're working on migrating to 64 bit server code and I wouldn't have thought to check for this. A: I've been trying for some time to get the 64-bit edition of Windows Server 2003 to connect to an Oracle 8i instance. It doesn't seem to be possible other than doing it through a 32-bit VM. Forced upgrading can really suck!
{ "language": "en", "url": "https://stackoverflow.com/questions/57179", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Get CVS history for a particular user How do I get the history of commits that have been made to the repository for a particular user? I am able to access CVS either through the command line or TortioseCVS, so a solution using either method is sufficient. A: As a coder, I am mostly interested in commit changes, (as opposed to tagging, branching, etc), so I usually include the -c commit option as well: cvs history -c -u username A: cvs history -u username gives a history of changes the user has made A: Or try this one: cvs history -x AMR -D "your-desired-date" Example cvs history -x AMR -D "2012-04-12"
{ "language": "en", "url": "https://stackoverflow.com/questions/57183", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "9" }
Q: FTP Timeout on NLST when directory is empty EDIT: Learned that Webmethods actually uses NLST, not LIST, if that matters Our business uses the WebMethods integration server to handle most of our outbound communications, and its FTP functionality leaves something to be desired. We are having a problem that may be specific to WebMethods, but if anyone can point me in a direction of what kinds of things might cause this I'd appreciate it. When polling two of our partners' FTP servers, we connect without issue but, when doing a NLST on a directory that is empty (no files and no subdirectories) it's timing out. The actual error is: com.wm.net.ftpCException: [ISC.0064.9010] java.net.SocketTimeoutException: Accept timed out It's being thrown during the invocation of the pub.client.ftp:ls service. I've logged in with a number of FTP clients without a problem to the same sites. I've used whatever the default FTP client is in windows, FileZilla and lftp. All without issue. The servers themselves aren't the same FTP server software from what I can tell. One is Microsoft FTP, the other I'm uncertain on but is definitely not Microsoft. Any idea what could cause an FTP client to timeout when waiting for a NLST response on an empty directory? The visible responses from the FTP server appear to be the same, but is there a difference in how NLST responds for an empty directory that I'm unaware of? This problem is consistent on these two servers. Everything functions fine on directories with files or subdirectories within it, but not when empty. Any thoughts or directions would be appreciated. Thanks! Eric Sipple A: I am not sure if it was the same problem but I had similar symptoms a while ago using another FTP client in Java (commons.net). The problem turned out to be caused by the active/passive mode of the connection. I am sorry I can't give you more details, that's all I can remember... hope that help. A: Guillermo Vasconcelos was correct in his answer. There are two FTP modes, Active and Passive. The default FTP mode is active. Active requires the server to connect back to the client on some TCP/IP port. This does not work with firewalls because chances are that this port would be blocked or if you are behind a Router with NAT, not mapped. If you use Passive (PASV) mode instead, you should not get the hang. A: I tried this in WebMethods IS Version 6.5 Updates WmPRT_6-5-1_SP1, IS_6-5_SP3. It worked perfectly first time. I turned on debugging on the FTP server (Debian's default ftpd). WebMethods' NLST honours the active/passive parameter passed to it. There's nothing special about the NLST command, nor its correct behaviour with an empty directory -- if LIST works, then so should RETR, STOR and NLST. If NLST works with a non-empty directory, it should work with an empty one. So my guess is that either: * *Your version of WM has a bug mine doesn't *Your FTP server has a bug mine doesn't *There's a wacky protocol-aware firewall in your system that doesn't like FTP data sockets with no data in them. Firewall vendors are a bit wayward when it comes to FTP... When testing with other clients, make sure it's from the same machine on which WebMethods Integration Server is running. Just for the record, here's what should happen for an active NLST * *client opens a listening socket, and sends a PORT command with that socket's details *client sends NLST command *server connects to client's listening socket (this is the data socket) *server transmits listing over data socket (in this case, zero bytes) *server closes data socket ... and in passive mode * *client sends PASV command *server opens a listening socket, and replies with PASV response containing its details *client connects to listening socket (this is the data socket) *client sends NLST command *server transmits listing over data socket (zero bytes again) *server closes data socket A: I'm going to run some new tests with the settings to passive tomorrow when maintenance is done here, but I'm not sure that's the issue. We are able to get a directory listing if there are files or subdirectories in that directory. It only fails when the directory we're NLST-ing on is empty. Would the active/passive difference only manifest for an empty directory, or is there another possibility? A: FTP requires that both the specified port and the one above it be opened through the firewall. When I had problems with webMethods timing out, it was because the firewall did not have the return port open. Howard
{ "language": "en", "url": "https://stackoverflow.com/questions/57194", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How do I put a link to a webpage in a JScript Alert dialog box? I would like to put a link to a webpage in an alert dialog box so that I can give a more detailed description of how to fix the error that makes the dialog box get created. How can I make the dialog box show something like this: There was an error. Go to this page to fix it. wwww.TheWebPageToFix.com Thanks. A: You can't. Alert boxes don't support html. You should display the error as part of the page, it's nicer than JS alerts anyway. A: If you really wanted to, you could override the default behavior of the alert() function. Not saying you should do this. Here's an example that uses the YUI library, but you don't have to use YUI to do it: YUI-based alert box - replace your ugly JavaScript alert box A: You can't - but here are some options: * *window.open() - make your own dialog *Use prompt() and instruct the user to copy the url *Use JavaScript to just navigate them to the url directly (maybe after using confirm() to ask them) *Include a div on your page with a [FIX IT] button and unhide it *Use JavaScript to put a fix it URL into the user's clipboard (not recommended) A: You could try asking them if they wish to visit via window.prompt: if(window.prompt('Do you wish to visit the following website?','http://www.google.ca')) location.href='http://www.google.ca/'; Also, Internet Explorer supports modal dialogs so you could try showing one of those: if (window.showModalDialog) window.showModalDialog("mypage.html","popup","dialogWidth:255px;dialogHeight:250px"); else window.open("mypage.html","name","height=255,width=250,toolbar=no,directories=no,status=no,menubar=no,scrollbars=no,resizable=no,modal=yes"); A: Or use window.open and put the link there. A: Even if you could, alert() boxes are generally modal - so any page opened from one would have to open in a new window. Annoying! A: alert("There was an error. Got to this page to fix it.\nwww.TheWebPageToFix.com"); That's the best you can do from a JavaScript alert(). Your alternative option is to try and open a new tiny window that looks like a dialog. With IE you can open it modal.
{ "language": "en", "url": "https://stackoverflow.com/questions/57202", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: ToolStrips in TabPages frequently disappear from Windows Forms designer I have a Windows Form app with a TabControl. One of the TabPages in the TabControl contains a ToolStrip. Frequently, the Windows Form designer will spontaneously set the Visible property of the Toolstrip to False. To get the toolstrip to reappear in my form, I have to manually find the control and set the property back to True. It's really annoying. Does anyone know why this happens, or how to stop it? I've tried setting the minimum height of the control to a non-zero value, but that has no effect. I'm using VS2008, VB.NET and the .Net framework 2.0, however I've struggled with this problem in VS2005 too, in several different applications. A: I may have found a workaround for this. My ToolStrip was placed directly on the TabPage, docked to Top. However, I found a thread on Microsoft Connect that described the same problem when the ToolStrip was in a ToolStripContainer on the TabPage. That problem was observed in a release candidate of VS2005, but supposedly fixed by Microsoft in September 2006. As such, I changed my code to put the ToolStrip inside a ToolStripContainer, and now I am unable to reproduce the problem. A: Open the designer code and explicitly set the control's visible property to true. Nick Hanshaw
{ "language": "en", "url": "https://stackoverflow.com/questions/57208", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: What .NET Framework version should I ship with; 2, 3, 3.5? My application uses 2.0. At some point in the future I may want to start using newer features added in later framework versions. Should I wait until then? Or are there advantages to updating to the latest .NET 3.5 now? I suppose by the time I am ready for next spring's release 4.0 will be out. Perhaps I should stick with 2.0 for my fall release and save my customers the HD space and install time of another framework version? A: In my opinion, you should ship with what your app needs. Otherwise you are making your install longer for no reason and as you noted using your customer's HD space again essentially for no reason. A: If you are planning to upgrade to 3.5 SP1, you should consider using the New .NET Framework Client Profile Setup Package. .NET 3.5 SP1 introduces a new setup package option for developers building .NET client applications called the ".NET Framework Client Profile". This provides a new setup installer that enables a smaller, faster, and simpler installation experience for .NET client applications on machines that do not already have the .NET Framework installed. The .NET Framework Client Profile setup contains just those assemblies and files in the .NET Framework that are typically used for client application scenarios. For example: it includes Windows Forms, WPF, and WCF. It does not include ASP.NET and those libraries and components used primarily for server scenarios. We expect this setup package to be about 26MB in size, and it can be downloaded and installed much quicker than the full .NET Framework setup package. The assemblies and APIs in the .NET Framework Client setup package are 100% identical to those in the full .NET Framework setup package (they are literally the same binaries). This means that applications can target both the client profile and full profile of .NET 3.5 SP1 (no recompilation required). All .NET applications that work using the .NET Client Profile setup automatically work with the full .NET Framework. A: I always use the most up-to-date version of the Framework. This may be a small up-front burden on users, but the app has a much longer life between upgrades. That may or may not be important to you, but consider: If you had shipped an application in 2005 using .NET 1.1, the framework your app runs on is now out of mainstream support, and may have unpatched security vulnerabilities, or other serious problems which Microsoft may not deal with, and which you cannot compensate for in your own code. Your only alternative in 2008 is to get your users to upgrade their framework version now. And, as we all know, getting users to update things in a timely fashion can be problematic. Likewise, consider your situation in 2011. If you program for .NET 3.5 now, your app, as-shipped, will be viable longer. If you ship for .NET 2.0 now, you'll be in the position, in a few years' time, of having to convince your users to upgrade their framework (code which has no perceived benefit to them, remember) so that you can properly support this application. Also, if you plan to implement 3.5-class features (LINQ to SQL next year, for example), it's in your interest to ship for 3.5 now, rather than 2.0, as it will make deployment later less of a problem for you. A: You should distribute your app with whatever version of .Net is the version you've done the most testing against. If you've been doing all your developing and testing in .Net 2.0, then ship with 2.0. But you may owe it to your customers to test against 3.5 and ship with that, instead, for the sake of any bugs that have been fixed in the framework since 2.0 was released. The framework is already so large that there probably isn't any benefit to distributing an earlier version, even if it came before WCF, WPF, etc., unless you're paying bandwidth costs to distribute it, or the target device has limited storage space. A: Remember that "a small burden" to users could mean the difference between acceptance and rejection of your application. I run IT for a company. Our company standard is not 3.5. You would have to have one really slick application to get me to upgrade everyone to .NET 3.5 just so your app can run. In other words, probably not happening. I'll find another app that doesn't add an additional "small burden" onto our already overloaded IS department. Somebody else commented about what features are you really going to use. If 1.1 or 2.0 has the real feature set you need stick with it. A: I appreciate the new language features in .NET 3.5 but until you're making use of them I would avoid upgrading to the latest runtime as it is a larger file / install that your users may have to deal with. A: The Linq to SQL features, well really pretty much the Linq Extensions in general are well worth the upgrade. As for your worries about HD space and install time, IMO these are not relevant on most modern systems for the newer frameworks. The newer versions of the frameworks (3.0 and 3.5) are really just "refreshes" of the 2.0 framework. Unless your customers/market is older PC's I think you will get a good tradeoff in functionality and productivity for your dev team as opposed to the negligible risk of losing customers because they can't risk adding another 20Mb on their hard drive (I made up the 20mb number, someone can call BS on that). A: 3.5 framework has had it's first Service Pack release, so it's more stable than it was after release, but bear in mind it is far easier to upgrade code from 2.0 to 3.5 than it is to go back to 3.5 if for whatever reason you encounter a show stopper. The wiki article shows the new features very well. A: I agree with EBGreen and Chris, but I want to add that you might want to consider testing your application against the newer versions of the framework and allow your application to run against those versions you deem to work well against (this can be done using some configuration trick, but unfortunately, I can't find reference to it). This way, your application could work against the version the client may already have installed. I suggest this because: * *New framework versions may give you a performance boost. *The client may already have another version installed on their computer and it would be a shame to, as you say, waste hard drive space. *You may want to run your application against a newer framework version sometime in the future and if your client already has that version and is running the current version of the application, there won't be an old framework on their computer. Still, I'm lacking some information you may have, such as the means of distribution, the profiling of clients' machines, etc. A: I've found version 2.0 to be the easiest version to target and deploy since a lot of people have it installed already, If a sizable portion of your client base use Vista you might consider upgrading to 3.0. Versions above that nearly always require an install which can be a pain for some users. Edit: The "framework version going out of support" argument holds no water since 3.0 is an extension of 2.0 and 3.5 is an extension of that. By definition 2.0 will be supported as long as 3.5 is. Version 1.1 is the only version that is a completely separate runtime and is no longer supported. A: One question I'd like to ask is what are the features of .NET 3.5 that you'd like to use? Many of the hyped features are actually C# 3.0 features, not features specific for .NET 3.0/3.5 and since C# 3.0 uses the same CLR as .NET Framework 2.0 you are free to use them in your 2.0 applications too. This only requires VS 2008. Examples are: * *Lambda expressions *Object initializers *Anonymous types *Local variable type inference *Extension methods I use many of these in my own .NET 2.0 projects without problems. If there are framework specific features you want (like Linq, WPF, etc), then you'd have to upgrade. A: I agree that you should with what your App needs, but you should also prepare for what your apps will need in the future. If you have a few spare cycles, you could migrate a separate branch of your apps in your SCM which is running with the 3.5 Runtime and when you actually need to upgrade, you have a working branch (Assuming that you keep it up-to-date with some bi-weekly merge). A: Don't forget that .Net 4.0 will be a little different from previous versions of the framework. .Net 4.0 will be installed side by side (SxS) .Net 3.5 and back. If you upgrade your app to use .Net 4.0 then your long term users (aka previous versions) will end up having to install a whole new version of the framework. If your considering how much disk space you are going to use up on the client machines with your app and the framework, then don't forget this "hidden" use of extra space. If you upgrade your app now from 2.0 to 3.5 then your app might be able to exist longer with complete functionality without forcing the user to install a 2nd framework that uses up another 20+ MB of space. A: .net 3.5sp1 bootstrapper is too slow especially if you are using asp.net application (compared to windows forms), in a machine which only has .net 2.0, it loads the whole framework and that means you are lookong at about 20-30 mins of download + install time on a moderate internet connection and machine speed.
{ "language": "en", "url": "https://stackoverflow.com/questions/57234", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "11" }
Q: Find Missing Javascript Includes in Website Say I have several JavaScript includes in a page: <script type="text/javascript" src="/js/script0.js"></script> <script type="text/javascript" src="/js/script1.js"></script> <script type="text/javascript" src="/js/script2.js"></script> <script type="text/javascript" src="/js/script3.js"></script> <script type="text/javascript" src="/js/script4.js"></script> Is there a way i can tell if any of those weren't found (404) without having to manually check each one? I guess i'm looking for an online tool or something similar. Any ideas? A: If you get the Firebug firefox plugin and enable the consoles it should tell you when there are errors retrieving resources in the console. A: I don't use other browsers enough to know where to find a similar feature in them, but Safari has an Activity window that displays all of the included files for a given web page and which ones were unable to be retrieved. A: If you want to monitor on the fly without actually checking if it exists, then I suggest placing dynamic variables inside the files. Then just do something like this: var script0Exists = true; // inside script0.js var script1Exists = true; // inside script1.js Then in your other files, just use: if ( script0Exists ) { // not a 404 - it exists } A: Log your 404's. A: If you don't want to check it manually on the client you will need to do this server-side. You need to make sure whichever webserver you are using is configured to log 404s and then check that log to see which HTTP requests have failed. A: If your webhost always returns the HTTP result "200 OK", whether the file exists or not (the latter should give a "404 Not Found"), the browser has no way of telling if it received a script or not. You might try retrieving the files via XMLHttpRequest, examine the data, and if they look like JS, either eval() them, or create a script tag pointing to the exact same URL you downloaded (if the script is cacheable, it won't be transferred again, as the browser already has it).
{ "language": "en", "url": "https://stackoverflow.com/questions/57238", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Finding missing emails in SQL Server I am trying to do something I've done a million times and it's not working, can anyone tell me why? I have a table for people who sent in resumes, and it has their email address in it... I want to find out if any of these people have NOT signed up on the web site. The aspnet_Membership table has all the people who ARE signed up on the web site. There are 9472 job seekers, with unique email addresses. This query produces 1793 results: select j.email from jobseeker j join aspnet_Membership m on j.email = m.email This suggests that there should be 7679 (9472-1793) emails of people who are not signed up on the web site. Since 1793 of them DID match, I would expect the rest of them DON'T match... but when I do the query for that, I get nothing! Why is this query giving me nothing??? select j.email from jobseeker j where j.email not in (select email from aspnet_Membership) I don't know how that could be not working - it basically says "show me all the emails which are IN the jobseeker table, but NOT IN the aspnet_Membership table... A: We had a very similar problem recently where the subquery was returning null values sometimes. Then, the in statement treats null in a weird way, I think always matching the value, so if you change your query to: select j.email from jobseeker j where j.email not in (select email from aspnet_Membership where email is not null) it may work.... A: You could have a lot of duplicates out there. I'm not seeing the query error off the top of my head, but you might try writing it this way: SELECT j.email FROM jobseeker j LEFT JOIN aspnet_Membership m ON m.email = j.email WHERE m.email IS NULL You might also throw a GROUP BY or DISTINCT in there to get rid of duplicates. A: Also see Five ways to return all rows from one table which are not in another table A: You could use exists instead of in like this: Select J.Email From Jobseeker j Where not exists (Select * From aspnetMembership a where j.email = a.email) You should get better performance and avoid the 'weird' behaviour (which I suspect is to do with null values/results) when using in.
{ "language": "en", "url": "https://stackoverflow.com/questions/57243", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Getting EPG info from DVB-T I'm interested in grabbing the EPG data from DVB-T streams. Does anyone know of any C libraries or an alternative means of getting the data? A: tv_grab_dvb can do this. See the subversion repository for sources. tv_grab_dvb is made to work with the stream grabbed from the DVB-T card using dvbtools on Linux, but it may be portable to other platforms - I think it just works with the raw data from the stream. A: ...a new answer to an old question: I wrote a utility called dvbtee that can be used as a c++ library, a cross-platform command line utility, or a node.js module. (despite it being a c++ library, one could still link to it from c code) The command line utility will parse your streams and output the EPG, depending on the arguments you specify, it can generate plain text or a JSON block of data. dvbtee: a digital television streamer / parser / service information aggregator supporting various interfaces including telnet CLI & http control The node.js module will emit events containing the PSIP table data (along with EPG info) node-dvbtee: MPEG2 transport stream parser for Node.js with support for television broadcast PSIP tables
{ "language": "en", "url": "https://stackoverflow.com/questions/57249", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: How to keep ReadDirectoryChangesW from missing file changes There are many posts on the internet about the ReadDirectoryChangesW API function missing files when there is a lot of file activity. Most blame the speed at which the ReadDirectoryChangesW function loop is called. This is an incorrect assumption. The best explanation I have seen is in the following post, the comment on Monday, April 14, 2008 2:15:27 PM http://social.msdn.microsoft.com/forums/en-US/netfxbcl/thread/4465cafb-f4ed-434f-89d8-c85ced6ffaa8/ The summary is that the ReadDirectoryChangesW function reports file changes as they leave the file-write-behind queue, not as they are added. And if too many are added before being committed, you lose notice on some of them. You can see this with your implementation, if you just write a program to generate a 1000+ files in a directory real quick. Just count how many file event notices you get and you will see there are times when you will not receive all of them. The question is, has anyone found a reliable method to use the ReadDirectoryChangesW function without having to flush the volume each time? This is not allowed if the user is not an Administrator and can also take some time to complete. A: If the API is unreliable, then a workaround may be your only option. That of course likely involves keeping track of lastmodified and filenames. What this doesn't mean is that you need to poll when looking for changes, rather, you can use the FileSystemWatcher as a means to trigger checking. So if you keep track of the last 50-100 times the ReadDirectoryChangesW/FSW event happened, and you see that it is being called rapidly, you can detect this and trigger the special condition to get all the files that have been changed (and set a flag to prevent future bogus FSW events temporarily) in a few seconds. Since some people are confused in the comments about this solution, I am proposing that you should monitor how fast events are arriving from the ReadDirectoryChangesW and when they are arriving too fast, try to attempt a workaround (usually a manual sweep of a directory). A: We've never seen ReadDirectoryChangesW to be 100% reliable. But, the best way to handle it is separate the "reporting" from the "handling". My implementation has a thread which has only one job, to re-queue all events. Then a second thread to process my intermediate queue. You basically, want to impede the reporting of events as little as possible. Under high CPU situations, you can also impede the reporting of watcher events. A: I met same problem. But, I didn't find a solution that guarantee to get all of events. In several tests, I could know that ReadDirectoryChangesW function should be called again as fast as possible after GetQueuedCompletionStatus function returned. I guess if a processing speed of filesystem is very faster than my application processing speed, the application might be able to lose some events. Anyway, I separated a parsing logic from a monitoring logic and placed a parsing logic on a thread.
{ "language": "en", "url": "https://stackoverflow.com/questions/57254", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "21" }
Q: How to connect to PostgreSQL from .NET using TLS with both client and server authentication? I want to connect a C# .NET application to a PostgreSQL database, using TLS with client and server authentication: in other words, if the certificate from the client can not be verified against the certificate of the server, the client should get access denied, and if the client can not verify the certificate of the server, the client should immediately abort connecting. I tried this using Npgsql 1.0, but I can not find any way in Npgsql to specify the client certificate that should be used for the connection. I did manage to get server certificate verification on the client working, and I also did get all the verification working using the commandline db admin tool psql, but this did not help me further in getting it to work with Npgsql. So, how would I connect my .NET app using TLS client & server authentication to a PostgreSQL database? Is there maybe a newer/other data provider that does support this? Is there actually anyone who did get this to work one way or another? A: Try version 2.0 RC2 - it's pretty stable. (As a note, support for server certificate validation wasn't added in CVS until 2009. See http://pgfoundry.org/tracker/?func=detail&atid=592&aid=1010558&group_id=1000140. I am editing this into the reply because the advice to upgrade, while premature, is correct.)
{ "language": "en", "url": "https://stackoverflow.com/questions/57261", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: SMTP Mail Timeout Issue When I'm creating a user for my web application, an SMTP email (using ASP.NET's SmtpClient) is sent to the user with the automatically generated password. However, sometimes what I notice is that it times out and the new user simply won't receive the email with the password. Alright, so I'll display a message indicating that the mail did not go through but the user is created. Therefore, the sys admin has 2 options so far: * *Reset the password for the user and hope another SMTP mail is sent with the auto-generated password. *Delete and recreate the user. I could rollback the user creation if the smtp is not sent but what is the best practice to tackle this problem? I'm thinking that I should retry sending the email 3 times with a timeout period of 5 seconds each. So 15 seconds would be the worse case scenario. Is this the way to go? A: Well, depending on your platform, if you can just hand off your mail to a local MTA, it should handle the retries and such. Your program can just queue the mail and move on, not worry about dealing with timeouts and graylists etc. If the message still can't be delivered, you could always try resending it (via a password reset feature). If that fails as well, most likely there was a mistake in the email address, and I would suggest deleting the account, causing the user to re-register. This, of course, might not be possible on some systems, depending what can be done with an unconfirmed user - that really depends on what you allow people to do before their email is validated. A: It sounds like your web app is speaking SMTP directly to your user's mail server. [Your web app is a MUA (Mail User Agent) talking to the user's MTA (Mail Transfer Agent).] Nothing says that the user's MTA must be reachable or working at the moment. You need to run your own MTA so you ensure that somebody is providing queueing, retries, etc. If you really want to bend over backwards, you could do what you're doing (only one attempt though), fallback to queueing the message and continuing to retry on a slower schedule for at least 24 hours, and expose that unfinished state to the user. The official answer on how your app is supposed to behave can be found in RFC1123 (Requirements for Internet Hosts - Application and Support): 5.3.1.1 Sending Strategy The general model of a sender-SMTP is one or more processes that periodically attempt to transmit outgoing mail. In a typical system, the program that composes a message has some method for requesting immediate attention for a new piece of outgoing mail, while mail that cannot be transmitted immediately MUST be queued and periodically retried by the sender. A mail queue entry will include not only the message itself but also the envelope information. The sender MUST delay retrying a particular destination after one attempt has failed. In general, the retry interval SHOULD be at least 30 minutes; however, more sophisticated and variable strategies will be beneficial when the sender-SMTP can determine the reason for non- delivery. Retries continue until the message is transmitted or the sender gives up; the give-up time generally needs to be at least 4-5 days. The parameters to the retry algorithm MUST be configurable. A: IMHO you should notify the user, asking him to verify the email, without retries. If the user does not verify the email and leaves the page, you better roll back the account since the user can not access it anyway. Most cases of timeout would be caused by invalid email accounts. Users either made a mistake or gave you a non existent email addressto avoid being spammed. If at all possible, do not ask for your users emails. Yhe number one rule of programming should be: DO NOT annoy the user. A: If you are using ASP.NET and the System.Net.Mail classes, you are probably sending the mail via the IIS instance on the web server machine (I'm not sure since you didn't specify). There's not a good way to know what's going on with your Mail Transfer Agent (IIS SMTP). It has its own retry logic, and by default, it could take a long time for the message to be delivered. How are you detecting that the mail was not delivered? What's the "timeout" coming from? You should have a background process that handles the sending of mail. If delivery to the MTA succeeds, you should assume all is well. Unless you are blacklisted for SPAM, most MTAs will keep retrying until they get through. If you actually get an error dropping the message off with you MTA, then definitely retry it, or figure out what's causing the failure and fix the bug. Honestly, this part should never fail. You might want to monitor the return address for NDR messages so you can take some sort of action when you know for sure when the email wasn't delivered. But if the user cannot yet log in to the system, there's no good way to let them know what happened. Maybe you could set a cookie with a value that you associate with the email, and put something up on the login/registration page if you were unable to deliver the mail.
{ "language": "en", "url": "https://stackoverflow.com/questions/57285", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: ASP.Net RSS feed How do I create an rss feed in ASP.Net? Is there anything built in to support it? If not, what third-party tools are available? I'm thinking webforms, not MVC, though I suppose since this isn't a traditional page the difference may be minimal. A: For built-in, there's nothing stopping you from using XmlDocument or XDocument (3.5) to build up the required XML for RSS. It's more work than it's worth though. I use the Argotic Syndication Framework and serve the feeds through Generic Handlers (.ashx) with the content type set to text/xml. The RSSToolkit is also nice. It comes with an RSSDataSource control if you're into that sort of thing. It also includes a control that will automatically insert the meta tag required for feed autodiscovery in browsers. I found the build provider for creating feeds to be a little kludgey however. A: Here's an RSS framework created by a Microsoft developer: ASP.NET RSS Toolkit A: Use one of the libraries available for generating the actual RSS. For example: http://www.rssdotnet.com/ If you check the code examples page at the bottom: http://www.rssdotnet.com/documents/code_examples.html you will find the code for clearing the content type in an ASP.net Page and outputting the RSS. Something along the lines of (not tested, not compiled, just typed): public void PageLoad() { // create channel RssChannel _soChannel = new RssChannel(); // create item RssItem _soItem = new RssItem(); _soItem.Title = "Answer"; _soItem.Description = "Example"; _soItem.PubDate = DateTime.Now.ToUniversalTime(); // add to channel _soChannel.Items.Add(_soItem.); // set channel props _soChannel.Title = "Stack Overflow"; _soChannel.Description = "Great site.. jada jada jada"; _soChannel.LastBuildDate = DateTime.Now.ToUniversalTime(); // change type and send to output RssFeed _f = new RssFeed(); _f.Channels.Add(channel); Response.ContentType = "text/xml"; _f.Write(Response.OutputStream); Response.End(); } Hope that helps. A: You could take a look at Argotic. It is a really cool framework. http://www.codeplex.com/Argotic A: The .NET Framework 3.5 has added a SyndicationFeed Class which allows you to create and/or consume feeds in Atom 1.0 and RSS 2.0 formats. SyndicationFeeds Class on MSDN A: Create an HTTP Handler to create a RSS feed
{ "language": "en", "url": "https://stackoverflow.com/questions/57287", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "16" }
Q: Is there a simpler way to deploy to WebSphere? I have seen this question about deploying to WebSphere using the WAS ant tasks. Is there a simpler way to do this? In the past I have deployed to Tomcat by dropping a war file into a directory. I was hoping there would be a similar mechanism for WebSphere that doesn't involve calling the IBM libraries or rely on RAD to be installed on your workstation. A: Just a hint: if you activate "Log command assistance commands" in System Administration / Console preferences, you will get a logfile in the server log directory that contains the jython scripts for all actions you did on the console. So you can just deploy your stuff per console the first time, and then grab the commands for later and feed them into wsadmin.bat -lang jython "thecommandscomehere" for the next deployment. A: One way to do it could be using Jython or jacl scripts. See those samples at IBM site. [EDIT] Especially the wsadminlib.py.zip download near the bottom of the page contains a huge set of examples and helper functions to get you started. A: There is the concept of WebSphere Rapid Deployment. It's supposed to be the same experience as what you describe for Tomcat. A: WAS does provide a client jar containing some custom ant tasks. However they seem to be extremely bugy and dont work with remote servers. IBM ANT TASK Javadoc Netbeans also has support for was 6 and 6.1 but this again is still quite buggy, however it can be useful for generating some the bindings files etc.
{ "language": "en", "url": "https://stackoverflow.com/questions/57291", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "10" }
Q: Validation framework for business app built on Spring 2.5 What could the best strategy for writing validation layer for mid-enterprise level business application built on Spring 2.5 I know that Spring provides facility where we can implement Validator interface and write validation logic in validate method. But this will be restricted to only web requests coming through spring controller. I would like to develop the validation framework which can be utilized during web-services calls. In other words, the framework can remain and be called independently without the need of implementing Validator interface and then too it can be automatically integrated into Spring MVC flow. Hope you get my point. A: The Spring Validation framework can be used outside of Spring MVC. What WebServices Stack are you using? If you are using Spring-WS (Spring's Web Services stack) they have special instructions on how to set up the validator here: http://static.springframework.org/spring-ws/sites/1.5/reference/html/server.html#d0e2313 If you are using some other stack, it is probably easier to implement something for that stack (or find one) that will use Spring's validation framework. A: Recall that the Validator interface defines two methods: boolean supports(Class clazz) void validate(Object target, Errors errors) The Object target is your form object, which is the whole object representing the page to be shown to the user. The Errors instance will contain the errors that will be displayed to the user. So, what you need to do is define an intermediary that can be called with the specifics in your form that you want to validate which are also the same as in your web service. The intermediary can take one of two forms: * *(probably the best): public interface ErrorReturning { public void getErrors(Errors errors); } *(this can get ugly really fast if more than two states are added): public interface ValidationObject { public Errors getErrors(Errors errors); public Object getResultOfWebServiceValidation(); } I would suggest that the first approach be implemented. With your common validation, pass an object that can be used for web service validation directly, but allow it to implement the getErrors() method. This way, in your validator for Spring, inside your validation method you can simply call: getCommonValidator().validate(partialObject).getErrors(errors); Your web service would be based around calls to getCommonValidator().validate(partialObject) for a direct object to be used in the web service. The second approach is like this, though the interface only allows for an object to be returned from the given object for a web service validation object, instead of the object being a usable web service validation object in and of itself.
{ "language": "en", "url": "https://stackoverflow.com/questions/57314", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Is there an easy way of using the RegularExpressionValidator control while ignoring white space? I can use a custom validator control with Regex and IgnorePatternWhitespace, but it would be good to just have an option in the RegularExpressionValidator control. A: Surround your regex with (?x: ) so "a b c" becomes "(?x:a b c) A: Remember that the regular expression validator want to validate with javascript, too, so you want to make sure your expression will work with both the .Net and javascript regex engines. That means that using .IgnorePatterWhitespace isn't the best idea.
{ "language": "en", "url": "https://stackoverflow.com/questions/57322", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: How can I stop losing all my IDE window position when pressing the start debugging button? I use Visual Studio 2008. I haven't seen this behavior before and, as far as I know, I didn't change anything in the options. When I press Start debugging all the possibly windows (watch 1 - 4), data sources, properties, registers (to be honest I have not even ever seen these windows before) appear in front of the code window and stay there after I stop the debugger. Anyone has an idea what could be causing this ? (I am using CodeRush and Refactor for quite a while now) When I close and restart visual studio all the windows are where they should be. PS: Previously I have seen normal switching from normal to debug mode and back with some repositioning changes. That is the way it used to work. Now it is not. It has suddenly gone mad and when going to the debug mode it sometimes shows all possible IDE windows and sometimes not. When it does it no longer returns to the previous state. I cannot find this in the options anywhere. A: Visual Studio remembers 2 sets of window layouts, normal mode and debugging mode. My solution is to arrange my normal windows exactly like I want them, then start debugging an application and once again arrange all of the windows the way I want, usually making it as similar to my normal layout as possible, then stopping the debugger and doing a File Exit so that VS saves my settings. After doing that, it recalls my 2 different layouts each time. A: I'm experiencing the same thing - whenever the debugger is running, switching focus back to the IDE immediately caused the debug panel to expand. I ended up just pinning the debug panel so that it always appears when debugging, and just changing its height as needed. A: To add to palehorse, another tip is Full Screen mode.
{ "language": "en", "url": "https://stackoverflow.com/questions/57345", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: How do I get the current user's Local Settings folder path in C#? I want to point a file dialog at a particular folder in the current user's Local Settings folder on Windows. What is the shortcut to get this path? A: How about this, for example: String appData = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData); I don't see an enum for just the Local Settings folder. http://web.archive.org/web/20080303235606/http://dotnetjunkies.com/WebLog/nenoloje/archive/2007/07/07/259223.aspx has a list with examples. A: string localPath = Directory.GetParent(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData)).FullName; is the simple answer. A: Environment.GetFolderPath( Environment.SpecialFolders.LocalApplicationData);? I can't remember if there is a "Local Settings" folder on Windows XP anymore, it seems vaguely familiar.
{ "language": "en", "url": "https://stackoverflow.com/questions/57350", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "23" }
Q: Const Struct& I'm having a little trouble figuring out exactly how const applies in a specific case. Here's the code I have: struct Widget { Widget():x(0), y(0), z(0){} int x, y, z; }; struct WidgetHolder //Just a simple struct to hold four Widgets. { WidgetHolder(Widget a, Widget b, Widget c, Widget d): A(a), B(b), C(c), D(d){} Widget& A; Widget& B; Widget& C; Widget& D; }; class Test //This class uses four widgets internally, and must provide access to them externally. { public: const WidgetHolder AccessWidgets() const { //This should return our four widgets, but I don't want anyone messing with them. return WidgetHolder(A, B, C, D); } WidgetHolder AccessWidgets() { //This should return our four widgets, I don't care if they get changed. return WidgetHolder(A, B, C, D); } private: Widget A, B, C, D; }; int main() { const Test unchangeable; unchangeable.AccessWidgets().A.x = 1; //Why does this compile, shouldn't the Widget& be const? } Basically, I have a class called test. It uses four widgets internally, and I need it to return these, but if test was declared const, I want the widgets returned const also. Can someone explain to me why the code in main() compiles? Thank you very much. A: You need to create a new type specifically for holding const Widget& objects. Ie: struct ConstWidgetHolder { ConstWidgetHolder(const Widget &a, const Widget &b, const Widget &c, const Widget &d): A(a), B(b), C(c), D(d){} const Widget& A; const Widget& B; const Widget& C; const Widget& D; }; class Test { public: ConstWidgetHolder AccessWidgets() const { return ConstWidgetHolder(A, B, C, D); } You will now get the following error (in gcc 4.3): widget.cc: In function 'int main()': widget.cc:51: error: assignment of data-member 'Widget::x' in read-only structure A similar idiom is used in the standard library with iterators ie: class vector { iterator begin(); const_iterator begin() const; A: unchangeable.AccessWidgets(): At this point, you are creating a new object of type WidgetHolder. This object is not protected by const. You are also creating new widgets in the WidgetHolder and not references to the Wdiget. A: Your WidgetHolder is going to hold invalid references (pointers). You are passing objects on the stack to the constructor and then holding references to their (temporary) addresses. This is guaranteed to break. You should only assign references to objects with the same (or greater) lifetime as the reference itself. Pass references to the constructor if you must hold references. Even better, don't hold the references at all and just make the copies. A: This compiles because although the WidgetHolder is a const object, this const-ness does not automatically apply to objects pointed to (referenced by) the WidgetHolder. Think of it at a machine level - if the WidgetHolder object itself were held in read-only memory, you could still write to things that were pointed to by the WidgetHolder. The problem appears to lie in this line: WidgetHolder(Widget a, Widget b, Widget c, Widget d): A(a), B(b), C(c), D(d){} As Frank mentioned, your references inside the WidgetHolder class are going to hold invalid references after the constructor returns. Therefore, you should change this to: WidgetHolder(Widget &a, Widget &b, Widget &c, Widget &d): A(a), B(b), C(c), D(d){} After you do that, it won't compile, and I leave it as an exercise for the reader to work out the rest of the solution. A: EDIT: he deleted his answer, making me look a bit foolish :) The answer by Flame is dangerously wrong. His WidgetHolder takes a reference to a value object in the constructor. As soon as the constructor returns, that passed-by-value object will be destroyed and so you'll hold a reference to a destroyed object. A very simple sample app using his code clearly shows this: #include <iostream> class Widget { int x; public: Widget(int inX) : x(inX){} ~Widget() { std::cout << "widget " << static_cast< void*>(this) << " destroyed" << std::endl; } }; struct WidgetHolder { Widget& A; public: WidgetHolder(Widget a): A(a) {} const Widget& a() const { std::cout << "widget " << static_cast< void*>(&A) << " used" << std::endl; return A; } }; int main(char** argv, int argc) { Widget test(7); WidgetHolder holder(test); Widget const & test2 = holder.a(); return 0; } The output would be something like widget 0xbffff7f8 destroyed widget 0xbffff7f8 used widget 0xbffff7f4 destroyed To avoid this the WidgetHolder constructor should take references to the variables it wants to store as references. struct WidgetHolder { Widget& A; public: WidgetHolder(Widget & a): A(a) {} /* ... */ }; A: The original query was how to return the WidgetHolder as const if the containing class was const. C++ uses const as part of the function signature and therefore you can have const and none const versions of the same function. The none const one is called when the instance is none const, and the const one is called when the instance is const. Therefore a solution is to access the widgets in the widget holder by functions, rather than directly. I have create a more simple example below which I believe answers the original question. #include <stdio.h> class Test { public: Test(int v){m_v = v;} ~Test(){printf("Destruct value = %d\n",m_v);} int& GetV(){printf ("None Const returning %d\n",m_v); return m_v; } const int& GetV() const { printf("Const returning %d\n",m_v); return m_v;} private: int m_v; }; void main() { // A none const object (or reference) calls the none const functions // in preference to the const Test one(10); int& x = one.GetV(); // We can change the member variable via the reference x = 12; const Test two(20); // This will call the const version two.GetV(); // So the below line will not compile // int& xx = two.GetV(); // Where as this will compile const int& xx = two.GetV(); // And then the below line will not compile // xx = 3; } In terms of the original code, I think it would be easier to have a WidgetHolder as a member of the class Test and then return either a const or none const reference to it, and make the Widgets private members of the holder, and provide a const and none const accessor for each Widget. class WidgetHolder { ... Widget& GetA(); const Widget& GetA() const; ... }; And then on the main class class Test { ... WigetHolder& AccessWidgets() { return m_Widgets;} const WidgetHolder&AcessWidgets() const { return m_Widgets;} private: WidgetHolder m_Widgets; ... };
{ "language": "en", "url": "https://stackoverflow.com/questions/57355", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }
Q: How do I sync between VSS and SVN I am forced to use VSS at work, but use SVN for a personal repository. What is the best way to sync between VSS and sync? A: To get rid of the manual merge step, I could use a separate svn branch (svn://branches/VSS) as follows: * *Create a working copy of svn://branches/VSS *Do a VSS Get Latest on this working copy *svn commit *svn merge from svn://trunk *svn commit *Do a VSS diff and checkout all files (without overwriting) with differences *Check in those files *reintegrate svn://branches/VSS into svn://trunk A: You could also treat this as a vendor supplied branch as defined in the redbean book: Vendor Branches With this, the basic flow would be: * *Have a vendor branch "branches/VSS/current" containing the latest code from VSS *Tag the current version as "branches/VSS/2008-09-15" *Next day, get the new files into "current" *Tag again into "branches/VSS/2008-09-16" *Merge differences between the two tags into trunk, resolving conflicts *Delete old tags as required This is actually the technique we used when migrating from VSS to SVN. If you care about the return trip from SVN->VSS, you'll just have to diff between trunk and branches/VSS/current and apply the diffs to VSS. A: What I have done in the past is as follows: * *Make sure all my changes are committed to svn://trunk *Do a get latest from VSS into my working copy. *Manually merge the changes in my working copy. *Commit the merged code into the svn://trunk *Do a VSS diff and checkout any files with differences (without overwriting files) *Check in those files.
{ "language": "en", "url": "https://stackoverflow.com/questions/57372", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "9" }
Q: web page cache setexpires Will the code below work if the clock on the server is ahead of the clock on the client? Response.Cache.SetExpires(DateTime.Now.AddSeconds(-1)) EDIT: the reason I ask is on one of our web apps some users are claiming they are seeing the pages ( account numbers, etc ) from a user that previously used that machine. Yet we use the line above and others to 'prevent' this from happening. A: This question covers making sure a webpage is not cached. It seems you have to set several properties to ensure a web page is not cached across all browsers. A: Your problem could be caused by the browser remembering data entered into form fields. You can turn this off like this: <input autocomplete="off"> A: As far as I can tell, the browser will check the expiry date against the local clock (although it will account for the time zone), so the code in your question may not work as you expect if the client's clock is inaccurate. Most commonly, this happens when their time looks right but is set to the wrong timezone, meaning the UTC timestamps are actually out by several hours. You could try setting a much older timestamp, say: 0000 1st Jan 1970 GMT (epoch) I think the code you have should work with the server side caching, but you can more explicitly disable it with: Response.Cache.SetNoServerCaching();
{ "language": "en", "url": "https://stackoverflow.com/questions/57380", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Obout controls in C# .Net Is anyone using the Obout controls in C# .Net? How would you rate these controls, especially the Grid Control? A: I was thoroughly impressed with them. Of all the other control sets out there (infragistics, telerik) this is the only (more than) respectable one I've worked with that was 1) free! and 2) lightweight!. The only caveat to Obout is I had trouble with merging some of these controls and some of the stock AJAX components. Infragistics is by far my favorite (my comment about Obout being "lightweight" is in comparison with the heavy use of viewstate in some of the Infragistics controls) but it's around 1000-1500 a seat, so it can get expensive if you have a larger team. A: I like obout for their lightweight'ness. Their licensing policy is very fair (pay once free updates for life) and they also give (free) educational licenses. However, I had to use Developer Express on one of my projects and never looked back since. Very powerful and not as bloated as Infragistics. Basically, if you decide to go obout way, you probably will not regret it. A: I like obout for their simplicity and functionality. They have pretty good documentation and samples of almost everything. And they cost a fraction of price than others (Componentart/Telerik). I am currently testing their Grid control ( after I gave up on Componentart grid for client side functionality) and find it pretty straightforward. A: I purchased the license a few years ago and have been using it ever since. The support is pretty good and the controls are great. I have looked at some of the other vendors (telerik, etc) but haven't moved any where because of cost transition. The nice thing with obout is that I bought it a few years ago and they still give me free updates. That may change inthe future, but for now, its great. The products work as expected and they are always making updates to the software. A: This is the first time I was working with obout controls.Previously,I was working with telerik controls and so,I had a good chance of comparing these two set of controls.I would prefer Obout for its light weight and functionality. A: I used their tree for a project. Not bad for free controls. A: I have been using their Calendar control for nearly 2 years. All of a sudden it stops working on Google Chrome (Vr: 17.0.963.56 m). Even their live demos don't work, try scrolling through the months a few times and it will just hang with the error 'Uncaught TypeError: this is not a Date object.'. I've emailed the company on two occasions regarding this issue as it has brought my site down and I'm getting customers contacting me incessantly. I'm afraid as of yet no reply!! Very frustrating!! It's really a shame because the tool is otherwise excellent...If they could at least acknowledge the fault and assure me they are working on a solution that would be something, but to be left in the dark shows a complete lack of basic customer service etiquette.
{ "language": "en", "url": "https://stackoverflow.com/questions/57382", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: How to rethrow InnerException without losing stack trace in C#? I am calling, through reflection, a method which may cause an exception. How can I pass the exception to my caller without the wrapper reflection puts around it? I am rethrowing the InnerException, but this destroys the stack trace. Example code: public void test1() { // Throw an exception for testing purposes throw new ArgumentException("test1"); } void test2() { try { MethodInfo mi = typeof(Program).GetMethod("test1"); mi.Invoke(this, null); } catch (TargetInvocationException tiex) { // Throw the new exception throw tiex.InnerException; } } A: It is possible to preserve the stack trace before rethrowing without reflection: static void PreserveStackTrace (Exception e) { var ctx = new StreamingContext (StreamingContextStates.CrossAppDomain) ; var mgr = new ObjectManager (null, ctx) ; var si = new SerializationInfo (e.GetType (), new FormatterConverter ()) ; e.GetObjectData (si, ctx) ; mgr.RegisterObject (e, 1, si) ; // prepare for SetObjectData mgr.DoFixups () ; // ObjectManager calls SetObjectData // voila, e is unmodified save for _remoteStackTraceString } This wastes a lot of cycles compared to calling InternalPreserveStackTrace via cached delegate, but has the advantage of relying only on public functionality. Here are a couple of common usage patterns for stack-trace preserving functions: // usage (A): cross-thread invoke, messaging, custom task schedulers etc. catch (Exception e) { PreserveStackTrace (e) ; // store exception to be re-thrown later, // possibly in a different thread operationResult.Exception = e ; } // usage (B): after calling MethodInfo.Invoke() and the like catch (TargetInvocationException tiex) { PreserveStackTrace (tiex.InnerException) ; // unwrap TargetInvocationException, so that typed catch clauses // in library/3rd-party code can work correctly; // new stack trace is appended to existing one throw tiex.InnerException ; } A: Guys, you are cool.. I'm gonna be a necromancer soon. public void test1() { // Throw an exception for testing purposes throw new ArgumentException("test1"); } void test2() { MethodInfo mi = typeof(Program).GetMethod("test1"); ((Action)Delegate.CreateDelegate(typeof(Action), mi))(); } A: In .NET 4.5 there is now the ExceptionDispatchInfo class. This lets you capture an exception and re-throw it without changing the stack-trace: using ExceptionDispatchInfo = System.Runtime.ExceptionServices.ExceptionDispatchInfo; try { task.Wait(); } catch(AggregateException ex) { ExceptionDispatchInfo.Capture(ex.InnerException).Throw(); } This works on any exception, not just AggregateException. It was introduced due to the await C# language feature, which unwraps the inner exceptions from AggregateException instances in order to make the asynchronous language features more like the synchronous language features. A: I think your best bet would be to just put this in your catch block: throw; And then extract the innerexception later. A: Anpother sample code which uses exception serialization/deserialization. It does not require the actual exception type to be serializable. Also it uses only public/protected methods. static void PreserveStackTrace(Exception e) { var ctx = new StreamingContext(StreamingContextStates.CrossAppDomain); var si = new SerializationInfo(typeof(Exception), new FormatterConverter()); var ctor = typeof(Exception).GetConstructor(BindingFlags.NonPublic | BindingFlags.Instance, null, new Type[] { typeof(SerializationInfo), typeof(StreamingContext) }, null); e.GetObjectData(si, ctx); ctor.Invoke(e, new object[] { si, ctx }); } A: Nobody has explained the difference between ExceptionDispatchInfo.Capture( ex ).Throw() and a plain throw, so here it is. The complete way to rethrow a caught exception is to use ExceptionDispatchInfo.Capture( ex ).Throw() (only available from .Net 4.5). Below there are the cases necessary to test this: 1. void CallingMethod() { //try { throw new Exception( "TEST" ); } //catch { // throw; } } 2. void CallingMethod() { try { throw new Exception( "TEST" ); } catch( Exception ex ) { ExceptionDispatchInfo.Capture( ex ).Throw(); throw; // So the compiler doesn't complain about methods which don't either return or throw. } } 3. void CallingMethod() { try { throw new Exception( "TEST" ); } catch { throw; } } 4. void CallingMethod() { try { throw new Exception( "TEST" ); } catch( Exception ex ) { throw new Exception( "RETHROW", ex ); } } Case 1 and case 2 will give you a stack trace where the source code line number for the CallingMethod method is the line number of the throw new Exception( "TEST" ) line. However, case 3 will give you a stack trace where the source code line number for the CallingMethod method is the line number of the throw call. This means that if the throw new Exception( "TEST" ) line is surrounded by other operations, you have no idea at which line number the exception was actually thrown. Case 4 is similar with case 2 because the line number of the original exception is preserved, but is not a real rethrow because it changes the type of the original exception. A: This is just a nice clean, modern implementation of some of the other ideas here, tested in .NET 6: public static class ExceptionExtensions { [DoesNotReturn] public static void Rethrow(this Exception ex) => ExceptionDispatchInfo.Capture(ex).Throw(); } I wanted the value of the PropertyName property on myObject but this will work just as well when using reflection to call methods (as per OP's problem) or anything else that results in you wanting to re-throw an inner exception. try { object? value = myObject.GetType().GetProperty("PropertyName")?.GetValue(myObject); } catch (TargetInvocationException ex) { (ex.InnerException ?? ex).Rethrow(); } A: public static class ExceptionHelper { private static Action<Exception> _preserveInternalException; static ExceptionHelper() { MethodInfo preserveStackTrace = typeof( Exception ).GetMethod( "InternalPreserveStackTrace", BindingFlags.Instance | BindingFlags.NonPublic ); _preserveInternalException = (Action<Exception>)Delegate.CreateDelegate( typeof( Action<Exception> ), preserveStackTrace ); } public static void PreserveStackTrace( this Exception ex ) { _preserveInternalException( ex ); } } Call the extension method on your exception before you throw it, it will preserve the original stack trace. A: Based on Paul Turners answer I made an extension method public static Exception Capture(this Exception ex) { ExceptionDispatchInfo.Capture(ex).Throw(); return ex; } the return ex ist never reached but the advantage is that I can use throw ex.Capture() as a one liner so the compiler won't raise an not all code paths return a value error. public static object InvokeEx(this MethodInfo method, object obj, object[] parameters) { { return method.Invoke(obj, parameters); } catch (TargetInvocationException ex) when (ex.InnerException != null) { throw ex.InnerException.Capture(); } } A: Even more reflection... catch (TargetInvocationException tiex) { // Get the _remoteStackTraceString of the Exception class FieldInfo remoteStackTraceString = typeof(Exception) .GetField("_remoteStackTraceString", BindingFlags.Instance | BindingFlags.NonPublic); // MS.Net if (remoteStackTraceString == null) remoteStackTraceString = typeof(Exception) .GetField("remote_stack_trace", BindingFlags.Instance | BindingFlags.NonPublic); // Mono // Set the InnerException._remoteStackTraceString // to the current InnerException.StackTrace remoteStackTraceString.SetValue(tiex.InnerException, tiex.InnerException.StackTrace + Environment.NewLine); // Throw the new exception throw tiex.InnerException; } Keep in mind that this may break at any time, as private fields are not part of API. See further discussion on Mono bugzilla. A: First: don't lose the TargetInvocationException - it's valuable information when you will want to debug things. Second: Wrap the TIE as InnerException in your own exception type and put an OriginalException property that links to what you need (and keep the entire callstack intact). Third: Let the TIE bubble out of your method.
{ "language": "en", "url": "https://stackoverflow.com/questions/57383", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "357" }
Q: Inter-convertability of asymmetric key containers (eg: X.509, PGP, OpenSSH) Are asymmetrical cryptographic keys fundamentally inter-convertible between the major key container formats? For example, can I convert an X.509 key file into a PGP or OpenGPG key file? And--assuming the answer is yes--is it "security neutral" to keep one key pair in whatever format and convert into whichever container file format is needed for the occasion? I'm getting a little tired of maintaining so many key pairs for X.509, OpenGPG, and SSH, when they're all RSA at the heart. A: Yes and no: yes, the RSA keys embedded into certificates and privkeys are just numbers. You can extract them from the certificate and use them to build keys in other formats. This is commonly done to convert between different certificate formats. PGP has some support for X.509 for S/MIME, but no ability to use X.509 privkeys verbatim. SSH has some beta support for directly using X.509 keys and certificates. A: You will found how to convert kes between these containers there: http://sysmic.org/dotclear/index.php?post/2010/03/24/Convert-keys-betweens-GnuPG,-OpenSsh-and-OpenSSL A: I'd also have a look at OpenSSL. It has so many different -in and -out functions that will likely be able to convert certs. from one type to the other. Have a look at http://marc.info/?l=openssl-users&m=105162569405053&w=2
{ "language": "en", "url": "https://stackoverflow.com/questions/57384", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Where should interfaces "physically live"? I like the idea of having Interfaces and Implementation separate. But how separate? Are the Interface definitions in a separate .Net assembly? Do you have a single project that defines all Interfaces for a solution? Otherwise are there issues with circular dependencies of Interfaces? A: Put your domain objects and interfaces in a seperate "domain" assembly. This assembly should never reference anything but the core .net assemblies. This way you get a clean seperation from your domain/service model and your implementation. Edit: http://jeffreypalermo.com/blog/the-onion-architecture-part-1/ A: I wouldn't put the interfaces into a separate assembly just for the sake of it. However, if the interfaces take part in any form of IPC or extensibility architecture then it often makes sense to give them their own assembly. If you have projects that need to reference each other, then yes, you will need a separate assembly for the interfaces, but you should also carefully examine architecture to see if there is another way of resolving the circular dependency. A: I prefer keeping the most common or simple implementations of the interface in a sub-folder (and namespace) following the name of the interface. \project\ \project\IAppender.cs \project\Appender\ \project\Appender\FileAppender.cs \project\Appender\ConsoleAppender.cs If I extend this class outside the project. In a special project, repeat the folders/namespace similarly. \specialproject\ \specialproject\Appender\ \specialproject\Appender\MemoryAppender.cs A: In the project I'm working on right now, the interfaces and related base classes go into assemblies that are logically divided among functions. The implementations of these providers and classes go inside a core assembly. The idea being that people who use our API can reference more or one of the API dlls in a clear and logical manner. Smaller applications don't need this kind of separation. But, no matter where I keep the interfaces, I would keep them in the same namespace as any base classes.
{ "language": "en", "url": "https://stackoverflow.com/questions/57386", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Indexed Views in OLTPs? I'm familiar with SQL Server Indexed Views (or Oracle Materialized Views), we use them in our OLAP applications. They have the really cool feature of being able to usurp an execution plan and remap it to the indexed view w/out having to change existing code. IE. Let's say I had a SPROC that was a really expensive join. SELECT [SOME COLUMNS] FROM Table1 INNER JOIN Table2 [DETAILS] INNER JOIN Table3 [BUNCH MORE JOINS] ... If I authored an indexed view that held a similar result set then the Query Optimizer will very likely send the SPROC to my indexed view as opposed to the base tables and I get a big performance increase. Now say I wanted to use indexed views in an OLTP!? I mean most OLTPs (like this site) are relatively read heavy, if they have expensive joins then we could speed them up a ton AND potentially reduce locking contention (http://www.codinghorror.com/blog/archives/001166.html). Even better is you wouldn't have to change any code, just author the indexed view. But this also means the database gets bigger since we need to keep a copy of these data in the indexed view... Has anyone ever used indexed views to solve contention or speed issues in an OLTP? How come I've never seen this in use? A: Materialized views can be useful for reporting against OLTP, especially is large numbers of rows are aggregated to get the results. The space requirements are completely dependent on how much data you are saving. Think of it as a cache. The tricky balance is between how recent the data needs to be for the reports, and how much of a hit you can take on OLTP performance. If somewhat stale data is OK, you may be able to schedule the updates to the views during a time when system activity is low. The one time I could not, and need very current data, I ended up using some custom development. Each update to the base table fired a trigger which wrote a record to a transaction table. The view looked at a cached aggregate, plus the delta stored in the transaction table. As system resources allowed, the transactions were applied to the aggregate table as delta transactions. This allowed me up to the second data, good performance on reporting (the only aggregation happening was recent transactions) and fairly little load on the database (only doubling the size of every write, not re-calculating a huge aggregate every time). Unfortunately, it was complex to maintain, and did not use simple built in tools. If you can wait on your reporting data, it is often best to use the built in materialized views and defer the refresh. A: We use materialized views to speed up things where I work. Most often for reports against the OLTP system. Many of our reports run from a data warehouse, but since we refresh the warehouse overnight, up to the moment data has to come from the OLTP tables.
{ "language": "en", "url": "https://stackoverflow.com/questions/57406", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: I don't get the concept of Visual Studio Projects and Solutions In Eclipse, I have a workspace that contains all of my projects. Each project builds and compiles separately. A project does not interact with another project. How does this relate to Visual Studio and Projects/Solutions there? A: A VS project is it's own entity. It will build and compile by itself. A Solution is just a way to contain multiple projects. The projects don't necessarily need the other projects to compile (though, they can depend on the other projects). This just lets you conceptually group projects together into one Big Project. For instance, you can have a separate testing project. It depends on the code from the actual project, and should be kept together with the actual project, but it does not need to be in the same exe/dll. A: Another way to look at it is, a solution is a container for projects. For most of my work , I create each tier as a project within a solution so my tree looks like: * *My Web App or Win App * *Presentation Layer * *files... *Business Layer * *files... *Data Access * *files Your mileage may vary A: Each VS project builds a single EXE or DLL. The solution is just a collection of related projects. So VS project:Eclipse project::VS solution:Eclipse workspace. A: @Thomas Owens: Yes, some (most?) people using Eclipse have more than one workspace. It's what surprised me the most when I first started using Eclipse, so I'm replying here to make this comment more visible. A: The thing that may be throwing you off is the following: In VS2003, everything had a Project file and a Solution file. If you had a Solution with one Project, you could open the Solution and see the one Project. If you opened the Project, it would try and create a new Solution file to contain the Project. But web projects and Winform projects all had Projects and Solutions. In VS2005 this changed a bit - by default now, Web projects no longer had Project files. They had received feedback from some web developers that didn't like Project files - their take was that if a file is in the directory, it's part of the app. After VS2005 shipped, they got more feedback from developers who did like the Project file notion, so they patched it back in. This is "Web Site" versus "Web Application" in VS2005 (and I can't remember which is which now). In addition, in VS2005, if you have a Solution open with only one Project, you won't see in the Solution Explorer that there's even a Solution at all, you'll only see the Project (as if it was not in a Solution). Only after adding the second Project will you see that there's a Solution containing them both. So basically you were on the right track - Solutions and Projects work the same in Visual Studio as they did in Eclipse, it's just some quirks that make things confusing. A: A Solution has 0 or many Projects... A: There are way too many kinds of web projects in Visual Studio 2008. There are Web Site Projects vs. Web Application Projects and they limit you in different ways. It's a good example of Microsoft providing too many choices instead of focusing on one strong solution. Even within the Web site Project option, there are at least 3 different ways to compile your application. A: I found that not always seeing the solution in the Solution Explorer to be irritating. There is a setting in Options->Projects and Solutions->General called "Always Show Solution" which was handy.
{ "language": "en", "url": "https://stackoverflow.com/questions/57409", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "9" }
Q: Ajax and a restricted uri I would like to make an ajax call to a different server (same domain and box, just a different port.) e.g. My page is http://localhost/index.html I would like to make a ajax get request to: http://localhost:7076/?word=foo I am getting this error: Access to restricted URI denied (NS_ERROR_DOM_BAD_URI) I know that you can not make an ajax request to a different domain, but it seem this also included different ports? are there any workarounds? A: Have a certain page on your port 80 server proxy requests to the other port. For example: http://localhost/proxy?port=7076&url=%2f%3fword%3dfoo Note the url encoding on the last query string argument value. A: You could use JSONP. This is where you specify a callback with the request, the response from your ajax request gets wrapped with the callback function name. Rather than using XmlHttpRequest you insert a tag into the HTML document with the URL. Then when the response is retrieved the callback function is called, passing the data as a parameter. Check this blog post out for an example A: This is a browser restriction. All javascript calls must be to the same server and port of the home of the script. This will require something server-side to get around. I.E. have the process at localhost forward the request to localhost:7076. A: It sucks, but it's necessary... Basically what you're going to need to do is proxy your AJAX request through a local proxy - some server side script / page / whatever on the same domain you're on - receive the call and forward it on to the other resource server-side. There might be some IFRAME tricks you could do but I don't think they work very well...could be wrong though, been awhile.
{ "language": "en", "url": "https://stackoverflow.com/questions/57421", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Sample code for using mac camera in a program? I'd like to use the camera in my Macbook in a program. I'm fairly language agnostic - C, Java, Python etc are all fine. Could anyone suggest the best place to look for documents or "Hello world" type code? A: The ImageKit framework in Leopard has an IKPictureTaker class that will let you run the standard picture-taking sheet or panel that you seen in iChat and other applications. If you don't want to use the standard picture-taker panel/sheet interface, you an use the QTKit Capture functionality to get an image from the iSight. Both of these will require writing some Cocoa code in Objective-C, but that shouldn't really be an obstacle these days. A: If you want to manipulate the camera directly from your code, you must use the QuickTime Capture APIs or the Cocoa QTKit Capture wrapper (much better). The only caveat is: if you use a QTCaptureDecompressedVideoOutput, remember that the callbacks aren't made on the main thread, but on the QuickTIme-managed capture thread. Use [someObject performSelectorOnMainThread:... withObject:... waitUntilDone:NO] to send messages to an object on the main thread. A: There is a utility called isightcapture that runs from the unix command line that takes a picture from the isight camera and saves it. You can check it out at this web site: http://www.macupdate.com/info.php/id/18598 An example of using this with AppleScript is: tell application "Terminal" do script "/Applications/isightcapture myimage.jpg" end tell A: From a related question which specifically asked the solution to be pythonic, you should give a try to motmot's camiface library from Andrew Straw. It also works with firewire cameras, but it works also with the isight, which is what you are looking for. From the tutorial: import motmot.cam_iface.cam_iface_ctypes as cam_iface import numpy as np mode_num = 0 device_num = 0 num_buffers = 32 cam = cam_iface.Camera(device_num,num_buffers,mode_num) cam.start_camera() frame = np.asarray(cam.grab_next_frame_blocking()) print 'grabbed frame with shape %s'%(frame.shape,) It is used in this sample neuroscience demo A: Quartz Composer is also a pleasant way to capture and work with video, when it's applicable. There's a video input patch. Quartz Composer is a visual programming environment that integrates into a larger Cocoa program if need be. http://developer.apple.com/graphicsimaging/quartz/quartzcomposer.html A: Another solution is OpenCV+python with a script like: import cv capture = cv.CaptureFromCAM(0) img = cv.QueryFrame(capture) Cannot do any simpler!
{ "language": "en", "url": "https://stackoverflow.com/questions/57424", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "13" }
Q: Activator.CreateInstance(string) and Activator.CreateInstance() difference No, this is not a question about generics. I have a Factory pattern with several classes with internal constructors (I don't want them being instantiated if not through the factory). My problem is that CreateInstance fails with a "No parameterless constructor defined for this object" error unless I pass "true" on the non-public parameter. Example // Fails Activator.CreateInstance(type); // Works Activator.CreateInstance(type, true); I wanted to make the factory generic to make it a little simpler, like this: public class GenericFactory<T> where T : MyAbstractType { public static T GetInstance() { return Activator.CreateInstance<T>(); } } However, I was unable to find how to pass that "true" parameter for it to accept non-public constructors (internal). Did I miss something or it isn't possible? A: If you absolutely require that the constructor be private you can try something like this: public abstract class GenericFactory<T> where T : MyAbstractType { public static T GetInstance() { return (T)Activator.CreateInstance(typeof(T), true); } } Otherwise you're best off adding the new constraint and going that route: public abstract class GenericFactory<T> where T : MyAbstractType, new() { public static T GetInstance() { return new T; } } You're trying to use GenericFactory as a base class for all of your factories rather than writing each from scratch right? A: To get around this, couldnt you just alter your usage as such: public class GenericFactory<T> where T : MyAbstractType { public static T GetInstance() { return Activator.CreateInstance(typeof(T), true); } } Your factory method will still be generic, but the call to the activator will not use the generic overload. But you should still achieve the same results. A: besides Activator.CreateInstance(typeof(T), true) to work, T should have default constructor
{ "language": "en", "url": "https://stackoverflow.com/questions/57439", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "11" }
Q: Upgrading from .NET 1.1 to .NET 2.0, what to expect? I'm working on a big .NET 1.1 project, and there exists a wish to upgrade this, majorily to be able to use better tools like Visual Studio 2008, but also because of the new features and smaller amount of bugs in the .NET 2.0 framework. The project consist for the bigger part of VB.NET, but there are also parts in C#. It is a Windows Forms application, using various third party controls. Using .NET remoting the rich client talks to a server process which interfaces with a MSSQL 2000 database. What kind of issues can we expect in case we decide to perform the upgrade? A: There is a change to the theading model in .Net 2.0 onwards where unhandled exceptions in a thread will cause the whole app to terminate. I ran into this when updating an app that did lots of threading and occasionally crashed. Obviously the .Net 2.0 model is more robust as you should certainly be catching these anyway, but it was the only really issue I came across when making the migration. This article talks all about it: http://odetocode.com/blogs/scott/archive/2005/12/14/2618.aspx A: We're looking at doing the same migration right now Tobi. First, you can get a good idea of what to expect by making a copy of your project (or a portion of it) and give it a "dry run" through the .NET 2.0 compiler. My experience with this was that the 2.0 compiler gives more warnings about bad programming practices that the 1.1 compiler let slide. The compiler will warn you about implicit casts, "ambiguous" return paths (a code path where a function doesn't return a value), and some other minor things. Here's a few links that you might find helpful: .NET Framework Compatability Word Document of Breaking changes in .NET Framework 2.0 A: Nothing, really. You'll find a couple warnings on compilation about obsolete methods, but often those are trivial to fix. You should shoot big and go for 3.5. The water is niiiiiiice in here. A: Take a peek at this whitepaper on evolving a .NET 2.0 application to 3.5. I hold that the changes from 1.1 to 2.0 are more significant, but the process should be similar. A: In addition to the app configuration stuff mentioned above, if you use any XSD validation you will need to replace some code around loading and validating XML. A: The most compilation warnings you'll see are if you use app.config to store program settings. The 1.1 configuration class was deprecated for System.Configuration.ConfigurationManager. Other warnings you may see coming from the compiler will be for uninitialized variables (set them to "= nothing" or "= null;" in the variable declaration to make them go away), and unused variables (the compiler is sure they're safe to delete). A: Most of the code should still compile except for a few warnings about stuff being obsolete. But there are a couple of things you should look out for with respect to Visual Studio generated code. If you've generated strongly typed datasets in Visual Studio 2003 you can forget about editing them in newer versions of visual studio. You'll have to rebuild them or better just replace them with something like nHibernate for ultimate OR-mapper-bliss The designer for forms should still work with old forms. You can get some confusion though because 2005 and 2008 use partial classes here. So if you create new forms the code looks different from the old ones. I have never upgraded an ASP.Net application so I don't know about web-forms but I guess it will work the same as winforms stuff. Mostly it will work but expect some designer weirdness. A: .NET 1.1 and .NET 2.0-3.5 are entirely different frameworks, and more importantly, .NET 3.5 is just a set of extra assemblies you can add to your .NET 2.0 project - none of the core assemblies actually got changed, as far as I'm aware - and an upgraded compiler that knows about the syntax sugar called LINQ, extension methods, etc. In other words, I do not think a .NET 2.0-3.5 upgrade is very similar to a .NET 1.1-2.0 upgrade. A: Things will probably compile OK, but we had a few nasty runtime issues with an application we upgraded at the start of the year. First, we had a number of problems with timezone handling in DateTime objects when calling 1.1 webservices from a 2.0 application, as the conversions to and from UTC when serializing to the wire appeared to work differently between framework versions. Also, 2.0 async webservices use the klutzy event-based mechanism instead of the IAsyncResult pattern, which is a royal pain if you are batching your requests. Finally, we had some legacy code that hosted an embedded browser using Microsoft.mshtml.dll. Upgrading to 2.0 caused the application to silently switch to a newer version of that dll, which had some changed behaviour related to javascript interaction. This last one is a bit of an obscure case, but shows that moving to the newer runtime may have implications for any COM interaction you might have. Hope this helps! A: The way we were doing email had to change. The 1.1 version used system.WEB.mail, with Imports System.Web.Mail ' Dim message As New MailMessage' this is a web.mail msg, not a net.mail msg Dim objConn As SmtpMail Dim objAttach As MailAttachment ' message .From = "[email protected]" ' more properties assigned to objMail objAttach = New MailAttachment(ExportName) message.Attachments.Add(objAttach) ' Here's where we actually send the thing SmtpMail.SmtpServer.Insert(0, "127.0.0.1") objConn.Send(objMail) and the new one has system.NET.mail Imports System.Net.Mail ' Dim message as MailMessage ' this is a net.mail msg, not a web.mail msg Dim data As Attachment Dim client As New SmtpClient("127.0.0.1") ' data = New Attachment(ExportName) ' Create the message and add the attachment message = New MailMessage(EmailFrom, EmailTo, reportDescription) message.Attachments.Add(data) ' Send the message client.Send(message) A: RESX files upgrade problems Watch out for internationalized RESX files. When you reopen a ,net 1.1 form in .net 2.0 the RESX file gets upgraded to a new version. In .net 1.1 the foreign language .resx file only contained the changes. In .net 2.0 ALL of the fields in the default .resx file now get moved into the foreign language resx file. (.fr.resx for example). If you have already internationalized the form all of the foreign language resx files will have to be looked at. Internationalisation Tools Some tools that you may have used/written yourself to do internationalization en mass may not work anymore as they may have used numbered resources. (Multi Lang & Infragistics) Infragistics Winforms controls modify the InitializeForm() in .net 1.1 and access resources using a resource numbering system. When migrated to .net 2.0 the numbering of the Infragistics resources will fail as the resx file is regenerated. You will need to upgrade your Infragistics libraries. A: You probably won't have any breaking issues, though you may get some deprecated method warnings. The compiler should generally tell you what the replacement is though. I know that some of the System.Configuration things were updated. A: There shouldn't be too much of a problem as in theory it is backward compatible (I note MikeeMike's comment about thread exceptions). After the move, you'll fine there are quite a few nice things like generics. Although you don't want to port all your collections to generics in one fell swoop, once you've done this your code should be more reliable due to the reduced number of casts - and probably quicker (although mileage may vary in this aspect). At the moment I'm about to start the .NET 2 -> .NET 4 conversion of three of my products. The main advantage will be the further improvements in multi-threaded support (parallel foreach loops, etc).
{ "language": "en", "url": "https://stackoverflow.com/questions/57449", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }
Q: What are some gotchas when retargeting .net 2.0 to 3.5? I am currently working on a project that is moving from .NET 2.0 to 3.5 across the board. I am well aware that 3.5 is basically a set of added functionality (libraries, if you will) on top of what 2.0 offers. Are there any gotchas that I might hit by simply re-targeting the compiler to 3.5? A: This isn't a gotcha, it's more of a heads up. .NET v3.0 and v3.5 are not new CLRs but simply an added set up assemblies, compilers, resources etc... Both .NET v3.0 AND v3.5 use the v2.0 CLR. Because of this you won't be able to say set an IIS App Pool to use a v3.5 CLR...cause it doesn't exist. Discussed in a little more detail here: http://www.hanselman.com/blog/HowToSetAnIISApplicationOrAppPoolToUseASPNET35RatherThan20.aspx A: The only issue I've seen is with name conflicts. You'll need to dis-ambiguate any class or method names in your code that share names with ones added to the .net framework between .net 2.0 and 3.5 A: Nope 3.5 is completely compatible with 2.0, not the other way around of course A: I recently migrated a small project from 2.0 to 3.5 and didn't encounter any specific problems, as the framework versions are backwards compatible. That said, there are a good number of optimisations and improvements that can be made by taking advantage of available features in the later framework versions. You may get some deprecated feature warnings, but nothing that will stop your project compiling. A: Other than that some users of the application will have to download the new framework run-time, none that I know of.
{ "language": "en", "url": "https://stackoverflow.com/questions/57458", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Equivalent of svn's blame for Perforce Is there an equivalent of svn's blame for Perforce on the command line? p4 annotate doesn't display usernames -- only changeset numbers (without ancestor history!). I currently have to track code back through ancestors and compare against the filelog, and there just has to be an easier way -- maybe a F/OSS utility? A: I'm not overly familiar with the blame command, but I assume that you are looking for who changes a particular line of code. The easiest way is to use Perforce's 'time lapse view' available from both p4win and p4v. This tool uses annotate and some other commands to give you a view of the code line over time. You can see who modified what code, when it was inserted or removed from the codeline, etc. It's not command line though. I checked briefly in the help and there doesnt' seem to be a way to launch the time lapse view directly from a p4win or p4v invocation. There might be though...I'll be checking further... Edit: I checked with support, and you can launch the timelapse view through p4v as follows: p4v.exe -cmd "annotate //<path/to/file>" HTH. A: I use a small script for blaming #!/bin/bash FILE="$1" LINE="$2" p4 annotate -cq "${FILE}" | sed "${LINE}q;d" | cut -f1 -d: | xargs p4 describe -s | sed -e '/Affected files/,$d' you can hook it to some of the editors that will pass the file name and line. There's a little more complex version here. A: From the p4v client, you can get "Time-lapse View" context menu on all the view displaying file like Files, Changelist etc. The time lapse view has quite a few options like Single Revision, Multiple Revision to analyze what was changed, when and by whom. A: Try taking a look at a couple of tools that I think could get you most of what you need: 1) p4pr Perl script by Bob Sidebotham and Jonathan Kamens. 2) Emacs Perforce interface has a command 'p4-print-with-rev-history' (bound to `C-x p V'). A: @alanw123: p4pr is close to what I'm looking for, but it doesn't cross branch boundaries: last if $type eq 'branch'; That was the main problem I had when I tried writing my own utility -- you can't (easily) tell how the lines map back to the file that was branched from. A: The p4 annotate command actually can follow merges/integrations and branching on the command line with the -I and -i commands (but it cannot do both at once :( ): -I Follow integrations into the file. If a line was introduced into the file by a merge, the source of the merge is indicated as the changelist that introduced the line. If that source was itself the result of an integration, that source will be used instead, and so on. The use of the -I option implies the -c option. The -I option cannot be combined with -i. -i Follow file history across branches. If a file was created by branching, Perforce includes revisions up to the branch point. The use of the -i option implies the -c option. The -i option cannot be combined with -I.
{ "language": "en", "url": "https://stackoverflow.com/questions/57467", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "51" }
Q: C# graph traversal - tracking path between any two nodes Looking for a good approach to keep track of a Breadth-First traversal between two nodes, without knowing anything about the graph. Versus Depth-First (where you can throw away the path if it doesn't pan out) you may have quite a few "open" possibilities during the traversal. A: The naive approach is to build a tree with the source node as the root and all its connections as its children. Depending on the amount of space you have, you might need to eliminate cycles as you go. You can do that with a bitmap where each bit corresponds to a distinct node in the graph. When you reach the target node, you can follow the parent links back to the root and that is your path. Since you are going breadth first, you are assured that it is a shortest path even if you don't eliminate cycles. A: For a breadth-first search you need to store at least two things. One is the set of already visited nodes and the other is the set of nodes that are directly reachable from the visited nodes but are not visited themselves. Then you keep moving states from the latter set to the former, adding newly reachable states to the latter. If you need the have a path from the root to some node(s), then you will also need to store a parent node for each node (except the root) in the aforementioned sets. Usually the union of the set of visited nodes and the set of not-visited child nodes (i.e. the set of seen nodes) is stored in a hash table. This is to be able to quickly determine whether or not a "new" state has been seen before and ignore it if this is the case. If you have really big number of states you might indeed need a bit array (as mentioned by Joseph Bui (57509), but unless your states can be used (directly or indirectly) as indices to that array, you will need to use a hash function to map states to indices. In the latter case you might completely ignore certain states because they are mapped to the same index as a different (and seen) node, so you might want to be careful with this. Also, to get a path you still need to store the parent information which pretty much negates the use of the bit-array. The set of unvisited but seen nodes can be stored as a queue. (Bit arrays are of no use for this set because the array will be mostly empty and finding the next set bit is relatively expensive.) A: I just submitted a solution over here that also applies to this question. Basically, I just keep a single list (a stack really) of visited nodes. Add a node to the list just before recursing or saving a solution. Always remove from the list directly after. A: If you are using .NET 3.5 consider using the Hashset to prevent duplicate nodes from being expanded, this happens when there is cycles in your graph. If you have any knowledge about the contents of the graph consider implementing an A* search to reduce the number of nodes that are expanded. Good luck and I hope it works out for you. If you are still a fan of treeware there are many excellent books on the topic of graphs and graph search such as Artificial Intelligence: A Modern Approach by Peter Norvig and Stuart Russell. The links in my response appear to have a bug they are Hashset: http://msdn.com/en-us/library/bb359438.aspx and A* search: http://en.wikipedia.org/wiki/A*_search_algorithm
{ "language": "en", "url": "https://stackoverflow.com/questions/57471", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: AJAX dropdowns (HTML Select) in Firefox with jQuery Help! I am using jQuery to make an AJAX call to fill in a drop-down dynamically given the user's previous input (from another drop-down, that is filled server-side). In all other browsers aside from Firefox (IE6/7, Opera, Safari), my append call actually appends the information below my existing option - "Select An ". But in Firefox, it automatically selects the last item given to the select control, regardless of whether I specify the JQuery action to .append or to replace (.html()). <select name="Products" id="Products" onchange="getHeadings(this.value);"> <option value="">Select Product</option> </select> function getProducts(Category) { $.ajax({ type: "GET", url: "getInfo.cfm", data: "Action=getProducts&Category=" + Category, success: function(result){ $("#Products").html(result); } }); }; Any thoughts? I have tried in the past to also transmit another blank first option, and then trigger a JavaScript option to re-select the first index, but this triggers the onChange event in my code, rather annoying for the user. Update: Here's an example of what the script would return <option value="3">Option 1</option> <option value="4">Option 2</option> <option value="6">Option 3</option> Optionally, if using the .html() method instead of the .append(), I would put another <option value="">Select a Product</option> at the top of the result. @Darryl Hein Here's an example of what the script would return <option value="3">Option 1</option> <option value="4">Option 2</option> <option value="6">Option 3</option> Optionally, if using the .html() method instead of the .append(), I would put another <option value="">Select a Product</option> at the top of the result. A: Can you just change your success function to reset the selected item to the first option? $("#Products").append(result).selectedIndex = 0; or to set it to the previous selection? var tmpIdx = $("#Products").selectedIndex; $("#Products").append(result).selectedIndex = tmpIdx; If the onChange event should not fire then you can always set a flag to indicate that the form is updating and change events can check for that flag and exit if it is set. A: I just did the following and it worked fine: <select name="Products" id="Products"> <option value="">Select Product</option> </select> <script type="text/javascript"> $('#Products').append('<option value="1">test 1</option><option value="3">test 3</option><option value="3">test 3</option>'); </script> What is your script returning? A: $('#field').find('option:first').attr('selected', 'selected').parent('select'); see this will work
{ "language": "en", "url": "https://stackoverflow.com/questions/57479", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: What are the differences between a pointer variable and a reference variable? What is the difference between a pointer variable and a reference variable? A: References are very similar to pointers, but they are specifically crafted to be helpful to optimizing compilers. * *References are designed such that it is substantially easier for the compiler to trace which reference aliases which variables. Two major features are very important: no "reference arithmetic" and no reassigning of references. These allow the compiler to figure out which references alias which variables at compile time. *References are allowed to refer to variables which do not have memory addresses, such as those the compiler chooses to put into registers. If you take the address of a local variable, it is very hard for the compiler to put it in a register. As an example: void maybeModify(int& x); // may modify x in some way void hurtTheCompilersOptimizer(short size, int array[]) { // This function is designed to do something particularly troublesome // for optimizers. It will constantly call maybeModify on array[0] while // adding array[1] to array[2]..array[size-1]. There's no real reason to // do this, other than to demonstrate the power of references. for (int i = 2; i < (int)size; i++) { maybeModify(array[0]); array[i] += array[1]; } } An optimizing compiler may realize that we are accessing a[0] and a[1] quite a bunch. It would love to optimize the algorithm to: void hurtTheCompilersOptimizer(short size, int array[]) { // Do the same thing as above, but instead of accessing array[1] // all the time, access it once and store the result in a register, // which is much faster to do arithmetic with. register int a0 = a[0]; register int a1 = a[1]; // access a[1] once for (int i = 2; i < (int)size; i++) { maybeModify(a0); // Give maybeModify a reference to a register array[i] += a1; // Use the saved register value over and over } a[0] = a0; // Store the modified a[0] back into the array } To make such an optimization, it needs to prove that nothing can change array[1] during the call. This is rather easy to do. i is never less than 2, so array[i] can never refer to array[1]. maybeModify() is given a0 as a reference (aliasing array[0]). Because there is no "reference" arithmetic, the compiler just has to prove that maybeModify never gets the address of x, and it has proven that nothing changes array[1]. It also has to prove that there are no ways a future call could read/write a[0] while we have a temporary register copy of it in a0. This is often trivial to prove, because in many cases it is obvious that the reference is never stored in a permanent structure like a class instance. Now do the same thing with pointers void maybeModify(int* x); // May modify x in some way void hurtTheCompilersOptimizer(short size, int array[]) { // Same operation, only now with pointers, making the // optimization trickier. for (int i = 2; i < (int)size; i++) { maybeModify(&(array[0])); array[i] += array[1]; } } The behavior is the same; only now it is much harder to prove that maybeModify does not ever modify array[1], because we already gave it a pointer; the cat is out of the bag. Now it has to do the much more difficult proof: a static analysis of maybeModify to prove it never writes to &x + 1. It also has to prove that it never saves off a pointer that can refer to array[0], which is just as tricky. Modern compilers are getting better and better at static analysis, but it is always nice to help them out and use references. Of course, barring such clever optimizations, compilers will indeed turn references into pointers when needed. EDIT: Five years after posting this answer, I found an actual technical difference where references are different than just a different way of looking at the same addressing concept. References can modify the lifespan of temporary objects in a way that pointers cannot. F createF(int argument); void extending() { const F& ref = createF(5); std::cout << ref.getArgument() << std::endl; }; Normally temporary objects such as the one created by the call to createF(5) are destroyed at the end of the expression. However, by binding that object to a reference, ref, C++ will extend the lifespan of that temporary object until ref goes out of scope. A: Actually, a reference is not really like a pointer. A compiler keeps "references" to variables, associating a name with a memory address; that's its job to translate any variable name to a memory address when compiling. When you create a reference, you only tell the compiler that you assign another name to the pointer variable; that's why references cannot "point to null", because a variable cannot be, and not be. Pointers are variables; they contain the address of some other variable, or can be null. The important thing is that a pointer has a value, while a reference only has a variable that it is referencing. Now some explanation of real code: int a = 0; int& b = a; Here you are not creating another variable that points to a; you are just adding another name to the memory content holding the value of a. This memory now has two names, a and b, and it can be addressed using either name. void increment(int& n) { n = n + 1; } int a; increment(a); When calling a function, the compiler usually generates memory spaces for the arguments to be copied to. The function signature defines the spaces that should be created and gives the name that should be used for these spaces. Declaring a parameter as a reference just tells the compiler to use the input variable memory space instead of allocating a new memory space during the method call. It may seem strange to say that your function will be directly manipulating a variable declared in the calling scope, but remember that when executing compiled code, there is no more scope; there is just plain flat memory, and your function code could manipulate any variables. Now there may be some cases where your compiler may not be able to know the reference when compiling, like when using an extern variable. So a reference may or may not be implemented as a pointer in the underlying code. But in the examples I gave you, it will most likely not be implemented with a pointer. A: Difference between pointer and reference A pointer can be initialized to 0 and a reference not. In fact, a reference must also refer to an object, but a pointer can be the null pointer: int* p = 0; But we can’t have int& p = 0; and also int& p=5 ;. In fact to do it properly, we must have declared and defined an object at the first then we can make a reference to that object, so the correct implementation of the previous code will be: Int x = 0; Int y = 5; Int& p = x; Int& p1 = y; Another important point is that is we can make the declaration of the pointer without initialization however no such thing can be done in case of reference which must make a reference always to variable or object. However such use of a pointer is risky so generally we check if the pointer is actually is pointing to something or not. In case of a reference no such check is necessary, because we know already that referencing to an object during declaration is mandatory. Another difference is that pointer can point to another object however reference is always referencing to the same object, let’s take this example: Int a = 6, b = 5; Int& rf = a; Cout << rf << endl; // The result we will get is 6, because rf is referencing to the value of a. rf = b; cout << a << endl; // The result will be 5 because the value of b now will be stored into the address of a so the former value of a will be erased Another point: When we have a template like an STL template such kind of a class template will always return a reference, not a pointer, to make easy reading or assigning new value using operator []: Std ::vector<int>v(10); // Initialize a vector with 10 elements V[5] = 5; // Writing the value 5 into the 6 element of our vector, so if the returned type of operator [] was a pointer and not a reference we should write this *v[5]=5, by making a reference we overwrite the element by using the assignment "=" A: Some key pertinent details about references and pointers Pointers * *Pointer variables are declared using the unary suffix declarator operator * *Pointer objects are assigned an address value, for example, by assignment to an array object, the address of an object using the & unary prefix operator, or assignment to the value of another pointer object *A pointer can be reassigned any number of times, pointing to different objects *A pointer is a variable that holds the assigned address. It takes up storage in memory equal to the size of the address for the target machine architecture *A pointer can be mathematically manipulated, for instance, by the increment or addition operators. Hence, one can iterate with a pointer, etc. *To get or set the contents of the object referred to by a pointer, one must use the unary prefix operator * to dereference it References * *References must be initialized when they are declared. *References are declared using the unary suffix declarator operator &. *When initializing a reference, one uses the name of the object to which they will refer directly, without the need for the unary prefix operator & *Once initialized, references cannot be pointed to something else by assignment or arithmetical manipulation *There is no need to dereference the reference to get or set the contents of the object it refers to *Assignment operations on the reference manipulate the contents of the object it points to (after initialization), not the reference itself (does not change where it points to) *Arithmetic operations on the reference manipulate the contents of the object it points to, not the reference itself (does not change where it points to) *In pretty much all implementations, the reference is actually stored as an address in memory of the referred to object. Hence, it takes up storage in memory equal to the size of the address for the target machine architecture just like a pointer object Even though pointers and references are implemented in much the same way "under-the-hood," the compiler treats them differently, resulting in all the differences described above. Article A recent article I wrote that goes into much greater detail than I can show here and should be very helpful for this question, especially about how things happen in memory: Arrays, Pointers and References Under the Hood In-Depth Article A: Summary from answers and links below: * *A pointer can be re-assigned any number of times while a reference cannot be re-assigned after binding. *Pointers can point nowhere (NULL), whereas a reference always refers to an object. *You can't take the address of a reference like you can with pointers. *There's no "reference arithmetic" (but you can take the address of an object pointed by a reference and do pointer arithmetic on it as in &obj + 5). To clarify a misconception: The C++ standard is very careful to avoid dictating how a compiler may implement references, but every C++ compiler implements references as pointers. That is, a declaration such as: int &ri = i; if it's not optimized away entirely, allocates the same amount of storage as a pointer, and places the address of i into that storage. So, a pointer and a reference both use the same amount of memory. As a general rule, * *Use references in function parameters and return types to provide useful and self-documenting interfaces. *Use pointers for implementing algorithms and data structures. Interesting read: * *My all-time favorite C++ FAQ lite. *References vs. Pointers. *An Introduction to References. *References and const. A: in simple words, we can say a reference is an alternative name for a variable whereas, a pointer is a variable that holds the address of another variable. e.g. int a = 20; int &r = a; r = 40; /* now the value of a is changed to 40 */ int b =20; int *ptr; ptr = &b; /*assigns address of b to ptr not the value */ A: The difference is that non-constant pointer variable(not to be confused with a pointer to constant) may be changed at some time during program execution, requires pointer semantics to be used(&,*) operators, while references can be set upon initialization only(that's why you can set them in constructor initializer list only, but not somehow else) and use ordinary value accessing semantics. Basically references were introduced to allow support for operators overloading as I had read in some very old book. As somebody stated in this thread - pointer can be set to 0 or whatever value you want. 0(NULL, nullptr) means that the pointer is initialized with nothing. It is an error to dereference null pointer. But actually the pointer may contain a value that doesn't point to some correct memory location. References in their turn try not to allow a user to initialize a reference to something that cannot be referenced due to the fact that you always provide rvalue of correct type to it. Although there are a lot of ways to make reference variable be initialized to a wrong memory location - it is better for you not to dig this deep into details. On machine level both pointer and reference work uniformly - via pointers. Let's say in essential references are syntactic sugar. rvalue references are different to this - they are naturally stack/heap objects. A: What's a C++ reference (for C programmers) A reference can be thought of as a constant pointer (not to be confused with a pointer to a constant value!) with automatic indirection, ie the compiler will apply the * operator for you. All references must be initialized with a non-null value or compilation will fail. It's neither possible to get the address of a reference - the address operator will return the address of the referenced value instead - nor is it possible to do arithmetics on references. C programmers might dislike C++ references as it will no longer be obvious when indirection happens or if an argument gets passed by value or by pointer without looking at function signatures. C++ programmers might dislike using pointers as they are considered unsafe - although references aren't really any safer than constant pointers except in the most trivial cases - lack the convenience of automatic indirection and carry a different semantic connotation. Consider the following statement from the C++ FAQ: Even though a reference is often implemented using an address in the underlying assembly language, please do not think of a reference as a funny looking pointer to an object. A reference is the object. It is not a pointer to the object, nor a copy of the object. It is the object. But if a reference really were the object, how could there be dangling references? In unmanaged languages, it's impossible for references to be any 'safer' than pointers - there generally just isn't a way to reliably alias values across scope boundaries! Why I consider C++ references useful Coming from a C background, C++ references may look like a somewhat silly concept, but one should still use them instead of pointers where possible: Automatic indirection is convenient, and references become especially useful when dealing with RAII - but not because of any perceived safety advantage, but rather because they make writing idiomatic code less awkward. RAII is one of the central concepts of C++, but it interacts non-trivially with copying semantics. Passing objects by reference avoids these issues as no copying is involved. If references were not present in the language, you'd have to use pointers instead, which are more cumbersome to use, thus violating the language design principle that the best-practice solution should be easier than the alternatives. A: A reference can never be NULL. A: I always decide by this rule from C++ Core Guidelines: Prefer T* over T& when "no argument" is a valid option A: I have an analogy for references and pointers, think of references as another name for an object and pointers as the address of an object. // receives an alias of an int, an address of an int and an int value public void my_function(int& a,int* b,int c){ int d = 1; // declares an integer named d int &e = d; // declares that e is an alias of d // using either d or e will yield the same result as d and e name the same object int *f = e; // invalid, you are trying to place an object in an address // imagine writting your name in an address field int *g = f; // writes an address to an address g = &d; // &d means get me the address of the object named d you could also // use &e as it is an alias of d and write it on g, which is an address so it's ok } A: You can use the difference between references and pointers if you follow a convention for arguments passed to a function. Const references are for data passed into a function, and pointers are for data passed out of a function. In other languages, you can explicit notate this with keywords such as in and out. In C++, you can declare (by convention) the equivalent. For example, void DoSomething(const Foo& thisIsAnInput, Foo* thisIsAnOutput) { if (thisIsAnOuput) *thisIsAnOutput = thisIsAnInput; } The use of references as inputs and pointers as outputs is part of the Google style guide. A: Beside all the answers here, you can implement operator overloading using references: my_point operator+(const my_point& a, const my_point& b) { return { a.x + b.x, a.y + b.y }; } Using parameters as value would create temporary copies of the original arguments and using pointers would not invoke this function because of pointers arithmetics. A: There is a semantic difference that may appear esoteric if you are not familiar with studying computer languages in an abstract or even academic fashion. At the highest-level, the idea of references is that they are transparent "aliases". Your computer may use an address to make them work, but you're not supposed to worry about that: you're supposed to think of them as "just another name" for an existing object and the syntax reflects that. They are stricter than pointers so your compiler can more reliably warn you when you about to create a dangling reference, than when you are about to create a dangling pointer. Beyond that, there are of course some practical differences between pointers and references. The syntax to use them is obviously different, and you cannot "re-seat" references, have references to nothingness, or have pointers to references. A: While both references and pointers are used to indirectly access another value, there are two important differences between references and pointers. The first is that a reference always refers to an object: It is an error to define a reference without initializing it. The behavior of assignment is the second important difference: Assigning to a reference changes the object to which the reference is bound; it does not rebind the reference to another object. Once initialized, a reference always refers to the same underlying object. Consider these two program fragments. In the first, we assign one pointer to another: int ival = 1024, ival2 = 2048; int *pi = &ival, *pi2 = &ival2; pi = pi2; // pi now points to ival2 After the assignment, ival, the object addressed by pi remains unchanged. The assignment changes the value of pi, making it point to a different object. Now consider a similar program that assigns two references: int &ri = ival, &ri2 = ival2; ri = ri2; // assigns ival2 to ival This assignment changes ival, the value referenced by ri, and not the reference itself. After the assignment, the two references still refer to their original objects, and the value of those objects is now the same as well. A: A reference is an alias for another variable whereas a pointer holds the memory address of a variable. References are generally used as function parameters so that the passed object is not the copy but the object itself. void fun(int &a, int &b); // A common usage of references. int a = 0; int &b = a; // b is an alias for a. Not so common to use. A: Taryn♦ said: You can't take the address of a reference like you can with pointers. Actually you can. I'm quoting from an answer on another question: The C++ FAQ says it best: Unlike a pointer, once a reference is bound to an object, it can not be "reseated" to another object. The reference itself isn't an object (it has no identity; taking the address of a reference gives you the address of the referent; remember: the reference is its referent). A: A pointer is a variable that holds the memory address of another variable , where as a reference is an alias to an existing variable. (another name of the already existing variable) 1. A pointer can be initialised as: int b = 15; int *q = &b; OR int *q; q = &b; where as reference, int b=15; int &c=b; (declare and initialize in a single step) *A pointer can be assigned to null, but reference cannot *Various arithmetic operations can be performed on pointers whereas there is no such thing called Reference Arithmetic. *A pointer can be reassigned , but reference cannot *A pointer has its own memory address and size on the stack whereas a reference shares the same memory address A: Think about a pointer as about a business card: * *It gives you a chance to contact someone *It can be empy *It can contain wrong or outdated information *You are not sure someone, mentioned on it, is even still alive *You can't talk directly to the card, you only can use it to call someone *Maybe there are many such cards exist Think about a reference as about an active call with someone: * *You are pretty sure someone, you contacted, is alive *You can talk directly, no extra calls are needed *You are pretty sure you talk not to an empty place or a piece of garbage *You can't be sure you are the only one, who is currently talking with this object A: The direct answer What is a reference in C++? Some specific instance of type that is not an object type. What is a pointer in C++? Some specific instance of type that is an object type. From the ISO C++ definition of object type: An object type is a (possibly cv-qualified) type that is not a function type, not a reference type, and not cv void. It may be important to know, object type is a top-level category of the type universe in C++. Reference is also a top-level category. But pointer is not. Pointers and references are mentioned together in the context of compound type. This is basically due to the nature of the declarator syntax inherited from (and extended) C, which has no references. (Besides, there are more than one kind of declarator of references since C++ 11, while pointers are still "unityped": &+&& vs. *.) So drafting a language specific by "extension" with similar style of C in this context is somewhat reasonable. (I will still argue that the syntax of declarators wastes the syntactic expressiveness a lot, makes both human users and implementations frustrating. Thus, all of them are not qualified to be built-in in a new language design. This is a totally different topic about PL design, though.) Otherwise, it is insignificant that pointers can be qualified as a specific sorts of types with references together. They simply share too few common properties besides the syntax similarity, so there is no need to put them together in most cases. Note the statements above only mentions "pointers" and "references" as types. There are some interested questions about their instances (like variables). There also come too many misconceptions. The differences of the top-level categories can already reveal many concrete differences not tied to pointers directly: * *Object types can have top-level cv qualifiers. References cannot. *Variable of object types do occupy storage as per the abstract machine semantics. Reference do not necessary occupy storage (see the section about misconceptions below for details). *... A few more special rules on references: * *Compound declarators are more restrictive on references. *References can collapse. * *Special rules on && parameters (as the "forwarding references") based on reference collapsing during template parameter deduction allow "perfect forwarding" of parameters. *References have special rules in initialization. The lifetime of variable declared as a reference type can be different to ordinary objects via extension. * *BTW, a few other contexts like initialization involving std::initializer_list follows some similar rules of reference lifetime extension. It is another can of worms. *... The misconceptions Syntactic sugar I know references are syntactic sugar, so code is easier to read and write. Technically, this is plain wrong. References are not syntactic sugar of any other features in C++, because they cannot be exactly replaced by other features without any semantic differences. (Similarly, lambda-expressions are not syntactic sugar of any other features in C++ because it cannot be precisely simulated with "unspecified" properties like the declaration order of the captured variables, which may be important because the initialization order of such variables can be significant.) C++ only has a few kinds of syntactic sugars in this strict sense. One instance is (inherited from C) the built-in (non-overloaded) operator [], which is defined exactly having same semantic properties of specific forms of combination over built-in operator unary * and binary +. Storage So, a pointer and a reference both use the same amount of memory. The statement above is simply wrong. To avoid such misconceptions, look at the ISO C++ rules instead: From [intro.object]/1: ... An object occupies a region of storage in its period of construction, throughout its lifetime, and in its period of destruction. ... From [dcl.ref]/4: It is unspecified whether or not a reference requires storage. Note these are semantic properties. Pragmatics Even that pointers are not qualified enough to be put together with references in the sense of the language design, there are still some arguments making it debatable to make choice between them in some other contexts, for example, when making choices on parameter types. But this is not the whole story. I mean, there are more things than pointers vs references you have to consider. If you don't have to stick on such over-specific choices, in most cases the answer is short: you do not have the necessity to use pointers, so you don't. Pointers are usually bad enough because they imply too many things you don't expect and they will rely on too many implicit assumptions undermining the maintainability and (even) portability of the code. Unnecessarily relying on pointers is definitely a bad style and it should be avoided in the sense of modern C++. Reconsider your purpose and you will finally find that pointer is the feature of last sorts in most cases. * *Sometimes the language rules explicitly require specific types to be used. If you want to use these features, obey the rules. * *Copy constructors require specific types of cv-& reference type as the 1st parameter type. (And usually it should be const qualified.) *Move constructors require specific types of cv-&& reference type as the 1st parameter type. (And usually there should be no qualifiers.) *Specific overloads of operators require reference or non reference types. For example: * *Overloaded operator= as special member functions requires reference types similar to 1st parameter of copy/move constructors. *Postfix ++ requires dummy int. *... *If you know pass-by-value (i.e. using non-reference types) is sufficient, use it directly, particularly when using an implementation supporting C++17 mandated copy elision. (Warning: However, to exhaustively reason about the necessity can be very complicated.) *If you want to operate some handles with ownership, use smart pointers like unique_ptr and shared_ptr (or even with homebrew ones by yourself if you require them to be opaque), rather than raw pointers. *If you are doing some iterations over a range, use iterators (or some ranges which are not provided by the standard library yet), rather than raw pointers unless you are convinced raw pointers will do better (e.g. for less header dependencies) in very specific cases. *If you know pass-by-value is sufficient and you want some explicit nullable semantics, use wrapper like std::optional, rather than raw pointers. *If you know pass-by-value is not ideal for the reasons above, and you don't want nullable semantics, use {lvalue, rvalue, forwarding}-references. *Even when you do want semantics like traditional pointer, there are often something more appropriate, like observer_ptr in Library Fundamental TS. The only exceptions cannot be worked around in the current language: * *When you are implementing smart pointers above, you may have to deal with raw pointers. *Specific language-interoperation routines require pointers, like operator new. (However, cv-void* is still quite different and safer compared to the ordinary object pointers because it rules out unexpected pointer arithmetics unless you are relying on some non conforming extension on void* like GNU's.) *Function pointers can be converted from lambda expressions without captures, while function references cannot. You have to use function pointers in non-generic code for such cases, even you deliberately do not want nullable values. So, in practice, the answer is so obvious: when in doubt, avoid pointers. You have to use pointers only when there are very explicit reasons that nothing else is more appropriate. Except a few exceptional cases mentioned above, such choices are almost always not purely C++-specific (but likely to be language-implementation-specific). Such instances can be: * *You have to serve to old-style (C) APIs. *You have to meet the ABI requirements of specific C++ implementations. *You have to interoperate at runtime with different language implementations (including various assemblies, language runtime and FFI of some high-level client languages) based on assumptions of specific implementations. *You have to improve efficiency of the translation (compilation & linking) in some extreme cases. *You have to avoid symbol bloat in some extreme cases. Language neutrality caveats If you come to see the question via some Google search result (not specific to C++), this is very likely to be the wrong place. References in C++ is quite "odd", as it is essentially not first-class: they will be treated as the objects or the functions being referred to so they have no chance to support some first-class operations like being the left operand of the member access operator independently to the type of the referred object. Other languages may or may not have similar restrictions on their references. References in C++ will likely not preserve the meaning across different languages. For example, references in general do not imply nonnull properties on values like they in C++, so such assumptions may not work in some other languages (and you will find counterexamples quite easily, e.g. Java, C#, ...). There can still be some common properties among references in different programming languages in general, but let's leave it for some other questions in SO. (A side note: the question may be significant earlier than any "C-like" languages are involved, like ALGOL 68 vs. PL/I.) A: It doesn't matter how much space it takes up since you can't actually see any side effect (without executing code) of whatever space it would take up. On the other hand, one major difference between references and pointers is that temporaries assigned to const references live until the const reference goes out of scope. For example: class scope_test { public: ~scope_test() { printf("scope_test done!\n"); } }; ... { const scope_test &test= scope_test(); printf("in scope\n"); } will print: in scope scope_test done! This is the language mechanism that allows ScopeGuard to work. A: This is based on the tutorial. What is written makes it more clear: >>> The address that locates a variable within memory is what we call a reference to that variable. (5th paragraph at page 63) >>> The variable that stores the reference to another variable is what we call a pointer. (3rd paragraph at page 64) Simply to remember that, >>> reference stands for memory location >>> pointer is a reference container (Maybe because we will use it for several times, it is better to remember that reference.) What's more, as we can refer to almost any pointer tutorial, a pointer is an object that is supported by pointer arithmetic which makes pointer similar to an array. Look at the following statement, int Tom(0); int & alias_Tom = Tom; alias_Tom can be understood as an alias of a variable (different with typedef, which is alias of a type) Tom. It is also OK to forget the terminology of such statement is to create a reference of Tom. A: If you want to be really pedantic, there is one thing you can do with a reference that you can't do with a pointer: extend the lifetime of a temporary object. In C++ if you bind a const reference to a temporary object, the lifetime of that object becomes the lifetime of the reference. std::string s1 = "123"; std::string s2 = "456"; std::string s3_copy = s1 + s2; const std::string& s3_reference = s1 + s2; In this example s3_copy copies the temporary object that is a result of the concatenation. Whereas s3_reference in essence becomes the temporary object. It's really a reference to a temporary object that now has the same lifetime as the reference. If you try this without the const it should fail to compile. You cannot bind a non-const reference to a temporary object, nor can you take its address for that matter. A: * *A pointer can be re-assigned: int x = 5; int y = 6; int *p; p = &x; p = &y; *p = 10; assert(x == 5); assert(y == 10); A reference cannot be re-bound, and must be bound at initialization: int x = 5; int y = 6; int &q; // error int &r = x; *A pointer variable has its own identity: a distinct, visible memory address that can be taken with the unary & operator and a certain amount of space that can be measured with the sizeof operator. Using those operators on a reference returns a value corresponding to whatever the reference is bound to; the reference’s own address and size are invisible. Since the reference assumes the identity of the original variable in this way, it is convenient to think of a reference as another name for the same variable. int x = 0; int &r = x; int *p = &x; int *p2 = &r; assert(p == p2); // &x == &r assert(&p != &p2); *You can have arbitrarily nested pointers to pointers offering extra levels of indirection. References only offer one level of indirection. int x = 0; int y = 0; int *p = &x; int *q = &y; int **pp = &p; **pp = 2; pp = &q; // *pp is now q **pp = 4; assert(y == 4); assert(x == 2); *A pointer can be assigned nullptr, whereas a reference must be bound to an existing object. If you try hard enough, you can bind a reference to nullptr, but this is undefined and will not behave consistently. /* the code below is undefined; your compiler may optimise it * differently, emit warnings, or outright refuse to compile it */ int &r = *static_cast<int *>(nullptr); // prints "null" under GCC 10 std::cout << (&r != nullptr ? "not null" : "null") << std::endl; bool f(int &r) { return &r != nullptr; } // prints "not null" under GCC 10 std::cout << (f(*static_cast<int *>(nullptr)) ? "not null" : "null") << std::endl; You can, however, have a reference to a pointer whose value is nullptr. *Pointers can iterate over an array; you can use ++ to go to the next item that a pointer is pointing to, and + 4 to go to the 5th element. This is no matter what size the object is that the pointer points to. *A pointer needs to be dereferenced with * to access the memory location it points to, whereas a reference can be used directly. A pointer to a class/struct uses -> to access its members whereas a reference uses a .. *References cannot be put into an array, whereas pointers can be (Mentioned by user @litb) *Const references can be bound to temporaries. Pointers cannot (not without some indirection): const int &x = int(12); // legal C++ int *y = &int(12); // illegal to take the address of a temporary. This makes const & more convenient to use in argument lists and so forth. A: A reference is not another name given to some memory. It's a immutable pointer that is automatically de-referenced on usage. Basically it boils down to: int& j = i; It internally becomes int* const j = &i; A: A reference to a pointer is possible in C++, but the reverse is not possible means a pointer to a reference isn't possible. A reference to a pointer provides a cleaner syntax to modify the pointer. Look at this example: #include<iostream> using namespace std; void swap(char * &str1, char * &str2) { char *temp = str1; str1 = str2; str2 = temp; } int main() { char *str1 = "Hi"; char *str2 = "Hello"; swap(str1, str2); cout<<"str1 is "<<str1<<endl; cout<<"str2 is "<<str2<<endl; return 0; } And consider the C version of the above program. In C you have to use pointer to pointer (multiple indirection), and it leads to confusion and the program may look complicated. #include<stdio.h> /* Swaps strings by swapping pointers */ void swap1(char **str1_ptr, char **str2_ptr) { char *temp = *str1_ptr; *str1_ptr = *str2_ptr; *str2_ptr = temp; } int main() { char *str1 = "Hi"; char *str2 = "Hello"; swap1(&str1, &str2); printf("str1 is %s, str2 is %s", str1, str2); return 0; } Visit the following for more information about reference to pointer: * *C++: Reference to Pointer *Pointer-to-Pointer and Reference-to-Pointer As I said, a pointer to a reference isn't possible. Try the following program: #include <iostream> using namespace std; int main() { int x = 10; int *ptr = &x; int &*ptr1 = ptr; } A: I use references unless I need either of these: * *Null pointers can be used as a sentinel value, often a cheap way to avoid function overloading or use of a bool. *You can do arithmetic on a pointer. For example, p += offset; A: There is one fundamental difference between pointers and references that I didn't see anyone had mentioned: references enable pass-by-reference semantics in function arguments. Pointers, although it is not visible at first do not: they only provide pass-by-value semantics. This has been very nicely described in this article. Regards, &rzej A: Apart from syntactic sugar, a reference is a const pointer (not pointer to a const). You must establish what it refers to when you declare the reference variable, and you cannot change it later. Update: now that I think about it some more, there is an important difference. A const pointer's target can be replaced by taking its address and using a const cast. A reference's target cannot be replaced in any way short of UB. This should permit the compiler to do more optimization on a reference. A: Another difference is that you can have pointers to a void type (and it means pointer to anything) but references to void are forbidden. int a; void * p = &a; // ok void & p = a; // forbidden I can't say I'm really happy with this particular difference. I would much prefer it would be allowed with the meaning reference to anything with an address and otherwise the same behavior for references. It would allow to define some equivalents of C library functions like memcpy using references. A: At the risk of adding to confusion, I want to throw in some input, I'm sure it mostly depends on how the compiler implements references, but in the case of gcc the idea that a reference can only point to a variable on the stack is not actually correct, take this for example: #include <iostream> int main(int argc, char** argv) { // Create a string on the heap std::string *str_ptr = new std::string("THIS IS A STRING"); // Dereference the string on the heap, and assign it to the reference std::string &str_ref = *str_ptr; // Not even a compiler warning! At least with gcc // Now lets try to print it's value! std::cout << str_ref << std::endl; // It works! Now lets print and compare actual memory addresses std::cout << str_ptr << " : " << &str_ref << std::endl; // Exactly the same, now remember to free the memory on the heap delete str_ptr; } Which outputs this: THIS IS A STRING 0xbb2070 : 0xbb2070 If you notice even the memory addresses are exactly the same, meaning the reference is successfully pointing to a variable on the heap! Now if you really want to get freaky, this also works: int main(int argc, char** argv) { // In the actual new declaration let immediately de-reference and assign it to the reference std::string &str_ref = *(new std::string("THIS IS A STRING")); // Once again, it works! (at least in gcc) std::cout << str_ref; // Once again it prints fine, however we have no pointer to the heap allocation, right? So how do we free the space we just ignorantly created? delete &str_ref; /*And, it works, because we are taking the memory address that the reference is storing, and deleting it, which is all a pointer is doing, just we have to specify the address with '&' whereas a pointer does that implicitly, this is sort of like calling delete &(*str_ptr); (which also compiles and runs fine).*/ } Which outputs this: THIS IS A STRING Therefore a reference IS a pointer under the hood, they both are just storing a memory address, where the address is pointing to is irrelevant, what do you think would happen if I called std::cout << str_ref; AFTER calling delete &str_ref? Well, obviously it compiles fine, but causes a segmentation fault at runtime because it's no longer pointing at a valid variable, we essentially have a broken reference that still exists (until it falls out of scope), but is useless. In other words, a reference is nothing but a pointer that has the pointer mechanics abstracted away, making it safer and easier to use (no accidental pointer math, no mixing up '.' and '->', etc.), assuming you don't try any nonsense like my examples above ;) Now regardless of how a compiler handles references, it will always have some kind of pointer under the hood, because a reference must refer to a specific variable at a specific memory address for it to work as expected, there is no getting around this (hence the term 'reference'). The only major rule that's important to remember with references is that they must be defined at the time of declaration (with the exception of a reference in a header, in that case it must be defined in the constructor, after the object it's contained in is constructed it's too late to define it). Remember, my examples above are just that, examples demonstrating what a reference is, you would never want to use a reference in those ways! For proper usage of a reference there are plenty of answers on here already that hit the nail on the head A: Also, a reference that is a parameter to a function that is inlined may be handled differently than a pointer. void increment(int *ptrint) { (*ptrint)++; } void increment(int &refint) { refint++; } void incptrtest() { int testptr=0; increment(&testptr); } void increftest() { int testref=0; increment(testref); } Many compilers when inlining the pointer version one will actually force a write to memory (we are taking the address explicitly). However, they will leave the reference in a register which is more optimal. Of course, for functions that are not inlined the pointer and reference generate the same code and it's always better to pass intrinsics by value than by reference if they are not modified and returned by the function. A: Another interesting use of references is to supply a default argument of a user-defined type: class UDT { public: UDT() : val_d(33) {}; UDT(int val) : val_d(val) {}; virtual ~UDT() {}; private: int val_d; }; class UDT_Derived : public UDT { public: UDT_Derived() : UDT() {}; virtual ~UDT_Derived() {}; }; class Behavior { public: Behavior( const UDT &udt = UDT() ) {}; }; int main() { Behavior b; // take default UDT u(88); Behavior c(u); UDT_Derived ud; Behavior d(ud); return 1; } The default flavor uses the 'bind const reference to a temporary' aspect of references. A: This program might help in comprehending the answer of the question. This is a simple program of a reference "j" and a pointer "ptr" pointing to variable "x". #include<iostream> using namespace std; int main() { int *ptr=0, x=9; // pointer and variable declaration ptr=&x; // pointer to variable "x" int & j=x; // reference declaration; reference to variable "x" cout << "x=" << x << endl; cout << "&x=" << &x << endl; cout << "j=" << j << endl; cout << "&j=" << &j << endl; cout << "*ptr=" << *ptr << endl; cout << "ptr=" << ptr << endl; cout << "&ptr=" << &ptr << endl; getch(); } Run the program and have a look at the output and you'll understand. Also, spare 10 minutes and watch this video: https://www.youtube.com/watch?v=rlJrrGV0iOg A: Contrary to popular opinion, it is possible to have a reference that is NULL. int * p = NULL; int & r = *p; r = 1; // crash! (if you're lucky) Granted, it is much harder to do with a reference - but if you manage it, you'll tear your hair out trying to find it. References are not inherently safe in C++! Technically this is an invalid reference, not a null reference. C++ doesn't support null references as a concept as you might find in other languages. There are other kinds of invalid references as well. Any invalid reference raises the spectre of undefined behavior, just as using an invalid pointer would. The actual error is in the dereferencing of the NULL pointer, prior to the assignment to a reference. But I'm not aware of any compilers that will generate any errors on that condition - the error propagates to a point further along in the code. That's what makes this problem so insidious. Most of the time, if you dereference a NULL pointer, you crash right at that spot and it doesn't take much debugging to figure it out. My example above is short and contrived. Here's a more real-world example. class MyClass { ... virtual void DoSomething(int,int,int,int,int); }; void Foo(const MyClass & bar) { ... bar.DoSomething(i1,i2,i3,i4,i5); // crash occurs here due to memory access violation - obvious why? } MyClass * GetInstance() { if (somecondition) return NULL; ... } MyClass * p = GetInstance(); Foo(*p); I want to reiterate that the only way to get a null reference is through malformed code, and once you have it you're getting undefined behavior. It never makes sense to check for a null reference; for example you can try if(&bar==NULL)... but the compiler might optimize the statement out of existence! A valid reference can never be NULL so from the compiler's view the comparison is always false, and it is free to eliminate the if clause as dead code - this is the essence of undefined behavior. The proper way to stay out of trouble is to avoid dereferencing a NULL pointer to create a reference. Here's an automated way to accomplish this. template<typename T> T& deref(T* p) { if (p == NULL) throw std::invalid_argument(std::string("NULL reference")); return *p; } MyClass * p = GetInstance(); Foo(deref(p)); For an older look at this problem from someone with better writing skills, see Null References from Jim Hyslop and Herb Sutter. For another example of the dangers of dereferencing a null pointer see Exposing undefined behavior when trying to port code to another platform by Raymond Chen. A: You forgot the most important part: member-access with pointers uses -> member-access with references uses . foo.bar is clearly superior to foo->bar in the same way that vi is clearly superior to Emacs :-) A: I feel like there is yet another point that hasn't been covered here. Unlike the pointers, references are syntactically equivalent to the object they refer to, i.e. any operation that can be applied to an object works for a reference, and with the exact same syntax (the exception is of course the initialization). While this may appear superficial, I believe this property is crucial for a number of C++ features, for example: * *Templates. Since template parameters are duck-typed, syntactic properties of a type is all that matters, so often the same template can be used with both T and T&. (or std::reference_wrapper<T> which still relies on an implicit cast to T&) Templates that cover both T& and T&& are even more common. *Lvalues. Consider the statement str[0] = 'X'; Without references it would only work for c-strings (char* str). Returning the character by reference allows user-defined classes to have the same notation. *Copy constructors. Syntactically it makes sense to pass objects to copy constructors, and not pointers to objects. But there is just no way for a copy constructor to take an object by value - it would result in a recursive call to the same copy constructor. This leaves references as the only option here. *Operator overloads. With references it is possible to introduce indirection to an operator call - say, operator+(const T& a, const T& b) while retaining the same infix notation. This also works for regular overloaded functions. These points empower a considerable part of C++ and the standard library so this is quite a major property of references. A: A reference is a const pointer. int * const a = &b is the same as int& a = b. This is why there's is no such thing as a const reference, because it is already const, whereas a reference to const is const int * const a. When you compile using -O0, the compiler will place the address of b on the stack in both situations, and as a member of a class, it will also be present in the object on the stack/heap identically to if you had declared a const pointer. With -Ofast, it is free to optimise this out. A const pointer and reference are both optimised away. Unlike a const pointer, there is no way to take the address of the reference itself, as it will be interpreted as the address of the variable it references. Because of this, on -Ofast, the const pointer representing the reference (the address of the variable being referenced) will always be optimised off the stack, but if the program absolutely needs the address of an actual const pointer (the address of the pointer itself, not the address it points to) i.e. you print the address of the const pointer, then the const pointer will be placed on the stack so that it has an address. Otherwise it is identical i.e. when you print the that address it points to: #include <iostream> int main() { int a =1; int* b = &a; std::cout << b ; } int main() { int a =1; int& b = a; std::cout << &b ; } they both have the same assembly output -Ofast: main: sub rsp, 24 mov edi, OFFSET FLAT:_ZSt4cout lea rsi, [rsp+12] mov DWORD PTR [rsp+12], 1 call std::basic_ostream<char, std::char_traits<char> >& std::basic_ostream<char, std::char_traits<char> >::_M_insert<void const*>(void const*) xor eax, eax add rsp, 24 ret -------------------------------------------------------------------- -O0: main: push rbp mov rbp, rsp sub rsp, 16 mov DWORD PTR [rbp-12], 1 lea rax, [rbp-12] mov QWORD PTR [rbp-8], rax mov rax, QWORD PTR [rbp-8] mov rsi, rax mov edi, OFFSET FLAT:_ZSt4cout call std::basic_ostream<char, std::char_traits<char> >::operator<<(void const*) mov eax, 0 leave ret The pointer has been optimised off the stack, and the pointer isn't even dereferenced on -Ofast in both cases, instead it uses a compile time value. As members of an object they are identical on -O0 through -Ofast. #include <iostream> int b=1; struct A {int* i=&b; int& j=b;}; A a; int main() { std::cout << &a.j << &a.i; } The address of b is stored twice in the object. a: .quad b .quad b mov rax, QWORD PTR a[rip+8] //&a.j mov esi, OFFSET FLAT:a //&a.i When you pass by reference, on -O0, you pass the address of the variable referenced, so it is identical to passing by pointer i.e. the address the const pointer contains. On -Ofast this is optimised out by the compiler in an inline call if the function can be inlined, as the dynamic scope is known, but in the function definition, the parameter is always dereferenced as a pointer (expecting the address of the variable being referenced by the reference) where it may be used by another translation unit and the dynamic scope is unknown to the compiler, unless of course the function is declared as a static function, then it can't be used outside of the translation unit and then it passes by value so long as it isn't modified in the function by reference, then it will pass the address of the variable being referenced by the reference that you're passing, and on -Ofast this will be passed in a register and kept off of the stack if there are enough volatile registers in the calling convention. A: There is a very important non-technical difference between pointers and references: An argument passed to a function by pointer is much more visible than an argument passed to a function by non-const reference. For example: void fn1(std::string s); void fn2(const std::string& s); void fn3(std::string& s); void fn4(std::string* s); void bar() { std::string x; fn1(x); // Cannot modify x fn2(x); // Cannot modify x (without const_cast) fn3(x); // CAN modify x! fn4(&x); // Can modify x (but is obvious about it) } Back in C, a call that looks like fn(x) can only be passed by value, so it definitely cannot modify x; to modify an argument you would need to pass a pointer fn(&x). So if an argument wasn't preceded by an & you knew it would not be modified. (The converse, & means modified, was not true because you would sometimes have to pass large read-only structures by const pointer.) Some argue that this is such a useful feature when reading code, that pointer parameters should always be used for modifiable parameters rather than non-const references, even if the function never expects a nullptr. That is, those people argue that function signatures like fn3() above should not be allowed. Google's C++ style guidelines are an example of this. A: Maybe some metaphors will help; In the context of your desktop screenspace - * *A reference requires you to specify an actual window. *A pointer requires the location of a piece of space on screen that you assure it will contain zero or more instances of that window type. A: "I know references are syntactic sugar, so code is easier to read and write" This. A reference is not another way to implement a pointer, although it covers a huge pointer use case. A pointer is a datatype -- an address that in general points to a actual value. However it can be set to zero, or a couple of places after the address using address arithmetic, etc. A reference is 'syntactic sugar' for a variable which has its own value. C only had pass by value semantics. Getting the address of the data a variable was referring to and sending that to a function was a way to pass by 'reference'. A reference shortcuts this semantically by 'referring' to the original data location itself. So: int x = 1; int *y = &x; int &z = x; Y is an int pointer, pointing to the location where x is stored. X and Z refer to the same storage place (the stack or the heap). Alot of people have talked about the difference between the two (pointers and references) as if they are the same thing with different usages. They are not the same at all. 1) "A pointer can be re-assigned any number of times while a reference cannot be re-assigned after binding." -- a pointer is an address data type which points to data. A reference is another name for the data. So you can 'reassign' a reference. You just can't reassign the data location it refers to. Just like you can't change the data location that 'x' refers to, you can't do that to 'z'. x = 2; *y = 2; z = 2; The same. It is a reassignment. 2) "Pointers can point nowhere (NULL), whereas a reference always refers to an object" -- again with the confusion. The reference is just another name for the object. A null pointer means (semantically) that it isn't referring to anything, whereas the reference was created by saying it was another name for 'x'. Since 3) "You can't take the address of a reference like you can with pointers" -- Yes you can. Again with the confusion. If you are trying to find the address of the pointer that is being used as a reference, that is a problem -- cause references are not pointers to the object. They are the object. So you can get the address of the object, and you can get the address of the pointer. Cause they are both getting the address of data (one the object's location in memory, the other the pointer to the objects location in memory). int *yz = &z; -- legal int **yy = &y; -- legal int *yx = &x; -- legal; notice how this looks like the z example. x and z are equivalent. 4) "There's no "reference arithmetic"" -- again with the confusion -- since the example above has z being a reference to x and both are therefore integers, 'reference' arithmetic means for example adding 1 to the value referred to by x. x++; z++; *y++; // what people assume is happening behind the scenes, but isn't. it would produce the same results in this example. *(y++); // this one adds to the pointer, and then dereferences it. It makes sense that a pointer datatype (an address) can be incremented. Just like an int can be incremented. A: Basic meaning of pointer(*) is "Value at address of" which means whatever address you provide it will give value at that address. Once you change the address it will give the new value, while reference variable used to reference any particular variable and which can't be change to reference any other variable in future. A: you can not dereference a reference like a pointer, which when dereferenced gives values at that location, both reference and pointer work by the address though... so you can do this int* val = 0xDEADBEEF; *val is something at 0xDEADBEEF. you can not do this int& val = 1; *val is not allowed. A: In short, Pointers: A pointer is a variable that holds the memory address of another variable. A pointer needs to be dereferenced with the * operator to access the memory location it points to. - Extracted from Geeks for Geeks References: A reference variable is an alias, that is, another name for an already existing variable. A reference, like a pointer, is also implemented by storing the address of an object. - Extracted from Geeks for Geeks Another picture for more details:
{ "language": "en", "url": "https://stackoverflow.com/questions/57483", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3818" }
Q: How do you "OR" criteria together when using a criteria query with hibernate? I'm trying to do a basic "OR" on three fields using a hibernate criteria query. Example class Whatever{ string name; string address; string phoneNumber; } I'd like to build a criteria query where my search string could match "name" or "address" or "phoneNumber". A: Assuming you have a hibernate session to hand then something like the following should work: Criteria c = session.createCriteria(Whatever.class); Disjunction or = Restrictions.disjunction(); or.add(Restrictions.eq("name",searchString)); or.add(Restrictions.eq("address",searchString)); or.add(Restrictions.eq("phoneNumber",searchString)); c.add(or); A: //Expression : (c1 AND c2) OR (c3) Criteria criteria = session.createCriteria(Employee.class); Criterion c1 = Restrictions.like("name", "%e%"); Criterion c2 = Restrictions.ge("salary", 10000.00); Criterion c3 = Restrictions.like("name", "%YYY%"); Criterion c4 = Restrictions.or(Restrictions.and(c1, c2), c3); criteria.add(c4); //Same thing can be done for (c1 OR c2) AND c3, or any complex expression. A: Just in case anyone should stumble upon this with the same question for NHibernate: ICriteria c = session.CreateCriteria(typeof (Whatever)) .Add(Expression.Disjunction() .Add(Expression.Eq("name", searchString)) .Add(Expression.Eq("address", searchString)) .Add(Expression.Eq("phoneNumber", searchString))); A: You want to use Restrictions.disjuntion(). Like so session.createCriteria(Whatever.class) .add(Restrictions.disjunction() .add(Restrictions.eq("name", queryString)) .add(Restrictions.eq("address", queryString)) .add(Restrictions.eq("phoneNumber", queryString)) ); See the Hibernate doc here. A: //Expression : (c1 AND c2) OR (c3) Criteria criteria = session.createCriteria(Employee.class); Criterion c1 = Restrictions.like("name", "%e%"); Criterion c2 = Restrictions.ge("salary", 10000.00); Criterion c3 = Restrictions.like("name", "%YYY%"); Criterion c4 = Restrictions.or(Restrictions.and(c1, c2), c3); criteria.add(c4); //Same thing can be done for (c1 OR c2) AND c3, or any complex expression. A: The conditions can be applied using the or / and in different levels of the query using disjunction Criteria query = getCriteria("ENTITY_NAME"); query.add(Restrictions.ne("column Name", current _value)); Disjunction disjunction = Restrictions.disjunction(); if (param_1 != null) disjunction.add(Restrictions.or(Restrictions.eq("column Name", param1))); if (param_2 != null) disjunction.add(Restrictions.or(Restrictions.eq("column Name", param_2))); if (param_3 != null) disjunction.add(Restrictions.or(Restrictions.eq("column Name", param_3))); if (param_4 != null && param_5 != null) disjunction.add(Restrictions.or(Restrictions.and(Restrictions.eq("column Name", param_4 ), Restrictions.eq("column Name", param_5 )))); if (disjunction.conditions() != null && disjunction.conditions().iterator().hasNext()) query.add(Restrictions.and(disjunction)); return query.list(); A: This is what worked for me for an OR condition, that too with an IN condition and not the answer up-voted most on this discussion: criteria.add( Restrictions.or( Restrictions.eq(ch.getPath(ch.propertyResolver().getXXXX()), "OR_STRING"), Restrictions.in(ch.getPath(ch.propertyResolver().getYYYY()), new String[]{"AA","BB","CC"}) )); Resulting Query: and ( this_.XXXX=? or this_.YYYY in ( ?, ?, ? ) ) A: If someone is using CriteriaQuery instead of Criteria, you can put all your expressions in a Predicate list and put a OR by predicates size like this: List<Predicate> predicates = new ArrayList<>(); if (...) { predicates.add(...); } criteriaQuery.where(cb.or(predicates.toArray(new Predicate[predicates.size()])));
{ "language": "en", "url": "https://stackoverflow.com/questions/57484", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "79" }
Q: .NET Date Const (with Globalization) Does anyone know of a way to declare a date constant that is compatible with international dates? I've tried: ' not international compatible public const ADate as Date = #12/31/04# ' breaking change if you have an optional parameter that defaults to this value ' because it isnt constant. public shared readonly ADate As New Date(12, 31, 04) A: If you look at the IL generated by the statement public const ADate as Date = #12/31/04# You'll see this: .field public static initonly valuetype [mscorlib]System.DateTime ADate .custom instance void [mscorlib]System.Runtime.CompilerServices.DateTimeConstantAttribute::.ctor(int64) = ( 01 00 00 C0 2F CE E2 BC C6 08 00 00 ) Notice that the DateTimeConstantAttribute is being initialized with a constructor that takes an int64 tick count. Since this tick count is being determined at complile time, it seems unlikely that any localization is coming into play when this value is initialized at runtime. My guess is that the error is with some other date handling in your code, not the const initialization. A: According to the Microsoft documentation, "You must enclose a Date literal within number signs (# #). You must specify the date value in the format M/d/yyyy, for example #5/31/1993#. This requirement is independent of your locale and your computer's date and time format settings." Are you saying that this is not correct and the parsing is affected by the current locale? Edit: Did you try with a 4-digit year? A: Once you have data into Date objects in VB, you don't have to worry about globalization until you compare something to it or try to export it. This is fine: Dim FirstDate as Date = Date.UtcNow() 'or this: = NewDate (2008,09,10)' Dim SecondDate as Date SecondDate = FirstDate.AddDays(1) This pulls in the globalization rules and prints in the current thread's culture format: HeaderLabel.Text = SecondDate.ToString() This is bad: Dim BadDate as Date = CDate("2/20/2000") Actually--even that is OK if you force CDate in that case to use the right culture (InvariantCulture): Dim OkButBadPracticeDate as Date = CDate("2/20/2000", CultureInfo.InvariantCulture) If you want to force everything to a particular culture, you need to set the executing thread culture and UI culture to the desired culture (en-US, invariant, etc.). Make sure you aren't doing any work with dates as strings--make sure they are actual Date objects! A: OK, I am unsure what you are trying to do here: * *The code you are posting is NOT .NET, are you trying to port? *DateTime's cannot be declared as constants. *DateTime's are a data type, so once init'ed, the format that they were init'ed from is irrelevant. *If you need a constant value, then just create a method to always return the same DateTime. For example: public static DateTime SadDayForAll() { return new DateTime(2001, 09, 11); } Update Where the hell are you getting all that from?! * *There are differences between C# and VB.NET, and this highlights one of them. *Date is not a .NET data type - DateTime is. *It looks like you can create DateTime constants in VB.NET but there are limitations *The method was there to try and help you, since you cannot create a const from a variable (i.e. optional param). That doesn't even make sense. A: Ok right, I understand more where you are coming from.. How about: * *Create a static method that returns the date constant. This overcomes the international issue since it is returned as the specific DateTime value. *Now I remember optional params from my VB6 days, but can you not just overload the method? If you are using the overloaded method without the date, just pull it from the static? EDIT: If you are unsure what I mean and would like a code sample, just comment this post and I will chuck one on.
{ "language": "en", "url": "https://stackoverflow.com/questions/57488", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: WPF Databind Before Saving In my WPF application, I have a number of databound TextBoxes. The UpdateSourceTrigger for these bindings is LostFocus. The object is saved using the File menu. The problem I have is that it is possible to enter a new value into a TextBox, select Save from the File menu, and never persist the new value (the one visible in the TextBox) because accessing the menu does not remove focus from the TextBox. How can I fix this? Is there some way to force all the controls in a page to databind? @palehorse: Good point. Unfortunately, I need to use LostFocus as my UpdateSourceTrigger in order to support the type of validation I want. @dmo: I had thought of that. It seems, however, like a really inelegant solution for a relatively simple problem. Also, it requires that there be some control on the page which is is always visible to receive the focus. My application is tabbed, however, so no such control readily presents itself. @Nidonocu: The fact that using the menu did not move focus from the TextBox confused me as well. That is, however, the behavior I am seeing. The following simple example demonstrates my problem: <Window x:Class="WpfApplication2.Window1" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="Window1" Height="300" Width="300"> <Window.Resources> <ObjectDataProvider x:Key="MyItemProvider" /> </Window.Resources> <DockPanel LastChildFill="True"> <Menu DockPanel.Dock="Top"> <MenuItem Header="File"> <MenuItem Header="Save" Click="MenuItem_Click" /> </MenuItem> </Menu> <StackPanel DataContext="{Binding Source={StaticResource MyItemProvider}}"> <Label Content="Enter some text and then File > Save:" /> <TextBox Text="{Binding ValueA}" /> <TextBox Text="{Binding ValueB}" /> </StackPanel> </DockPanel> </Window> using System; using System.Text; using System.Windows; using System.Windows.Data; namespace WpfApplication2 { public partial class Window1 : Window { public MyItem Item { get { return (FindResource("MyItemProvider") as ObjectDataProvider).ObjectInstance as MyItem; } set { (FindResource("MyItemProvider") as ObjectDataProvider).ObjectInstance = value; } } public Window1() { InitializeComponent(); Item = new MyItem(); } private void MenuItem_Click(object sender, RoutedEventArgs e) { MessageBox.Show(string.Format("At the time of saving, the values in the TextBoxes are:\n'{0}'\nand\n'{1}'", Item.ValueA, Item.ValueB)); } } public class MyItem { public string ValueA { get; set; } public string ValueB { get; set; } } } A: This is a UGLY hack but should also work TextBox focusedTextBox = Keyboard.FocusedElement as TextBox; if (focusedTextBox != null) { focusedTextBox.GetBindingExpression(TextBox.TextProperty).UpdateSource(); } This code checks if a TextBox has focus... If 1 is found... update the binding source! A: Suppose you have a TextBox in a window, and a ToolBar with a Save button in it. Assume the TextBox’s Text property is bound to a property on a business object, and the binding’s UpdateSourceTrigger property is set to the default value of LostFocus, meaning that the bound value is pushed back to the business object property when the TextBox loses input focus. Also, assume that the ToolBar’s Save button has its Command property set to ApplicationCommands.Save command. In that situation, if you edit the TextBox and click the Save button with the mouse, there is a problem. When clicking on a Button in a ToolBar, the TextBox does not lose focus. Since the TextBox’s LostFocus event does not fire, the Text property binding does not update the source property of the business object. Obviously you should not validate and save an object if the most recently edited value in the UI has not yet been pushed into the object. This is the exact problem Karl had worked around, by writing code in his window that manually looked for a TextBox with focus and updated the source of the data binding. His solution worked fine, but it got me thinking about a generic solution that would also be useful outside of this particular scenario. Enter CommandGroup… Taken from Josh Smith’s CodeProject article about CommandGroup A: Simple solution is update the Xaml code as shown below <StackPanel DataContext="{Binding Source={StaticResource MyItemProvider}}"> <Label Content="Enter some text and then File > Save:" /> <TextBox Text="{Binding ValueA, UpdateSourceTrigger=PropertyChanged}" /> <TextBox Text="{Binding ValueB, UpdateSourceTrigger=PropertyChanged}" /> </StackPanel> A: I've run into this issue and the best solution I've found was to change the focusable value of the button (or any other component such as MenuItem) to true: <Button Focusable="True" Command="{Binding CustomSaveCommand}"/> The reason it works, is because it forces the button to get focused before it invokes the command and therefore makes the TextBox or any other UIElement for that matter to loose their focus and raise lost focus event which invokes the binding to be changed. In case you are using bounded command (as I was pointing to in my example), John Smith's great solution won't fit very well since you can't bind StaticExtension into bounded property (nor DP). A: I found that removing the menu items that are scope depended from the FocusScope of the menu causes the textbox to lose focus correctly. I wouldn't think this applies to ALL items in Menu, but certainly for a save or validate action. <Menu FocusManager.IsFocusScope="False" > A: Have you tried setting the UpdateSourceTrigger to PropertyChanged? Alternatively, you could call the UpdateSOurce() method, but that seems like a bit overkill and defeats the purpose of TwoWay databinding. A: Assuming that there is more than one control in the tab sequence, the following solution appears to be complete and general (just cut-and-paste)... Control currentControl = System.Windows.Input.Keyboard.FocusedElement as Control; if (currentControl != null) { // Force focus away from the current control to update its binding source. currentControl.MoveFocus(new TraversalRequest(FocusNavigationDirection.Next)); currentControl.Focus(); } A: Could you set the focus somewhere else just before saving? You can do this by calling focus() on a UI element. You could focus on whatever element invokes the "save". If your trigger is LostFocus then you have to move the focus somewhere. Save has the advantage that it isn't modified and would make sense to the user. A: Since I noticed this issue is still a pain in the ass to solve on a very generic way, I tried various solutions. Eventually one that worked out for me: Whenever the need is there that UI changes must be validated and updated to its sources (Check for changes upon closeing a window, performing Save operations, ...), I call a validation function which does various things: - make sure a focused element (like textbox, combobox, ...) loses its focus which will trigger default updatesource behavior - validate any controls within the tree of the DependencyObject which is given to the validation function - set focus back to the original focused element The function itself returns true if everything is in order (validation is succesful) -> your original action (closeing with optional asking confirmation, saveing, ...) can continue. Otherwise the function will return false and your action cannot continue because there are validation errors on one or more elements (with the help of a generic ErrorTemplate on the elements). The code (validation functionality is based on the article Detecting WPF Validation Errors): public static class Validator { private static Dictionary<String, List<DependencyProperty>> gdicCachedDependencyProperties = new Dictionary<String, List<DependencyProperty>>(); public static Boolean IsValid(DependencyObject Parent) { // Move focus and reset it to update bindings which or otherwise not processed until losefocus IInputElement lfocusedElement = Keyboard.FocusedElement; if (lfocusedElement != null && lfocusedElement is UIElement) { // Move to previous AND to next InputElement (if your next InputElement is a menu, focus will not be lost -> therefor move in both directions) (lfocusedElement as UIElement).MoveFocus(new TraversalRequest(FocusNavigationDirection.Previous)); (lfocusedElement as UIElement).MoveFocus(new TraversalRequest(FocusNavigationDirection.Next)); Keyboard.ClearFocus(); } if (Parent as UIElement == null || (Parent as UIElement).Visibility != Visibility.Visible) return true; // Validate all the bindings on the parent Boolean lblnIsValid = true; foreach (DependencyProperty aDependencyProperty in GetAllDependencyProperties(Parent)) { if (BindingOperations.IsDataBound(Parent, aDependencyProperty)) { // Get the binding expression base. This way all kinds of bindings (MultiBinding, PropertyBinding, ...) can be updated BindingExpressionBase lbindingExpressionBase = BindingOperations.GetBindingExpressionBase(Parent, aDependencyProperty); if (lbindingExpressionBase != null) { lbindingExpressionBase.ValidateWithoutUpdate(); if (lbindingExpressionBase.HasError) lblnIsValid = false; } } } if (Parent is Visual || Parent is Visual3D) { // Fetch the visual children (in case of templated content, the LogicalTreeHelper will return no childs) Int32 lintVisualChildCount = VisualTreeHelper.GetChildrenCount(Parent); for (Int32 lintVisualChildIndex = 0; lintVisualChildIndex < lintVisualChildCount; lintVisualChildIndex++) if (!IsValid(VisualTreeHelper.GetChild(Parent, lintVisualChildIndex))) lblnIsValid = false; } if (lfocusedElement != null) lfocusedElement.Focus(); return lblnIsValid; } public static List<DependencyProperty> GetAllDependencyProperties(DependencyObject DependencyObject) { Type ltype = DependencyObject.GetType(); if (gdicCachedDependencyProperties.ContainsKey(ltype.FullName)) return gdicCachedDependencyProperties[ltype.FullName]; List<DependencyProperty> llstDependencyProperties = new List<DependencyProperty>(); List<FieldInfo> llstFieldInfos = ltype.GetFields(BindingFlags.Public | BindingFlags.FlattenHierarchy | BindingFlags.Instance | BindingFlags.Static).Where(Field => Field.FieldType == typeof(DependencyProperty)).ToList(); foreach (FieldInfo aFieldInfo in llstFieldInfos) llstDependencyProperties.Add(aFieldInfo.GetValue(null) as DependencyProperty); gdicCachedDependencyProperties.Add(ltype.FullName, llstDependencyProperties); return llstDependencyProperties; } } A: The easiest way is to set the focus somewhere. You can set the focus back immediately, but setting the focus anywhere will trigger the LostFocus-Event on any type of control and make it update its stuff: IInputElement x = System.Windows.Input.Keyboard.FocusedElement; DummyField.Focus(); x.Focus(); Another way would be to get the focused element, get the binding element from the focused element, and trigger the update manually. An example for TextBox and ComboBox (you would need to add any control type you need to support): TextBox t = Keyboard.FocusedElement as TextBox; if ((t != null) && (t.GetBindingExpression(TextBox.TextProperty) != null)) t.GetBindingExpression(TextBox.TextProperty).UpdateSource(); ComboBox c = Keyboard.FocusedElement as ComboBox; if ((c != null) && (c.GetBindingExpression(ComboBox.TextProperty) != null)) c.GetBindingExpression(ComboBox.TextProperty).UpdateSource(); A: What do you think about this? I believe I've figured out a way to make it a bit more generic using reflection. I really didn't like the idea of maintaining a list like some of the other examples. var currentControl = System.Windows.Input.Keyboard.FocusedElement; if (currentControl != null) { Type type = currentControl.GetType(); if (type.GetMethod("MoveFocus") != null && type.GetMethod("Focus") != null) { try { type.GetMethod("MoveFocus").Invoke(currentControl, new object[] { new TraversalRequest(FocusNavigationDirection.Next) }); type.GetMethod("Focus").Invoke(currentControl, null); } catch (Exception ex) { throw new Exception("Unable to handle unknown type: " + type.Name, ex); } } } See any problems with that? A: Using BindingGroup will help to understand and mitigate this kind of problem. Sometimes we consider to apply MVVM model against WPF data bindings. For example, we consider about mail's subject property: <TextBox x:Name="SubjectTextBox" Text="{Binding Subject}" /> * *TextBox SubjectTextBox is on side of View. *The bound property like ViewModel.Subject will belong to ViewModel. The problem is that changes remain to View in this case. When we close the WPF window, WPF TextBox won't loose focus on window close. It means data binding won't perform writing back, and then changes are lost silently. Introducing of BindingGroup helps to control whether we should apply changes: from View to ViewModel. BindingGroup.CommitEdit(); will ensure apply changes of direction View → ViewModel BindingGroup.CancelEdit(); will ensure to discard changes on View. If you don't call neither, changes are lost silently! In the following sample, we attach RibbonWindow_Closing event handler so that we can deal with this case of problem. XAML: <R:RibbonWindow Closing="RibbonWindow_Closing" ...> <FrameworkElement.BindingGroup> <BindingGroup /> </FrameworkElement.BindingGroup> ... </R:RibbonWindow> C# private void RibbonWindow_Closing(object sender, CancelEventArgs e) { e.Cancel = !NeedSave(); } bool NeedSave() { if (!BindingGroup.CommitEdit()) { // There may be validation error. return false; // changes this to true to allow closing. } // Insert your business code to check modifications. // return true; if Saved/DontSave/NotChanged // return false; if Cancel } It should work.
{ "language": "en", "url": "https://stackoverflow.com/questions/57493", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "39" }
Q: Recommendation on Tools to migrate from Clearcase to SVN? I'm on the lookout for tools to migrate from ClearCase to SVN. Ideally would like to get all history information, or as much as can be acquired. Incremental merges would be very beneficial but isn't required. A: This looks about the best. Polarion's business is SVN, so I guess they have a vested interest in making as many people as possible use it... Oh, back up all your data before hand, do it on a test repository first, etc, etc. A: I experienced the same issue than Peter: the Polarion script was unable to proceed with large CleraCase VOBs and always ended up in a Java Heap Size out-of-memory error. I also experienced another critical issue leading to corrupted data after import. Polarion script is working that way: * *Use cleartool command to access ClearCase data *Use its own algorithm to dump these data in SVN DUMP a flat file *Use svnadmin to import the dump file in SVN I managed to run the Polarion script on a smaller VOB. Everything was looking good (import completed successfully with no error message) but the SVN repository was not usable (no way checking it out, don't have the exact error message in mind) - tried several times, same result. I understand the script is rebuilding a SVN DUMP file based on its own code, not on any SVN API. It was probably designed for a particular version of SVN (1.4, maybe 1.5?) and I was using SVN 1.6. The DUMP file format has maybe changed since, or the Polarion script doesn't handle correctly some side effects with particular ClearCase data. However at the end of the day it was just not working. I would therefore strongly recommend using another solution, and probably build your own script based on cleartool and actual SVN API to avoid any data consistency issue. A: The migration from clearcase is not an easy task. The polarion importer does a job to support you, however, the history and speed for large clearcase repositories is difficult to estimate. The history will only import all files from main and will not take into account any directory versioning. The problem is that your files which will be placed into your tags have the latest name, if you renamed them. Also the importer will not migrate deleted files. As the importer cannot use your config-specs, it will show only the changed files in branches, as clearcase uses lazy branching, which is fully different to svns branching mechanism. Merge tracking is not supoorted by migration tool, as SVN supports it only from 1.5 A: Just another experience: We went with "custom scripts" rather than the Polarion tool. That way, we can: * *use a dynamic view (quick for updates) *select exactly the branch we want to import *import only the versions with labels on it (avoid import a gazillon number of versions, whereas nobody will actually exploit that huge history) *import all versions between last label and LATEST (for a given branch) We used the dynamic view for changing its config spec with all the label we are interesting to import to SVN. Note: that fact that we are using UCM is a big help for export operations: * *the branch are clearly identified (after their attached streams), and *the label is set on all the files of a given component (in Base ClearCase, a label can be set of a arbitrary number of files) A: The last version of the Polarion tool is from 2006 and it just does not do the job with large CC vobs. In my case it always crashes with heap overrun, and even the largest java heap space is not enough to it. So it is no good for me.
{ "language": "en", "url": "https://stackoverflow.com/questions/57494", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: Users of Gallio, what Advantages and Disadvantages have you experienced using this Tool? For those of you familiar with Gallio, what Advantages and Disadvantages have you experienced using this tool, a so-called Test Automation Platform? A: I tried Gallio as well and it runs much slower than either TDD.Net or the native NUnit GUI test runner. It is even slower than the Resharper runner! I should add that I'm talking about running NUnit tests here. I don't remember the exact numbers but it was taking around 3 minutes for the same tests, that NUnit finished in 30s (running on one thread, single process,multiple domain). That in itself already makes it a no go. Add to that the bulky GUI and you know to stay way from it. Some extra information: * *In my solution I have NUnit tests and recently started adding MSpec specifications. I have the NUnit Gui open to automatically rerun my old tests (all new tests are written as MSpecs) after I recompile and the test dlls change. *I use TDD.Net to run my Mspec specifications. *This enables me to already continue working once my Specs have finished running while the NUnit Gui runner is still finishing. A: When we evaluated Gallio, we experienced stability issues with large projects. Our smaller projects ran beautifully, however. Great concept...I think it will generate a big buzz once it's a bit more refined. I might want to add that Resharper support was missing (or broken) for a while, but I've heard it's back. A: The latest release of Gallio (3.0.6) has address a lot of the stability issues mentioned in the these posts. In particular, Icarus is much more stable now and has the ability to attach to the debugger built in, so it can be even faster to use than Resharper which recompiles the code before each test run. A: It's terrible unstable, I used it about 3-4 months ago it was terrible unstable and slow. Now I've just tried it and it crashes when you click "Save", then it never opens again unless you go and clean up the "Local Settings", I assume it's still terrible unstable. I wish they would stop adding new features and instead fix these rather obvious bugs. P.S. Project got 1000~ unit tests and it's using nUnit (maybe it's just my nUnit and Gallio don't play well together ) I really want to use it and I've got 3.1 - 313, I couldn't even save a project without getting a crash! After all bad stuff advantages Here: * *Great support for different flavours, I've used it for nUnit and mbUnit it's really good. It even support RowTest in nUnit very well. *GUI is pretty cool, clean *Got great features like setting working directory *Reporting & Integration A: We're using Gallio/MbUnit for a year now. We're quite happy with it, the Gallio guys keep introducing cool new features and the development is active. If you decide to use it, here are some hints/notes: * *Buy yourself a TestDriven.NET license - I think it is a must for Gallio unit tests, since Resharper test runner doesn't know how to run certain tests + Gallio has one of its test runners targeted for TD.NET. *We use Gallio.Echo command line runner for CI scripts/builds. Gallio Icarus - the GUI runner (at least the current version) is pretty unstable and not very user friendly. *If you want to use the latest Gallio features (like parallel tests etc), be prepared to have to use the latest daily builds of Gallio. If this is an issue, keep to "official" builds, but we haven't had any real problems with daily build versions. *I recommend adding the basic Gallio .DLLs and .EXEs to your source control. And actually reference these in your projects, not ones from GAC. This way you'll avoid any "works on my machine" problems if someone in your team has a different version of Gallio installed on his/her machine. A: On the advantages front, integration with everything is quite nice :) Seriously, I'm a huge fan of the experimental integration with Visual Studio Team System (screenshots here). I think that really lowers the bar for those new to unit testing. The only disadvantage from my perspective so far is the fact that it isn't released yet. A: I have been evaluating Gallio and it is truly a great concept. Now I don't have to tell my developers what unit testing framework they have to use, because it has integration with all the major ones that I know of. They can use which ever they are most comfortable with and I get unit tested code. The Resharper integration is nice also. I can run all the unit tests with Resharper without having to jump out to a command line to run them. This should definitely make introducing unit testing into shops a lot easier in my opinion. I agree with @David, the downside is that it isn't released yet.
{ "language": "en", "url": "https://stackoverflow.com/questions/57512", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "12" }
Q: Is it possible for SelectNodes on an XmlDocument to return null? Is it possible for SelectNodes() called on an XmlDocument to return null? My predicament is that I am trying to reach 100% unit test code coverage; ReSharper tells me that I need to guard against a null return from the SelectNodes() method, but I can see no way that an XmlDocument can return null (and therefore, no way to test my guard clause and reach 100% unit test coverage!) A: If you are calling SelectNodes on the XmlDocument itself and it really is an XmlDocument and not a derived class than SelectNodes won't return null. If you create a descendant class and override the CreateNavigator(XmlNode) method then SelectNodes could return null. Similarly, if you call SelectNodes on an EntityReference, DocumentType or XmlDeclaration node, you'll get null as well In short, for 100% coverage on an XmlDocument or XmlNode you didn't just create, you have to test for null. A: Is it necessary to reach 100% code coverage? Indeed, is it even possible under normal (i.e. controllable, testable) circumstances? We often find that using "syntactic sugar" constructions like the using {} block, there are "hidden" code paths created (most likely finally {} or catch {} blocks) that can't be exercised unless some environmental condition (like a broken socket or broken disk) gets in the way. A: Looking at Reflector, the SelectNodes() method on XmlDocument's base class, XmlNode, can return null if its attempt to create a navigator returns null. CreateNavigator() is pretty complex and will indeed return null under a few circumstances. Those circumstances appear to be around a malformed XML document - so there's your test case for failure of SelectNodes().
{ "language": "en", "url": "https://stackoverflow.com/questions/57518", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "9" }
Q: Javascript array with a mix of literals and arrays I can create the following and reference it using area[0].states[0] area[0].cities[0] var area = [ { "State" : "Texas", "Cities" : ['Austin','Dallas','San Antonio'] }, { "State" :"Arkansas", "Cities" : ['Little Rock','Texarkana','Hot Springs'] } ] ; How could I restructure "area" so that if I know the name of the state, I can use it in a reference to get the array of cities? Thanks EDIT Attempting to implement with the answers I received (thanks @Eli Courtwright, @17 of 26, and @JasonBunting) I realize my question was incomplete. I need to loop through "area" the first time referencing "state" by index, then when I have the selection of the "state", I need to loop back through a structure using the value of "state" to get the associated "cities". I do want to start with the above structure (although I am free to build it how I want) and I don't mind a conversion similar to @eli's answer (although I was not able to get that conversion to work). Should have been more complete in first question. Trying to implement 2 select boxes where the selection from the first populates the second...I will load this array structure in a js file when the page loads. A: var area = { "Texas" : { "Cities" : ['Austin','Dallas','San Antonio'] }, "Arkansas" : { "Cities" : ['Little Rock','Texarkana','Hot Springs'] } }; Then you can do: area["Texas"].Cities[0]; A: (With help from the answers, I got this to work like I wanted. I fixed the syntax in selected answer, in the below code) With the following select boxes <select id="states" size="2"></select> <select id="cities" size="3"></select> and data in this format (either in .js file or received as JSON) var area = [ { "states" : "Texas", "cities" : ['Austin','Dallas','San Antonio'] }, { "states" :"Arkansas", "cities" : ['Little Rock','Texarkana','Hot Springs'] } ] ; These JQuery functions will populate the city select box based on the state select box selection $(function() { // create an array to be referenced by state name state = [] ; for(var i=0; i<area.length; i++) { state[area[i].states] = area[i].cities ; } }); $(function() { // populate states select box var options = '' ; for (var i = 0; i < area.length; i++) { options += '<option value="' + area[i].states + '">' + area[i].states + '</option>'; } $("#states").html(options); // populate select box with array // selecting state (change) will populate cities select box $("#states").bind("change", function() { $("#cities").children().remove() ; // clear select box var options = '' ; for (var i = 0; i < state[this.value].length; i++) { options += '<option value="' + state[this.value][i] + '">' + state[this.value][i] + '</option>'; } $("#cities").html(options); // populate select box with array } // bind function end ); // bind end }); A: If you want to just create it that way to begin with, just say area = { "Texas": ['Austin','Dallas','San Antonio'] } and so on. If you're asking how to take an existing object and convert it into this, just say states = {} for(var j=0; j<area.length; j++) states[ area[0].State ] = area[0].Cities After running the above code, you could say states["Texas"] which would return ['Austin','Dallas','San Antonio'] A: This would give you the array of cities based on knowing the state's name: var area = { "Texas" : ["Austin","Dallas","San Antonio"], "Arkansas" : ["Little Rock","Texarkana","Hot Springs"] }; // area["Texas"] would return ["Austin","Dallas","San Antonio"]
{ "language": "en", "url": "https://stackoverflow.com/questions/57522", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: parametrization in VBScript/ASP Classic and ADO I'm a bit confused here. Microsoft as far as I can tell claims that parametrization is the best way to protect your database from SQL injection attacks. But I find two conflicting sources of information here: This page says to use the ADO command object. But this page says that the command object isn't safe for scripting. I seem to recall reading somewhere that the command object shouldn't be used in VBScript or JScript because of security vulnerabilities, but I can't seem to find that article. Am I missing something here, or do those two articles seem to contradict each other? A: I could be wrong here, but I think this just means that someone could use the Command object to do bad things. I.e. it's not to be trusted if someone else is scripting it. See safe for scripting in this article. Every instance that talks about this phrase online, references it as if you are marking an ActiveX control saying "This control does no I/O or only talks back to the server that it came from" but the Command object doesn't do that. It can be used to do a lot of things which could be unsafe. The "safe" they are talking about and the "safe" to prevent from SQL injection are two different things. The article about using the ADO Command object to parametrize your data is spot on. You should do that. And, Microsoft further confirms this here: http://msdn.microsoft.com/en-us/library/ms676585(v=VS.85).aspx A: I think "safe for scripting" means "safe to be run from a webpage we just retrieved from some Nigerian prince". The command object should be safe to run on the server. At work though, back in the day my colleagues didn't trust it so we had an in-house framework that basically did the same thing.
{ "language": "en", "url": "https://stackoverflow.com/questions/57528", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Any tool to migrate repo from Vault to Subversion? Are there any tools to facilitate a migration from Sourcegear's Vault to Subversion? I'd really prefer an existing tool or project (I'll buy!). Requirements: * *One-time migration only *Full history with comments Optional: * *Some support for labels/branches/tags *Relatively speedy. It can take hours but not days. *Cost if available Bonus points if you can share personal experience related to this process. One of the reasons I'd like to do this is because we have lots of projects spread between Vault and Subversion (we're finally away from sourcesafe). It'd be helpful in some situations to be able to consolidate a particular customer's repos to SVN. Additionally, SVN is better supported among third party tools. For example, Hudson and Redmine. Again, though: we're not abandoning vault altogether. A: If you want full version history, you may want to just write a script that checks out each version from vault and checks it in with the comments to Subversion. https://www.mercurial-scm.org/wiki/GenericConversion is a good example Based on the documentation that I saw on the Vault website, look into the command line GETVERSION. Use your favorite scripting language... Implement the following process: * *Check out a version from vault. *Get the commit comments for the changeset. *Add/remove the files to the SVN repo *Commit files using the commit comments *Go back to step one with the next version A: I never found an easy way to convert from Vault to svn. Basically we took our latest branches and trunk and started new in svn. Honestly I went two or three labels back, just because. I kept the vault db around for six months and we never needed to go back to it for data. So I assume you want to carry forward your history for a bug tracker tie-in; at this same time we transferred our outstanding bug list to a new tracker, so that definitely made things more convenient. If we where staying with the same bug tracker, I would think we would of started a new instance of it for the new repo. Good Luck! Brett A: We are thinking about migrating from vault to git. I wrote vault2git converter that takes care of history and removes vault bindings from *.sln, *.csproj files. Once you have git repo, there is git2svn. I know it sounds like going rounds, but it might be faster than writing vault2svn from scratch. A: Free. The vault user license costs have tripled since we went to it. A: We are considering migration as well. One reason is cost, but another reason is that Vault does not use valid xml (or any) for its commit comments so special characters fail our automated CCNet build system (e.g. a bullet character is one of them, and specifically causes us a problem). A way around this has been to A) ask our developers to not use these special, "invalid" characters (characters outside the range of ASCII 32 - 126) and B) to manually go in and re-commit code with a "valid" comment. This may not seem like a big deal, but not allowing these characters prevents easy copy/paste of bug and other comments into the commit comment. This slows people down and anything that hinders flow and productivity and creates frustration needs to be reduced or removed. From my research, it seems that there is no way to directly migrate from Vault to SVN. Perhaps it is possible to use another version control system as a migration middle step: Vault --> OtherSourceControlProduct --> SVN ...but I think that we would either script the commits (as Joshua suggested at the beginning of this thread) or - which more likely - just commit the last few revisions and leave the Vault repos around a while for history, etc. This actually gives us a a good opportunity to clean out and refactor our current code and hierarchy. Paul
{ "language": "en", "url": "https://stackoverflow.com/questions/57530", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "16" }
Q: Accessing Tomcat Context Path from Servlet In my Servlet I would like to access the root of the context so that I can do some JavaScript minifying. It would be possible to do the minify as part of the install process but I would like to do it on Servlet startup to reduce the implementation cost. Does anyone know of a method for getting the context directory so that I can load and write files to disk? A: In my Servlet I would like to access the root of the context so that I can do some JavaScript minifying You can also access the files in the WebContent by ServletContext#getResource(). So if your JS file is for example located at WebContent/js/file.js then you can use the following in your Servlet to get a File handle of it: File file = new File(getServletContext().getResource("/js/file.js").getFile()); or to get an InputStream: InputStream input = getServletContext().getResourceAsStream("/js/file.js"); That said, how often do you need to minify JS files? I have never seen the need for request-based minifying, it would only unnecessarily add much overhead. You probably want to do it only once during application's startup. If so, then using a Servlet for this is a bad idea. Better use ServletContextListener and do your thing on contextInitialized(). A: This should give you the real path that you can use to extract / edit files. Javadoc Link We're doing something similar in a context listener. public class MyServlet extends HttpServlet { public void init(final ServletConfig config) { final String context = config.getServletContext().getRealPath("/"); ... } ... } A: I was googling the result and getting no where. In JSP pages that need to use Java Script to access the current contextPath it is actually quite easy. Just put the following lines into your html head inside a script block. // set up a global java script variable to access the context path var contextPath = "${request.contextPath}" A: Do you mean: public class MyServlet extends HttpServlet { public void init(final ServletConfig config) { final String context = config.getServletContext(); ... } ... } Or something more complex?
{ "language": "en", "url": "https://stackoverflow.com/questions/57537", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: What's the best way to embed video in a Windows Mobile 6 application? App needs to run on the .Net Compact Framework v.3.5. Video can be any format, but I do need to be able to know when it's finished playing, so I can start another one. I'm hoping for a method that doesn't involve unmanaged code, if possible. A: You need to embed it using ActiveX Hosting. There is an MSDN tutorial on it (note there is a bug in the MS-published code). If you want a more friendly way, then OpenNETCF has a commercial control for it as well. A: The version of Flash Lite that can be downloaded from Adobe 2.1 won't support video so you can't embed that as an ActiveX control. Your only real option is to follow @ctacke's advice and embed Windows Media Player, or other media player that offers a ActiveX control you can use (I'm not aware of any - sorry!). A: Silverlight is coming to windows mobile 6, its in super elite beta right now, maybe get in on that action.
{ "language": "en", "url": "https://stackoverflow.com/questions/57545", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: IMAP forwarder I'm wondering what is the quickest and most reliable way to forward mail from an IMAP account. My university does not allow our student-mailbox to forward to a private e-mail account (everybody uses either Gmail or Hotmail here). It's a political thing, not technical. We do have IMAP access to the mailbox. I would like to have a service which downloads the mail through IMAP, and forwards. And it would be nice to scale it, so thousands of students can use it. Eventually, I want to build a public signup page, and have it processed automatically from there. So far, I've made a decent PHP script which connects, downloads headers and body parts, and ties it all together. I have two problems with that. 1) I'm downloading all kind of parts, and sticking them back together. I hope that every exotic attached file, weird encoded piece of text and every type of header survives this. I'm not even sure I have the complete header. 2) The to: e-mail address becomes the private e-mail address, not the original student e-mail address. I think this is lame, and inconvenient in searching and archiving. Is the PHP script the way to go? Is there a trick using a particular linux mail service/daemon? Does IMAP have a 'forward' command, I'm missing? A: You might want to look at Fetchmail, as this sounds like the problem it was designed to solve. Fetchmail retrieves mail from POP/IMAP/etc servers and forwards it to SMTP/LMTP/etc servers. Fetchmail has the advantage of a few years and lots of users ironing out problems with various IMAP servers. A: Fetchmail seems like the way to go. I can use PHP to generate/edit a fetchmail command file, so that will cover the public sign-up. I'm looking for a package/script who allready does this. The Gmail pull only works with POP3, not with IMAP. A: If using Gmail you can configure GMAIL to pick up mail from other accounts.
{ "language": "en", "url": "https://stackoverflow.com/questions/57547", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }
Q: GPS and Embedded Development - Where to find resources? I'm just starting to design some embedded devices, and am looking for resources. What I want to be able to do is to connect a GPS receiver to a lightweight SBC or mini-ITX, x86-based computer, and track a remote-controlled vehicle's location/progress. Ideally, this could morph into building some hobby, semi-autonomous vehicles. But what I need to start with is a development board for GPS programming. What boards/packages have you used, and where can I find [preferably open source] development for them? A: OpenEmbedded is a good place to go to get started. A lot of embedded products use ARM and other processors, so cross-compiling is a big deal. Buildroot is another resource for building custom linux kernels for small systems. You can also find lots of manufacturers with Single Board Computers (SBCs) that have tools to do what you want - do a google search for "SBC Linux" and you should have a gold mine. LinuxDevices keeps a pulse on the linux embedded community and you should find several good articles there that lead you to products or software to help you. Debian has an embedded build, but I haven't explored that. There are several books on embedded linux available if you want to go that route. The GPS receiver simply connects to a serial or USB port, and present an NMEA stream of data, which you can parse with GPSD and several programs can access it through GPSD. It's a very simple text based format. I've used regular PC motherboards, and Atmel AT91 processors for embedded systems (with GPS, cellular, etc). There's a lot of information out there right now, and it's not expensive to get into. If I were to start a new project, I'd look at the AVR32 processors from Atmel - they are very hobbyist friendly, and provide a lot of community support for linux on the AVR32 architecture. They provide free GCC compilers and significant framework and examples if you want to go the OS-less route and have a single program running on the processer as well. Good luck! -Adam A: "NMEA" is the keyword to be searching for when looking for this stuff. While I haven't done anything with this in a long, long time, here is a good source for some boards and other hardware: http://www.sparkfun.com/commerce/categories.php?c=4 A: We have had good luck with Holux GPS recievers (designed for samsung q1). A farily simple connect over serial port and you can read the NMEA string. A: What OS are you targeting? If it's Linux there are a lot of GPS libraries available (here's a good list). GPSd and GpsDrive are two of the more popular ones I've seen. I haven't see any GPS devices specifically for lightweight/embedded use, but many of the consumer GPS devices have USB hookups available that could probably work (watch out for low end ones, they usually don't have the computer interface). A: I suggest starting with a plain old c project that reads and parses NMEA from a serial port. You can do this in Windows or Linux. I usually break down any project like this into a set of smaller projects like: * *read and parse NMEA from serial port *establish a serial / network link from the remote device to the tracking system server *integrate the components Wikipedia has a good article on the NMEA protocol. As Adam points out it's actually pretty simple. Circuit Cellar magazine often has projects like this as well. Depending on what you want to do, there are various sizes of target to consider. Use Atmel AVR for small low power (battery) stuff. Perhapse use Linux on an old laptop if I just wanted to rough out the concept and needed WiFi (or cellular) for internet. The laptop Linux prototype then could be trimmed down and ported to an embedded Cinux system for even lower battery usage and portability later on. (not as low as Atmel though). A: If you are comfortable with programming in Linux I would recommend the Gumstix range of small computers - http://www.gumstix.com/ You could pair the vedex motherboard with the GPSstix expansion board tp make a tiny GPS receiver with a well supported programming environment. A: I suggest GPSBabel to communicate with your GPS receiver. GPSBabel * *Handles waypoints, tracks, and routes, *Knows lots of format (this explains the name Babel), *Runs on Windows, Linux, OSX, *Free. A: Some people here have suggested devices like the gumstix - embedded devices which cost $149 without GPS. I don't understand that bit. A off-the-shelf TomTom comes with running Linux on ARM, built-in GPS, lots of flash, battery and screen. It's hard to beat the price advantage that comes with mass production. For your hobby project, the map included is not needed, but who cares?
{ "language": "en", "url": "https://stackoverflow.com/questions/57549", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: AJAX Dropdown Extender Question Ok, so I got my extender working on a default.aspx page on my website and it looks good. I basically copied and pasted the code for it into a user control control.ascx page. When I do this I completely loose the functionality (just shows the target control label and no dropdown, even upon hover). Is there any reason why it doesn't work in a custom user control inside a masterpage setup? Edit: Didn't quite do the trick. Any other suggestions? Its in a master page setup, using eo web tabs (I tried it inside the tabs and outside the tabs but on the same page as the tabs, to no avail), and its in a custom user control. Think there are dependency issues? A: Apparently EO has compatibility issues with MS Ajax Control Toolkit. http://www.essentialobjects.com/Forum/Default.aspx?g=posts&t=1319 I guess I'll leave this question open to see if anyone figures out some sort of workaround. A: After a few days of looking I found a call to a modal popup extender .show() in the code behind. After commenting it out everything worked fine. A: Check the DocType. Here is what I have found useful <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd" > Place this in your user control (or the page that uses it) and all should be well. I had a similar problem with a collapsible extender and this worked for me. Edit: Here is a link to my question for further details. A: I don't know if this helps, but I had the same problem with the autocomplete extender and determined that the server-side function could not be in the user control, but needed to be on the page (or in a webservice, I guess). Once I moved the function, it worked fine. A: Hmm all that functionality on the loose! careful you don't lose it (sorry!) Are you using something like Firebug (firefox plug-in) so you can see what ajax calls the page is trying to make? If it is making the call but the server is behaving oddly then you will see the error there too. IE users maybe able to use dev toolbar.
{ "language": "en", "url": "https://stackoverflow.com/questions/57552", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Mail Storage Quota Checker in C# We have a requirement to build a tool for users in an Intranet scenario. The tool should check how much percentage of the Mailbox Quota (set in Active Directory) is being used. Currently, they can check their Folder size using Outlook 2003 but this does not show the Quota Limit set for them or the percentage being used. This blog has all the exact information I need including vbscript samples. If you have any similar C# code, please post it. That will give me a good lead on writing a small system tray application which will poll the Active Directory and show the percentage in real time. PS: I am not being lazy. Already started writing code for this. Just checking if any of you went through a similar exercise and have code to share. A: Querying ActiveDirectory is pretty simple. You can find some good examples I've used before here.
{ "language": "en", "url": "https://stackoverflow.com/questions/57557", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: How do I check that a Windows QFE/patch has been installed from c#? What's the best way in c# to determine is a given QFE/patch has been installed? A: Use WMI and inspect the Win32_QuickFixEngineering enumeration. From TechNet: strComputer = "." Set objWMIService = GetObject("winmgmts:" _ & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2") Set colQuickFixes = objWMIService.ExecQuery _ ("Select * from Win32_QuickFixEngineering") For Each objQuickFix in colQuickFixes Wscript.Echo "Computer: " & objQuickFix.CSName Wscript.Echo "Description: " & objQuickFix.Description Wscript.Echo "Hot Fix ID: " & objQuickFix.HotFixID Wscript.Echo "Installation Date: " & objQuickFix.InstallDate Wscript.Echo "Installed By: " & objQuickFix.InstalledBy Next The HotFixID is what you want to examine. Here's the output on my system: Hot Fix ID: KB941569 Description: Security Update for Windows XP (KB941569) Hot Fix ID: KB937143-IE7 Description: Security Update for Windows Internet Explorer 7 (KB937143) Hot Fix ID: KB938127-IE7 Description: Security Update for Windows Internet Explorer 7 (KB938127) Hot Fix ID: KB939653-IE7 Description: Security Update for Windows Internet Explorer 7 (KB939653) Hot Fix ID: KB942615-IE7 Description: Security Update for Windows Internet Explorer 7 (KB942615) Hot Fix ID: KB944533-IE7 Description: Security Update for Windows Internet Explorer 7 (KB944533) Hot Fix ID: KB947864-IE7 Description: Hotfix for Windows Internet Explorer 7 (KB947864) Hot Fix ID: KB950759-IE7 Description: Security Update for Windows Internet Explorer 7 (KB950759) Hot Fix ID: KB953838-IE7 Description: Security Update for Windows Internet Explorer 7 (KB953838) Hot Fix ID: MSCompPackV1 Description: Microsoft Compression Client Pack 1.0 for Windows XP Hot Fix ID: KB873339 Description: Windows XP Hotfix - KB873339 Hot Fix ID: KB885835 Description: Windows XP Hotfix - KB885835 Hot Fix ID: KB885836 Description: Windows XP Hotfix - KB885836 Hot Fix ID: KB886185 Description: Windows XP Hotfix - KB886185 Hot Fix ID: KB887472 Description: Windows XP Hotfix - KB887472 Hot Fix ID: KB888302 Description: Windows XP Hotfix - KB888302 Hot Fix ID: KB890046 Description: Security Update for Windows XP (KB890046) A: The most reliable way is to determine which files are impacted by the QFE and use System.Diagnostics.FileVersionInfo.GetVersionInfo(path) on each file and compare the version numbers. edit: I think there's a way to check the uninstall information in the registry as well, but if the QFE ever becomes part of a Service Pack or rollup package that might report false negatives
{ "language": "en", "url": "https://stackoverflow.com/questions/57560", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Handles vs. AddHandler Is there an advantage to dynamically attaching/detaching event handlers? Would manually detaching handlers help ensure that there isn't a reference remaining to a disposed object? A: I'm pretty sure that the Handles clause is just syntactic sugar and inserts an AddHandler statement into your constructor. I tested using this code and disabled the application framework so the constructor wouldn't have extra stuff: Public Class Form1 Public Sub New() ' This call is required by the Windows Form Designer. ' InitializeComponent() ' Add any initialization after the InitializeComponent() call. ' AddHandler Me.Load, AddressOf Form1_Load End Sub Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load Dim breakpoint As Integer = 4 End Sub End Class The IL ended up like this: IL_0000: nop IL_0001: ldarg.0 IL_0002: call instance void [System.Windows.Forms]System.Windows.Forms.Form::.ctor() IL_0007: nop IL_0008: ldarg.0 IL_0009: ldarg.0 IL_000a: dup IL_000b: ldvirtftn instance void WindowsApplication1.Form1::Form1_Load(object, class [mscorlib]System.EventArgs) IL_0011: newobj instance void [mscorlib]System.EventHandler::.ctor(object, native int) IL_0016: call instance void [System.Windows.Forms]System.Windows.Forms.Form::add_Load(class [mscorlib]System.EventHandler) '... lots of lines here ' IL_0047: ldarg.0 IL_0048: callvirt instance void WindowsApplication1.Form1::InitializeComponent() IL_004d: nop IL_004e: ldarg.0 IL_004f: ldarg.0 IL_0050: dup IL_0051: ldvirtftn instance void WindowsApplication1.Form1::Form1_Load(object, class [mscorlib]System.EventArgs) IL_0057: newobj instance void [mscorlib]System.EventHandler::.ctor(object, native int) IL_005c: callvirt instance void [System.Windows.Forms]System.Windows.Forms.Form::add_Load(class [mscorlib]System.EventHandler) IL_0061: nop IL_0062: nop IL_0063: ret } // end of method Form1::.ctor Notice two identical blocks of code around IL_000b and IL_0051. I think it's just syntactic sugar. A: It's not a question of using AddHandler versus Handles. If you are concerned about the reference to your event handler interfering with garbage collection, you should use RemoveHandler, regardless of how the handler was attached. In the form or control's Dispose method, remove any handlers. I have had situations in Windows Forms apps (.NET 1.1 days) where an event handler would be called on controls that had no other references to them (and which for all intents and purposes were dead and I would have thought been GC'ed) -- extremely hard to debug. I would use RemoveHandler to get rid of handlers on controls that you are not going to reuse. A: Declaring a field as WithEvents will cause the compiler to automatically generate a property with that name. The getter returns the value of a backing field. The setter is a little more complicated. It first checks whether the backing field already has the correct value. If so, it exits. Otherwise, if the backing field is non-null, it issues "RemoveHandler" requests for all its events to the object identified by the backing field. Next, regardless of whether the backing field was non-null, it sets it equal to the requested value. Finally, if the new value is non-null, whether the old one was or not, the property issues "AddHandler" requests for all its events to the object identified by the new value. Provided that one sets all of an object's WithEvents members to Nothing before abandoning it, and avoids manipulating WithEvents members in multiple threads, the auto-generated event code will not leak. A: I find that dynamically attaching/detaching event handlers is only of use where you have a long-lived object exposes events that are consumed by many short-lived objects. For most other cases the two objects are disposed around the same time and the CLR does a sufficient job of cleaning up on its own A: I manually attach handlers when I manually create controls (for example, dynamically creating a TextBox for each database record). I manually detach handlers when they are handling things I'm not quite ready to handle yet (possibly because I'm using the wrong events? :) ) A: Most of the time the framework takes care of that for you. A: Manually detaching an event can be important to prevent memory leaks: the object that connects to an event fired by another object, will not be garbage collected until the object that fires the event is garbage collected. In other words, an "event-raiser" has a strong reference to all the "event-listeners" connected to it.
{ "language": "en", "url": "https://stackoverflow.com/questions/57567", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Secure-Wave and click once applications I have users who are using "secure-wave" security. Evidently it is some sort of white-listing application monitor. With my click-once application, the name of the folders that are used are runtime generated, so the administrators are not able to properly whitelist the application and its files. Any suggestions? A: There's no way to override the ClickOnce installation location. As you said, it's runtime generated, and resides within the user ClickOnce App Cache within the individual users directory. Have you considered having having the admins whitelisting this specific folder? I guess the only other way to handle it would be to switch to Windows Installer and implement your update code yourself, which is obviously less than idea. Whitelisting the Click Once cache would be the easiest way, but obviously bare in mind the security considerations of doing this.
{ "language": "en", "url": "https://stackoverflow.com/questions/57576", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: How do I merge XML from distinct DomDocuments What is the easiest way to merge XML from two distinct DOM Documents? Is there a way other than using the Canonical DataReader approach and then messing with the outputted DOM. What I basically want is to AppendChild to XmlElements without getting: The node to be inserted is from a different document context. Here is C# code that I want to work, that obviously won't (what I am doing is merging two documents which have bunch of nodes that I am interested in parts of): XmlDocument doc1 = new XmlDocument(); doc1.LoadXml("<a><items><item1/><item2/><item3/></items></a>"); XmlDocument doc2 = new XmlDocument(); doc2.LoadXml("<b><items><item4/><item5/><item6/></items></b>"); XmlNode doc2Node = doc2.SelectSingleNode("/b/items"); XmlNodeList doc1Nodes = doc1.SelectNodes("/a/items/*"); foreach (XmlNode doc1Node in doc1Nodes) { doc2Node.AppendChild(doc1Node); } A: You can use the XmlDocument.ImportNode method to copy a node from a XmlDocument to another. A: You might be interested in http://msdn.microsoft.com/en-us/library/system.xml.xmldocument.importnode.aspx. But take a close look at the "The following table describes the specific behavior for each XmlNodeType."-part of that document.
{ "language": "en", "url": "https://stackoverflow.com/questions/57577", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How can I make a ListView's columns auto-resize programmatically? I've found some examples using the Win32 api or simulating the ^+ button combination (ctrl-+) using SendKeys, but at least with the SendKeys method the listview grabs the cursor and sets it to an hourglass until I hit the start button on my keyboard. What is the cleanest way to do this? A: Looks like a call to myListView.AutoResizeColumns(ColumnHeaderAutoResizeStyle.ColumnContent) will do what you want. I would think, just call it after adding an item. More info here A: According to MSDN, if you set the column width to -1 then it will autosize to the widest item A: loop through all columns and set width to -1 after adding content. A: After adding the following routine to your code then call it from any procedure/function. Do not use it in your "Form_Load" procedure though. Only call it after you have added an item to your ListView (or if you are making multiple additions, call it once at the end of all the additions): Private Sub AutoSizeListViewColumns(oListView As ListView) Dim nCol As Integer = 0 SuspendLayout() For nCol = 0 To (oListView.Columns.Count - 1) oListView.Columns(nCol).Width = -1 'forces autosizing on column Next oListView.Refresh() ResumeLayout() End Sub
{ "language": "en", "url": "https://stackoverflow.com/questions/57584", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: ASP.Net UpdatePanel ImageButton causes "this._postbackSettings.async is null or not an object" I get this error on an update panel within a popupControlExtender which is within a dragPanelExtender. I see that a lot of other people have this issue and have various fixes none of which have worked for me. I would love to hear a logical explanation for why this is occurring and a foolproof way to avoid such issues in the future. I have found that like others maintain this error does not occur when the trigger is a LinkButton rather than an ImageButton, still wondering if anyone has an explanation. A: I've had the same problem and haven't really found any satisfying solution until I ended up on https://siderite.dev/blog/thispostbacksettingsasync-is-null-or.html which does exactly what I want. Just to avoid problems with possible dead links in the future here is the code: var script = @" if (Sys && Sys.WebForms && Sys.WebForms.PageRequestManager && Sys.WebForms.PageRequestManager.getInstance) { var prm = Sys.WebForms.PageRequestManager.getInstance(); if (prm && !prm._postBackSettings) { prm._postBackSettings = prm._createPostBackSettings(false, null, null); }"; ScriptManager.RegisterOnSubmitStatement( Page, Page.GetType(), "FixPopupFormSubmit", script); In case of a submit without the _postBackSettings being set it creates them, causing the null reference exception to disappear as _postBackSettings.async is then available. Hope this helps, G. A: My best guess is that the UpdatePanel is not able to write out the custom "async" property to the postback request properly. This is likely due to blocking from one of the controls wrapping it (my gut feeling is that it's the popupControlExtender - it tends to have odd behavior with updatepanels, as it is intended to manage the events inside it for it's show/hide purposes). I would recommend either removing the updatepanel and rolling your own solution for your specific business need for having it there, or implementing your own popup script (probably slightly easier to write). Incidentally, for some background, the "this._postbackSettings.async" is your AJAX.NET framework trying to figure out whether this is an async call or not. You might be able to overcome it by setting this programaticly before the postback is sent (catch the postback event and add the field to the postback request if it is not already there). Just some thoughts...I do not believe there is a "plug and play" answer for this one! A: Settign "EnablePartialRendering" to false on the ScriptManager control prevents the error, but it is not an optimal solution. Losing the benefit of partial rendering could be a big deal, depending on your application. Just for the record, I wasn't doing exactly the same as other folks who saw the error. I have a PopupControlExtender, in which is a checkboxlist. I added a "select all" link with a javascript method to programmatically select/deselect all. I'm not using an Imagebutton. I didn't see the error before adding the javascript and now even after removing it the error remains. There has to be another change I'm missing. I hope this helps someone... --Matt
{ "language": "en", "url": "https://stackoverflow.com/questions/57586", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: How to find (and keep) a tester who is developer I work for a software vendor whose market is developer tools and we have been looking for a QA person for our products. Since we are a small shop the position will be a combination of Support and QA however since we make developer tools, our support consists in large part of actual development (in that the person must read and understand our customers code and find and point out bugs in it). The QA portion will also consist of writing applications (in a variety of platforms and languages) and testing how they work with our tools. The main issue I am running into is when you tell someone with development experience that the position contains "QA" it its title (or even in the job description) they shy away from considering the job. I'm very interested in feedback and suggestions for how I can find a good person to fill this job and ensure that they are happy doing it. Any ideas? A: Money and responsibility. The reason I shy away from these types of jobs is they dont tend to hold my interest long enough. Having real development tasks should keep you out of that category. The other problem is the salary is usually significantly lower with that in the title. A: I am a developer, but spent time working as a QA person (test writing, automation, tool writing/coding). I saw it as something I was doing on the side, and would eventually move out of. The main reason I wanted out was that it simply was not the career I wanted. No amount of money/responsibility would change that. However I think respect has something to do with it as well. A lot of QA work is simply unappreciated, so that is something that would need to be clearly explained as "not how things work at your company." I would find someone who wants a QA position, but has strong developement/coding/problem solving skills. They could fill in doing the tool creation or other small coding tasks, but it would be on the side. Sort of a reverse of my feelings above. A: I think the ideal combination of jobs is product manager + QA. What I mean by product manager is someone who writes requirements documents and is responsible for making sure the product meets the requirements. This person would be a peer of the lead developer, not a superior. A person who is a developer but likes management and wants to take that career path might be very interested in that combination of roles. A: To start with you can just take "QA" out of the title and description if that seems to be 'hot button' that is keeping candidates from looking at the position seriously. From your description, your position doesn't have much in common with a traditional 'tester' role - the work is mostly writing and thinking about code, not banging on someone else's code and trying to break it. Think of it as a fairly eclectic, tools-oriented development position, and try to advertise and staff it accordingly. (And expect to pay accordingly as well - you get what you pay for.) There are quite a few developers out there who have good skills, but maybe a little shorter attention span than others, and who would prefer to work on a succession of mini projects rather than a longer-lasting piece of a bigger project. A: You may just want to keep "QA" out of the title, and call the position "Developer Support" or something like that. Don't mislead any candidates about the duties of the role, but you can cast it more as a "You will be responsible for building the releases and ensuring they are ready to ship to customers." Also make sure that there is a career path that leads into more development, not more QA, if that's what the candidate wants. Finally, make sure that the other developers treat this person as a fellow developer, and not as somebody outside the team. It's sad that "QA" has some stigma attached to it among developers, but it does. A: I was a programmer working as a tester for a little time. If I may, the answer is quite simple: let them do whatever they want. If you give them free reign, I can guarantee that your software will be tested in ways you never imagined. If, on the other hand, you try to control such a person, then they will grow to despise you. This is inevitable. The benefits outweight the costs. If you're a large corp then this decision is easy. Just hire software developers and tell them to "go to town" on your product. You'll love the results. A: Money and responsibility are key, as Adam and Chops point out. Quality engineers should be on the same pay scale as the developers. Interesting work is also an important factor. The role sounds like a nice variety of tasks. At my company, developers are often loaned to the test team between projects or when test team is swamped. Some have a knack, others don't. Still, most developers would rather test their own code than find bugs in others' work. The test managers actively woo developers with strong testing skills. I resisted switching to the test team for seven years. A promotion, a 20% raise and a promise that my role was primarily trouble-shooting, management and planning finally convinced me to switch. I do more hands on testing than I thought I would, but I get the challenging work too. Pay comparable to development. Be truthful; disclose actual expectations of the role. Change the title to Software Quality Engineer. A: I agree with Adam, money and responsibility are key. I would suggest that, if you're within a small company, that your QA team is small/non-existent. That probably means there's good opportunity for someone to come in and make a genuine effort to contribute and shape your companies QA policy, procedure and workflow. Our company had a similar issue with QA, and we're still not there 100% with it. But giving the QA person the power to dictate policy and procedure, and participate in all aspects of product development so as to keep them in the loop has worked well for us. This means, when it comes to QA and testing, we've got someone who understands the product, knows it inside and out, has been heavily involved from the start, and has heavily shaped the procedures they themselves, and the development team, will follow. Responsibility is key. A: Most developers are neither good testers nor do they enjoy testing, and you want someone who is both. Be honest in your job ad that the position is NOT a stepping stone to a developer position and you will have fewer applicants but a better chance of keeping who you do hire. QA typically has lousy pay, so if you are willing to pay better, you should be able to find someone. You won't keep them if you hire someone who wants to write code all day, regardless of how much you pay them. A: I think you have a toughie here: * *The cost of a full time developer for doing the job you require would be too high. *Most dev's (including myself) would get incredibly fed up, very quickly. Most dev's passion is coding, they want to do it as much as possible. Where TBH, from what you have said, it may be very little in the job role you have. *I would say perhaps look for a Junior, someone fresh with little experience. They will probably mould better to your testing/QA process, and it gives them a chance to start looking at production code, with perhaps opportunity to work with it. *Unless you are lucky, I would not expect a "developer" to stay for long, so either expect a bit of turnover, or possibly expand to a full dev role if required, and get a cheaper sole tester in. *I know you are a small shop, so finances may be a large part to play, but I would say you need to weigh up the possibility of getting a dev in and fixing the problems you have if they occur that often. Testers are cheap by comparison. May be best to get a tester in, find all the issues, then get a contractor/part time dev in to fix issues. A: Dude, A certain company I work for has found the solution to your problems. Hire QE not QA. QA (Quality Assurance) does have a stigma to it. The job title itself implies boring rote tasks to most developers. QE (Quality Engineering) sounds just as bad, but doesn't scare off nearly as many people. If all else fails just hire a developer. I mean seriously, you want someone who can write code, so hire someone who has training in that. The thing is, you need to look at your applicants and talk to them. You are looking for someone who knows how QE works and you want to hire a developer that works in the language your program uses not what it's written in. A: The most common title for this posotion is "Software Developer in Test". But I think another trouble is much more important - its hard to prevent a person with good testing and dev knowledge from migrating to Dev team
{ "language": "en", "url": "https://stackoverflow.com/questions/57587", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "11" }
Q: How to calculate age in T-SQL with years, months, and days What would be the best way to calculate someone's age in years, months, and days in T-SQL (SQL Server 2000)? The datediff function doesn't handle year boundaries well, plus getting the months and days separate will be a bear. I know I can do it on the client side relatively easily, but I'd like to have it done in my stored procedure. A: Here is some T-SQL that gives you the number of years, months, and days since the day specified in @date. It takes into account the fact that DATEDIFF() computes the difference without considering what month or day it is (so the month diff between 8/31 and 9/1 is 1 month) and handles that with a case statement that decrements the result where appropriate. DECLARE @date datetime, @tmpdate datetime, @years int, @months int, @days int SELECT @date = '2/29/04' SELECT @tmpdate = @date SELECT @years = DATEDIFF(yy, @tmpdate, GETDATE()) - CASE WHEN (MONTH(@date) > MONTH(GETDATE())) OR (MONTH(@date) = MONTH(GETDATE()) AND DAY(@date) > DAY(GETDATE())) THEN 1 ELSE 0 END SELECT @tmpdate = DATEADD(yy, @years, @tmpdate) SELECT @months = DATEDIFF(m, @tmpdate, GETDATE()) - CASE WHEN DAY(@date) > DAY(GETDATE()) THEN 1 ELSE 0 END SELECT @tmpdate = DATEADD(m, @months, @tmpdate) SELECT @days = DATEDIFF(d, @tmpdate, GETDATE()) SELECT @years, @months, @days A: Implemented by arithmetic with ISO formatted date. declare @now date,@dob date, @now_i int,@dob_i int, @days_in_birth_month int declare @years int, @months int, @days int set @now = '2013-02-28' set @dob = '2012-02-29' -- Date of Birth set @now_i = convert(varchar(8),@now,112) -- iso formatted: 20130228 set @dob_i = convert(varchar(8),@dob,112) -- iso formatted: 20120229 set @years = ( @now_i - @dob_i)/10000 -- (20130228 - 20120229)/10000 = 0 years set @months =(1200 + (month(@now)- month(@dob))*100 + day(@now) - day(@dob))/100 %12 -- (1200 + 0228 - 0229)/100 % 12 = 11 months set @days_in_birth_month = day(dateadd(d,-1,left(convert(varchar(8),dateadd(m,1,@dob),112),6)+'01')) set @days = (sign(day(@now) - day(@dob))+1)/2 * (day(@now) - day(@dob)) + (sign(day(@dob) - day(@now))+1)/2 * (@days_in_birth_month - day(@dob) + day(@now)) -- ( (-1+1)/2*(28 - 29) + (1+1)/2*(29 - 29 + 28)) -- Explain: if the days of now is bigger than the days of birth, then diff the two days -- else add the days of now and the distance from the date of birth to the end of the birth month select @years,@months,@days -- 0, 11, 28 Test Cases The approach of days is different from the accepted answer, the differences shown in the comments below: dob now years months days 2012-02-29 2013-02-28 0 11 28 --Days will be 30 if calculated by the approach in accepted answer. 2012-02-29 2016-02-28 3 11 28 --Days will be 31 if calculated by the approach in accepted answer, since the day of birth will be changed to 28 from 29 after dateadd by years. 2012-02-29 2016-03-31 4 1 2 2012-01-30 2016-02-29 4 0 30 2012-01-30 2016-03-01 4 1 2 --Days will be 1 if calculated by the approach in accepted answer, since the day of birth will be changed to 30 from 29 after dateadd by years. 2011-12-30 2016-02-29 4 1 30 An short version of Days by case statement: set @days = CASE WHEN day(@now) >= day(@dob) THEN day(@now) - day(@dob) ELSE @days_in_birth_month - day(@dob) + day(@now) END If you want the age of years and months only, it could be simpler set @years = ( @now_i/100 - @dob_i/100)/100 set @months =(12 + month(@now) - month(@dob))%12 select @years,@months -- 1, 0 NOTE: A very useful link of SQL Server Date Formats A: Here is a (slightly) simpler version: CREATE PROCEDURE dbo.CalculateAge @dayOfBirth datetime AS DECLARE @today datetime, @thisYearBirthDay datetime DECLARE @years int, @months int, @days int SELECT @today = GETDATE() SELECT @thisYearBirthDay = DATEADD(year, DATEDIFF(year, @dayOfBirth, @today), @dayOfBirth) SELECT @years = DATEDIFF(year, @dayOfBirth, @today) - (CASE WHEN @thisYearBirthDay > @today THEN 1 ELSE 0 END) SELECT @months = MONTH(@today - @thisYearBirthDay) - 1 SELECT @days = DAY(@today - @thisYearBirthDay) - 1 SELECT @years, @months, @days GO A: The same sort of thing as a function. create function [dbo].[Age](@dayOfBirth datetime, @today datetime) RETURNS varchar(100) AS Begin DECLARE @thisYearBirthDay datetime DECLARE @years int, @months int, @days int set @thisYearBirthDay = DATEADD(year, DATEDIFF(year, @dayOfBirth, @today), @dayOfBirth) set @years = DATEDIFF(year, @dayOfBirth, @today) - (CASE WHEN @thisYearBirthDay > @today THEN 1 ELSE 0 END) set @months = MONTH(@today - @thisYearBirthDay) - 1 set @days = DAY(@today - @thisYearBirthDay) - 1 return cast(@years as varchar(2)) + ' years,' + cast(@months as varchar(2)) + ' months,' + cast(@days as varchar(3)) + ' days' end A: create procedure getDatedifference ( @startdate datetime, @enddate datetime ) as begin declare @monthToShow int declare @dayToShow int --set @startdate='01/21/1934' --set @enddate=getdate() if (DAY(@startdate) > DAY(@enddate)) begin set @dayToShow=0 if (month(@startdate) > month(@enddate)) begin set @monthToShow= (12-month(@startdate)+ month(@enddate)-1) end else if (month(@startdate) < month(@enddate)) begin set @monthToShow= ((month(@enddate)-month(@startdate))-1) end else begin set @monthToShow= 11 end -- set @monthToShow= convert(int, DATEDIFF(mm,0,DATEADD(dd,DATEDIFF(dd,0,@enddate)- DATEDIFF(dd,0,@startdate),0)))-((convert(int,FLOOR(DATEDIFF(day, @startdate, @enddate) / 365.25))*12))-1 if(@monthToShow<0) begin set @monthToShow=0 end declare @amonthbefore integer set @amonthbefore=Month(@enddate)-1 if(@amonthbefore=0) begin set @amonthbefore=12 end if (@amonthbefore in(1,3,5,7,8,10,12)) begin set @dayToShow=31-DAY(@startdate)+DAY(@enddate) end if (@amonthbefore=2) begin IF (YEAR( @enddate ) % 4 = 0 AND YEAR( @enddate ) % 100 != 0) OR YEAR( @enddate ) % 400 = 0 begin set @dayToShow=29-DAY(@startdate)+DAY(@enddate) end else begin set @dayToShow=28-DAY(@startdate)+DAY(@enddate) end end if (@amonthbefore in (4,6,9,11)) begin set @dayToShow=30-DAY(@startdate)+DAY(@enddate) end end else begin --set @monthToShow=convert(int, DATEDIFF(mm,0,DATEADD(dd,DATEDIFF(dd,0,@enddate)- DATEDIFF(dd,0,@startdate),0)))-((convert(int,FLOOR(DATEDIFF(day, @startdate, @enddate) / 365.25))*12)) if (month(@enddate)< month(@startdate)) begin set @monthToShow=12+(month(@enddate)-month(@startdate)) end else begin set @monthToShow= (month(@enddate)-month(@startdate)) end set @dayToShow=DAY(@enddate)-DAY(@startdate) end SELECT FLOOR(DATEDIFF(day, @startdate, @enddate) / 365.25) as [yearToShow], @monthToShow as monthToShow ,@dayToShow as dayToShow , convert(varchar,FLOOR(DATEDIFF(day, @startdate, @enddate) / 365.25)) +' Year ' + convert(varchar,@monthToShow) +' months '+convert(varchar,@dayToShow)+' days ' as age return end A: I use this Function I modified (the Days part) From @Dane answer: https://stackoverflow.com/a/57720/2097023 CREATE FUNCTION dbo.EdadAMD ( @FECHA DATETIME ) RETURNS NVARCHAR(10) AS BEGIN DECLARE @tmpdate DATETIME , @years INT , @months INT , @days INT , @EdadAMD NVARCHAR(10); SELECT @tmpdate = @FECHA; SELECT @years = DATEDIFF(yy, @tmpdate, GETDATE()) - CASE WHEN (MONTH(@FECHA) > MONTH(GETDATE())) OR ( MONTH(@FECHA) = MONTH(GETDATE()) AND DAY(@FECHA) > DAY(GETDATE()) ) THEN 1 ELSE 0 END; SELECT @tmpdate = DATEADD(yy, @years, @tmpdate); SELECT @months = DATEDIFF(m, @tmpdate, GETDATE()) - CASE WHEN DAY(@FECHA) > DAY(GETDATE()) THEN 1 ELSE 0 END; SELECT @tmpdate = DATEADD(m, @months, @tmpdate); IF MONTH(@FECHA) = MONTH(GETDATE()) AND DAY(@FECHA) > DAY(GETDATE()) SELECT @days = DAY(EOMONTH(GETDATE(), -1)) - (DAY(@FECHA) - DAY(GETDATE())); ELSE SELECT @days = DATEDIFF(d, @tmpdate, GETDATE()); SELECT @EdadAMD = CONCAT(@years, 'a', @months, 'm', @days, 'd'); RETURN @EdadAMD; END; GO It works pretty well. A: Try this... SELECT CASE WHEN (DATEADD(year,DATEDIFF(year, @datestart ,@dateend) , @datestart) > @dateend) THEN DATEDIFF(year, @datestart ,@dateend) -1 ELSE DATEDIFF(year, @datestart ,@dateend) END Basically the "DateDiff( year...", gives you the age the person will turn this year, so i have just add a case statement to say, if they have not had a birthday yet this year, then subtract 1 year, else return the value. A: Simple way to get age as text is as below: Select cast((DATEDIFF(m, date_of_birth, GETDATE())/12) as varchar) + ' Y & ' + cast((DATEDIFF(m, date_of_birth, GETDATE())%12) as varchar) + ' M' as Age Results Format will be: **63 Y & 2 M** A: I've seen the question several times with results outputting Years, Month, Days but never a numeric / decimal result. (At least not one that doesn't round incorrectly). I welcome feedback on this function. Might not still need a little adjusting. -- Input to the function is two dates. -- Output is the numeric number of years between the two dates in Decimal(7,4) format. -- Output is always always a possitive number. -- NOTE:Output does not handle if difference is greater than 999.9999 -- Logic is based on three steps. -- 1) Is the difference less than 1 year (0.5000, 0.3333, 0.6667, ect.) -- 2) Is the difference exactly a whole number of years (1,2,3, ect.) -- 3) (Else)...The difference is years and some number of days. (1.5000, 2.3333, 7.6667, ect.) CREATE Function [dbo].[F_Get_Actual_Age](@pi_date1 datetime,@pi_date2 datetime) RETURNS Numeric(7,4) AS BEGIN Declare @l_tmp_date DATETIME ,@l_days1 DECIMAL(9,6) ,@l_days2 DECIMAL(9,6) ,@l_result DECIMAL(10,6) ,@l_years DECIMAL(7,4) --Check to make sure there is a date for both inputs IF @pi_date1 IS NOT NULL and @pi_date2 IS NOT NULL BEGIN IF @pi_date1 > @pi_date2 --Make sure the "older" date is in @pi_date1 BEGIN SET @l_tmp_date = @pi_date2 SET @pi_date2 = @Pi_date1 SET @pi_date1 = @l_tmp_date END --Check #1 If date1 + 1 year is greater than date2, difference must be less than 1 year IF DATEADD(YYYY,1,@pi_date1) > @pi_date2 BEGIN --How many days between the two dates (numerator) SET @l_days1 = DATEDIFF(dd,@pi_date1, @pi_date2) --subtract 1 year from date2 and calculate days bewteen it and date2 --This is to get the denominator and accounts for leap year (365 or 366 days) SET @l_days2 = DATEDIFF(dd,dateadd(yyyy,-1,@pi_date2),@pi_date2) SET @l_years = @l_days1 / @l_days2 -- Do the math END ELSE --Check #2 Are the dates an exact number of years apart. --Calculate years bewteen date1 and date2, then add the years to date1, compare dates to see if exactly the same. IF DATEADD(YYYY,DATEDIFF(YYYY,@pi_date1,@pi_date2),@pi_date1) = @pi_date2 SET @l_years = DATEDIFF(YYYY,@pi_date1, @pi_date2) --AS Years, 'Exactly even Years' AS Msg ELSE BEGIN --Check #3 The rest of the cases. --Check if datediff, returning years, over or under states the years difference SET @l_years = DATEDIFF(YYYY,@pi_date1, @pi_date2) IF DATEADD(YYYY,@l_years,@pi_date1) > @pi_date2 SET @l_years = @l_years -1 --use basicly same logic as in check #1 SET @l_days1 = DATEDIFF(dd,DATEADD(YYYY,@l_years,@pi_date1), @pi_date2) SET @l_days2 = DATEDIFF(dd,dateadd(yyyy,-1,@pi_date2),@pi_date2) SET @l_years = @l_years + @l_days1 / @l_days2 --SELECT @l_years AS Years, 'Years Plus' AS Msg END END ELSE SET @l_years = 0 --If either date was null RETURN @l_Years --Return the result as decimal(7,4) END ` A: Quite Old question, but I want to share what I have done to calculate age Declare @BirthDate As DateTime Set @BirthDate = '1994-11-02' SELECT DATEDIFF(YEAR,@BirthDate,GETDATE()) - (CASE WHEN MONTH(@BirthDate)> MONTH(GETDATE()) THEN 1 WHEN MONTH(@BirthDate)= MONTH(GETDATE()) AND DAY(@BirthDate) > DAY(GETDATE()) THEN 1 Else 0 END) A: Are you trying to calculate the total days/months/years of an age? do you have a starting date? Or are you trying to dissect it (ex: 24 years, 1 month, 29 days)? If you have a start date that you're working with, datediff will output the total days/months/years with the following commands: Select DateDiff(d,'1984-07-12','2008-09-11') Select DateDiff(m,'1984-07-12','2008-09-11') Select DateDiff(yyyy,'1984-07-12','2008-09-11') with the respective outputs being (8827/290/24). Now, if you wanted to do the dissection method, you'd have to subtract the number of years in days (days - 365*years), and then do further math on that to get the months, etc. A: DateTime values in T-SQL are stored as floats. You can just subtract the dates from each other and you now have a new date that is the timespan between them. declare @birthdate datetime set @birthdate = '6/15/1974' --age in years - short version print year(getdate() - @birthdate) - year(0) --age in years - visualization declare @mindate datetime declare @span datetime set @mindate = 0 set @span = getdate() - @birthdate print @mindate print @birthdate print getdate() print @span --substract minyear from spanyear to get age in years print year(@span) - year(@mindate) print month(@span) print day(@span) A: Here is SQL code that gives you the number of years, months, and days since the sysdate. Enter value for input_birth_date this format(dd_mon_yy). note: input same value(birth date) for years, months & days such as 01-mar-85 select trunc((sysdate -to_date('&input_birth_date_dd_mon_yy'))/365) years, trunc(mod(( sysdate -to_date('&input_birth_date_dd_mon_yy'))/365,1)*12) months, trunc((mod((mod((sysdate -to_date('&input_birth_date_dd_mon_yy'))/365,1)*12),1)*30)+1) days from dual A: CREATE FUNCTION DBO.GET_AGE ( @DATE AS DATETIME ) RETURNS VARCHAR(MAX) AS BEGIN DECLARE @YEAR AS VARCHAR(50) = '' DECLARE @MONTH AS VARCHAR(50) = '' DECLARE @DAYS AS VARCHAR(50) = '' DECLARE @RESULT AS VARCHAR(MAX) = '' SET @YEAR = CONVERT(VARCHAR,(SELECT DATEDIFF(MONTH,CASE WHEN DAY(@DATE) > DAY(GETDATE()) THEN DATEADD(MONTH,1,@DATE) ELSE @DATE END,GETDATE()) / 12 )) SET @MONTH = CONVERT(VARCHAR,(SELECT DATEDIFF(MONTH,CASE WHEN DAY(@DATE) > DAY(GETDATE()) THEN DATEADD(MONTH,1,@DATE) ELSE @DATE END,GETDATE()) % 12 )) SET @DAYS = DATEDIFF(DD,DATEADD(MM,CONVERT(INT,CONVERT(INT,@YEAR)*12 + CONVERT(INT,@MONTH)),@DATE),GETDATE()) SET @RESULT = (RIGHT('00' + @YEAR, 2) + ' YEARS ' + RIGHT('00' + @MONTH, 2) + ' MONTHS ' + RIGHT('00' + @DAYS, 2) + ' DAYS') RETURN @RESULT END SELECT DBO.GET_AGE('04/12/1986') A: DECLARE @BirthDate datetime, @AgeInMonths int SET @BirthDate = '10/5/1971' SET @AgeInMonths -- Determine the age in "months old": = DATEDIFF(MONTH, @BirthDate, GETDATE()) -- .Get the difference in months - CASE WHEN DATEPART(DAY,GETDATE()) -- .If today was the 1st to 4th, < DATEPART(DAY,@BirthDate) -- (or before the birth day of month) THEN 1 ELSE 0 END -- ... don't count the month. SELECT @AgeInMonths / 12 as AgeYrs -- Divide by 12 months to get the age in years ,@AgeInMonths % 12 as AgeXtraMonths -- Get the remainder of dividing by 12 months = extra months ,DATEDIFF(DAY -- For the extra days, find the difference between, ,DATEADD(MONTH, @AgeInMonths -- 1. Last Monthly Birthday , @BirthDate) -- (if birthdays were celebrated monthly) ,GETDATE()) as AgeXtraDays -- 2. Today's date. A: For the ones that want to create a calculated column in a table to store the age: CASE WHEN DateOfBirth< DATEADD(YEAR, (DATEPART(YEAR, GETDATE()) - DATEPART(YEAR, DateOfBirth))*-1, GETDATE()) THEN DATEPART(YEAR, GETDATE()) - DATEPART(YEAR, DateOfBirth) ELSE DATEPART(YEAR, GETDATE()) - DATEPART(YEAR, DateOfBirth) -1 END A: Here is how I calculate the age given a birth date and the current date. select case when cast(getdate() as date) = cast(dateadd(year, (datediff(year, '1996-09-09', getdate())), '1996-09-09') as date) then dateDiff(yyyy,'1996-09-09',dateadd(year, 0, getdate())) else dateDiff(yyyy,'1996-09-09',dateadd(year, -1, getdate())) end as MemberAge go A: There is an easy way, based on the hours between the two days BUT with the end date truncated. SELECT CAST(DATEDIFF(hour,Birthdate,CAST(GETDATE() as Date))/8766.0 as INT) AS Age FROM <YourTable> This one has proven to be extremely accurate and reliable. If it weren't for the inner CAST on the GETDATE() it might flip the birthday a few hours before midnight but, with the CAST, it is dead on with the age changing over at exactly midnight. A: There is another method for calculate age is See below table FirstName LastName DOB sai krishnan 1991-11-04 Harish S A 1998-10-11 For finding age,you can calculate through month Select datediff(MONTH,DOB,getdate())/12 as dates from [Organization].[Employee] Result will be firstname dates sai 27 Harish 20 A: I have created a function calculateAge that takes parameter dateOfBirth from outside and then it calculates the age in years, months and days and finally it returns in string format. CREATE FUNCTION calculateAge(dateOfBirth datetime) RETURNS varchar(40) BEGIN set @currentdatetime = CURRENT_TIMESTAMP; set @years = TIMESTAMPDIFF(YEAR,dateOfBirth,@currentdatetime); set @months = TIMESTAMPDIFF(MONTH,dateOfBirth,@currentdatetime) - @years*12 ; set @dayOfBirth = EXTRACT(DAY FROM dateOfBirth); set @today = EXTRACT(DAY FROM @currentdatetime); set @days = 0; if (@today > @dayOfBirth) then set @days = @today - @dayOfBirth; else set @decreaseMonth = DATE_SUB(@currentdatetime, INTERVAL 1 MONTH); set @days = DATEDIFF(dateOfBirth, @decreaseMonth); end if; RETURN concat(concat( concat(@years , "years\n") , concat(@months , "months\n")), concat(@days , "days")); END A: Plenty of solutions have been given already, but I beleive this one to be both easy to understand and reliable, as it will handle leap years as well : case when datepart(dayofyear, @birth) <= datepart(dayofyear, getdate()) then datepart(year, getdate()) - datepart(year, @birth) else datepart(year, getdate()) - datepart(year, @birth) - 1 end The idea is to simply compute the difference in years between the two years (birth and now), and substract 1 if the anniversary has not been reached for the current year. A: DECLARE @DoB AS DATE = '1968-10-24' DECLARE @cDate AS DATE = CAST('2000-10-23' AS DATE) SELECT --Get Year difference DATEDIFF(YEAR,@DoB,@cDate) - --Cases where year difference will be augmented CASE --If Date of Birth greater than date passed return 0 WHEN YEAR(@DoB) - YEAR(@cDate) >= 0 THEN DATEDIFF(YEAR,@DoB,@cDate) --If date of birth month less than date passed subtract one year WHEN MONTH(@DoB) - MONTH(@cDate) > 0 THEN 1 --If date of birth day less than date passed subtract one year WHEN MONTH(@DoB) - MONTH(@cDate) = 0 AND DAY(@DoB) - DAY(@cDate) > 0 THEN 1 --All cases passed subtract zero ELSE 0 END A: declare @StartDate datetime = '2016-01-31' declare @EndDate datetime = '2016-02-01' SELECT @StartDate AS [StartDate] ,@EndDate AS [EndDate] ,DATEDIFF(Year,@StartDate,@EndDate) - CASE WHEN DATEADD(Year,DATEDIFF(Year,@StartDate,@EndDate), @StartDate) > @EndDate THEN 1 ELSE 0 END AS [Years] ,DATEDIFF(Month,(DATEADD(Year,DATEDIFF(Year,@StartDate,@EndDate) - CASE WHEN DATEADD(Year,DATEDIFF(Year,@StartDate,@EndDate), @StartDate) > @EndDate THEN 1 ELSE 0 END,@StartDate)),@EndDate) - CASE WHEN DATEADD(Month, DATEDIFF(Month,DATEADD(Year,DATEDIFF(Year,@StartDate,@EndDate) - CASE WHEN DATEADD(Year,DATEDIFF(Year,@StartDate,@EndDate), @StartDate) > @EndDate THEN 1 ELSE 0 END,@StartDate),@EndDate) , @StartDate) > @EndDate THEN 1 ELSE 0 END AS [Months] ,DATEDIFF(Day, DATEADD(Month,DATEDIFF(Month, (DATEADD(Year,DATEDIFF(Year,@StartDate,@EndDate) - CASE WHEN DATEADD(Year,DATEDIFF(Year,@StartDate,@EndDate), @StartDate) > @EndDate THEN 1 ELSE 0 END,@StartDate)),@EndDate) - CASE WHEN DATEADD(Month, DATEDIFF(Month,DATEADD(Year,DATEDIFF(Year,@StartDate,@EndDate) - CASE WHEN DATEADD(Year,DATEDIFF(Year,@StartDate,@EndDate), @StartDate) > @EndDate THEN 1 ELSE 0 END,@StartDate),@EndDate) , @StartDate) > @EndDate THEN 1 ELSE 0 END ,DATEADD(Year,DATEDIFF(Year,@StartDate,@EndDate) - CASE WHEN DATEADD(Year,DATEDIFF(Year,@StartDate,@EndDate), @StartDate) > @EndDate THEN 1 ELSE 0 END,@StartDate)) ,@EndDate) - CASE WHEN DATEADD(Day,DATEDIFF(Day, DATEADD(Month,DATEDIFF(Month, (DATEADD(Year,DATEDIFF(Year,@StartDate,@EndDate) - CASE WHEN DATEADD(Year,DATEDIFF(Year,@StartDate,@EndDate), @StartDate) > @EndDate THEN 1 ELSE 0 END,@StartDate)),@EndDate) - CASE WHEN DATEADD(Month, DATEDIFF(Month,DATEADD(Year,DATEDIFF(Year,@StartDate,@EndDate) - CASE WHEN DATEADD(Year,DATEDIFF(Year,@StartDate,@EndDate), @StartDate) > @EndDate THEN 1 ELSE 0 END,@StartDate),@EndDate) , @StartDate) > @EndDate THEN 1 ELSE 0 END ,DATEADD(Year,DATEDIFF(Year,@StartDate,@EndDate) - CASE WHEN DATEADD(Year,DATEDIFF(Year,@StartDate,@EndDate), @StartDate) > @EndDate THEN 1 ELSE 0 END,@StartDate)) ,@EndDate),DATEADD(Month,DATEDIFF(Month, (DATEADD(Year,DATEDIFF(Year,@StartDate,@EndDate) - CASE WHEN DATEADD(Year,DATEDIFF(Year,@StartDate,@EndDate), @StartDate) > @EndDate THEN 1 ELSE 0 END,@StartDate)),@EndDate) - CASE WHEN DATEADD(Month, DATEDIFF(Month,DATEADD(Year,DATEDIFF(Year,@StartDate,@EndDate) - CASE WHEN DATEADD(Year,DATEDIFF(Year,@StartDate,@EndDate), @StartDate) > @EndDate THEN 1 ELSE 0 END,@StartDate),@EndDate) , @StartDate) > @EndDate THEN 1 ELSE 0 END ,DATEADD(Year,DATEDIFF(Year,@StartDate,@EndDate) - CASE WHEN DATEADD(Year,DATEDIFF(Year,@StartDate,@EndDate), @StartDate) > @EndDate THEN 1 ELSE 0 END,@StartDate))) > @EndDate THEN 1 ELSE 0 END AS [Days] A: select DOB as Birthdate, YEAR(GETDATE()) as ThisYear, YEAR(getdate()) - EAR(date1) as Age from TableName A: SELECT DOB AS Birthdate , YEAR(GETDATE()) AS ThisYear, YEAR(getdate()) - YEAR(DOB) AS Age FROM tableprincejain A: declare @BirthDate datetime declare @TotalYear int declare @TotalMonths int declare @TotalDays int declare @TotalWeeks int declare @TotalHours int declare @TotalMinute int declare @TotalSecond int declare @CurrentDtTime datetime set @BirthDate='1998/01/05 05:04:00' -- Set Your date here set @TotalYear= FLOOR(DATEDIFF(DAY, @BirthDate, GETDATE()) / 365.25) set @TotalMonths= FLOOR(DATEDIFF(DAY,DATEADD(year, @TotalYear,@BirthDate),GetDate()) / 30.436875E) set @TotalDays= FLOOR(DATEDIFF(DAY, DATEADD(month, @TotalMonths,DATEADD(year, @TotalYear,@BirthDate)), GETDATE())) set @CurrentDtTime=CONVERT(datetime,CONVERT(varchar(50), DATEPART(year, GetDate()))+'/' +CONVERT(varchar(50), DATEPART(MONTH, GetDate())) +'/'+ CONVERT(varchar(50),DATEPART(DAY, GetDate()))+' ' + CONVERT(varchar(50),DATEPART(HOUR, @BirthDate))+':'+ CONVERT(varchar(50),DATEPART(MINUTE, @BirthDate))+ ':'+ CONVERT(varchar(50),DATEPART(Second, @BirthDate))) set @TotalHours = DATEDIFF(hour, @CurrentDtTime, GETDATE()) if(@TotalHours < 0) begin set @TotalHours = DATEDIFF(hour,DATEADD(Day,-1, @CurrentDtTime), GETDATE()) set @TotalDays= @TotalDays -1 end set @TotalMinute= DATEPART(MINUTE, GETDATE())-DATEPART(MINUTE, @BirthDate) if(@TotalMinute < 0) set @TotalMinute = DATEPART(MINUTE, DATEADD(hour,-1,GETDATE()))+(60-DATEPART(MINUTE, @BirthDate)) set @TotalSecond= DATEPART(Second, GETDATE())-DATEPART(Second, @BirthDate) Print 'Your age are'+ CHAR(13) + CONVERT(varchar(50), @TotalYear)+' Years, ' + CONVERT(varchar(50),@TotalMonths) +' Months, ' + CONVERT(varchar(50),@TotalDays)+' Days, ' + CONVERT(varchar(50),@TotalHours)+' Hours, ' + CONVERT(varchar(50),@TotalMinute)+' Minutes, ' + CONVERT(varchar(50),@TotalSecond)+' Seconds. ' +char(13)+ 'Your are born at day of week was - ' + CONVERT(varchar(50),DATENAME(dw , @BirthDate )) +char(13)+char(13)+ +'Your Birthdate to till date your '+ CHAR(13) +'Years - ' + CONVERT(varchar(50), FLOOR(DATEDIFF(DAY, @BirthDate, GETDATE()) / 365.25)) +' , Months - ' + CONVERT(varchar(50),DATEDIFF(MM,@BirthDate,getdate())) +' , Weeks - ' + CONVERT(varchar(50),DATEDIFF(wk,@BirthDate,getdate())) +' , Days - ' + CONVERT(varchar(50),DATEDIFF(dd,@BirthDate,getdate()))+char(13)+ +'Hours - ' + CONVERT(varchar(50),DATEDIFF(HH,@BirthDate,getdate())) +' , Minutes - ' + CONVERT(varchar(50),DATEDIFF(mi,@BirthDate,getdate())) +' , Seconds - ' + CONVERT(varchar(50),DATEDIFF(ss,@BirthDate,getdate())) Output Your age are 22 Years, 0 Months, 2 Days, 11 Hours, 30 Minutes, 16 Seconds. Your are born at day of week was - Monday Your Birthdate to till date your Years - 22 , Months - 264 , Weeks - 1148 , Days - 8037 Hours - 192899 , Minutes - 11573970 , Seconds - 694438216
{ "language": "en", "url": "https://stackoverflow.com/questions/57599", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "55" }
Q: Continue Considered Harmful? Should developers avoid using continue in C# or its equivalent in other languages to force the next iteration of a loop? Would arguments for or against overlap with arguments about Goto? A: I think there should be more use of continue! Too often I come across code like: for (...) { if (!cond1) { if (!cond2) { ... highly indented lines ... } } } instead of for (...) { if (cond1 || cond2) { continue; } ... } Use it to make the code more readable! A: There are not harmful keywords. There's only harmful uses of them. Goto is not harmful per se, neither is continue. They need to be used carefully, that's all. A: If continue is causing a problem with readability, then chances are you have other problems. For example, massive amounts of code inside a for loop. If you have to write large for loops, I would try to stick to using continue close to the top of the for loop. Otherwise, a continue buried deep in the middle of a for loop can easily be missed. A: I like to use continue at the beginning of loops for handling simple if conditions. To me it makes the code more readable since there is not extra nesting and you can see that I have explicitly dealt with these cases. Is this the same reason that I would use a goto? Perhaps. I do use them for readability at times and to stop the nesting of code but I usually use them more for cleanup/error handling. A: I'd say: "it depends". If you have reasonably small loop code (where you can see the whole loop-code without scrolling) its usually ok to use a continue. However, if the loops body is large (for example due to a big switch), and there is some followup code (say below the switch), you may easily introduce bugs by adding a continue and thus skipping over that code sometimes. I have encountered this in the heart of a bytecode interpreter, where some instrumentation code was sometimes not executed due to a continue in some case-branches. This might be a somewhat artificially constructed case, but I generally try to avoid continue and use an if (but not nesting too deep as in the Rob's sample code). A: Is continue any more harmful than, say, break? If anything, in the majority of cases where I encounter/use it, I find it makes code clearer and less spaghetti-like. A: I don't think continue could ever be as difficult as goto since continue never moves execution out of the code block that it is in. A: If you are iterating through any kind of a result set, and performing operations on said results, for e.g within a for each, and if one particular result caused a problem, its rather useful in capturing an expected error (via try-catch), logging it, and moving on to the next result via continue. Continue is especially useful, imo, for unattended services that do jobs at odd hours, and one exception shouldn't affect the other x number of records. A: As far as this programmer is concerned, Nested if/else considered harmful. A: * *Using continue at the beginning of a loop to avoid iteration over unnecessary elements is not harmful and can be very useful, but using it in the middle of nested ifs and elses can turn the loop code into a complex maze, to understand and validate. *I think its usage avoidance is also the result of a semantic misunderstanding. People who does never see/write 'continue' keyword on their code, when seeing a code with continue can interpret it as "the continuation of the natural flow". If instead of continue we had next, for instance, I think more people would appreciate this valuable cursor feature. A: You can write good code with or without continue and you can write bad code with or without continue. There probably is some overlap with arguments about goto, but as far as I'm concerned the use of continue is equivalent to using break statements (in loops) or return statement from anywhere in a method body - if used correctly it can simplify the code (less likely to contain bugs, easier to maintain). A: goto can be used as a continue, but not the reverse. You can "goto" anywhere, thus break flow control arbitrarily. Thus continue, not nearly as harmful. A: Others have hinted at it... but continue and break are enforced by the compiler and have their own associated rules. Goto has no such limitations, though the net effect might almost be the same, in some circumstances. I do not consider continue or break to be harmful per se, though I'm sure either can be used poorly in a way that would make any sane programmer gag. A: Continue is a really useful function in most languages, because it allows blocks of code to be skipped for certain conditions. One alternative would be to uses boolean variables in if statements, but these would need to be reset after every use. A: I'd say yes. To me, it just breaks the 'flow' of a fluidly-written piece of code. Another argument could also be that if you stick to the basic keywords supported by most modern languages, then your program flow (if not the logic or code) could be ported to any other language. Having an unsupported keyword (ie, continue or goto) would break that. It's really more of a personal preference, but I've never had to use it and don't really consider it an option when I'm writing new code. (same as goto.) A: continue feels wrong to me. break gets you out of there, but continue seems just to be spaghetti. On the other hand, you can emulate continue with break (at least in Java). for (String str : strs) contLp: { ... break contLp; ... } (This posting had an obvious bug in the above code for over a decade. That doesn't look good for break/continue.) continue can be useful in some circumstances, but it still feels dirty to me. It might be time to introduce a new method. for (char c : cs) { final int i; if ('0' <= c && c <= '9') { i = c - '0'; } else if ('a' <= c && c <= 'z') { i = c - 'a' + 10; } else { continue; } ... use i ... } These uses should be very rare. A: I believe the bottom line argument against continue is that it makes it harder to PROVE that the code is correct. This is prove in the mathematical sense. But it probably doesn't matter to you because no one has the resources to 'prove' a computer program that is significantly complex. Enter the static-analysis tools. You may make things harder on them... And the goto, that sounds like a nightmare for the same reasons but at any random place in code.
{ "language": "en", "url": "https://stackoverflow.com/questions/57600", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "22" }
Q: Save registry values in WinCE using a C# app I'm working on a WinCE 6.0 system with a touchscreen that stores its calibration data (x-y location, offset, etc.) in the system registry (HKLM\HARDWARE\TOUCH). Right now, I'm placing the cal values into registry keys that get put into the OS image at build time. That works fine for the monitor that I get the original cal values from, but when I load this image into another system with a different monitor, the touchscreen pointer location is (understandably) off, because the two monitors do not have the same cal values. My problem is that I don't know how to properly store values into the registry so that they persist after a power cycle. See, I can recalibrate the screen on the second system, but the new values only exist in volatile memory. I suggested to my boss that we could just tell our customer to leave the power on the unit at all times -- that didn't go over well. I need advice on how to save the new constants into the registry, so that we can calibrate the monitors once before shipping them out to our customer, and not have to make separate OS images for each unit we build. A C# method that is known to work in CE6.0 would be helpful. Thanks. -Odbasta A: Follow-up on this question: Thanks DannySmurf, flushing the registry key was ultimately what needed to be done. However, there were a few steps that I was missing before reaching that stage. So, here's what came to light: * *I was using a RAM-based registry, where by design the registry does not persist after a cold boot. I had to switch the registry to hive-based. *When switching to a hive-based registry structure, you need to make sure that the hive exists on a non-volatile medium. This is specified in the platform.reg file: [HKEY_LOCAL_MACHINE\init\BootVars] "SystemHive"="\\Hard Disk\\system.hv" "ProfileDir"="\\Documents and Settings" "RegistryFlags"=dword:1 ; Flush hive on every RegCloseKey call "SystemHiveInitialSize"=dword:19000 ; Initial size for hive-registry file "Start DevMgr"=dword:1 *Once the system.hv file is on the hard disk (CF card in my case), the values in the registry will persist after a cold boot. Note that the system.hv file contains all the HKLM keys. *It's also important to note that any drivers that need to be initialized on boot have to be specified as such in the .reg files of the solution. For example, I had to make sure that the hard disk drivers (PCMCIA) were loaded before trying to read the system hive file from them. The way to do this is to add a directive in the following format around each driver init key: ;HIVE BOOT SECTION [HKEY_LOCAL_MACHINE\Drivers\PCCARD\PCMCIA\TEMPLATE\PCMCIA] "Dll"="pcmcia.dll" "NoConfig"=dword:1 "IClass"=multi_sz:"{6BEAB08A-8914-42fd-B33F-61968B9AAB32}=PCMCIA Card Services" "Flags"=dword:1000 ;END HIVE BOOT SECTION That, plus a lot of luck, is about it. A: I think what you're probably looking for is the Flush function of the RegistryKey class. This is normally not necessary (the registry is lazily-flushed by default), but if the power is turned off on the device before the system has a chance to do this, changes will be discarded: http://msdn.microsoft.com/en-us/library/microsoft.win32.registrykey.flush.aspx This function is available in .NET Compact Framework version 2.0 and better. A: As I understood you need to know how to set a value to the registry during runtime. I hope the codes bellow can help you. using Microsoft.Win32; /// <summary> /// store a key value in registry. if it don't exist it will be created. /// </summary> /// <param name="mainKey">the main key of key path</param> /// <param name="subKey">the path below the main key</param> /// <param name="keyName">the key name</param> /// <param name="value">the value to be stored</param> public static void SetRegistry(int mainKey, String subKey, String keyName, object value) { if (mainKey != CURRENT_USER && mainKey != LOCAL_MACHINE) { throw new ArgumentOutOfRangeException("mainKey", "\'mainKey\' argument can only be AppUtils.CURRENT_USER or AppUtils.LOCAL_MACHINE values"); } if (subKey == null) { throw new ArgumentNullException("subKey", "\'subKey\' argument cannot be null"); } if (keyName == null) { throw new ArgumentNullException("keyName", "\'keyName\' argument cannot be null"); } const Boolean WRITABLE = true; RegistryKey key = null; if (mainKey == CURRENT_USER) { key = Registry.CurrentUser.OpenSubKey(subKey, WRITABLE); if (key == null) { key = Registry.CurrentUser.CreateSubKey(subKey); } } else if (mainKey == LOCAL_MACHINE) { key = Registry.LocalMachine.OpenSubKey(subKey, WRITABLE); if (key == null) { key = Registry.LocalMachine.CreateSubKey(subKey); } } key.SetValue(keyName, value); } /// <summary> /// find a key value in registry. if it don't exist the default value will be returned. /// </summary> /// <param name="mainKey">the main key of key path</param> /// <param name="subKey">the path below the main key</param> /// <param name="keyName">the key name</param> /// <param name="defaultValue">the value to be stored</param> public static object GetRegistry(int mainKey, String subKey, String keyName, object defaultValue) { if (mainKey != CURRENT_USER && mainKey != LOCAL_MACHINE) { throw new ArgumentOutOfRangeException("mainKey", "\'mainKey\' argument can only be AppUtils.CURRENT_USER or AppUtils.LOCAL_MACHINE values"); } if (subKey == null) { throw new ArgumentNullException("subKey", "\'subKey\' argument cannot be null"); } if (keyName == null) { throw new ArgumentNullException("keyName", "\'keyName\' argument cannot be null"); } RegistryKey key = Registry.CurrentUser.OpenSubKey(subKey); if (mainKey == CURRENT_USER) { key = Registry.CurrentUser.OpenSubKey(subKey); } else if (mainKey == LOCAL_MACHINE) { key = Registry.LocalMachine.OpenSubKey(subKey); } object result = defaultValue; if (key != null) { result = key.GetValue(keyName, defaultValue); } return result; }
{ "language": "en", "url": "https://stackoverflow.com/questions/57609", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: How to add a Timeout to Console.ReadLine()? I have a console app in which I want to give the user x seconds to respond to the prompt. If no input is made after a certain period of time, program logic should continue. We assume a timeout means empty response. What is the most straightforward way of approaching this? A: // Wait for 'Enter' to be pressed or 5 seconds to elapse using (Stream s = Console.OpenStandardInput()) { ManualResetEvent stop_waiting = new ManualResetEvent(false); s.BeginRead(new Byte[1], 0, 1, ar => stop_waiting.Set(), null); // ...do anything else, or simply... stop_waiting.WaitOne(5000); // If desired, other threads could also set 'stop_waiting' // Disposing the stream cancels the async read operation. It can be // re-opened if needed. } A: If you're in the Main() method, you can't use await, so you'll have to use Task.WaitAny(): var task = Task.Factory.StartNew(Console.ReadLine); var result = Task.WaitAny(new Task[] { task }, TimeSpan.FromSeconds(5)) == 0 ? task.Result : string.Empty; However, C# 7.1 introduces the possiblity to create an async Main() method, so it's better to use the Task.WhenAny() version whenever you have that option: var task = Task.Factory.StartNew(Console.ReadLine); var completedTask = await Task.WhenAny(task, Task.Delay(TimeSpan.FromSeconds(5))); var result = object.ReferenceEquals(task, completedTask) ? task.Result : string.Empty; A: I think you will need to make a secondary thread and poll for a key on the console. I know of no built in way to accomplish this. A: Calling Console.ReadLine() in the delegate is bad because if the user doesn't hit 'enter' then that call will never return. The thread executing the delegate will be blocked until the user hits 'enter', with no way to cancel it. Issuing a sequence of these calls will not behave as you would expect. Consider the following (using the example Console class from above): System.Console.WriteLine("Enter your first name [John]:"); string firstName = Console.ReadLine(5, "John"); System.Console.WriteLine("Enter your last name [Doe]:"); string lastName = Console.ReadLine(5, "Doe"); The user lets the timeout expire for the first prompt, then enters a value for the second prompt. Both firstName and lastName will contain the default values. When the user hits 'enter', the first ReadLine call will complete, but the code has abandonded that call and essentially discarded the result. The second ReadLine call will continue to block, the timeout will eventually expire and the value returned will again be the default. BTW- There is a bug in the code above. By calling waitHandle.Close() you close the event out from under the worker thread. If the user hits 'enter' after the timeout expires, the worker thread will attempt to signal the event which throws an ObjectDisposedException. The exception is thrown from the worker thread, and if you haven't setup an unhandled exception handler your process will terminate. A: I struggled with this problem for 5 months before I found an solution that works perfectly in an enterprise setting. The problem with most of the solutions so far is that they rely on something other than Console.ReadLine(), and Console.ReadLine() has a lot of advantages: * *Support for delete, backspace, arrow keys, etc. *The ability to press the "up" key and repeat the last command (this comes in very handy if you implement a background debugging console that gets a lot of use). My solution is as follows: * *Spawn a separate thread to handle the user input using Console.ReadLine(). *After the timeout period, unblock Console.ReadLine() by sending an [enter] key into the current console window, using http://inputsimulator.codeplex.com/. Sample code: InputSimulator.SimulateKeyPress(VirtualKeyCode.RETURN); More information on this technique, including the correct technique to abort a thread that uses Console.ReadLine: .NET call to send [enter] keystroke into the current process, which is a console app? How to abort another thread in .NET, when said thread is executing Console.ReadLine? A: I may be reading too much into the question, but I am assuming the wait would be similar to the boot menu where it waits 15 seconds unless you press a key. You could either use (1) a blocking function or (2) you could use a thread, an event, and a timer. The event would act as a 'continue' and would block until either the timer expired or a key was pressed. Pseudo-code for (1) would be: // Get configurable wait time TimeSpan waitTime = TimeSpan.FromSeconds(15.0); int configWaitTimeSec; if (int.TryParse(ConfigManager.AppSetting["DefaultWaitTime"], out configWaitTimeSec)) waitTime = TimeSpan.FromSeconds(configWaitTimeSec); bool keyPressed = false; DateTime expireTime = DateTime.Now + waitTime; // Timer and key processor ConsoleKeyInfo cki; // EDIT: adding a missing ! below while (!keyPressed && (DateTime.Now < expireTime)) { if (Console.KeyAvailable) { cki = Console.ReadKey(true); // TODO: Process key keyPressed = true; } Thread.Sleep(10); } A: As if there weren't already enough answers here :0), the following encapsulates into a static method @kwl's solution above (the first one). public static string ConsoleReadLineWithTimeout(TimeSpan timeout) { Task<string> task = Task.Factory.StartNew(Console.ReadLine); string result = Task.WaitAny(new Task[] { task }, timeout) == 0 ? task.Result : string.Empty; return result; } Usage static void Main() { Console.WriteLine("howdy"); string result = ConsoleReadLineWithTimeout(TimeSpan.FromSeconds(8.5)); Console.WriteLine("bye"); } A: string ReadLine(int timeoutms) { ReadLineDelegate d = Console.ReadLine; IAsyncResult result = d.BeginInvoke(null, null); result.AsyncWaitHandle.WaitOne(timeoutms);//timeout e.g. 15000 for 15 secs if (result.IsCompleted) { string resultstr = d.EndInvoke(result); Console.WriteLine("Read: " + resultstr); return resultstr; } else { Console.WriteLine("Timed out!"); throw new TimedoutException("Timed Out!"); } } delegate string ReadLineDelegate(); A: .NET 4 makes this incredibly simple using Tasks. First, build your helper: Private Function AskUser() As String Console.Write("Answer my question: ") Return Console.ReadLine() End Function Second, execute with a task and wait: Dim askTask As Task(Of String) = New TaskFactory().StartNew(Function() AskUser()) askTask.Wait(TimeSpan.FromSeconds(30)) If Not askTask.IsCompleted Then Console.WriteLine("User failed to respond.") Else Console.WriteLine(String.Format("You responded, '{0}'.", askTask.Result)) End If There's no trying to recreate ReadLine functionality or performing other perilous hacks to get this working. Tasks let us solve the question in a very natural way. A: Will this approach using Console.KeyAvailable help? class Sample { public static void Main() { ConsoleKeyInfo cki = new ConsoleKeyInfo(); do { Console.WriteLine("\nPress a key to display; press the 'x' key to quit."); // Your code could perform some useful task in the following loop. However, // for the sake of this example we'll merely pause for a quarter second. while (Console.KeyAvailable == false) Thread.Sleep(250); // Loop until input is entered. cki = Console.ReadKey(true); Console.WriteLine("You pressed the '{0}' key.", cki.Key); } while(cki.Key != ConsoleKey.X); } } A: EDIT: fixed the problem by having the actual work be done in a separate process and killing that process if it times out. See below for details. Whew! Just gave this a run and it seemed to work nicely. My coworker had a version which used a Thread object, but I find the BeginInvoke() method of delegate types to be a bit more elegant. namespace TimedReadLine { public static class Console { private delegate string ReadLineInvoker(); public static string ReadLine(int timeout) { return ReadLine(timeout, null); } public static string ReadLine(int timeout, string @default) { using (var process = new System.Diagnostics.Process { StartInfo = { FileName = "ReadLine.exe", RedirectStandardOutput = true, UseShellExecute = false } }) { process.Start(); var rli = new ReadLineInvoker(process.StandardOutput.ReadLine); var iar = rli.BeginInvoke(null, null); if (!iar.AsyncWaitHandle.WaitOne(new System.TimeSpan(0, 0, timeout))) { process.Kill(); return @default; } return rli.EndInvoke(iar); } } } } The ReadLine.exe project is a very simple one which has one class which looks like so: namespace ReadLine { internal static class Program { private static void Main() { System.Console.WriteLine(System.Console.ReadLine()); } } } A: I can't comment on Gulzar's post unfortunately, but here's a fuller example: while (Console.KeyAvailable == false) { Thread.Sleep(250); i++; if (i > 3) throw new Exception("Timedout waiting for input."); } input = Console.ReadLine(); A: My code is based entirely on the friend's answer @JSQuareD But I needed to use Stopwatch to timer because when I finished the program with Console.ReadKey() it was still waiting for Console.ReadLine() and it generated unexpected behavior. It WORKED PERFECTLY for me. Maintains the original Console.ReadLine () class Program { static void Main(string[] args) { Console.WriteLine("What is the answer? (5 secs.)"); try { var answer = ConsoleReadLine.ReadLine(5000); Console.WriteLine("Answer is: {0}", answer); } catch { Console.WriteLine("No answer"); } Console.ReadKey(); } } class ConsoleReadLine { private static string inputLast; private static Thread inputThread = new Thread(inputThreadAction) { IsBackground = true }; private static AutoResetEvent inputGet = new AutoResetEvent(false); private static AutoResetEvent inputGot = new AutoResetEvent(false); static ConsoleReadLine() { inputThread.Start(); } private static void inputThreadAction() { while (true) { inputGet.WaitOne(); inputLast = Console.ReadLine(); inputGot.Set(); } } // omit the parameter to read a line without a timeout public static string ReadLine(int timeout = Timeout.Infinite) { if (timeout == Timeout.Infinite) { return Console.ReadLine(); } else { var stopwatch = new Stopwatch(); stopwatch.Start(); while (stopwatch.ElapsedMilliseconds < timeout && !Console.KeyAvailable) ; if (Console.KeyAvailable) { inputGet.Set(); inputGot.WaitOne(); return inputLast; } else { throw new TimeoutException("User did not provide input within the timelimit."); } } } } A: This worked for me. ConsoleKeyInfo k = new ConsoleKeyInfo(); Console.WriteLine("Press any key in the next 5 seconds."); for (int cnt = 5; cnt > 0; cnt--) { if (Console.KeyAvailable) { k = Console.ReadKey(); break; } else { Console.WriteLine(cnt.ToString()); System.Threading.Thread.Sleep(1000); } } Console.WriteLine("The key pressed was " + k.Key); A: I'm surprised to learn that after 5 years, all of the answers still suffer from one or more of the following problems: * *A function other than ReadLine is used, causing loss of functionality. (Delete/backspace/up-key for previous input). *Function behaves badly when invoked multiple times (spawning multiple threads, many hanging ReadLine's, or otherwise unexpected behavior). *Function relies on a busy-wait. Which is a horrible waste since the wait is expected to run anywhere from a number of seconds up to the timeout, which might be multiple minutes. A busy-wait which runs for such an ammount of time is a horrible suck of resources, which is especially bad in a multithreading scenario. If the busy-wait is modified with a sleep this has a negative effect on responsiveness, although I admit that this is probably not a huge problem. I believe my solution will solve the original problem without suffering from any of the above problems: class Reader { private static Thread inputThread; private static AutoResetEvent getInput, gotInput; private static string input; static Reader() { getInput = new AutoResetEvent(false); gotInput = new AutoResetEvent(false); inputThread = new Thread(reader); inputThread.IsBackground = true; inputThread.Start(); } private static void reader() { while (true) { getInput.WaitOne(); input = Console.ReadLine(); gotInput.Set(); } } // omit the parameter to read a line without a timeout public static string ReadLine(int timeOutMillisecs = Timeout.Infinite) { getInput.Set(); bool success = gotInput.WaitOne(timeOutMillisecs); if (success) return input; else throw new TimeoutException("User did not provide input within the timelimit."); } } Calling is, of course, very easy: try { Console.WriteLine("Please enter your name within the next 5 seconds."); string name = Reader.ReadLine(5000); Console.WriteLine("Hello, {0}!", name); } catch (TimeoutException) { Console.WriteLine("Sorry, you waited too long."); } Alternatively, you can use the TryXX(out) convention, as shmueli suggested: public static bool TryReadLine(out string line, int timeOutMillisecs = Timeout.Infinite) { getInput.Set(); bool success = gotInput.WaitOne(timeOutMillisecs); if (success) line = input; else line = null; return success; } Which is called as follows: Console.WriteLine("Please enter your name within the next 5 seconds."); string name; bool success = Reader.TryReadLine(out name, 5000); if (!success) Console.WriteLine("Sorry, you waited too long."); else Console.WriteLine("Hello, {0}!", name); In both cases, you cannot mix calls to Reader with normal Console.ReadLine calls: if the Reader times out, there will be a hanging ReadLine call. Instead, if you want to have a normal (non-timed) ReadLine call, just use the Reader and omit the timeout, so that it defaults to an infinite timeout. So how about those problems of the other solutions I mentioned? * *As you can see, ReadLine is used, avoiding the first problem. *The function behaves properly when invoked multiple times. Regardless of whether a timeout occurs or not, only one background thread will ever be running and only at most one call to ReadLine will ever be active. Calling the function will always result in the latest input, or in a timeout, and the user won't have to hit enter more than once to submit his input. *And, obviously, the function does not rely on a busy-wait. Instead it uses proper multithreading techniques to prevent wasting resources. The only problem that I foresee with this solution is that it is not thread-safe. However, multiple threads can't really ask the user for input at the same time, so synchronization should be happening before making a call to Reader.ReadLine anyway. A: One way or another you do need a second thread. You could use asynchronous IO to avoid declaring your own: * *declare a ManualResetEvent, call it "evt" *call System.Console.OpenStandardInput to get the input stream. Specify a callback method that will store its data and set evt. *call that stream's BeginRead method to start an asynchronous read operation *then enter a timed wait on a ManualResetEvent *if the wait times out, then cancel the read If the read returns data, set the event and your main thread will continue, otherwise you'll continue after the timeout. A: Simple threading example to solve this Thread readKeyThread = new Thread(ReadKeyMethod); static ConsoleKeyInfo cki = null; void Main() { readKeyThread.Start(); bool keyEntered = false; for(int ii = 0; ii < 10; ii++) { Thread.Sleep(1000); if(readKeyThread.ThreadState == ThreadState.Stopped) keyEntered = true; } if(keyEntered) { //do your stuff for a key entered } } void ReadKeyMethod() { cki = Console.ReadKey(); } or a static string up top for getting an entire line. A: Im my case this work fine: public static ManualResetEvent evtToWait = new ManualResetEvent(false); private static void ReadDataFromConsole( object state ) { Console.WriteLine("Enter \"x\" to exit or wait for 5 seconds."); while (Console.ReadKey().KeyChar != 'x') { Console.Out.WriteLine(""); Console.Out.WriteLine("Enter again!"); } evtToWait.Set(); } static void Main(string[] args) { Thread status = new Thread(ReadDataFromConsole); status.Start(); evtToWait = new ManualResetEvent(false); evtToWait.WaitOne(5000); // wait for evtToWait.Set() or timeOut status.Abort(); // exit anyway return; } A: Isn't this nice and short? if (SpinWait.SpinUntil(() => Console.KeyAvailable, millisecondsTimeout)) { ConsoleKeyInfo keyInfo = Console.ReadKey(); // Handle keyInfo value here... } A: This is a fuller example of Glen Slayden's solution. I happended to make this when building a test case for another problem. It uses asynchronous I/O and a manual reset event. public static void Main() { bool readInProgress = false; System.IAsyncResult result = null; var stop_waiting = new System.Threading.ManualResetEvent(false); byte[] buffer = new byte[256]; var s = System.Console.OpenStandardInput(); while (true) { if (!readInProgress) { readInProgress = true; result = s.BeginRead(buffer, 0, buffer.Length , ar => stop_waiting.Set(), null); } bool signaled = true; if (!result.IsCompleted) { stop_waiting.Reset(); signaled = stop_waiting.WaitOne(5000); } else { signaled = true; } if (signaled) { readInProgress = false; int numBytes = s.EndRead(result); string text = System.Text.Encoding.UTF8.GetString(buffer , 0, numBytes); System.Console.Out.Write(string.Format( "Thank you for typing: {0}", text)); } else { System.Console.Out.WriteLine("oy, type something!"); } } A: Here is safe solution which fakes console input to unblock thread after timeout. https://github.com/Igorium/ConsoleReader project provides a sample user dialog implementation. var inputLine = ReadLine(5); public static string ReadLine(uint timeoutSeconds, Func<uint, string> countDownMessage, uint samplingFrequencyMilliseconds) { if (timeoutSeconds == 0) return null; var timeoutMilliseconds = timeoutSeconds * 1000; if (samplingFrequencyMilliseconds > timeoutMilliseconds) throw new ArgumentException("Sampling frequency must not be greater then timeout!", "samplingFrequencyMilliseconds"); CancellationTokenSource cts = new CancellationTokenSource(); Task.Factory .StartNew(() => SpinUserDialog(timeoutMilliseconds, countDownMessage, samplingFrequencyMilliseconds, cts.Token), cts.Token) .ContinueWith(t => { var hWnd = System.Diagnostics.Process.GetCurrentProcess().MainWindowHandle; PostMessage(hWnd, 0x100, 0x0D, 9); }, TaskContinuationOptions.NotOnCanceled); var inputLine = Console.ReadLine(); cts.Cancel(); return inputLine; } private static void SpinUserDialog(uint countDownMilliseconds, Func<uint, string> countDownMessage, uint samplingFrequencyMilliseconds, CancellationToken token) { while (countDownMilliseconds > 0) { token.ThrowIfCancellationRequested(); Thread.Sleep((int)samplingFrequencyMilliseconds); countDownMilliseconds -= countDownMilliseconds > samplingFrequencyMilliseconds ? samplingFrequencyMilliseconds : countDownMilliseconds; } } [DllImport("User32.Dll", EntryPoint = "PostMessageA")] private static extern bool PostMessage(IntPtr hWnd, uint msg, int wParam, int lParam); A: I've got a solution to this using the Windows API that has some benefits over many of the solutions here: * *Uses Console.ReadLine to retrieve the input, so you get all of the niceties associated with that (input history, etc) *Forces the Console.ReadLine call to complete after the timeout, so you don't accumulate a new thread for every call that times out. *Doesn't abort a thread unsafely. *Doesn't have issues with focus like the input faking approach does. The two main downsides: * *Only works on Windows. *It's pretty complicated. The basic idea is that the Windows API has a function to cancel outstanding I/O requests: CancelIoEx. When you use it to cancel operations on STDIN, Console.ReadLine throws an OperationCanceledException. So here's how you do it: using System; using System.Runtime.InteropServices; using System.Threading; using System.Threading.Tasks; namespace ConsoleHelper { public static class ConsoleHelper { public static string ReadLine(TimeSpan timeout) { return ReadLine(Task.Delay(timeout)); } public static string ReadLine(Task cancel_trigger) { var status = new Status(); var cancel_task = Task.Run(async () => { await cancel_trigger; status.Mutex.WaitOne(); bool io_done = status.IODone; if (!io_done) status.CancellationStarted = true; status.Mutex.ReleaseMutex(); while (!status.IODone) { var success = CancelStdIn(out int error_code); if (!success && error_code != 0x490) // 0x490 is what happens when you call cancel and there is not a pending I/O request throw new Exception($"Canceling IO operation on StdIn failed with error {error_code} ({error_code:x})"); } }); ReadLineWithStatus(out string input, out bool read_canceled); if (!read_canceled) { status.Mutex.WaitOne(); bool must_wait = status.CancellationStarted; status.IODone = true; status.Mutex.ReleaseMutex(); if (must_wait) cancel_task.Wait(); return input; } else // read_canceled == true { status.Mutex.WaitOne(); bool cancel_started = status.CancellationStarted; status.IODone = true; status.Mutex.ReleaseMutex(); if (!cancel_started) throw new Exception("Received cancelation not triggered by this method."); else cancel_task.Wait(); return null; } } private const int STD_INPUT_HANDLE = -10; [DllImport("kernel32.dll", SetLastError = true)] private static extern IntPtr GetStdHandle(int nStdHandle); [DllImport("kernel32.dll", SetLastError = true)] private static extern bool CancelIoEx(IntPtr handle, IntPtr lpOverlapped); private static bool CancelStdIn(out int error_code) { var handle = GetStdHandle(STD_INPUT_HANDLE); bool success = CancelIoEx(handle, IntPtr.Zero); if (success) { error_code = 0; return true; } else { var rc = Marshal.GetLastWin32Error(); error_code = rc; return false; } } private class Status { public Mutex Mutex = new Mutex(false); public volatile bool IODone; public volatile bool CancellationStarted; } private static void ReadLineWithStatus(out string result, out bool operation_canceled) { try { result = Console.ReadLine(); operation_canceled = false; } catch (OperationCanceledException) { result = null; operation_canceled = true; } } } } Avoid the temptation to simplify this, getting the threading right is pretty tricky. You need to handle all of these cases: * *Cancel is triggered and CancelStdIn is called before Console.ReadLine starts (this is why you need the loop in the cancel_trigger). *Console.ReadLine returns before cancel is triggered (possibly long before). *Console.ReadLine returns after the cancel is triggered but before CancelStdIn is called. *Console.ReadLine throws an exception due to the call to CancelStdIn in response to the cancel trigger. Credits: Got the idea for CancelIoEx from a SO answer who got it from Gérald Barré's blog. However those solutions have subtle concurrency bugs. A: Another cheap way to get a 2nd thread is to wrap it in a delegate. A: Example implementation of Eric's post above. This particular example was used to read information that was passed to a console app via pipe: using System; using System.Collections.Generic; using System.IO; using System.Threading; namespace PipedInfo { class Program { static void Main(string[] args) { StreamReader buffer = ReadPipedInfo(); Console.WriteLine(buffer.ReadToEnd()); } #region ReadPipedInfo public static StreamReader ReadPipedInfo() { //call with a default value of 5 milliseconds return ReadPipedInfo(5); } public static StreamReader ReadPipedInfo(int waitTimeInMilliseconds) { //allocate the class we're going to callback to ReadPipedInfoCallback callbackClass = new ReadPipedInfoCallback(); //to indicate read complete or timeout AutoResetEvent readCompleteEvent = new AutoResetEvent(false); //open the StdIn so that we can read against it asynchronously Stream stdIn = Console.OpenStandardInput(); //allocate a one-byte buffer, we're going to read off the stream one byte at a time byte[] singleByteBuffer = new byte[1]; //allocate a list of an arbitary size to store the read bytes List<byte> byteStorage = new List<byte>(4096); IAsyncResult asyncRead = null; int readLength = 0; //the bytes we have successfully read do { //perform the read and wait until it finishes, unless it's already finished asyncRead = stdIn.BeginRead(singleByteBuffer, 0, singleByteBuffer.Length, new AsyncCallback(callbackClass.ReadCallback), readCompleteEvent); if (!asyncRead.CompletedSynchronously) readCompleteEvent.WaitOne(waitTimeInMilliseconds); //end the async call, one way or another //if our read succeeded we store the byte we read if (asyncRead.IsCompleted) { readLength = stdIn.EndRead(asyncRead); if (readLength > 0) byteStorage.Add(singleByteBuffer[0]); } } while (asyncRead.IsCompleted && readLength > 0); //we keep reading until we fail or read nothing //return results, if we read zero bytes the buffer will return empty return new StreamReader(new MemoryStream(byteStorage.ToArray(), 0, byteStorage.Count)); } private class ReadPipedInfoCallback { public void ReadCallback(IAsyncResult asyncResult) { //pull the user-defined variable and strobe the event, the read finished successfully AutoResetEvent readCompleteEvent = asyncResult.AsyncState as AutoResetEvent; readCompleteEvent.Set(); } } #endregion ReadPipedInfo } } A: string readline = "?"; ThreadPool.QueueUserWorkItem( delegate { readline = Console.ReadLine(); } ); do { Thread.Sleep(100); } while (readline == "?"); Note that if you go down the "Console.ReadKey" route, you lose some of the cool features of ReadLine, namely: * *Support for delete, backspace, arrow keys, etc. *The ability to press the "up" key and repeat the last command (this comes in very handy if you implement a background debugging console that gets a lot of use). To add a timeout, alter the while loop to suit. A: Please don't hate me for adding another solution to the plethora of existing answers! This works for Console.ReadKey(), but could easily be modified to work with ReadLine(), etc. As the "Console.Read" methods are blocking, it's necessary to "nudge" the StdIn stream to cancel the read. Calling syntax: ConsoleKeyInfo keyInfo; bool keyPressed = AsyncConsole.ReadKey(500, out keyInfo); // where 500 is the timeout Code: public class AsyncConsole // not thread safe { private static readonly Lazy<AsyncConsole> Instance = new Lazy<AsyncConsole>(); private bool _keyPressed; private ConsoleKeyInfo _keyInfo; private bool DoReadKey( int millisecondsTimeout, out ConsoleKeyInfo keyInfo) { _keyPressed = false; _keyInfo = new ConsoleKeyInfo(); Thread readKeyThread = new Thread(ReadKeyThread); readKeyThread.IsBackground = false; readKeyThread.Start(); Thread.Sleep(millisecondsTimeout); if (readKeyThread.IsAlive) { try { IntPtr stdin = GetStdHandle(StdHandle.StdIn); CloseHandle(stdin); readKeyThread.Join(); } catch { } } readKeyThread = null; keyInfo = _keyInfo; return _keyPressed; } private void ReadKeyThread() { try { _keyInfo = Console.ReadKey(); _keyPressed = true; } catch (InvalidOperationException) { } } public static bool ReadKey( int millisecondsTimeout, out ConsoleKeyInfo keyInfo) { return Instance.Value.DoReadKey(millisecondsTimeout, out keyInfo); } private enum StdHandle { StdIn = -10, StdOut = -11, StdErr = -12 }; [DllImport("kernel32.dll")] private static extern IntPtr GetStdHandle(StdHandle std); [DllImport("kernel32.dll")] private static extern bool CloseHandle(IntPtr hdl); } A: Here is a solution that uses Console.KeyAvailable. These are blocking calls, but it should be fairly trivial to call them asynchronously via the TPL if desired. I used the standard cancellation mechanisms to make it easy to wire in with the Task Asynchronous Pattern and all that good stuff. public static class ConsoleEx { public static string ReadLine(TimeSpan timeout) { var cts = new CancellationTokenSource(); return ReadLine(timeout, cts.Token); } public static string ReadLine(TimeSpan timeout, CancellationToken cancellation) { string line = ""; DateTime latest = DateTime.UtcNow.Add(timeout); do { cancellation.ThrowIfCancellationRequested(); if (Console.KeyAvailable) { ConsoleKeyInfo cki = Console.ReadKey(); if (cki.Key == ConsoleKey.Enter) { return line; } else { line += cki.KeyChar; } } Thread.Sleep(1); } while (DateTime.UtcNow < latest); return null; } } There are some disadvantages with this. * *You do not get the standard navigation features that ReadLine provides (up/down arrow scrolling, etc.). *This injects '\0' characters into input if a special key is press (F1, PrtScn, etc.). You could easily filter them out by modifying the code though. A: Ended up here because a duplicate question was asked. I came up with the following solution which looks straightforward. I am sure it has some drawbacks I missed. static void Main(string[] args) { Console.WriteLine("Hit q to continue or wait 10 seconds."); Task task = Task.Factory.StartNew(() => loop()); Console.WriteLine("Started waiting"); task.Wait(10000); Console.WriteLine("Stopped waiting"); } static void loop() { while (true) { if ('q' == Console.ReadKey().KeyChar) break; } } A: I came to this answer and end up doing: /// <summary> /// Reads Line from console with timeout. /// </summary> /// <exception cref="System.TimeoutException">If user does not enter line in the specified time.</exception> /// <param name="timeout">Time to wait in milliseconds. Negative value will wait forever.</param> /// <returns></returns> public static string ReadLine(int timeout = -1) { ConsoleKeyInfo cki = new ConsoleKeyInfo(); StringBuilder sb = new StringBuilder(); // if user does not want to spesify a timeout if (timeout < 0) return Console.ReadLine(); int counter = 0; while (true) { while (Console.KeyAvailable == false) { counter++; Thread.Sleep(1); if (counter > timeout) throw new System.TimeoutException("Line was not entered in timeout specified"); } cki = Console.ReadKey(false); if (cki.Key == ConsoleKey.Enter) { Console.WriteLine(); return sb.ToString(); } else sb.Append(cki.KeyChar); } } A: A simple example using Console.KeyAvailable: Console.WriteLine("Press any key during the next 2 seconds..."); Thread.Sleep(2000); if (Console.KeyAvailable) { Console.WriteLine("Key pressed"); } else { Console.WriteLine("You were too slow"); } A: Much more contemporary and Task based code would look something like this: public string ReadLine(int timeOutMillisecs) { var inputBuilder = new StringBuilder(); var task = Task.Factory.StartNew(() => { while (true) { var consoleKey = Console.ReadKey(true); if (consoleKey.Key == ConsoleKey.Enter) { return inputBuilder.ToString(); } inputBuilder.Append(consoleKey.KeyChar); } }); var success = task.Wait(timeOutMillisecs); if (!success) { throw new TimeoutException("User did not provide input within the timelimit."); } return inputBuilder.ToString(); } A: I had a unique situation of having a Windows Application (Windows Service). When running the program interactively Environment.IsInteractive (VS Debugger or from cmd.exe), I used AttachConsole/AllocConsole to get my stdin/stdout. To keep the process from ending while the work was being done, the UI Thread calls Console.ReadKey(false). I wanted to cancel the waiting the UI thread was doing from another thread, so I came up with a modification to the solution by @JSquaredD. using System; using System.Diagnostics; internal class PressAnyKey { private static Thread inputThread; private static AutoResetEvent getInput; private static AutoResetEvent gotInput; private static CancellationTokenSource cancellationtoken; static PressAnyKey() { // Static Constructor called when WaitOne is called (technically Cancel too, but who cares) getInput = new AutoResetEvent(false); gotInput = new AutoResetEvent(false); inputThread = new Thread(ReaderThread); inputThread.IsBackground = true; inputThread.Name = "PressAnyKey"; inputThread.Start(); } private static void ReaderThread() { while (true) { // ReaderThread waits until PressAnyKey is called getInput.WaitOne(); // Get here // Inner loop used when a caller uses PressAnyKey while (!Console.KeyAvailable && !cancellationtoken.IsCancellationRequested) { Thread.Sleep(50); } // Release the thread that called PressAnyKey gotInput.Set(); } } /// <summary> /// Signals the thread that called WaitOne should be allowed to continue /// </summary> public static void Cancel() { // Trigger the alternate ending condition to the inner loop in ReaderThread if(cancellationtoken== null) throw new InvalidOperationException("Must call WaitOne before Cancelling"); cancellationtoken.Cancel(); } /// <summary> /// Wait until a key is pressed or <see cref="Cancel"/> is called by another thread /// </summary> public static void WaitOne() { if(cancellationtoken==null || cancellationtoken.IsCancellationRequested) throw new InvalidOperationException("Must cancel a pending wait"); cancellationtoken = new CancellationTokenSource(); // Release the reader thread getInput.Set(); // Calling thread will wait here indefiniately // until a key is pressed, or Cancel is called gotInput.WaitOne(); } } A: This seems to be the simplest, working solution, that doesn't use any native APIs: static Task<string> ReadLineAsync(CancellationToken cancellation) { return Task.Run(() => { while (!Console.KeyAvailable) { if (cancellation.IsCancellationRequested) return null; Thread.Sleep(100); } return Console.ReadLine(); }); } Example usage: static void Main(string[] args) { AsyncContext.Run(async () => { CancellationTokenSource cancelSource = new CancellationTokenSource(); cancelSource.CancelAfter(1000); Console.WriteLine(await ReadLineAsync(cancelSource.Token) ?? "null"); }); }
{ "language": "en", "url": "https://stackoverflow.com/questions/57615", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "133" }
Q: PHP Object Oriented or not? I have a start of a webapp that I wrote without using the Object Oriented features of PHP. I don't really know if it is worth it to go back and rewrite the parts I have finished. Is object oriented PHP worth rewriting all or part of a decent working app? A: Typical answer: "It depends." I tend to write the display page as a start-to-finish, < html > to < /html > scripted page. But the things that happen on that page were objects. Kinda like a poor man's ASP. While you can have OOP-base output, I alwasy thought it too cumbersome for a task as tedious as dumping data to a browser. So, business rules and data access were OOP. Presentation was script. If you have business rules that are not OOP, I would seriously consider writing those as objects on two conditions: (1) is "Do you have time/effort/money to do so?" and (2) is "Do you have a good PHP IDE that will make your life easier?" If it works, and changing it means writing in Notepad++, then I would call it done. :-) A: Given that you have an incomplete app I would say that reworking it into an Object based app will probably be helpful. One thing to consider is the expected size of the end application. Below a certain complexity Object based may be overkill except for the learning experience. I started out avoiding Objects like the plague because my initial introduction to them in university classes was terrible. I somewhat recently had to work on a project which was implemented in php objects. making the required changes was much easier than other projects. I have since then worked in the object model frequently and find it very handy for quick creation and easier upkeep. A: I wouldn't say it is critical, but if you are going to go much further with the app, I would recommend doing it now while it is not as much of a monumental task. I would say the maintainability of a well written OOP program could far outweigh the up front costs. Especially when you consider that you will be able to refactor much of the code as you go along. A: Learning object oriented techinques will be really useful, especially for programming in other languages in the future. Since you have only just started the application, you could rewrite and improve the parts you have written. It depends on your deadline. A: Just to disagree with the consensus... I would say no in most cases. Not as an academic exercise on commercial code anyway. If it's working don't re-write it. If you have to go in to change / add bits, then refactor towards OO practices (there are lots of posts on SO about refactoring when you are changing code anyway, and not just for the sake of it). In practise if you haven't done a lot of OOP, then you'll want to start small and get a feel for it. Once you get a handle on the basics, a good beginners guide to Design Patterns (I like the Head First book) is very useful. Most PHP books would teach you OOP fairly poorly. They teach you about inheritance, but usually don't teach you about loose coupling and favouring composition over inheritance. A design patterns book will give you a better insight into this. PHP still has a reputation for not "doing" OO right. I don't think this is fair, but is a reflection of the fact that it's so easy for people to get started without really grokking OOP. I would go out on a limb and say the majority (ever so slightly - call it 51%) of PHP programmers aren't comfortable with OOP. I think it's possible to do good OO in PHP, and if you're already comfortable with the language it's a great way to grow your skills. EDIT: Just to add a couple of disclaimers... * *My comment about most PHP programmers not being comfortable with OOP wouldn't apply to the current SO audience! *Not suggesting you aren't comfortable with OOP, this applies if you're not A: There are two possibilities: either your app is a one-off that just has to work right now and will never be touched, adapted, expanded or modified, or else your app is the beginning of something that you will keep working with and using over a long time. If the former, don't break perfectly usable code. You have better things to do with your time. If the latter, you have to bear in mind an important fact about PHP, which is this: poorly written PHP is a nightmare to maintain. Not as bad as poorly written Perl -- because what is? -- but bad enough that sooner or later you will feel a strong urge to steal a time machine, travel back to the moment you wrote the code you now find yourself maintaining, and stab yourself in the eye socket with an icepick. So if you're going to be maintaining this code over time, take the time to do it right. That means: some kind of templating system, no PHP tags embedded inside HTML, separate files for separate functionality, and classes classes classes! Your eye sockets will thank you. A: I would say try and go OO just because what you have can be reused much easier than procedural if done right I will also say that OO is much more organized then procedural. When your at a small scale it's easy to get away with sloppy code OO or not. But when you get to larger projects your procedural must be much more organized and thought out. Where as on some larger projects OO tends to force you to be more organized making things a little easier. A: No, i think if the app is working like it should there's no need to rewrite it. PHP isn't really OOP at all. They try hard but sometimes i think even the PHP-Developers dont really understand the sense of OOP. If you wish to learn OOP (which is surely a good idea) try a real OOP-language like Smalltalk to learn the basic concepts. Java is also nice 2 learn the basic, although it isnt fully OOP as well A: I'd like to reiterate the other answers here. It depends upon size of application and how much you'd like to learn about OOP. I'd be careful of learning OOP by using PHP though. As for how much PHP is object oriented... PHP4 had some OOP elements slapped onto it, PHP5 is better but it's not baked into the language. PHP works both ways, and personally I like that you can choose. A: In my mind, we phper can thorouly throw away the concept of Object(class instance), we only need Array and Mode Class: All arrays in initial mode support any array function as it's method: <?php $array1->array_flip(this); ?> Use ->mode() to validate the minimal data set, and then switch mode class: <?php $array1->mode('class1', $success); ?> Any mode class has no ->construct() in it, but has ->validate() to validate the minimal data set. The array in a mode still could use array function as its method, but after using any of them the array will be switched back into basic array mode, and we need to use ->mode('class1', $success); to switch mode back. The radical thought is data-centric programming, we need separate the data(array) and the activity(class method). We could modify PHP engine, to get rid of parts of OO(object oriented), and support Mode Class, we could call it MyPHP. For example: $array_man1 could be set into two modes:cls_normal_man and cls_crazy_man: <?php $array_man1->mode('cls_normal_man')->normal_method1()->mode('cls_crazy_man')->crazy_method1(); ?>
{ "language": "en", "url": "https://stackoverflow.com/questions/57622", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "10" }
Q: How do you lock tables in SQL Server 2005, and should I even do it? This one will take some explaining. What I've done is create a specific custom message queue in SQL Server 2005. I have a table with messages that contain timestamps for both acknowledgment and completion. The stored procedure that callers execute to obtain the next message in their queue also acknowledges the message. So far so good. Well, if the system is experiencing a massive amount of transactions (thousands per minute), isn't it possible for a message to be acknowledged by another execution of the stored procedure while another is prepared to so itself? Let me help by showing my SQL code in the stored proc: --Grab the next message id declare @MessageId uniqueidentifier set @MessageId = (select top(1) ActionMessageId from UnacknowledgedDemands); --Acknowledge the message update ActionMessages set AcknowledgedTime = getdate() where ActionMessageId = @MessageId --Select the entire message ... ... In the above code, couldn't another stored procedure running at the same time obtain the same id and attempt to acknowledge it at the same time? Could I (or should I) implement some sort of locking to prevent another stored proc from acknowledging messages that another stored proc is querying? Wow, did any of this even make sense? It's a bit difficult to put to words... A: Something like this --Grab the next message id begin tran declare @MessageId uniqueidentifier select top 1 @MessageId = ActionMessageId from UnacknowledgedDemands with(holdlock, updlock); --Acknowledge the message update ActionMessages set AcknowledgedTime = getdate() where ActionMessageId = @MessageId -- some error checking commit tran --Select the entire message ... ... A: This seems like the kind of situation where OUTPUT can be useful: -- Acknowledge and grab the next message declare @message table ( -- ...your `ActionMessages` columns here... ) update ActionMessages set AcknowledgedTime = getdate() output INSERTED.* into @message where ActionMessageId in (select top(1) ActionMessageId from UnacknowledgedDemands) and AcknowledgedTime is null -- Use the data in @message, which will have zero or one rows assuming -- `ActionMessageId` uniquely identifies a row (strongly implied in your question) ... ... There, we update and grab the row in the same operation, which tells the query optimizer exactly what we're doing, allowing it to choose the most granular lock it can and maintain it for the briefest possible time. (Although the column prefix is INSERTED, OUTPUT is like triggers, expressed in terms of the UPDATE being like deleting the row and inserting the new one.) I'd need more information about your ActionMessages and UnacknowledgedDemands tables (views/TVFs/whatever), not to mention a greater knowledge of SQL Server's automatic locking, to say whether that and AcknowledgedTime is null clause is necessary. It's there to defend against a race condition between the sub-select and the update. I'm certain it wouldn't be necessary if we were selecting from ActionMessages itself (e.g., where AcknowledgedTime is null with a top on the update, instead of the sub-select on UnacknowledgedDemands). I expect even if it's unnecessary, it's harmless. Note that OUTPUT is in SQL Server 2005 and above. That's what you said you were using, but if compatibility with geriatric SQL Server 2000 installs were required, you'd want to go another way. A: @Kilhoffer: The whole SQL batch is parsed before execution, so SQL knows that you're going to do an update to the table as well as select from it. Edit: Also, SQL will not necessarily lock the whole table - it could just lock the necessary rows. See here for an overview of locking in SQL server. A: Instead of explicit locking, which is often escalated by SQL Server to higher granularity than desired, why not just try this approach: declare @MessageId uniqueidentifier select top 1 @MessageId = ActionMessageId from UnacknowledgedDemands update ActionMessages set AcknowledgedTime = getdate() where ActionMessageId = @MessageId and AcknowledgedTime is null if @@rowcount > 0 /* acknoweldge succeeded */ else /* concurrent query acknowledged message before us, go back and try another one */ The less you lock - the higher concurrency you have. A: Should you really be processing things one-by-one? Shouldn't you just have SQL Server acknowledge all unacknowledged messages with todays date and return them? (all also in a transaction of course) A: Read more about SQL Server Select Locking here and here. SQL Server has the ability to invoke a table lock on a select. Nothing will happen to the table during the transaction. When the transaction completes, any inserts or updates will then resolve themselves. A: You want to wrap your code in a transaction, then SQL server will handle locking the appropriate rows or tables. begin transaction --Grab the next message id declare @MessageId uniqueidentifier set @MessageId = (select top(1) ActionMessageId from UnacknowledgedDemands); --Acknowledge the message update ActionMessages set AcknowledgedTime = getdate() where ActionMessageId = @MessageId commit transaction --Select the entire message ...
{ "language": "en", "url": "https://stackoverflow.com/questions/57625", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "13" }
Q: How do I get JavaScript to open a popup window on the current monitor Scenario: * *The user has two monitors. *Their browser is open on the secondary monitor. *They click a link in the browser which calls window.open() with a specific top and left window offset. *The popup window always opens on their primary monitor. Is there any way in JavaScript to get the popup window to open on the same monitor as the initial browser window (the opener)? A: // Pops a window relative to the current window position function popup(url, winName, xOffset, yOffset) { var x = (window.screenX || window.screenLeft || 0) + (xOffset || 0); var y = (window.screenY || window.screenTop || 0) + (yOffset || 0); return window.open(url, winName, 'top=' +y+ ',left=' +x)) } Call it like the following and it will open on top of the current window popup('http://www.google.com', 'my-win'); Or make it slightly offset popup('http://www.google.com', 'my-win', 30, 30); The point is that window.screenX/screenLeft give you the position in relationship to the entire desktop, not just the monitor. window.screen.left would be the ideal candidate to give you the information you need. The problem is that it's set when the page is loaded and the user could move the window to the other monitor. More research A final solution to this problem (beyond just offsetting from the current window position) requires knowing the dimensions of the screen that the window is in. Since the screen object doesn't update as the user moves a window around, we need to craft our own way of detecting the current screen resolution. Here's what I came up with /** * Finds the screen element for the monitor that the browser window is currently in. * This is required because window.screen is the screen that the page was originally * loaded in. This method works even after the window has been moved across monitors. * * @param {function} cb The function that will be called (asynchronously) once the screen * object has been discovered. It will be passed a single argument, the screen object. */ function getScreenProps (cb) { if (!window.frames.testiframe) { var iframeEl = document.createElement('iframe'); iframeEl.name = 'testiframe'; iframeEl.src = "about:blank"; iframeEl.id = 'iframe-test' document.body.appendChild(iframeEl); } // Callback when the iframe finishes reloading, it will have the // correct screen object document.getElementById('iframe-test').onload = function() { cb( window.frames.testiframe.screen ); delete document.getElementById('iframe-test').onload; }; // reload the iframe so that the screen object is reloaded window.frames.testiframe.location.reload(); }; So if you wanted to always open the window at the top left of whatever monitor the window is in, you could use the following: function openAtTopLeftOfSameMonitor(url, winName) { getScreenProps(function(scr){ window.open(url, winName, 'top=0,left=' + scr.left); }) } A: Open centered window on current monitor, working also with Chrome: function popupOnCurrentScreenCenter(url, title, w, h) { var dualScreenLeft = typeof window.screenLeft !== "undefined" ? window.screenLeft : screen.left; var dualScreenTop = typeof window.screenTop !== "undefined" ? window.screenTop : screen.top; var width = window.innerWidth ? window.innerWidth : document.documentElement.clientWidth ? document.documentElement.clientWidth : screen.width; var height = window.innerHeight ? window.innerHeight : document.documentElement.clientHeight ? document.documentElement.clientHeight : screen.height; var left = ((width / 2) - (w / 2)) + dualScreenLeft; var top = ((height / 2) - (h / 2)) + dualScreenTop; var newWindow = window.open(url, title, 'scrollbars=yes, width=' + w + ', height=' + h + ', top=' + top + ', left=' + left); // Puts focus on the newWindow if (window.focus) { newWindow.focus(); } } A: You can't specify the monitor, but you can specify the position of the popup window as being relative to the where the click caused the window to popup. Use the getMouseXY() function to get values to pass as the left and top args to the window.open() method. (the left and top args only work with V3 and up browsers). window.open docs: http://www.javascripter.net/faq/openinga.htm function getMouseXY( e ) { if ( event.clientX ) { // Grab the x-y pos.s if browser is IE. CurrentLeft = event.clientX + document.body.scrollLeft; CurrentTop = event.clientY + document.body.scrollTop; } else { // Grab the x-y pos.s if browser isn't IE. CurrentLeft = e.pageX; CurrentTop = e.pageY; } if ( CurrentLeft < 0 ) { CurrentLeft = 0; }; if ( CurrentTop < 0 ) { CurrentTop = 0; }; return true; } A: Here is something I shamelessly reverse engineered from the Facebook oauth API. Tested on a primary and secondary monitor in Firefox/Chrome. function popup_params(width, height) { var a = typeof window.screenX != 'undefined' ? window.screenX : window.screenLeft; var i = typeof window.screenY != 'undefined' ? window.screenY : window.screenTop; var g = typeof window.outerWidth!='undefined' ? window.outerWidth : document.documentElement.clientWidth; var f = typeof window.outerHeight != 'undefined' ? window.outerHeight: (document.documentElement.clientHeight - 22); var h = (a < 0) ? window.screen.width + a : a; var left = parseInt(h + ((g - width) / 2), 10); var top = parseInt(i + ((f-height) / 2.5), 10); return 'width=' + width + ',height=' + height + ',left=' + left + ',top=' + top + ',scrollbars=1'; } window.open(url, "window name", "location=1,toolbar=0," + popup_params(modal_width, modal_height)); A: If you know the resolution of each monitor, you could estimate this. A bad idea for a public website, but might be useful if you know (for some odd reason) that this scenario will always apply. Relative position to the mouse (as said above) or to the original browser window could also be useful, Though you'd have to suppose the user uses the browser maximized (which is not necessarily true). A: I ran into this issue recently and finally found a way to position the pop up window on the screen that it's triggered from. Take a look at my solution on my github page here: https://github.com/svignara/windowPopUp The trick is in using the window.screen object, which returns availWidth, availHeight, availLeft and availTop values (as well as width and height). For a complete list of the variables in the object and what these variables represent look at https://developer.mozilla.org/en-US/docs/DOM/window.screen. Essentially, my solution finds the values of the window.screen whenever the trigger for the popup is clicked. This way I know for sure which monitor screen it's being clicked from. The availLeft value takes care of the rest. Here's how: Basically if the first available pixel from the left (availLeft) is negative, that's telling us there is a monitor to the left of the "main" monitor. Likewise, if the first available pixel from left is greater than 0, this means one of 2 things: * *The monitor is to the right of the "main" monitor, OR *There is some "junk" on the left side of the screen (possibly the application dock or windows start menu) In either case you want the offset of your popup to start from after the available pixel from the left. offsetLeft = availableLeft + ( (availableWidth - modalWidth) / 2 ) A: Only user11153's version works with Chrome and dual screen. Here is its TypeScript version. popupOnCurrentScreenCenter(url: string, title: string, w: number, h: number): Window|null { var dualScreenLeft = typeof window.screenLeft !== "undefined" ? window.screenLeft : (<any>screen).left; var dualScreenTop = typeof window.screenTop !== "undefined" ? window.screenTop : (<any>screen).top; var width = window.innerWidth ? window.innerWidth : document.documentElement.clientWidth ? document.documentElement.clientWidth : screen.width; var height = window.innerHeight ? window.innerHeight : document.documentElement.clientHeight ? document.documentElement.clientHeight : screen.height; var left = ((width / 2) - (w / 2)) + dualScreenLeft; var top = ((height / 2) - (h / 2)) + dualScreenTop; var newWindow = window.open(url, title, 'scrollbars=yes, width=' + w + ', height=' + h + ', top=' + top + ', left=' + left); // Puts focus on the newWindow if (window.focus && newWindow) { newWindow.focus(); } return newWindow; } A: as long as you know the x and y position that falls on the particular monitor you can do: var x = 0; var y = 0; var myWin = window.open(''+self.location,'mywin','left='+x+',top='+y+',width=500,height=500,toolbar=1,resizable=0');
{ "language": "en", "url": "https://stackoverflow.com/questions/57652", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "22" }
Q: How do I expose data in a JSON format through a web service using Rails? Is there an easy way to return data to web service clients in JSON using Rails? A: http://wiki.rubyonrails.org/rails/pages/HowtoGenerateJSON A: Rails monkeypatches most things you'd care about to have a #to_json method. Off the top of my head, you can do it for hashes, arrays, and ActiveRecord objects, which should cover about 95% of the use cases you might want. If you have your own custom objects, it's trivial to write your own to_json method for them, which can just jam data into a hash and then return the jsonized hash. A: Rails resource gives a RESTful interface for your model. Let's see. Model class Contact < ActiveRecord::Base ... end Routes map.resources :contacts Controller class ContactsController < ApplicationController ... def show @contact = Contact.find(params[:id] respond_to do |format| format.html format.xml {render :xml => @contact} format.js {render :json => @contact.json} end end ... end So this gives you an API interfaces without the need to define special methods to get the type of respond required Eg. /contacts/1 # Responds with regular html page /contacts/1.xml # Responds with xml output of Contact.find(1) and its attributes /contacts/1.js # Responds with json output of Contact.find(1) and its attributes A: There is a plugin that does just this, http://blog.labnotes.org/2007/12/11/json_request-handling-json-request-in-rails-20/ And from what I understand this functionality is already in Rails. But go see that blog post, there are code examples and explanations. A: ActiveRecord also provides methods to interact with JSON. To create JSON out of an AR object, just call object.to_json. TO create an AR object out of JSON you should be able to create a new AR object and then call object.from_json.. as far as I understood, but this did not work for me.
{ "language": "en", "url": "https://stackoverflow.com/questions/57665", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: How do you create a process-wide singleton object? I read that the unit of granularity for static fields in .Net are per AppDomain, not per process. Is it possible to create a process-wide singleton object? A: You must use marshalled calls to communicate information across AppDomains. So you need to create the state object in your parent AppDomain and then pass it to any children that want to use it. If you didn't have to do this, you'd be sharing memory across AppDomains, which defeats the purpose. Within each AppDomain you could have a singleton that holds a reference to the (marshalled) reference to the actual singleton in the primary domain. So your code would still look "singleton-y", but there would be some hidden wiring behind it.
{ "language": "en", "url": "https://stackoverflow.com/questions/57677", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How can I determine why a jQuery ajax $.post request wasn't successful? I'm trying to determine, based on the result of this call, if it was successful. The successFunction doesn't get called, so I'm assuming it was not. How do I know what went wrong? xmlRequest = $.post("/url/file/", { 'id' : object.id }, successFunction, 'json'); Do I use the xmlRequest object? A: You can use: $.ajax({ url:"/url/file/", dataType:"json" data:{ 'id' : object.id } error:function(request){alert(request.statusText)} success:successFunction }) A: You could use the $.ajaxComplete() and/or $.ajaxError() methods to attach function to those events. I would also recommend using the Firefox browser with the Firebug pluging, you can get a lot of information about the requests and responses.
{ "language": "en", "url": "https://stackoverflow.com/questions/57679", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: SSRS - Sub Totals Customization - Moving Column to beginning of line I Have a request for the TOTAL's and subtotals column to be moved to the top/left of columns it represents, and by default SSRS does it on the bottom or right hand side of the columns being totaled. Is there a way to this? A: I found my own solution, when you right click on the tiny green triangle, in the top right hand corner of the sub total column. Then select properties, and you can adjust the "Layout" property.. it has 2 options, Before and After. A: You can just add a row which comes before your set of data, for each field you want to total just give that cell an expression which does a SUM() of that particular field.
{ "language": "en", "url": "https://stackoverflow.com/questions/57683", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How do I expose data in a JSON format through a web service using Java? Is there an easy way to return data to web service clients in JSON using java? I'm fine with servlets, spring, etc. A: We have been using Flexjson for converting Java objects to JSON and have found it very easy to use. http://flexjson.sourceforge.net Here are some examples: public String searchCars() { List<Car> cars = carsService.getCars(manufacturerId); return new JSONSerializer().serialize(cars); } It has some cool features such as deepSerialize to send the entire graph and it doesn't break with bi directional relationships. new JSONSerializer().deepSerialize(user); Formatting dates on the server side is often handy too new JSONSerializer().transform( new DateTransformer("dd/MM/yyyy"),"startDate","endDate" ).serialize(contract); A: To me, the best Java <-> JSON parser is XStream (yes, I'm really talking about json, not about xml). XStream already deals with circular dependencies and has a simple and powerful api where you could write yours drivers, converters and so on. Kind Regards A: http://www.json.org/java/index.html has what you need. A: Yup! Check out json-lib Here is a simplified code snippet from my own code that send a set of my domain objects: private String getJsonDocumenent(Object myObj) ( String result = "oops"; try { JSONArray jsonArray = JSONArray.fromObject(myObj); result = jsonArray.toString(2); //indent = 2 } catch (net.sf.json.JSONException je) { throw je; } return result; } A: I have found google-gson compelling. It converts to JSON and back. http://code.google.com/p/google-gson/ It's very flexible and can handle complexities with objects in a straightforward manner. I love its support for generics. /* * we're looking for results in the form * {"id":123,"name":thename},{"id":456,"name":theOtherName},... * * TypeToken is Gson--allows us to tell Gson the data we're dealing with * for easier serialization. */ Type mapType = new TypeToken<List<Map<String, String>>>(){}.getType(); List<Map<String, String>> resultList = new LinkedList<Map<String, String>>(); for (Map.Entry<String, String> pair : sortedMap.entrySet()) { Map<String, String> idNameMap = new HashMap<String, String>(); idNameMap.put("id", pair.getKey()); idNameMap.put("name", pair.getValue()); resultList.add(idNameMap); } return (new Gson()).toJson(resultList, mapType); A: It might be worth looking into Jersey. Jersey makes it easy to expose restful web services as xml and/or JSON. An example... start with a simple class @XmlType(name = "", propOrder = { "id", "text" }) @XmlRootElement(name = "blah") public class Blah implements Serializable { private Integer id; private String text; public Blah(Integer id, String text) { this.id = id; this.text = text; } @XmlElement public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } @XmlElement public String getText() { return text; } public void setText(String value) { this.text = value; } } Then create a Resource @Path("/blah") public class BlahResource { private Set<Blah> blahs = new HashSet<Blah>(); @Context private UriInfo context; public BlahResource() { blahs.add(new Blah(1, "blah the first")); blahs.add(new Blah(2, "blah the second")); } @GET @Path("/{id}") @ProduceMime({"application/json", "application/xml"}) public Blah getBlah(@PathParam("id") Integer id) { for (Blah blah : blahs) { if (blah.getId().equals(id)) { return blah; } } throw new NotFoundException("not found"); } } and expose it. There are many ways to do this, such as by using Jersey's ServletContainer. (web.xml) <servlet> <servlet-name>jersey</servlet-name> <servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>jersey</servlet-name> <url-pattern>/*</url-pattern> </servlet-mapping> Thats all you need to do... pop open your browser and browse to http://localhost/blah/1. By default you will see XML output. If you are using FireFox, install TamperData and change your accept header to application/json to see the JSON output. Obviously there is much more to it, but Jersey makes all that stuff quite easy. Good luck! A: For RESTful web services in Java, also check out the Restlet API which provides a very powerful and flexible abstraction for REST web services (both server and client, in a container or standalone), and also integrates nicely with Spring and JSON. A: As already mentioned, Jersey (JAX-RS impl) is the framework to use; but for basic mapping of Java objects to/from JSON, Tutorial is good. Unlike many alternatives, it does not use strange XML-compatibility conventions but reads and writes clean JSON that directly maps to and from objects. It also has no problems with null (there is difference between missing entry and one having null), empty Lists or Strings (both are distinct from nulls). Jackson works nicely with Jersey as well, either using JAX-RS provider jar, or even just manually. Similarly it's trivially easy to use with plain old servlets; just get input/output stream, call ObjectMapper.readValue() and .writeValue(), and that's about it. A: I have been using jaxws-json, for providing JSON format web services. you can check the project https://jax-ws-commons.dev.java.net/json/. it's a nice project, once you get it up, you'll find out how charming it is.
{ "language": "en", "url": "https://stackoverflow.com/questions/57689", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "22" }
Q: What are the performance characteristics of 'is' reflection in C#? It's shown that 'as' casting is much faster than prefix casting, but what about 'is' reflection? How bad is it? As you can imagine, searching for 'is' on Google isn't terribly effective. A: The way I learned it is that this: if (obj is Foo) { Foo f = (Foo)obj; f.doSomething(); } is slower than this: Foo f = obj as Foo; if (f != null) { f.doSomething(); } Is it slow enough to matter? Probably not, but it's such a simple thing to pay attention for, that you might as well do it. A: "is" is basically equivalent to the "isinst" IL operator -- which that article describes as fast. A: There are a few options: * *The classic cast: Foo foo = (Foo)bar *The as cast operator: Foo foo = bar as Foo *The is test: bool is = bar is Foo * *The classic cast needs to check if bar can be safely cast to Foo (quick), and then actually do it (slower), or throw an exception (really slow). *The as operator needs to check if bar can be cast, then do the cast, or if it cannot be safely cast, then it just returns null. *The is operator just checks if bar can be cast to Foo, and return a boolean. The is test is quick, because it only does the first part of a full casting operation. The as operator is quicker than a classic cast because doesn't throw an exception if the cast fails (which makes it good for situations where you legitimately expect that the cast might fail). If you just need to know if the variable baris a Foo then use the is operator, BUT, if you're going to test if bar is a Foo, and if so, then cast it, then you should use the as operator. Essentially every cast needs to do the equivalent of an is check internally to begin with, in order to ensure that the cast is valid. So if you do an is check followed by a full cast (either an as cast, or with the classic cast operator) you are effectively doing the is check twice, which is a slight extra overhead. A: It should be quick enough to not matter. If you are checking the type of an object enough for it to make a noticeable impact on performance you need to rethink your design
{ "language": "en", "url": "https://stackoverflow.com/questions/57701", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "21" }
Q: Convert XML/HTML Entities into Unicode String in Python I'm doing some web scraping and sites frequently use HTML entities to represent non ascii characters. Does Python have a utility that takes a string with HTML entities and returns a unicode type? For example: I get back: &#x01ce; which represents an "ǎ" with a tone mark. In binary, this is represented as the 16 bit 01ce. I want to convert the html entity into the value u'\u01ce' A: You could find an answer here -- Getting international characters from a web page? EDIT: It seems like BeautifulSoup doesn't convert entities written in hexadecimal form. It can be fixed: import copy, re from BeautifulSoup import BeautifulSoup hexentityMassage = copy.copy(BeautifulSoup.MARKUP_MASSAGE) # replace hexadecimal character reference by decimal one hexentityMassage += [(re.compile('&#x([^;]+);'), lambda m: '&#%d;' % int(m.group(1), 16))] def convert(html): return BeautifulSoup(html, convertEntities=BeautifulSoup.HTML_ENTITIES, markupMassage=hexentityMassage).contents[0].string html = '<html>&#x01ce;&#462;</html>' print repr(convert(html)) # u'\u01ce\u01ce' EDIT: unescape() function mentioned by @dF which uses htmlentitydefs standard module and unichr() might be more appropriate in this case. A: The standard lib’s very own HTMLParser has an undocumented function unescape() which does exactly what you think it does: up to Python 3.4: import HTMLParser h = HTMLParser.HTMLParser() h.unescape('&copy; 2010') # u'\xa9 2010' h.unescape('&#169; 2010') # u'\xa9 2010' Python 3.4+: import html html.unescape('&copy; 2010') # u'\xa9 2010' html.unescape('&#169; 2010') # u'\xa9 2010' A: Python has the htmlentitydefs module, but this doesn't include a function to unescape HTML entities. Python developer Fredrik Lundh (author of elementtree, among other things) has such a function on his website, which works with decimal, hex and named entities: import re, htmlentitydefs ## # Removes HTML or XML character references and entities from a text string. # # @param text The HTML (or XML) source text. # @return The plain text, as a Unicode string, if necessary. def unescape(text): def fixup(m): text = m.group(0) if text[:2] == "&#": # character reference try: if text[:3] == "&#x": return unichr(int(text[3:-1], 16)) else: return unichr(int(text[2:-1])) except ValueError: pass else: # named entity try: text = unichr(htmlentitydefs.name2codepoint[text[1:-1]]) except KeyError: pass return text # leave as is return re.sub("&#?\w+;", fixup, text) A: This is a function which should help you to get it right and convert entities back to utf-8 characters. def unescape(text): """Removes HTML or XML character references and entities from a text string. @param text The HTML (or XML) source text. @return The plain text, as a Unicode string, if necessary. from Fredrik Lundh 2008-01-03: input only unicode characters string. http://effbot.org/zone/re-sub.htm#unescape-html """ def fixup(m): text = m.group(0) if text[:2] == "&#": # character reference try: if text[:3] == "&#x": return unichr(int(text[3:-1], 16)) else: return unichr(int(text[2:-1])) except ValueError: print "Value Error" pass else: # named entity # reescape the reserved characters. try: if text[1:-1] == "amp": text = "&amp;amp;" elif text[1:-1] == "gt": text = "&amp;gt;" elif text[1:-1] == "lt": text = "&amp;lt;" else: print text[1:-1] text = unichr(htmlentitydefs.name2codepoint[text[1:-1]]) except KeyError: print "keyerror" pass return text # leave as is return re.sub("&#?\w+;", fixup, text) A: Not sure why the Stack Overflow thread does not include the ';' in the search/replace (i.e. lambda m: '&#%d*;*') If you don't, BeautifulSoup can barf because the adjacent character can be interpreted as part of the HTML code (i.e. &#39B for &#39Blackout). This worked better for me: import re from BeautifulSoup import BeautifulSoup html_string='<a href="/cgi-bin/article.cgi?f=/c/a/2010/12/13/BA3V1GQ1CI.DTL"title="">&#x27;Blackout in a can; on some shelves despite ban</a>' hexentityMassage = [(re.compile('&#x([^;]+);'), lambda m: '&#%d;' % int(m.group(1), 16))] soup = BeautifulSoup(html_string, convertEntities=BeautifulSoup.HTML_ENTITIES, markupMassage=hexentityMassage) * *The int(m.group(1), 16) converts the number (specified in base-16) format back to an integer. *m.group(0) returns the entire match, m.group(1) returns the regexp capturing group *Basically using markupMessage is the same as: html_string = re.sub('&#x([^;]+);', lambda m: '&#%d;' % int(m.group(1), 16), html_string) A: Use the builtin unichr -- BeautifulSoup isn't necessary: >>> entity = '&#x01ce' >>> unichr(int(entity[3:],16)) u'\u01ce' A: If you are on Python 3.4 or newer, you can simply use the html.unescape: import html s = html.unescape(s) A: An alternative, if you have lxml: >>> import lxml.html >>> lxml.html.fromstring('&#x01ce').text u'\u01ce' A: Another solution is the builtin library xml.sax.saxutils (both for html and xml). However, it will convert only &gt, &amp and &lt. from xml.sax.saxutils import unescape escaped_text = unescape(text_to_escape) A: Here is the Python 3 version of dF's answer: import re import html.entities def unescape(text): """ Removes HTML or XML character references and entities from a text string. :param text: The HTML (or XML) source text. :return: The plain text, as a Unicode string, if necessary. """ def fixup(m): text = m.group(0) if text[:2] == "&#": # character reference try: if text[:3] == "&#x": return chr(int(text[3:-1], 16)) else: return chr(int(text[2:-1])) except ValueError: pass else: # named entity try: text = chr(html.entities.name2codepoint[text[1:-1]]) except KeyError: pass return text # leave as is return re.sub("&#?\w+;", fixup, text) The main changes concern htmlentitydefs that is now html.entities and unichr that is now chr. See this Python 3 porting guide.
{ "language": "en", "url": "https://stackoverflow.com/questions/57708", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "77" }
Q: ASP.NET MVC and IIS 5 What is the best way to get hosting of an ASP.NET MVC application to work on IIS 5 (6 or 7). When I tried to publish my ASP.NET MVC application, all I seemed to get is 404 errors. I've done a bit of googleing and have found a couple of solutions, but neither seem super elegant, and I worry if they will be unusable once I come to use a shared hosting environment for the application. Solution 1 * *Right-click your application virtual directory on inetmgr.exe. *Properties->Virtual Directory Tab-> Configuration. *Add a new mapping extension. The extension should be .*, which will be mapped to the Executable C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\aspnet_isapi.dll, or the appropriate location on your computer (you can simply copy this from the mapping for .aspx files). On the mapping uncheck "check that file exists". *3 X OK and you're good to go. *If you want, you can apply this setting to all your web sites. In step1, click on the "Default Web Site" node instead of your own virtual directory, and in step 2 go to the "Home Directory" tab. The rest is the same. It seems a tad hacky to route everything through ASP.NET. Solutions 2 Edit the MVC routing to contain .mvc in the URL and then follow the steps in solution 1 based around this extension. Edit: The original image link was lost, but here it is from Google's Cache: A: I think either way you'll have to do Solution 1. Consider the HTTP Request pipeline. * *A request comes into IIS. *IIS checks port/host header to see if it has a web site set up to capture requests for that host header/port. *IIS investigates the file extension of the request (.php, .asp, .aspx) and hands it off to an ISAPI that can handle that type of request. Only at this point does ASP.NET (or a PHP runtime) kick in. If IIS does't have that mapping then it'll never hand off the request to the ASP.NET runtime and the request will never reach your code. That's why you need that glob (*) mapping to the ASP.NET ISAPI. ASP.NET MVC framework urls often end with no file extension at all. If you want these requests to get handled by ASP.NET (or some other runtime) you have to map all requests regardless of the file extension to that ISAPI (ie. aspnet_isapi.dll). This is often also done for HttpHandlers that need to serve off media like .jpg, .gif. For the handler to be hit it needs to get mapped to your code even though .jpg isn't a "normal" ASP.NET file extension. HTH, Tyler A: Run: C:\WINDOWS\Microsoft.NET\Framework\v4.0.30319\aspnet_isapi.dll -i This will reset IIS registry settings for aspnet user. Create the virtual directory: 1. Right click on the directory you want to convert * *select Properties * *under Directory, select Create. *under Configuration, select Add. *for Executable insert: C:\WINDOWS\Microsoft.NET\Framework\v4.0.30319\aspnet_isapi.dll for Extension insert: .* * *uncheck “Check that file exists” *under Documents add entry point file, ie: Default.htm, index.htm, Global.asax *under Directory Settings * *select Edit... *select Anonymous access *uncheck Allow IIS to control password *uncheck Basic authentication *uncheck Integrated Windows authentication *under ASP.NET, make sure version = v4.0.30319 TAKE NOTE of User Name ie: IUSR_AVSJ82S Set sharing permission of physical directory: * *In windows explorer, go to the physical directory that was converted to a virtual directory. Right click the directory name *select properties *under security tab, select Add *enter the IIS User name ie: IUSR_AVSJ82S click check name. *click OK *set permissions to Read and Write. A: Answer is here If *.mvc extension is not registered to the hosting , it will give 404 exception. The working way of hosting MVC apps in that case is to modify global.asax routing caluse in the following way. routes.Add(new Route("{controller}.mvc.aspx/{action}", new MvcRouteHandler()) { Defaults = new RouteValueDictionary (new{ controller = "YourController"} ) }); In this way all your controller request will end up in *.mvc.aspx, which is recognized by your hosting. And as the MVC dlls are copied into your local bin , no special setttings need to be done for it. A: Have you tried adding .aspx to the end of the controller name? It worked for Stack Overflow question Where can I get ASP.NET MVC hosting?. A: FYI:On server 2003 (developing an app that had to connect to the RPS), it didnt' allow me to add the extension .*, I used the alternate solution modifying the route clause, and that worked.
{ "language": "en", "url": "https://stackoverflow.com/questions/57712", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "25" }
Q: Anyone using the Entity Framework *Well*? Has anyone actually shipped an Entity Framework project that does O/R mapping into conceptual classes that are quite different from the tables in the datastore? I mean collapse junction (M:M) tables into other entities to form Conceptual classes that exist in the business domain but are organized as multiple tables in the datastore. All the examples that I see on the MSDN have little use of inheritance, collapsing junction tables into other entities, or collapsing lookup tables into entities. I'd love to hear of or see examples of the below which support all the CRUD operations you would typically expect to do on a business object.: * *Vehicle table and a Color table. A Color can appear in many Vehicles (1:M). They form the conceptual class UsedCar which has the property Color. *Doctor, DoctorPatients, and Patients tables (form a many to many). Doctors have many Patients, Patients can have many Doctors (M:M). Map out the two conceptual classes Doctor (which has a Patients collection) and Patients (which has a Doctors collection). Anyone seen/done this with CSDL AND SSDL in the Entity Framework? The CSDL is no good if it doesn't actaully map to anything! A: I attempted to use the Entity Framework on an existing project (~60 tables, 3 with inheritance) just to see what it was all about. My experience boiled down to: The designer surface is kludgy. The mapping isn’t intuitive and someone must have thought that having several tool windows open at the same time is acceptable. It took a long time to manually create an object and map the right fields – then it was still odd talking to it from the code. While having something handling the database communication is essential, I feel that handing the control over to EF was far more of a fight than doing it manually. Sometimes the designer just doesn’t load until you restart Visual Studio. I’m sure it’s just a bug but restarting VS is annoying. All your work ends up in a single file, I’d hate to merge multiple developer editions. The resultant SQL (watched via the Profiler) wasn’t very good. I didn’t really delve into looking why, but you’d be pressed to write something worse on a first attempt. A: Entity Framework - Vote of no confidence That's all I have to say... A: You mean like this? <edmx:ConceptualModels> <Schema xmlns="http://schemas.microsoft.com/ado/2006/04/edm" Namespace="Model1" Alias="Self"> <EntityContainer Name="Model1Container" > <EntitySet Name="ColorSet" EntityType="Model1.Color" /> <EntitySet Name="DoctorSet" EntityType="Model1.Doctor" /> <EntitySet Name="PatientSet" EntityType="Model1.Patient" /> <EntitySet Name="UsedCarSet" EntityType="Model1.UsedCar" /> <AssociationSet Name="Vehicle_Color" Association="Model1.Vehicle_Color"> <End Role="Colors" EntitySet="ColorSet" /> <End Role="Vehicles" EntitySet="UsedCarSet" /></AssociationSet> <AssociationSet Name="DoctorPatient" Association="Model1.DoctorPatient"> <End Role="Doctor" EntitySet="DoctorSet" /> <End Role="Patient" EntitySet="PatientSet" /></AssociationSet> </EntityContainer> <EntityType Name="Color"> <Key> <PropertyRef Name="ColorID" /></Key> <Property Name="ColorID" Type="Int32" Nullable="false" /> <NavigationProperty Name="Vehicles" Relationship="Model1.Vehicle_Color" FromRole="Colors" ToRole="Vehicles" /></EntityType> <EntityType Name="Doctor"> <Key> <PropertyRef Name="DoctorID" /></Key> <Property Name="DoctorID" Type="Int32" Nullable="false" /> <NavigationProperty Name="Patients" Relationship="Model1.DoctorPatient" FromRole="Doctor" ToRole="Patient" /></EntityType> <EntityType Name="Patient"> <Key> <PropertyRef Name="PatientID" /></Key> <Property Name="PatientID" Type="Int32" Nullable="false" /> <NavigationProperty Name="Doctors" Relationship="Model1.DoctorPatient" FromRole="Patient" ToRole="Doctor" /> </EntityType> <EntityType Name="UsedCar"> <Key> <PropertyRef Name="VehicleID" /></Key> <Property Name="VehicleID" Type="Int32" Nullable="false" /> <NavigationProperty Name="Color" Relationship="Model1.Vehicle_Color" FromRole="Vehicles" ToRole="Colors" /></EntityType> <Association Name="Vehicle_Color"> <End Type="Model1.Color" Role="Colors" Multiplicity="1" /> <End Type="Model1.UsedCar" Role="Vehicles" Multiplicity="*" /></Association> <Association Name="DoctorPatient"> <End Type="Model1.Doctor" Role="Doctor" Multiplicity="*" /> <End Type="Model1.Patient" Role="Patient" Multiplicity="*" /></Association> </Schema> </edmx:ConceptualModels>
{ "language": "en", "url": "https://stackoverflow.com/questions/57718", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "12" }
Q: How can I display just a portion of an image in HTML/CSS? Let's say I want a way to display just the the center 50x50px of an image that's 250x250px in HTML. How can I do that. Also, is there a way to do this for css:url() references? I'm aware of clip in CSS, but that seems to only work when used with absolute positioning. A: Another alternative is the following, although not the cleanest as it assumes the image to be the only element in a container, such as in this case: <header class="siteHeader"> <img src="img" class="siteLogo" /> </header> You can then use the container as a mask with the desired size, and surround the image with a negative margin to move it into the right position: .siteHeader{ width: 50px; height: 50px; overflow: hidden; } .siteHeader .siteLogo{ margin: -100px; } Demo can be seen in this JSFiddle. Only seems to work in IE>9, and probably all significant versions of all other browsers. A: Adjust the background-position to move background images in different positions of the div: div { background-image: url('image url'); background-position: 0 -250px; } A: As mentioned in the question, there is the clip css property, although it does require that the element being clipped is position: absolute; (which is a shame): .container { position: relative; } #clip { position: absolute; clip: rect(0, 100px, 200px, 0); /* clip: shape(top, right, bottom, left); NB 'rect' is the only available option */ } <div class="container"> <img src="http://lorempixel.com/200/200/nightlife/3" /> </div> <div class="container"> <img id="clip" src="http://lorempixel.com/200/200/nightlife/3" /> </div> JS Fiddle demo, for experimentation. To supplement the original answer – somewhat belatedly – I'm editing to show the use of clip-path, which has replaced the now-deprecated clip property. The clip-path property allows a range of options (more-so than the original clip), of: * *inset — rectangular/cuboid shapes, defined with four values as 'distance-from' (top right bottom left). *circle — circle(diameter at x-coordinate y-coordinate). *ellipse — ellipse(x-axis-length y-axis-length at x-coordinate y-coordinate). *polygon — defined by a series of x/y coordinates in relation to the element's origin of the top-left corner. As the path is closed automatically the realistic minimum number of points for a polygon should be three, any fewer (two) is a line or (one) is a point: polygon(x-coordinate1 y-coordinate1, x-coordinate2 y-coordinate2, x-coordinate3 y-coordinate3, [etc...]). *url — this can be either a local URL (using a CSS id-selector) or the URL of an external file (using a file-path) to identify an SVG, though I've not experimented with either (as yet), so I can offer no insight as to their benefit or caveat. div.container { display: inline-block; } #rectangular { -webkit-clip-path: inset(30px 10px 30px 10px); clip-path: inset(30px 10px 30px 10px); } #circle { -webkit-clip-path: circle(75px at 50% 50%); clip-path: circle(75px at 50% 50%) } #ellipse { -webkit-clip-path: ellipse(75px 50px at 50% 50%); clip-path: ellipse(75px 50px at 50% 50%); } #polygon { -webkit-clip-path: polygon(50% 0, 100% 38%, 81% 100%, 19% 100%, 0 38%); clip-path: polygon(50% 0, 100% 38%, 81% 100%, 19% 100%, 0 38%); } <div class="container"> <img id="control" src="http://lorempixel.com/150/150/people/1" /> </div> <div class="container"> <img id="rectangular" src="http://lorempixel.com/150/150/people/1" /> </div> <div class="container"> <img id="circle" src="http://lorempixel.com/150/150/people/1" /> </div> <div class="container"> <img id="ellipse" src="http://lorempixel.com/150/150/people/1" /> </div> <div class="container"> <img id="polygon" src="http://lorempixel.com/150/150/people/1" /> </div> JS Fiddle demo, for experimentation. References: * *clip — note: deprecated. *clip-path (MDN). *clip-path (W3C). A: One way to do it is to set the image you want to display as a background in a container (td, div, span etc) and then adjust background-position to get the sprite you want. A: div{ width: 50px; height: 50px; background: no-repeat -100px -100px/500% url("https://qce.quantum.ieee.org/2022/wp-content/uploads/sites/6/2022/02/[email protected]") }; <html> <head> </head> <body> <div></div> </body> </html>
{ "language": "en", "url": "https://stackoverflow.com/questions/57725", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "174" }
Q: Best build process solution to manage build versions I run a rather complex project with several independent applications. These use however a couple of shared components. So I have a source tree looking something like the below. * *My Project * *Application A *Shared1 *Shared2 *Application B *Application C All applications have their own MSBuild script that builds the project and all the shared resources it needs. I also run these builds on a CruiseControl controlled continuous integration build server. When the applications are deployed they are deployed on several servers to distribute load. This means that it’s extremely important to keep track of what build/revision is deployed on each of the different servers (we need to have the current version in the DLL version, for example “1.0.0.68”). It’s equally important to be able to recreate a revision/build that been built to be able to roll back if something didn’t work out as intended (o yes, that happends ...). Today we’re using SourceSafe for source control but that possible to change if we could present good reasons for that (SS it’s actually working ok for us so far). Another principle that we try to follow is that it’s only code that been build and tested by the integration server that we deploy further. "CrusieControl Build Labels" solution We had several ideas on solving the above. The first was to have the continuous integration server build and locally deploy the project and test it (it does that now). As you probably know a successful build in CruiseControl generates a build label and I guess we somehow could use that to set the DLL version of our executables (so build label 35 would create a DLL like “1.0.0.35” )? The idea was also to use this build label to label the complete source tree. Then we probably could check out by that label and recreate the build later on. The reason for labeling the complete tree is to include not only the actual application code (that’s in one place in the source tree) but also all the shared items (that’s in different places in the tree). So a successful build of “Application A” would label to whole tree with label “ApplicationA35” for example. There might however be an issue when trying to recreate this build and setting the DLL version before deploying as we then don’t have access to the CruiseControl generated build label anymore. If all CrusieControl build labels were unique for all the projects we could use only the number for labeling but that’s not the case (both application A and B could at the same time be on build 35) so we have to include the application name in the label. Hence SourceSafe label “Application35”. How can I then recreate build 34 and set 1.0.0.34 to the DLL version numbers once we built build 35? "Revision number" solution Someone told me that Subversion for example creates a revision number for the entire source tree on every check in – is this the case? Has SourceSafe something similar? If this is correct the idea is then to grab that revision number when getting latest and build on the CruiseControl server. The revision number could then be used to set the DLL version number (to for example “1.0.0.5678”). I guess we could then get this specific revision for the Subversion if needed and that then would include that application and all the shared items to be able to recreate a specific version from the past. Would that work and could this also be achived using SourceSafe? Summarize So the two main requirements are: * *Be able to track build/revision number of the build and deployed DLL. *Be able to rebuild a past revision/build, set the old build/revision number on the executables of that build (to comply with requirement 1). So how would you solve this? What would be your preferred approach and how would you solve it (or do you have a totally different idea?)? **Pleased give detailed answers. ** Bonus question What are the difference between a revision number and a build number and when would one really need both? A: Your scheme is sound and achievable in VSS (although I would suggest you consider an alternative, VSS is really an outdated product). For your "CI" Build - you would do the Versioning take a look at MSBuild Community Tasks Project which has a "Version" tasks. Typically you will have a "Version.txt" in your source tree and the MSBuild task will increment the "Release" number while the developers control the Major.Minor.Release.Revision numbers (that's how a client of mine wanted it). You can use revision if you prefer. You then would have a "FileUpdate" tasks to edit the AssemblyInfo.cs file with that version, and your EXE's and "DLL's" will have the desired version. Finally the VSSLabel task will label all your files appropriately. For your "Rebuild" Build - you would modify your "Get" to get files from that Label, obviously not execute the "Version" task (as you are SELECTING a version to build) and then the FileUpdate tasks would use that version number. Bonus question: These are all "how you want to use them" - I would use build number for, well the build number, that is what I'd increment. If you are using CI you'll have very many builds - the vast majority with no intention of ever deploying anywhere. The major and minor are self evident - but revision I've always used for a "Hotfix" indicator. I intend to have a "1.3" release - which would in reality be a product with say 1.3.1234.0 version. While working on 1.4 - I find a bug - and need a hot fix as 1.3.2400.1. Then when 1.4 is ready - it would be say 1.4.3500.0 A: I need more space than responding as comments directly allows... Thanks! Good answer! What would be the difference, what would be better solving this using SubVersion for example?Richard Hallgren (15 hours ago) The problems with VSS have nothing to do with this example (although the "Labeling" feature I believe is implemented inefficiently...) Here are a few of the issues with VSS 1) Branching is basically impossible 2) Shared checkout is generally not used (I know of a few people who have had success with it) 3) performance is very poor - it is exteremly "chatty" 4) unless you have a very small repository - it is completely unreliable, to the point for most shops it's a ticking timebomb. For 4 - the problem is that VSS is implemented by the entire repository being represented as "flat files" in the file system. When the repository gets over a certain size (I believe 4GB but I'm not confident in that figure) you get a chance for "corruption". As the size increases the chances of corruption grow until it becomes an almost certainty. So take a look at your repository size - and if you are getting into the Gigabytes - I'd strongly recommend you begin planning on replacing VSS. Regardless - a google of "VSS Sucks" gives 30K hits... I think if you did start using an alterantive - you will realize it's well worth the effort. A: * *Have CC.net label the successful builds *have each project in the solution link to a common solutioninfo.cs file which contains assembly and file version attributes (remove from each projects assemblyinfo.cs) *Before the build have cruise control run an msbuild regex replace (from msbuild community tasks) to update the version information using the cc.net build label (passed in as a parameter to the msbuild task) *build the solution, run tests, fx cop etc *Optionally revert the solution info file The result is that all assemblies in the cc.net published build have the same version numbers which conform to a label in the source code repository A: UppercuT can do all of this with a custom packaging task to split the applications up. And to get the version number of the source, you might think about Subversion. It's also insanely easy to get started. http://code.google.com/p/uppercut/ Some good explanations here: UppercuT
{ "language": "en", "url": "https://stackoverflow.com/questions/57730", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Sporadically Slow Calls From .NET Application To SQL Server I have a table in SQL Server that I inherited from a legacy system thats still in production that is structured according to the code below. I created a SP to query the table as described in the code below the table create statement. My issue is that, sporadically, calls from .NET to this SP both through the Enterprise Library 4 and through a DataReader object are slow. The SP is called through a loop structure in the Data Layer that specifies the params that go into the SP for the purpose of populating user objects. It's also important to mention that a slow call will not take place on every pass the loop structure. It will generally be fine for most of a day or more, and then start presenting which makes it extremely hard to debug. The table in question contains about 5 million rows. The calls that are slow, for instance, will take as long as 10 seconds, while the calls that are fast will take 0 to 10 milliseconds on average. I checked for locking/blocking transactions during the slow calls, none were found. I created some custom performance counters in the data layer to monitor call times. Essentially, when performance is bad, it's really bad for that one call. But when it's good, it's really good. I've been able to recreate the issue on a few different developer machines, but not on our development and staging database servers, which of course have beefier hardware. Generally, the problem is resolved through restarting the SQL server services, but not always. There are indexes on the table for the fields I'm querying, but there are more indexes than I would like. However, I'm hesitant to remove any or toy with the indexes due to the impact it may have on the legacy system. Has anyone experienced a problem like this before, or do you have a recommendation to remedy it? CREATE TABLE [dbo].[product_performance_quarterly]( [performance_id] [int] IDENTITY(1,1) NOT FOR REPLICATION NOT NULL, [product_id] [int] NULL, [month] [int] NULL, [year] [int] NULL, [performance] [decimal](18, 6) NULL, [gross_or_net] [char](15) NULL, [vehicle_type] [char](30) NULL, [quarterly_or_monthly] [char](1) NULL, [stamp] [datetime] NULL CONSTRAINT [DF_product_performance_quarterly_stamp] DEFAULT (getdate()), [eA_loaded] [nchar](10) NULL, [vehicle_type_id] [int] NULL, [yearmonth] [char](6) NULL, [gross_or_net_id] [tinyint] NULL, CONSTRAINT [PK_product_performance_quarterly_4_19_04] PRIMARY KEY CLUSTERED ( [performance_id] ASC )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 80) ON [PRIMARY] ) ON [PRIMARY] GO SET ANSI_PADDING OFF GO ALTER TABLE [dbo].[product_performance_quarterly] WITH NOCHECK ADD CONSTRAINT [FK_product_performance_quarterlyProduct_id] FOREIGN KEY([product_id]) REFERENCES [dbo].[products] ([product_id]) GO ALTER TABLE [dbo].[product_performance_quarterly] CHECK CONSTRAINT [FK_product_performance_quarterlyProduct_id] CREATE PROCEDURE [eA.Analytics.Calculations].[USP.GetCalculationData] ( @PRODUCTID INT, --products.product_id @BEGINYEAR INT, --year to begin retrieving performance data @BEGINMONTH INT, --month to begin retrieving performance data @ENDYEAR INT, --year to end retrieving performance data @ENDMONTH INT, --month to end retrieving performance data @QUARTERLYORMONTHLY VARCHAR(1), --do you want quarterly or monthly data? @VEHICLETYPEID INT, --what product vehicle type are you looking for? @GROSSORNETID INT --are your looking gross of fees data or net of fees data? ) AS BEGIN SET NOCOUNT ON DECLARE @STARTDATE VARCHAR(6), @ENDDATE VARCHAR(6), @vBEGINMONTH VARCHAR(2), @vENDMONTH VARCHAR(2) IF LEN(@BEGINMONTH) = 1 SET @vBEGINMONTH = '0' + CAST(@BEGINMONTH AS VARCHAR(1)) ELSE SET @vBEGINMONTH = @BEGINMONTH IF LEN(@ENDMONTH) = 1 SET @vENDMONTH = '0' + CAST(@ENDMONTH AS VARCHAR(1)) ELSE SET @vENDMONTH = @ENDMONTH SET @STARTDATE = CAST(@BEGINYEAR AS VARCHAR(4)) + @vBEGINMONTH SET @ENDDATE = CAST(@ENDYEAR AS VARCHAR(4)) + @vENDMONTH --because null values for gross_or_net_id and vehicle_type_id are represented in --multiple ways (true null, empty string, or 0) in the PPQ table, need to account for all possible variations if --a -1 is passed in from the .NET code, which represents an enumerated value that --indicates that the value(s) should be true null. IF @VEHICLETYPEID = '-1' AND @GROSSORNETID = '-1' SELECT PPQ.YEARMONTH, PPQ.PERFORMANCE FROM PRODUCT_PERFORMANCE_QUARTERLY PPQ WITH (NOLOCK) WHERE (PPQ.PRODUCT_ID = @PRODUCTID) AND (PPQ.YEARMONTH BETWEEN @STARTDATE AND @ENDDATE) AND (PPQ.QUARTERLY_OR_MONTHLY = @QUARTERLYORMONTHLY) AND (PPQ.VEHICLE_TYPE_ID IS NULL OR PPQ.VEHICLE_TYPE_ID = '0' OR PPQ.VEHICLE_TYPE_ID = '') AND (PPQ.GROSS_OR_NET_ID IS NULL OR PPQ.GROSS_OR_NET_ID = '0' OR PPQ.GROSS_OR_NET_ID = '') ORDER BY PPQ.YEARMONTH ASC IF @VEHICLETYPEID <> '-1' AND @GROSSORNETID <> '-1' SELECT PPQ.YEARMONTH, PPQ.PERFORMANCE FROM PRODUCT_PERFORMANCE_QUARTERLY PPQ WITH (NOLOCK) WHERE (PPQ.PRODUCT_ID = @PRODUCTID) AND (PPQ.YEARMONTH BETWEEN @STARTDATE AND @ENDDATE) AND (PPQ.QUARTERLY_OR_MONTHLY = @QUARTERLYORMONTHLY) AND (PPQ.VEHICLE_TYPE_ID = @VEHICLETYPEID ) AND (PPQ.GROSS_OR_NET_ID = @GROSSORNETID) ORDER BY PPQ.YEARMONTH ASC IF @VEHICLETYPEID = '-1' AND @GROSSORNETID <> '-1' SELECT PPQ.YEARMONTH, PPQ.PERFORMANCE FROM PRODUCT_PERFORMANCE_QUARTERLY PPQ WITH (NOLOCK) WHERE (PPQ.PRODUCT_ID = @PRODUCTID) AND (PPQ.YEARMONTH BETWEEN @STARTDATE AND @ENDDATE) AND (PPQ.QUARTERLY_OR_MONTHLY = @QUARTERLYORMONTHLY) AND (PPQ.VEHICLE_TYPE_ID IS NULL OR PPQ.VEHICLE_TYPE_ID = '0' OR PPQ.VEHICLE_TYPE_ID = '') AND (PPQ.GROSS_OR_NET_ID = @GROSSORNETID) ORDER BY PPQ.YEARMONTH ASC IF @VEHICLETYPEID <> '-1' AND @GROSSORNETID = '-1' SELECT PPQ.YEARMONTH, PPQ.PERFORMANCE FROM PRODUCT_PERFORMANCE_QUARTERLY PPQ WITH (NOLOCK) WHERE (PPQ.PRODUCT_ID = @PRODUCTID) AND (PPQ.YEARMONTH BETWEEN @STARTDATE AND @ENDDATE) AND (PPQ.QUARTERLY_OR_MONTHLY = @QUARTERLYORMONTHLY) AND (PPQ.VEHICLE_TYPE_ID = @VEHICLETYPEID) AND (PPQ.GROSS_OR_NET_ID IS NULL OR PPQ.GROSS_OR_NET_ID = '0' OR PPQ.GROSS_OR_NET_ID = '') ORDER BY PPQ.YEARMONTH ASC END A: I have seen this happen with indexes that were out of date. It could also be a parameter sniffing problem, where a different query plan is being used for different parameters that come in to the stored procedure. You should capture the parameters of the slow calls and see if they are the same ones each time it runs slow. You might also try running the tuning wizard and see if it recommends any indexes. You don't want to worry about having too many indexes until you can prove that updates and inserts are happening too slow (time needed to modify the index plus locking/contention), or you are running out of disk space for them. A: Sounds like another query is running in the background that has locked the table and your innocent query is simply waiting for it to finish A: A strange, edge case but I encountered it recently. If the queries run longer in the application than they do when run from within Management Studio, you may want to check to make sure that Arithabort is set off. The connection parameters used by Management Studio are different from the ones used by .NET. A: It seems like it's one of two things - either the parameters on the slow calls are different in some way than on the fast calls, and they're not able to use the indexes as well, or there's some type of locking contention that's holding you up. You say you've checked for blocking locks while a particular process is hung, and saw none - that would suggest that it's the first one. However - are you sure that your staging server (that you can't reproduce this error on) and the development servers (that you can reproduce it on) have the same database configuration? For example, maybe "READ COMMITTED SNAPSHOT" is enabled in production, but not in development, which would cause read contention issues to disappear in production. If it's a difference in parameters, I'd suggest using SQL Profiler to watch the transactions and capture a few - some slow ones and some faster ones, and then, in a Management Studio window, replace the variables in that SP above with the parameter values and then get an execution plan by pressing "Control-L". This will tell you exactly how SQL Server expects to process your query, and you can compare the execution plan for different parameter combination to see if there's a difference with one set, and work from there to optimize it. Good luck!
{ "language": "en", "url": "https://stackoverflow.com/questions/57731", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: What is the best workaround for the ASP.NET forms authentication timeout when using wildcard mapping? My team is working on a crappy old website and most of the pages are still ASP classic. However, we've recently migrated to forms authentication using ASP.NET and wildcard mapping. Everything works surprisingly well except for one thing: logged in users are timing out too quickly. After looking in the logs it appears people are timing out exactly after 20 minutes (which is the specified timeout due to inactivity). So, our hypothesis is that the ASP classic pages are not tripping whatever mechanism in the forms authentication framework that resets the inactivity timer. I've googled around and even read the wildcard mapping post by the Great Gu but still can't find anyone else who is having this problem. So, 1) Have you ever seen this problem? and 2) What's the best workaround? (other than manually placing a hidden frame in every janky ASP page that loads a dumb .NET page in the background) Update: slidingExpiration is set to true Also: We can't use perpetual sessions because we need the application to time out after 20 minutes of inactivity. Also, this terrible site was written so that the interface is usually stored in the page. There's no simple piece of interface code I could slip the JavaScript into. We tried to put some js into an include file that was called by about 80% of our pages but it's caused some esoteric problems with file download buffers so we may have to try a different tack. Thanks. A: Create a perpetual session. Essentially you end up emitting some JavaScript and an image tag in your master page or navigation users controls (whatever you're using for consistent navigation). This JavaScript on some interval changes the source of the image tag to an http handler endpoint (some .aspx, .ashx) which returns a 1x1 pix clear gif as a response for the image. The constant request ensures that idle pages will keep the session alive. As long as a browser window is open to your page your ASP.NET session will never time out. Often the JavaScript will tack on a random number to the request so that the browser doesn't cache the request. A decent walkthrough is available here. A: I am assuming that you have manually created the cookie, in which case your timeout value in code is probably overriding your timeout value in the configuration. First, if possible (which it probably isn't) don't create the cookie manually, it will save you from not only this headache but dozens of others. If you must manually create the cookie, make sure that the timeout you are using is actually reading the timeout value that you have set in the configuration file and that sliding expiration is set to true (which you have said it was). That said, we still have ocassional strange timeout problems when the cookies are manually created. Where I work we implemented a solution which allowed the cookies to be created automatically and timeouts were no longer a problem; however, it did create other issues and we were forced to switch back.
{ "language": "en", "url": "https://stackoverflow.com/questions/57739", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Setting up Team foundation server I have to setup team foundation server for a company, something that I don't have any experience in. The company will have about 5 or so developers that will be using it. Is this a big task or something that is fairly easy to do (with instructions)? Any helpful tutorials that you can recommend? Any recommendations on server specs for a team of 5-10? A: Disregard the "Cliff's Note" link - it's for VSTS 2005. There's no reason to install an old version - the installer (and everything else about the product) is MUCH improved with VSTS2008. Also make sure you install SP1 - it's not just bug fixes but some MAJOR enhancements. Instructions for install are here: Team Foundation VSTS2008 Install Guide make sure you closely follow the recommendations for the Accounts necessary for install. Blog post with recommendations for server specs The link that Espo posted is excellent walkthroughs for configuring TFS after you get it installed. TFS 2008 SP1 Download Also you will want the following TFS 2008 Power Tools in particular there is a "Team Foundation Server Best Practices Analyzer" which you can run against the server before the install to make sure everything is patched correctly etc (and afterwards to make sure the install went properly). It will require Windows Powershell installed on the server as pre-req. Also you will want Team System Web Access 2008 SP1 - (formerly Team Plain) which will allow you to access the features of TFS as a web application. A: Here is a great guide for setting up TFS 2012 on Windows 8 machine with Visual Studio 2012 http://www.codeproject.com/Articles/426135/Team-Foundation-Server-2012-RC-Install-Configure Here's TFS 2012 on Windows Server 2012 with SQL Server 2012 http://blog.hinshelwood.com/installing-tfs-2012-on-server-2012-with-sql-2012/ A: Your first step should be to download the latest TFS Installation Guide (TFSInstall.chm) from here: http://www.microsoft.com/downloads/details.aspx?FamilyID=FF12844F-398C-4FE9-8B0D-9E84181D9923&displaylang=en You should use TFS 2008 SP1, since it is the latest release and includes many new features and performance improvements. If you are planning on installing with Windows 2008 & SQL 2008, you will need to "integrate" the TFS 2008 SP1 into the installation disc. Instructions are included in the TFSInstall.chm, but Martin Woodward also has a walkthrough on his blog: http://www.woodwardweb.com/vsts/creating_a_tfs.html (This isn't required for SQL 2005 SP2 + Windows 2003) The install guide also has hardware recommendations. For a team of your size, you should also consider running your TFS instance as a Virtual Machine. This will allow you to up-size and move your installation around more easily at a later date. TFS is supported on the Hyper-V virtualization platform: http://blogs.msdn.com/granth/archive/2008/06/27/team-foundation-server-and-hyper-v-virtualization.aspx And if you need help along the way, you have three options: * *Call up MS product support ($$, but you will get an answer) *Post on the official Team Foundation Server - Setup forums: http://forums.microsoft.com/MSDN/ShowForum.aspx?ForumID=68&SiteID=1 *Sign up to the http://OzTFS.com/ mailing list. The people on this list are pretty good at responding to questions almost instantaneously. It's also a great list to join if you just want to "watch" what's happening. A: See the link below for a condensed walkthrough: Cliff's Notes for a Team System Install A: VSTS2005 was quite challenging to install and configure correctly. I have heard 2008 is MUCH better, but have yet to try it yet. Be prepared to spend a fair bit of time on this and read everything before starting. However, don't loose heart, TFS is well worth the effort!!
{ "language": "en", "url": "https://stackoverflow.com/questions/57747", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "25" }
Q: Emacs query-replace with textual transformation I want to find any text in a file that matches a regexp of the form t[A-Z]u (i.e., a match t followed by a capital letter and another match u, and transform the matched text so that the capital letter is lowercase. For example, for the regexp x[A-Z]y xAy becomes xay and xZy becomes xzy Emacs' query-replace function allows back-references, but AFAIK not the transformation of the matched text. Is there a built-in function that does this? Does anybody have a short Elisp function I could use? UPDATE @Marcel Levy has it: \, in a replacement expression introduces an (arbitrary?) Elisp expression. E.g., the solution to the above is M-x replace-regexp <RET> x\([A-Z]\)z <RET> x\,(downcase \1)z A: It looks like Steve Yegge actually already posted the answer to this a few years back: "Shiny and New: Emacs 22." Scroll down to "Changing Case in Replacement Strings" and you'll see his example code using the replace-regexp function. The general answer is that you use "\," to call any lisp expression as part of the replacement string, as in \,(capitalize \1). Reading the help text, it looks like it's only in interactive mode, but that seems like the one place where this would be most necessary. A: An alternative to qrr in this case is recording a macro and replaying it. (isearch-forward-regexp, select the character, downcase-region.) I find on the fly macros easier, since you get immediate feedback if your regexp is wrong. A: I'd do this with a macro as well, but only because executing code from within a replacement string for a regular expression is very unintuitive to me. If you're writing a batch script or something that needs to go very fast, \, is certainly the way to go.
{ "language": "en", "url": "https://stackoverflow.com/questions/57751", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "9" }
Q: Why does Vista not allow creation of shortcuts to "Programs" on a NonAdmin account? Not supposed to install apps from NonAdmin account? I'm working on an installer (using Wise Installer, older version from like 1999). I'm creating a shortcut in the Programs group to an EXE. I'm also creating a shortcut on the Desktop. If the install is run from an Admin account, then I create the shortcut on the Common Desktop and Common Program Group (i.e., read from the HKEY_LOCAL_MACHINE\Explorer\Shellfor All Users). If it's installed from a NonAdmin account, then I install to the HKEY_CURRENT_USER's desktop and Program Group. Behavior Install on: XP NonAdmin - Desktop and Program Shortcuts install OK. Vista Admin - Desktop & Program Shortcuts install OK. Vista Non-Admin, UAC off- Desktop shortcut installs, but Program Shortcut does not. However, the Program group folder they're supposed to be installed to does get created. At the end of the install, I launch the Program Group that has the shorcut. It launches in all of the above. I can manually drag a shortcut into that folder and it works just fine. I'm bloody baffled. I've tried installing some other commercial apps (Opera, Foxit, FireFox) Only FireFox will install under NonAdmin (and only if you select something other than Program Files, which I was aware is off limits to nonAdmin acounts). And FF doesn't install an Uninstall Icon nor Uninstall support from the Remove Programs. I tried installing IE 7 and it requires Admin to install. It won't even install with temporarily elevated Admin. Perhaps the idea is that you're not supposed to install software in Vista from a NonAdmin account? A: Vista does some nifty transparent redirection to provide backwards compatibility with non-vista applications. Try installing to the All Users location as a non-admin, and Vista should transparently put your shortcuts somewhere unique to that user. A: I had a permissions issue with an installer I created when users started installing on Vista. What solved my problem was renaming the installer to install.exe (or setup.exe). -Dave
{ "language": "en", "url": "https://stackoverflow.com/questions/57759", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Step-By-Step ASP.NET Automated Build/Deploy Seems like there are so many different ways of automating one's build/deployment that it becomes difficult to parse through all the different scenarios that people support in tutorials on the web. So I wanted to present the question to the stackoverflow crowd ... what would be the best way to set up an automated build and deployment system using the following configuration: * *Visual Studio 2008 *Web Application Project *CruiseControl.NET One of the first things I tried was to have CCnet automatically zip the output and copy it to the server, but then that requires manual work to unzip at the destination. However, if we try to copy all the files individually, then it could potentially take a long time if it's a large application (build server lives outside of the datacenter in our office ... I know). Also of particular interest is how we would support multiple environments as we have dev, qa, uat, and then of course prod. MSDeploy seems really interesting, but unless I'm interpreting the literature incorrectly, doesn't help in the scenario of deploying from the output of a build server. If anything, it seems like it'll be useful in deploying one build across a build farm ... but even for deploying from one environment to another, one would have to manually change config settings and web service URLs, etc. A: You might be interested in MSDeploy. Here's a Scott Hanselman post on this. It's only available as a technical preview at the moment (September 2008) but is worth evaluating against your requirements. A: There is another new build tool (a very intelligent wrapper) called NUBuild. Its lightweight, open source and extremely easy to setup and provides almost no-touch maintenance. I really like this new tool and we have made it standard tool for our continuous build and integration process of our projects (we have about 400 projects across 75 developers). Try it out. http://nubuild.codeplex.com/ * *Easy to use command line interface *Ability to target all .Net framework version i.e. 1.1, 2.0, 3.0 and 3.5 *Supports XML based configuration *Supports both project and file references *Automatically generates the “complete ordered build list” for a given project – No touch maintenance. *Ability to detect and display circular dependencies *Perform parallel build - automatically decides which of the projects in the generated build list can be built independently. *Ability to handle proxy assemblies *Provides visual clue to the build process e.g. showing “% completed”, “current status” etc. *Generates detailed execution log both in XML and text format *Easily integrated with Cruise-Control.Net continuous integration system *Can use custom logger like XMLLogger when targeting 2.0 + version *Ability to parse error logs *Ability to deploy built assemblies to user specified location *Ability to synchronize source code with source-control system *Version management capability A: Do you have the ability to run commands remotely? The PsExec utility from Systinternals would let run a command line unzip program on the remote machine. If you have a script that copies the build as a .zip file to the remote site, you would just need one more line for the PsExec call to unzip the files. A: I recently spent a few days working on automating deployments at my company. We use a combination of CruiseControl, NAnt, MSBuild to generate a release version of the app. Then a separate script uses MSDeploy and XCopy to backup the live site and transfer the new files over. Our solution is briefly described in an answer to this question Automate Deployment for Web Applications? A: I had a related question about getting a deployable set of files from an automated build. I found Web Deployment Projects (links and all in the old question) did what I needed - they're a VS and MSBuild add-on. A: This is a common problem (and I wish I had read it sooner) for all development, not just ASP.NET. Being one of its developers, my team naturally uses BuildMaster internally for the entire release process, and for most scenarios it's free. Within the tool, we are able to perform all the standard CI builds to create artifacts and then set up an automation process to deploy these artifacts to any one of the 40+ servers we have internally or externally hosted, depending on the specific application or environment. Since you specifically mentioned deployment to different testing environments, this is a fundamental aspect of the tool. The idea is to model the environment workflow (e.g. Integration -> QA -> Production) you already have in place and essentially promote a build all the way from source control to production. Most times, it's as simple as adding a deployment action that deploys an artifact to the environment, other times it can be much more complex. You also casually mentioned configuration file changes are part of deployment, which is another built-in component to BuildMaster. The idea we had was to use the tool itself as the central hub for all configuration files and deployments, thus ensuring the latest changes are applied automatically with a simple "deploy configuration files" action in your deployment plan. One thing you didn't mention with regard to this process is the database deployment aspect. Most ASP.NET applications require an associated database, otherwise they could just be static HTML files. It is crucial that the database schema gets updated to the appropriate database version with every deployment. There is, not surprisingly, a module within BuildMaster that handles this for you as well. The idea is to store DDL-DML scripts within the tool itself, and by executing scripts only once per environment, it ensures that all of your databases across each environment are up-to-date as your builds are deployed through them. Other scripts (e.g. stored procedures, views, triggers, etc.) are essentially code files and therefore belong in source control. These DROP-CREATE-CONFIGURE type scripts can be run each and every time in most cases with a simple deployment action. Another piece of the deployment puzzle that most developers do not think about is process automation. Many developers need to perform sign-offs or fill out change request forms in order to manually perform these processes. Again, this is all available as part of the automated workflow setup within BuildMaster. You can setup blockers that do not allow promotion to say the QA environment unless all unit tests have passed, or block promotion to the Staging environment unless someone from the QA team approves the build and all issues in your issue tracking tool are resolved/closed for that particular release. While I realize I left out CC.NET from the answer, our applications are all built and deployed through BuildMaster so we no longer need it, though we could however just as easily pickup the artifacts from a drop location and deploy them in later environments. A: I see that many people use CC for their .NET projects, but why not use Jenkins, Sonarqube? They got all you need. I setup all this in 3 days. I have a Win 2008 server R2, MSSQL, Jenkins, VIsual SVN and Sonarqube. It all works great and u get all metrics on your project. Sonarqube uses Gallio, Gendarme, FXcop, Stylecop, NDepths and PartCover to get your metrics and all this is pretty straight forward since SonarQube do this automatically without much configuration. i post som pictures for u too get a feeling for it. Here is Jenkins witch builds and get Sonar metrics and a another job for deploying automatically to IIS And Sonarqube, all metrics for my project. This is a simple MVC4 app, but it works great!: If you want more information i can be more specific but i think you should at least consider jenkins. If CC suites you better, at least you looked at good alternative before you chose. This whole setup uses MSBuild, too build and deploy the apps.
{ "language": "en", "url": "https://stackoverflow.com/questions/57762", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "30" }
Q: BufferedGraphicsContext Error I am getting the below error and call stack at the same time everyday after several hours of application use. Can anyone shed some light on what is happening? System.InvalidOperationException: BufferedGraphicsContext cannot be disposed of because a buffer operation is currently in progress. at System.Drawing.BufferedGraphicsContext.Dispose(Boolean disposing) at System.Drawing.BufferedGraphicsContext.Dispose() at System.Drawing.BufferedGraphicsContext.AllocBufferInTempManager(Graphics targetGraphics, IntPtr targetDC, Rectangle targetRectangle) at System.Drawing.BufferedGraphicsContext.Allocate(IntPtr targetDC, Rectangle targetRectangle) at System.Windows.Forms.Control.WmPaint(Message& m) at System.Windows.Forms.Control.WndProc(Message& m) at System.Windows.Forms.ScrollableControl.WndProc(Message& m) at System.Windows.Forms.ToolStrip.WndProc(Message& m) at System.Windows.Forms.MenuStrip.WndProc(Message& m) at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m) at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m) at System.Windows.Forms.NativeWindow.Callback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam) A: There is a very long MSDN forums discussion of this error here. In most cases the error is apparently associated with either: * *An underlying OutOfMemory problem, which manifests as the BufferedGraphicsContext exception, possibly due to a framework bug. *A GDI object leak (creating GDI objects and not disposing them). I recall seeing this error myself a year or so ago, and it was definitely associated with a memory problem that made our app fill up all available VM after a long run, so #1 agrees with what I have observed. A: a shot in the dark - are you painting from multiple threads? If you are doing painting related work, do it on the GUI thread or synchronize your code carefully. A: I know this question is old, but i had the same problem and found out, that it only showed up, when i used multiple controls which implemented manual double buffering. For me, i found the problem at this point: BufferedGraphicsContext _BackbufferContext = BufferedGraphicsManager.Current; So all my controls used the Current context, which i assume is always the same. After i replaced it by BufferedGraphicsContext _BackbufferContext = new BufferedGraphicsContext(); everything works like wanted. I hope this is a little bit helpfull.
{ "language": "en", "url": "https://stackoverflow.com/questions/57766", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }