instruction
stringlengths
0
30k
this happens to me all the time. protected void Page_Load(object sender, EventArgs e) { if (!Page.IsPostBack) { // populate text boxes from database } }
Start with unit testing. Specifically, check out TDD, Test Driven Development. The concept behind TDD is you write the unit tests first, then write your code. If the test fails, you go back and re-work your code. If it passes, you move on to the next one. I take a hybrid approach to TDD. I don't like to write tests against nothing, so I usually write some of the code first, then put the unit tests in. It's an iterative process, one which you're never really done with. You change the code, you run your tests. If there's any failures, fix and repeat. The other sort of testing is integration testing, which comes along later in the process, and might typically be done by a QA testing team. In any case, integration testing addresses the need to test the pieces as a whole. It's the working product you're concerned with testing. This one is more difficult to deal with b/c it usually involves having automated testing tools (like Robot, for ex.). Also, take a look at a product like CruiseControl.NET to do continuous builds. CC.NET is nice b/c it will run your unit tests with each build, notifying you immediately of any failures.
I set up a task to do this. I'm not aware of any way to make CruiseControl be that specific. I usually just chain a batch file to do the copy to the CC.net task.
My experience is that 90% of queries and/or stored procedures should not be written at all (at least by hand). Data access should be generated somehow automaticly. You can decide if you'd like to staticly generate procedures in compile time or dynamically at run time but when you want add column to the table (property to the object) you should modify only one file.
Well, if you want to follow the TDD guys, **before you start to code** ;) I am very much in the same position as you. I want to get more into testing, but I am currently in a position where we are working to "get the code out" rather than "get the code out right" which scares the crap out of me. So I am slowly trying to integrate testing processes in my development cycle. Currently, **I test as I code, trying to bust the code as I write it**. I do find it hard to get into the TDD mindset.. Its taking time, but that is the way I would _want_ to work..
Well, if you want to follow the TDD guys, **before you start to code** ;) I am very much in the same position as you. I want to get more into testing, but I am currently in a position where we are working to "get the code out" rather than "get the code out right" which scares the crap out of me. So I am slowly trying to integrate testing processes in my development cycle. Currently, **I test as I code, trying to bust the code as I write it**. I do find it hard to get into the TDD mindset.. Its taking time, but that is the way I would _want_ to work.. ###EDIT: I thought I should probably expand on this, this is my basic "working process"... 1. Plan what I want from the code, possible object design, whatever. 2. Create my first class, add a huge comment to the top outlining what my "vision" for the class is. 3. Outline the basic test scenarios.. These will basically become the unit tests. 4. Create my first method.. Also writing a short comment explaining how it is _expected_ to work. 5. Write an automated test to see if it does what I expect. 6. Repeat steps 4-6 for each method (note the automated tests are in a huge list that runs on F5). 7. I then create some beefy tests to emulate the class in the working environment, obviously fixing any issues. 8. If any new bugs come to light following this, I then go back and write the new test in, make sure it fails (this also serves as proof-of-concept for the bug) then fix it.. I hope that helps.. Open to comments on how to improve this, as I said it is a concern of mine..
R# has a feature called Highlight current line, which you have to enable in the ReSharper options. This looks like crap on dark background, high contrast themes, so if you use one I'd suggest going into the Visual Studio options, under Fonts & Colors and going to "ReSharper - current Line" and making the background color a darker shade that doesn't have as much contrast with the background. R# also has matching brace highlighting, which is color-configurable as well under the same VS option dialog. Does that answer you question?
Yes, 32 bit ubuntu has the same memory limitations. There are exceptions to the 4GB limitation, but they are application specific... As in, Microsoft Sql Server can use 16 gigabytes with "Physical address Extensions" [PAE] configured and supported and... ugh http://forums.microsoft.com/TechNet/ShowPost.aspx?PostID=3703755&SiteID=17
Yes, 32 bit ubuntu has the same memory limitations. There are exceptions to the 4GB limitation, but they are application specific... As in, Microsoft Sql Server can use 16 gigabytes with "Physical address Extensions" [PAE] configured and supported and... ugh http://forums.microsoft.com/TechNet/ShowPost.aspx?PostID=3703755&SiteID=17 Also drivers in ubuntu and windows both reduce the amount of memory available from the 4GB address space by mapping memory from that 4GB to devices. Graphics cards are particularly bad at this, your 256MB graphics card is using up at least 256MB of your address space... If you can [your drivers support it, and cpu is new enough] install a 64 bit os. Your 32 bit applications and games will run fine.
Linux supports a technology called PAE that lets you use more than 4GB of memory, however I don't know whether Ubuntu has it on by default. You may need to compile a new kernel.
Linux supports a technology called PAE that lets you use more than 4GB of memory, however I don't know whether Ubuntu has it on by default. You may need to compile a new kernel. Edit: Some threads on the Ubuntu forums suggest that the server kernel has PAE on by default, you could try installing that.
Choosing a desktop database
|oracle-database|sql-server-ce|
I'm looking for a desktop/embedded database. The two candidates I'm looking at are Microsoft SQL Server CE and Oracle Lite. If anyone's used both of these products, it'd be great if you could compare them. I haven't been able to find any comparisons online. The backend DB is Oracle10g. Thanks!
I'm looking for a desktop/embedded database. The two candidates I'm looking at are Microsoft SQL Server CE and Oracle Lite. If anyone's used both of these products, it'd be great if you could compare them. I haven't been able to find any comparisons online. The backend DB is Oracle10g. Thanks! Update: Clarification, the business need is a client-server app with offline functionality (hence the need for a local data store on the client)
|database|oracle-database|sql-server-ce|
If you have shell access you can run the command $ du -h or perhaps use this, if PHP is configured to allow execution: <?php $d = escapeshellcmd(dirname(__FILE__)); echo nl2br(`du -h $d`) ?>
[http://code.google.com/p/geckofx/](http://code.google.com/p/geckofx/) This is a nice .NET-wrapped version of Gecko
Use encryption to protect information on the way. Use obfuscation to protect information while your program still has it.
Timeout not being honoured in connection string
|sql-server|timeout|
I have a long running SQL statement that I want to run, and no matter what I put in the "timeout=" clause of my connection string, it always seems to end after 30 seconds. I'm just using SqlHelper.ExecuteNonQuery() to execute it, and letting it take care of opening connections, etc. Is there something else that could be overriding my timeout, or causing sql server to ignore it? I have run profiler over the query, and the trace doesn't look any different when I run it in management studio, versus in my code. Management studio completes the query in roughly a minute, but even with a timeout set to 300, or 30000, my code still times out after 30 seconds.
|sql-server|database|timeout|
I think if you still want/need the data to be accessible, then partitioning some of your biggest or most-used tables could be an option.
Why does Visual Studio create a new .vsmdi file?
|visual-studio-2008|
If I open a solution in Visual Studio 2008 and run a unit test then VS creates a new .vsmdi file in the Solution Items folder and gives it the next number available e.g. My Solution2.vsmdi. Any idea why VS is doing this and how I can get it to stop doing this?
|visual-studio-2008|visualstudioteamsystem|mstest|
|visual-studio|visual-studio-2008|mstest|
Using VLOOKUP in an array formula on Google Spreadsheets
|google|spreadsheet|excel|formula|
Effectively I want to give numeric scores to alphabetic grades and sum them. In Excel, putting the `LOOKUP` function into an array formula works: {=SUM(LOOKUP(grades, scoringarray))} With the `VLOOKUP` function this does not work (only gets the score for the first grade). Google Spreadsheets does not appear to have the `LOOKUP` function and `VLOOKUP` fails in the same way using: =SUM(ARRAYFORMULA(VLOOKUP(grades, scoresarray, 2, 0))) or =ARRAYFORMULA(SUM(VLOOKUP(grades, scoresarray, 2, 0))) Is it possible to do this (but I have the syntax wrong)? Can you suggest a method that allows having the calculation in one simple cell like this rather than hiding the lookups somewhere else and summing them afterwards?
|excel|google|spreadsheet|
There is a site called [Softies on Rails][1] that is written by a couple of ex-.NET developers that may be of some use. They have a book called [Rails for .NET Developers][2] coming out in the next few months... I started out on a Windows box using the [RadRails][3] plugin for Eclipse and the [RubyWeaver][4] extension for Dreamweaver (back during the 1.x days of Rails). Since then I have moved to a Mac running TextMate and haven't thought of going back. As for books, I started with The Ruby Way and Agile Web Development with Rails. It definately helps to build a background in Ruby as you start to make your way into Rails development. Definately watch the Railscast series by Ryan Bates. [1]: http://www.softiesonrails.com/ [2]: http://pragprog.com/titles/cerailn/rails-for-net-developers [3]: http://www.aptana.com/rails [4]: http://rubyweaver.gilluminate.com/
If you are targeting .NET 2.0 or later, the class System.Security.Principal.SecurityIdentifier wraps a SID and allows you to avoid the error-prone Win32 APIs. Not exactly an answer to your question, but who knows it may be useful.
Cursors do have their place, however I think it's mainly because they are often used when a single select statement would suffice to provide aggregation and filtering of results. Avoiding cursors allows SQL Server to more fully optimize the performance of the query, very important in larger systems.
Sometimes the nature of the processing you need to perform requires cursors, though for performance reasons it's always better to write the operation(s) using set-based logic if possible. I wouldn't call it "bad practice" to use cursors, but they do consume more resources on the server (than an equivalent set-based approach) and more often than not they aren't necessary. Given that, my advice would be to consider other options before resorting to a cursor. There are several types of cursors (forward-only, static, keyset, dynamic). Each one has different performance characteristics and associated overhead. Make sure you use the correct cursor type for your operation. Forward-only is the default. One argument for using a cursor is when you need to process and update individual rows, especially for a dataset that doesn't have a good unique key. In that case you can use the FOR UPDATE clause when declaring the cursor and process updates with UPDATE ... WHERE CURRENT OF. Note that "server-side" cursors used to be popular (from ODBC and OLE DB), but ADO.NET does not support them, and AFAIK never will.
A couple questions: - Does the user that executes your app (you?) have permission to write to the file? - Is the file read-only? - What is your connection string? If you're using ASP, you'll need to add the IUSER_* user as in [this example][1]. [1]: http://support.microsoft.com/kb/195951/
There are very, very few cases where the use of a cursor is justified. There are almost no cases where it will outperform a relational, set-based query. Sometimes it is easier for a programmer to think in terms of loops, but the use of set logic, for example to update a large number of rows in a table, will result in a solution that is not only many less lines of SQL code, but that runs much faster, often *several orders of magnitude* faster. Even the fast forward cursor in Sql Server 2005 can't compete with set-based queries. The graph of performance degradation often starts to look like an n^2 operation compared to set-based, which tends to be more linear as the data set grows very large.
I'm no XML expert, but I find Option B to be more human readable, and I think it's just as machine readable as Option A. I believe that XML is designed to be both human and machine readable, so I would go for Option B myself. ---------- I just realized something else after Ryan Farley's post. If the Students or Classes section becomes too big and must be moved to another XML file, it seems like it would be easier to copy the node and create a new XML file out of that node with Option B.
First and often. If I'm creating some new functionality for the system I'll be looking to initially define the interfaces and then write unit tests for those interfaces. To work out what tests to write consider the API of the interface and the functionality it provides, get out a pen and paper and think for a while about potential error conditions or ways to prove that it is doing the correct job. If this is too difficult then it's likely that your API isn't good enough. In regards to the tests, see if you can avoid writing "integration" tests that test more than one specific object and keep them as "unit" test. Then create a default implementation of your interface (that does nothing, returns rubbish values but doesn't throw exceptions), plug it into the tests to make sure that the tests fail (this tests that your tests work! :) ). Then write in the functionality and re-run the tests. This mechanism isn't perfect but will cover a lot of simple coding mistakes and provide you with an opportunity to run your new feature without having to plug it into the entire application. Following this you then need to test it in the main application with the combination of existing features. This is where testing is more difficult and if possible should be partially outsourced to good QA tester as they'll have the knack of breaking things. Although it helps if you have these skills too. Getting testing right is a knack that you have to pick up to be honest. My own experience comes from my own naive deployments and the subsequent bugs that were reported by the users when they used it in anger. At first when this happened to me I found it irritating that the user was intentionally trying to break my software and I wanted to mark all the "bugs" down as "training issues". However after reflecting on it I realised that it is our role (as developers) to make the application as simple and reliable to use as possible even by idiots. It is our role to empower idiots and thats why we get paid the dollar. Idiot handling. To effectively test like this you have to get into the mindset of trying to break everything. Assume the mantle of a user that bashes the buttons and generally attempts to destroy your application in weird and wonderful ways. Assume that if you don't find flaws then they will be discovered in production to your companies serious loss of face. Take full responsibility for all of these issues and curse yourself when a bug you are responsible (or even part responsible) for is discovered in production. If you do most of the above then you should start to produce much more robust code, however it is a bit of an art form and requires a lot of experience to be good at.
If you are using SQL Server 2005. Fire up the Management Studio and look at the Maintenance Plan section. See [http://msdn.microsoft.com/en-us/library/ms187658.aspx][1] for an overview and [http://msdn.microsoft.com/en-us/library/ms189036.aspx][2] for details on the Maintenance plan wizard. Finally, [http://msdn.microsoft.com/en-us/library/ms140255.aspx][3] is a list of all the maintenance tasks available. I am pretty sure this is all available even in the Express Edition. I can't speak to if anything has changed in 2008, I haven't used it yet. [1]: http://msdn.microsoft.com/en-us/library/ms189036.aspx [2]: http://msdn.microsoft.com/en-us/library/ms189036.aspx [3]: http://msdn.microsoft.com/en-us/library/ms140255.aspx
In Excel, you would likely just write code to open the other worksheet, modify it and then save the data. See [this tutorial][1] for more info. I'll have to edit my VBA later, so pretend this is pseudocode, but it should look something like: Dim xl: Set xl = CreateObject("Excel.Application") xl.Open "\\the\share\file.xls" Dim ws: Set ws = xl.Worksheets(1) ws.Cells(0,1).Value = "New Value" ws.Save xl.Quit constSilent [1]: http://pubs.logicalexpressions.com/Pub0009/LPMArticle.asp?ID=302
One expression per line. There is no reason to obfuscate your code. The extra time you take typing the few extra terms, you save in debug time.
What's the best way to detect if an IDataReader is empty?
|c#|ado.net|
It seems like IDataReader.Read() is always true at least one time (If I'm wrong about this let me know.) So how do you tell if it has no records without just wrapping it in a try/catch?
As @Nir mentioned, it's better to have homogeneous environment. However if you decide to not use Oracle Light, I would highly recommend you to take a look at [Firebird][1]. It's one of best choices for desktop database scenarios. [1]: http://www.firebirdsql.org/
Plugin for R# similar to CodeRush "statement highlight"
|resharper|codehighlighter|
See here [http://www.hanselman.com/blog/InSearchOfThePerfectMonospacedProgrammersFontInconsolata.aspx][1] - for want of a better description - the statement block highlighting. I understand this is a feature of CodeRush - does R# have either anything similar, or a plugin to do the same? [1]: http://www.hanselman.com/blog/InSearchOfThePerfectMonospacedProgrammersFontInconsolata.aspx
See here [http://www.hanselman.com/blog/InSearchOfThePerfectMonospacedProgrammersFontInconsolata.aspx][1] - for want of a better description - the statement block highlighting - eg in the pics on the link the "statement blocks" are grouped with a vertical line. I understand this is a feature of CodeRush - does R# have either anything similar, or a plugin to do the same? [1]: http://www.hanselman.com/blog/InSearchOfThePerfectMonospacedProgrammersFontInconsolata.aspx
If you can't use the fileinfo extension, and you don't want to use mime_content_type, your options are limited. Most likely you'll need to do a lookup based on the file extension. mime_content_type did something a bit more intelligent and actually looked for special data in the file to determine the mime type.
You can leverage MySql in a number of ORMs, one of which is NHibernate. For the most part you can treat it as if you were running on SQL Server or Oracle. And with Linq2NHibernate, you can get nice LINQ syntax. You'd lose the SqlDataSource control, but some would argue that it would actually be a blessing :) And of course you'd lose Linq2SQL. EntityFramework will have 3rd party adapters MySql, Oracle and a few others soon after release.
The inherited call has to be made explicitly. It is easy to forget to make the inherited call in a class constructor. In such a situation if a base class needs to initialize any data you have an access violation waiting to happen. Perhaps you could override DoCreate and DoDestory in your TBaseForm class so you could ensure some code is executed regardless of the implementation of child classes. // interface TBaseForm = Class(TForm) ... Protected Procedure DoCreate(Sender : TObject); Override; End // implementation Procedure TBaseForm.DoCreate(Sender : TObject); Begin // do work here // let parent call the OnCreate property Inherited DoCreate(Sender); End;
The inherited call has to be made explicitly. In general no language automatically calls the inherited function in equivalent situations (class constructors not included). It is easy to forget to make the inherited call in a class constructor. In such a situation if a base class needs to initialize any data you have an access violation waiting to happen. Perhaps you could override DoCreate and DoDestory in your TBaseForm class so you could ensure some code is executed regardless of the implementation of child classes. // interface TBaseForm = Class(TForm) ... Protected Procedure DoCreate(Sender : TObject); Override; End // implementation Procedure TBaseForm.DoCreate(Sender : TObject); Begin // do work here // let parent call the OnCreate property Inherited DoCreate(Sender); End;
Unlike Java, where there are exceptions that must be declared to be raised (and some that don't have to be, but that's another story), any Python code may raise any exception at any time. There are a list of [built-in exceptions][1], which generally has some description of when these exceptions might be raised. Its up to you as to how much exception handling you will do, and if you will handle stuff gracefully, or just fail with a traceback. [1]: http://docs.python.org/lib/module-exceptions.html
Reintroducing functions in Delphi
|delphi|
Does anyone know what the motivation was for having the reintroduce keyword in Delphi? If you have a child class that contains a function with the same name as a virtual function in the parent class and it is not declared with the override modifier then it is a compile error. Adding the reintroduce modifier in such situations fixes the error but I have never grasped the reasoning for the compile error.
|delphi|oop|polymorphism|
You mean... you want some sort of tree view? You can actually get the treeview control to work... but you have to wrap it in server side form tag to function. You'll get the usual nastiness that that brings (like generated ids and viewstate) but it will work from a rendering perspective. If you want to just create <ul> tags and nest them, it would be pretty easy to do with foreach() loops.
How to implement password protection for individual files?
|ruby|gems|
|ruby|rubygems|
What are differences generic in C++ and Java?
|c++|java|generic|
Java has generic keyword and C++ provides very strong programming model with generic. Then what is difference between C++ and Java generic?
|c++|java|generic|templates|language-features|
|java|c++|generics|templates|language-features|
Print out the keys and Data of a Hashtable in C# .NET 1.1
|c#|.net|hashtable|
I need debug some old code that uses a Hashtable to store response from various threads. I need a way to go through the entire Hashtable and print out both keys and the data in the Hastable. How can this be done?
|c#|.net-1.1|hashtable|
|c#|.net-1.1|hashtable|
I wrote some C# code to scan the cipher and give me some stats back. Here are some interesting results: With a chunk size of 3, - There are 236 chunks. - There are 172 duplicates. - The 323 code shows up a whopping total of 29 times! - The 333 code shows up 11 times. - All other codes show up 7 times or less. - 35 chunks start with a 2. - 200 chunks start with a 3. (Interesting!) - 1 chunk starts with a 4. - Despite the cipher containing 2s, 3s, 4s, 5s, 6s, 7s, 8s, and 9s, chunks only start with 2 and 3, except the 1 chunk that starts with 4. - There are no 0s. - There are no 1s. - There are 115 2s. - There are 293 3s. - There are 56 4s. - There are 38 5s. - There are 49 6s. - There are 52 7s. - There are 63 8s. - There are 42 9s. Given these interesting stats, I'm leaning towards a 3 chunk
I wrote some C# code to scan the cipher and give me some stats back. Here are some interesting results: With a chunk size of 3, - There are 236 chunks. - There are 172 duplicates. - The 323 code shows up a whopping total of 29 times! - The 333 code shows up 11 times. - All other codes show up 7 times or less. - 35 chunks start with a 2. - 200 chunks start with a 3. (Interesting!) - 1 chunk starts with a 4. - Despite the cipher containing 2s, 3s, 4s, 5s, 6s, 7s, 8s, and 9s, chunks only start with 2 and 3, except the 1 chunk that starts with 4. - There are no 0s. - There are no 1s. - There are 115 2s. - There are 293 3s. - There are 56 4s. - There are 38 5s. - There are 49 6s. - There are 52 7s. - There are 63 8s. - There are 42 9s. I'd describe the 323 appearance count highly irregular. I'd also suggest that the fact that all of the chunks start with either 3 or 2 (barring the 1 appearance of a 4 chunk) is also highly irregular. I'm leaning towards a 3 chunk.
I went to a presentation on unit testing at FoxForward 2007 and was told never to unit test anything that works with data. After all, if you test on live data, the results are unpredictable, and if you don't test on live data, you're not actually testing the code you wrote. Unfortunately, that's most of the coding I do these days. :-) I did take a shot at TDD recently when I was writing a routine to save and restore settings. First, I verified that I could create the storage object. Then, that it had the method I needed to call. Then, that I could call it. Then, that I could pass it parameters. Then, that I could pass it specific parameters. And so on, until I was finally verifying that it would save the specified setting, allow me to change it, and then restore it, for several different syntaxes. I didn't get to the end, because I needed-the-routine-now-dammit, but it was a good exercise.
**Definitely - Option B.** I wouldn't mix students and classes in the XML just the same way that I wouldn't mix students and classes in the same table in a database.
I haven't found any compelling argument for using ad-hoc queries. Especially those mixed up with your C#/Java/PHP code.
yeah everything you described (except maybe perf monitoring) can be done with database maintenance plans, back ups, shrinking log files etc.
Being the author of cfix, I might be a little biased here -- but as a matter of fact, I am currently not aware of any other unit-testing framework for NT kernel mode. If you should experience any problems with cfix, feel free to contact me.
Option B, absolutely. When there's a logical grouping of similar items, it should have a parent item. That way, my parser won't have to step through all 500 student records checking to see if there are class records mixed in.
Another compelling reason to use option B is error checking. If the original file is modified outside an XML application, or if no XSD schema is applied, there could be the case where you have an uneven number of students and classes. At least if you have the students and classes grouped together, you will easily be able to tell if each record is complete, independently of any other record.
It sounds like you are trying to allow the "special content creators" save files in TFS Source Control without having to buy them a license to a Visual Studio Team Edition -- correct me if I'm wrong. If that's the case, unfortunately I believe that you can't quite do that. Your users still need a Client Access License ("CAL") to access TFS. I think that you can acquire just CALs for your users without having to buy Visual Studio for them (I presume for less than a full blown Visual Studio would cost). At that point, you can just distribute to them the Team Explorer, which is a VS shell with nothing but TFS access components. That is available in your TFS server media. I found this via Google. You might want to review it to decide your best options: [Visual Studio Team System 2008 Licensing White Paper][1] The only exception to the CAL rules I'm aware of is access to Work Items. Assuming properly licensed servers, anyone in your organization can create new Work Items or view and update existing ones *created by them*, using the [Work Item Web Access][2] component. [1]: http://www.microsoft.com/downloads/details.aspx?FamilyID=ce194742-a6e8-4126-aa30-5c4e969af2a3&DisplayLang=en [2]: http://www.microsoft.com/downloads/details.aspx?FamilyID=faed8359-f54d-480e-8a86-f154d3dea07e&displaylang=en
I don't know about this control, but TinyMCE is: http://tinymce.moxiecode.com/ It's what wordpress etc use.
How do you represent your graph in memory? Basically you have two (good) options: - [an adjacency list representation][1] - [an adjacency matrix representation][2] in which the adjacency list representation is best used for a sparse graph, and a matrix representation for the dense graphs. If you used suchs representations then you could serialize those representations instead. If it has to be *human readable* you could still opt for creating your own serialization algorithm. For example you could write down the matrix representation like you would do with any "normal" matrix: just print out the columns and rows, and all the data in it like so: 1 2 3 1 #t #f #f 2 #f #f #t 3 #f #t #f (this is a non-optimized, non weighted representation, but can be used for directed graphs) [1]: http://en.wikipedia.org/wiki/Adjacency_list [2]: http://en.wikipedia.org/wiki/Adjacency_matrix
One other thing that an RDBMS generally does for you is to provide concurrency by protecting you from simultaneous access by another process. This is done by placing locks, and there's some overhead from that. If you're dealing with entirely static data that never changes, and especially if you're in a basically "single user" scenario, then using a relational database doesn't necessarily gain you much benefit.
What you want to get its the instant CPU usage (kind of)... Actually, the instant CPU usage for a process does not exists. Instead you have to make two measurements and calculate the average CPU usage, the formula is quite simple: AvgCpuUsed = [TotalCPUTime(process,time2) - TotalCPUTime(process,time1)] / [time2-time1] The lower Time2 and Time1 difference is, the more "instant" your meassurement will be. Windows Task Manager calculate the CPU use with an interval of one second. I've found that is more than enough and you might even consider doing it in 5 seconds intervals cause the act of measuring itself takes up CPU cicles... So, first, to get the average CPU time using System.Diagnostics; float GetAverageCPULoad(int procID, DateTme from, DateTime, to) { // For the current process //Process proc = Process.GetCurrentProcess(); // Or for any other process given its id Process proc = Process.GetProcessById(procID); System.TimeSpan lifeInterval = (to - from); // Get the CPU use float CPULoad = (proc.TotalProcessorTime.TotalMilliseconds / lifeInterval.TotalMilliseconds) * 100; // You need to take the number of present cores into account return CPULoad / System.Environment.ProcessorCount; } now, for the "instant" CPU load you'll need an specialized class: class ProcLoad { // Last time you checked for a process public Dictionary<int, DateTime> lastCheckedDict = new Dictionary<int, DateTime>(); public float GetCPULoad(int procID) { if (lastCheckedDict.ContainsKey(procID)) { DateTime last = lastCheckedDict[procID]; lastCheckedDict[procID] = DateTime.Now; return GetAverageCPULoad(procID, last, lastCheckedDict[procID]); } else { lastCheckedDict.Add(procID, DateTime.Now); return 0; } } } You should call that class from a timer (or whatever interval method you like) for **each process you want to monitor**, if you want all the processes just use the [Process.GetProcesses][1] static method [1]: http://msdn.microsoft.com/en-us/library/1f3ys1f9.aspx
|encryption|cryptography|password|
I'm writing a little desktop app that should be able to encrypt a data file and protect it with a password (i.e. one must enter the correct password to decrypt). I want the encrypted data file to be self-contained and portable, so the authentication has to be embedded in the file (or so I assume). I have a strategy that appears workable and seems logical based on what I know (which is probably just enough to be dangerous), but I have no idea if it's actually a good design or not. So tell me: is this crazy? Is there a better/best way to do it? * Step 1: User enters plain-text password, e.g. "MyDifficultPassword" * Step 2: App hashes the user-password and uses that value as the symmetric key to encrypt/decrypt the data file. e.g. "MyDifficultPassword" --> "HashedUserPwdAndKey". * Step 3: App hashes the hashed value from step 2 and saves the new value in the data file header (i.e. the unencrypted part of the data file) and uses that value to validate the user's password. e.g. "HashedUserPwdAndKey" --> "HashedValueForAuthentication" Basically I'm extrapolating from the common way to implement web-site passwords (when you're not using OpenID, that is), which is to store the (salted) hash of the user's password in your DB and never save the actual password. But since I use the hashed user password for the symmetric encryption key, I can't use the same value for authentication. So I hash it again, basically treating it just like another password, and save the doubly-hashed value in the data file. That way, I can take the file to another PC and decrypt it by simply entering my password. So is this design reasonably secure, or hopelessly naive, or somewhere in between? Thanks!
|encryption|passwords|cryptography|
I'm writing a little desktop app that should be able to encrypt a data file and protect it with a password (i.e. one must enter the correct password to decrypt). I want the encrypted data file to be self-contained and portable, so the authentication has to be embedded in the file (or so I assume). I have a strategy that appears workable and seems logical based on what I know (which is probably just enough to be dangerous), but I have no idea if it's actually a good design or not. So tell me: is this crazy? Is there a better/best way to do it? * Step 1: User enters plain-text password, e.g. "MyDifficultPassword" * Step 2: App hashes the user-password and uses that value as the symmetric key to encrypt/decrypt the data file. e.g. "MyDifficultPassword" --> "HashedUserPwdAndKey". * Step 3: App hashes the hashed value from step 2 and saves the new value in the data file header (i.e. the unencrypted part of the data file) and uses that value to validate the user's password. e.g. "HashedUserPwdAndKey" --> "HashedValueForAuthentication" Basically I'm extrapolating from the common way to implement web-site passwords (when you're not using OpenID, that is), which is to store the (salted) hash of the user's password in your DB and never save the actual password. But since I use the hashed user password for the symmetric encryption key, I can't use the same value for authentication. So I hash it again, basically treating it just like another password, and save the doubly-hashed value in the data file. That way, I can take the file to another PC and decrypt it by simply entering my password. So is this design reasonably secure, or hopelessly naive, or somewhere in between? Thanks! EDIT: clarification and follow-up question re: Salt. I thought the salt had to be kept secret to be useful, but your answers and links imply this is not the case. For example, [this spec][1] linked by erickson (below) says: >Thus, password-based key derivation as defined here is a function of a password, a salt, and an iteration count, where the latter two quantities need not be kept secret. Does this mean that I could store the salt value in the same place/file as the hashed key and still be more secure than if I used no salt at all when hashing? How does that work? A little more context: the encrypted file isn't meant to be shared with or decrypted by others, it's really single-user data. But I'd like to deploy it in a shared environment on computers I don't fully control (e.g. at work) and be able to migrate/move the data by simply copying the file (so I can use it at home, on different workstations, etc.). [1]: ftp://ftp.rsasecurity.com/pub/pkcs/pkcs-5v2/pkcs5v2-0.pdf
if(dr.Read()) { //do stuff } else { //it's empty } usually you'll do this though: while(dr.Read()) { }
Yes, if you want to use the interface then Read until false is the only way to test. If you are looking for a generic IDataReader implementation, you could try DbDataReader and use the HasRows property.
Get MIME type of a local file in PHP5 without a PECL extension?
|mime|php5|
mime_content_type() is deprecated. How can I find the MIME type of a local file using PHP5 but without using this deprecated method or the PECL fileinfo extension?
mime_content_type() is deprecated. How can I find the MIME type of a local file using PHP5 but without using this deprecated method or the PECL fileinfo extension? Edit: That's what I was afraid of. It's unfortunate that they deprecated a built-in function in favour of one that requires an extension that isn't always available.
How do you Modify TextBox Control Tab Stops