Hire a web Developer and Designer to upgrade and boost your online presence with cutting edge Technologies

Saturday, February 26, 2011

Jquery Lazy Load Plugin

Jquery Effect - Bouncing div

Learn how to make a jquery plugin



Learn how to make a jquery plugin

Working with the Official jQuery Templating Plugin



The jQuery team announced that Microsoft's templating plugin (along with a couple others) is now being officially supported. What this means is that the plugin will now be maintained and updated directly by the core team. In this video tutorial, we'll review the essentials of the plugin, and why it's so awesome.

An Introduction to jQuery Templating



JavaScript Templating is a neat idea: it allows you to easily convert JSON to HTML without the work of parsing the it. At Microsoft's MIX10 conference, they announced that they would be starting to work with the jQuery team; one of their efforts was to provide a templating plugin. In this quick tip, I'll show you how to use it!

Awesome jQuery plugin to filter/animate HTML lists - QuickSand

Saturday, February 19, 2011

Few Concepts for the Programmer/Developers about migration from Delphi to .NET

I've one of my friend that was programming using Delphi and due to increase in demand of .NET in market, he decide to upgrade himself. Here is details of conversation that is done between he and me:


I was hinted by the boss that I will be the mentor of fellow Delphi programmers who want to learn C#. Though I do not consider I has mastered half of what a senior C# programmer should have, I would share some experiences in my learning path.

I am well aware of the mindset of common Delphi programmers, and why we loved Delphi, as I started using Delphi since 1997, moving from C/C++.


I started .NET programming unwillingly in year 2003, in a project of developing some class libraries of ASP.NET. Somethings I felt bad included:

1. .NET provides garbage collection. I spent years to acquire profession of developing memory-leak-free Delphi applications. With such garbage collection, the skills I developed become insignificant. In the first year or two using C#, I kept the habit of releasing objects after uses, though now I understand this is bad practice in .NET. In addition, memory management in large projects particularly distributed applications is always difficult. Leaving memory management to GC will make developers concentrate more on designs and coding, rather than busy house keeping of releasing objects.
2. The libraries of .NET framework look very foreign to me. There are many functions available in Delphi but not in .NET framework. Nevertheless, after .NET 2, apparently Anders the farther of Delphi and C# had altered some conventions of the .NET framework dramatically to appeal to Delphi programmers. No more complaints.
3. High memory usage. Now I understand this is by design in order to lower the cost of memory allocation, and the memory usage is well managed by CLR.

Comparing with programmers from Java and C++, Delphi programmers have the following conveniences when moving to C#:
1. The casing convention is Pascal convention.
2. Since .NET 2, the naming convention of .NET libraries became more appealing to Delphi programmers who may research needed functions in a more speedy manner.
3. The block convention of C# syntax is similar to Object Pascal. So Delphi programmers may read C# codes faster. I have seen some C# programmers from C background insisted on constructing blocks in C style, however, they may have harder time when reading others' C# codes.

Of course Java programmers and C++ programmers may argue that they have more conveniences, as the C# syntax is more similar to the ones of Java and C++, and C# was built on the top of the concept of Java.


I think, a Delphi programmer may treat C# as Delphi in Java syntax flavor at the very beginning of studying, say, when developing a few demo projects to get familiar with basic C# syntax and VS IDE. However, don't let such mindset last long, as I did lasting one year. I think, one or two months is more than enough. Otherwise, when you review conventional C# codes written by others with more experiences, you will feel very awful.

There's nothing to prevent you from writing C# codes in Object Pascal style so you feel comfortable, however, staying in your comfort zone will lead to 4 major drawbacks:
1. You do not take advantages of those C# syntax designed by Anders.
2. Code Analysis will complain bitterly. The warnings from Codes Analysis come with good reasons: they are the collective wisdom of programmers around the world over years.
3. You will be re-inventing the wheel when developing enterprise applications, as many features have already been available in .NET Framework. Without mindset change for new style, you will be basically writing Delphi codes in C# syntax running on VM, but without using the powers of .NET Framework.
4. It will be hard for you to read conventional C# codes in order to learn from others.


Common Misconception from the mindset of RAD:

1. Code Analysis find errors for you, so you write correct codes faster. A handful numbers of defects found by Code Analysis became compiler errors, that was, MS put some of the analysis rules into the parser of .NET compiler. However, code analysis is mostly for locating vulnerable codes and improving maintainability. Without doing code analysis, your codes may still run well in an ivory tower. If you buy the concept of code review, code analysis is your good friend as it is automatic code review. The machine is doing code review for you, so you can concentrate on those vulnerabilities or defects which can not possibly checked by the machine.
2. Unit test will slow programmers down.There are many text books about the productivity you can get from unit tests. My experience: unit test force you to make good designs which are generally friendly to unit tests; unit test give you assurance and confidence when you move forward during bug fixing, refactoring and adding new features.


The following factors support the importance of mindset change:

1. The sole soul of Delphi is RAD, in contrast, some of the souls of C# .NET are agile and enterprise architecture, though VS .NET well support RAD. Borland/Inprise tried to transform Delphi toward enterprise architecture, but failed, partially because of the soul. There are tons of discussion in the Internet about RAD, though I was a big fan of RAD.
2. The elements illustrated below which are generally weak or absent in Delphi except Delphi 2010. And you should search MSDN as well as other resources to learn the accurate concepts of these elements.



Configuration
Delphi programmers generally use INI file, database tables or free form XML to persist settings. .NET provide a solid framework of configuration, and on the top of that, MS also provide an application block for configuration. And, you can build derived classes of ISettingsProvider to interface with settings stored in legacy storage.

Configuration has significant impact on design and deployment. In many Delphi applications, a configuration file is generally for storing setting used by the business logic of the applications. In .NET, a configuration is always used by CLR for binding components together.

Many .NET technologies are based on the combination of configuration and reflection, for example, unit tests.

The library of configuration is vast. Studying the library is an on going process.

Reflection
Programmers have been long using variety of design patterns to remove couplings, and reflection provides another paradigm for removing coupling, though reflection is not only for removing coupling.

Many of the .NET technologies are built on the foundation of reflection, such as attribute, configuration binding, and unit tests etc.

Assembly
Actually Delphi has similar concept: Package or Borland Package Library (BPL). A BPL file is a dll file and supports object oriented interfacing.So you may consider a .NET assembly is an advanced "BPL" file with byte codes rather than machine codes. In addition, an assembly contain a chunk of meta data describing the assembly for various purposes.

Short life cycle
There are many text books about the advantage of making objects have short life cycle. In Delphi as well as other languages without automatic garbage collection, it is hard to implement a design encouraging short life cycle.

GC
While GC is for automatic garbage collection, you should still avoid unintended memory build-up which is generally caused by a long live object holding up short live objects unnecessarily.

GAC
Global Assembly Cache is a special directory managed by .NET framework along with Windows kernels. Basically assemblies installed in GAC are trusted because only admin can install them there. .NET CLR will always search for needed assemblies in GAC first then elsewhere.

Resource management
While GC will dispose unused objects automatically, however, when the collection operates is not deterministic. GC is for managing memory, not for resources which are provided by the OS and managed by OS. You as a programmer should be responsible for releasing unused resources ASAP:
1. A class which owns a resource MUST implement IDisposable.
2. When using an object of the class, it is desirable to put it within a Using statement which will guarantee the resource used is disposed no matter what happen even if an exception is raised withing the Using block.

Without conforming to these 2 guidelines, you will see your program runs out of resources soon when requests to resources (e.g. internet connections) become frequent, for example, during unit test or stress test.

Attributes
Attributes are basically meta data associated with classes, properties or methods. It is up to the CLR, framework codes or your domain specific codes to interrupt the attributes and react. Attributes give loose couplings and great flexibility. Your first encounter with Attributes would be those in unit tests, such as TestClassAttribute and TestMethodAttribute.

Unit tests/TDD
There are many articles and books about unit tests and Test Driven Development. And MS Test provides powerful supports and conveniences to unit tests. Surely codes under mouse won't be good for testing, neither be good design at all. In general, a good design is easy to test automatically.

While constructing test codes takes time, however, it will greatly reduce debugging and speed up the whole development. When you add new features to your product, you will have less worry about whether newly introduced codes will break the product, because your test codes will likely be broker first. Evaluating new codes against unit tests is easier that evaluating new codes against the whole product.

Microsoft .NET programming guidelines
Borland had provided a few pages of programming guidelines, mostly focusing on naming conventions and styles. And much of the context is integrated into a few implementations of Delphi formaters.

Microsoft has provided more than 100 pages of .NET programming guidelines, and much of the context is integrated into Code Analysis.

Code Analysis
It is not for finding bugs for you. Please check Wikipedia about Code Analysis.

Components
"Programming .NET Components" by Lowy is a book must read after you have used C# in commercial projects for half year.

Common Object Model/Interoperability
COM is one of the basic glue between Windows applications, and the other is Windows messages which is hard to use. In native Windows, majority of coordination between applications and components within a machine is implemented through COM. So .NET applications running on CLR should not give up the coordination with other applications running on native Windows. Interoperability is the bridge between 2 environments.




After all, I think the most important thing of all is changing mindset. It took me one year or two to change. Hopefully through reading this post you will take less time.




To be continued and updated ...

Sunday, February 13, 2011

Know About Windows Server 2008

Introduction

Windows Server 2008 was introduced on February 4, 2008, and was an exponential leap since it was modeled on the Windows NT 6.0 SP1 kernel, which is used in Windows Vista. A Release 2 is currently under development.


Features

Microsoft have introduced an innovative approach to installation of Windows Server 2008 by a new methodology, Server Core, which does not install a Windows Explorer Shell. (All the installation is done in a command-line session, saving time considerably over previous methods.) Also it connects via the MMC (Microsoft Managament Console.) During the installation, some applets are available such as Windows Notepad and Regional Settings.

A Server Core machine may be used for some basic roles. A Domain Controller may be built fairly quickly along with several other types of server which are not application-based. One of the other more advantageous aspects of building a Server Core rather than a fully fledged machine is that it has a reduced attack surface, meaning greater security and less vulnerability to attack, while providing an efficient service.

Windows Server 2008 comes with greater features of Active Directory and enhancements to Terminal Services. The latest Terminal Services in Windows Server 2008 makes for many fewer scenarios where the extra cost of Citrix Metaframe is required. It supports remote printing and resource sharing much more elegantly compared with prior versions. It also ships with Windows Powershell a very useful command-line shell and scripting technology which is task-based. There are also some significant improvements to the server-type file system through the utilization of a "self-healing NTFS" file system, obviating the need to take a server down because the volume was marked "dirty." Whatever is thought of the S.M.A.R.T. technology, it has been featured extensively in Windows systems, and drives that are do not display S.M.A.R.T. codes, should not be considered for Windows Server 2008 nor Windows Vista, since integral parts of these Windows Operating systems use S.M.A.R.T. to check the health of hard drives.

Windows Server 2008 also features Hyper-V (hypervisor-based virtualization.) Servers are virtualized on the operating system's kernel layer. This can be seen as the multiple partitioning of a single physical server and can be very useful for running multiple applications which ought not to be in the same physical space. This is good security and also helps to keep the costs down. It is also a far greener methodology.

A couple of things have been taken out of Windows Server 2008: NNTP protocol no longer ships with IIS v 7 and NT Backup has been replaced by Windows Server Backup, along with exchange backups. A replacement for this is in place, but not on Windows Server 2008.

And, as with all new Microsoft products, there are several editions to be enjoyed: from the Standard Editions which ship in x86 and x64 to Windows Server 2008 for Itanium, there is a lot in between.

Few Things About Windows Powershell

Introduction

Windows Powershell 1.0 creates a useful task-based command-line scripting shell for performing some of the more important tasks which are needed on a server. In fact, Windows Powershell was originally available with Windows XP SP2 and SP3, Windows Server 2003, Windows Vista and in Windows Server 2008. It is being shipped with this server operating system and with Windows 7.0 as an optional beta product.

Features

PowerShell 1.0 integrates with Microsoft Visual Studio .NET and gives the task of administration a boost by supplying an environment to perform these tasks by the execution of "commandlets," scripts which combine commandlets with imperative logic, a set of executables and via regular .NET classes.

Windows PowerShell 1.0 providers give access to data in sections of the data store such as the system registry and the file system. And other Microsoft applications like Microsoft SQL Server 2008 and MS Exchange Server 2007 are integrated by the commandlets in Windows PowerShell.

And Windows PowerShell 1.0 has a comprehensive command-line console-based help system (which is accessed in much the same way as a man-page in a UNIX shell.)

The difference between the regular Command.com and CMD.exe in traditional MS-DOS and Windows environments and the new shell provided by Windows PowerShell is that it is capable of automating a full range of core admin tasks. It originally came out as Monad in 2003 and, since then, has gone through several enhancements and improvements until, in April 2006, Microsoft renamed Monad to Windows PowerShell and utilize Microsoft Visual Studio .NET to increase the functionality to a level not seen before in a Windows command interpreter, because it has the added functions embedded in .Net.

To be specific, the specific functions which are run as commands in PowerShell are native in the PowerShell stack and take the form of naming convention. An example of this would be BeginProcessing or EndProcessing. Also included are the complex operations involved in a scripting language which will combine a branch as well, such as if-then-else or while-wend. PowerShell also provides arrays and associative arrays, evaluates arithmetic expressions on the command-line, and parses common abbreviations like KB, MB and GB.

Microsoft are working on a future version of PowerShell, Version 2.0 and probably it got success to it now.

Dirty Disk Check Procedure in Windows XP

ntroduction

A disk volume in a Windows computer running MS Windows XP and later can occasionally be marked as "dirty" which essentially means that the CHKDSK facility runs every time the computer starts. Why is the volume dirty? The Windows XP operating system does a regular check of the underlying file system where all the files needed to run the system are stored. If it finds inconsistencies in that file system, a check disk is scheduled to run at boot-up time (because it cannot run on files which are being used in a Windows environment. Once it has run, Windows can restart.
How To Unset A Dirty Bit On A Windows Disk Volume

A dirty volume can be checked by running the command:-

fsutil dirty query [drive volume name]

Example:

fsutil dirty query f:

or if the drive to be checked is d: then it would be

fsutil dirty query d:

It will likely come back with

Volume - f: is Dirty

If the volume is OK it will come back with:

Volume - f: is NOT Dirty

So now the volume must be manually checked to stop this endless loop of booting and rebooting and every time it does the volume is checked.
At a command prompt, type the command

CHKNTFS /X F:

(This will tell Windows NOT to check the disk at boot time.)

Reboot the computer, and unless another volume has issues, it will not pause for the CHKDSK facility before going back into Windows.
Now, once the computer has gone fully back into Windows, a thorough CHKDSK needs to be performed in order for the volume to be fixed so that it won't need checking at the next reboot. Type the command:

CHKDSK /f /r f:

and volume f: will be taken through five stages and the dirty bit will be finally unset. You can check that it is clean by issuing the command,

fsutil dirty query f:

and it will likely tell you

Volume - f: is NOT Dirty
So, why does it run over and over again? There are levels of operation within CHKDSK and CHKNTFS. And frequently, a drive will not require the very deep five stage scan required to fix this problem.

How To Start Windows XP in Safe Mode and then Normal Mode using MSConfig

Introduction

* Before scanning with any program; Turn off the restore feature. most programs cannot scan the resore feature files and if you have malware, chances are the system has made a copy and is storing it in the Restore files.
* If the files are difficult to remove or are memory resident, you will have to boot into Safe Mode.

Steps

To start Windows XP in Safe Mode using MSConfig:

* Close all open programs.
* Click Start and Run.
* In the Run dialog box, type msconfig and then click OK.
* In the System Configuration Utility, on the BOOT.INI tab, check /SAFEBOOT.
* Click OK.
* When you are asked to restart the computer, click Restart.

To start Windows XP in Normal Mode using MSConfig:

* Finish what you need to do in Safe mode.
* In the section "To use the System Configuration Utility to start Windows XP" above, repeat steps 1-7, but in step 4, uncheck /SAFEBOOT.
* Close all programs, and restart the computer

Reverse Engineering in MS Visio

Hi, If you want to reverse Engineering the model, First check MS visio version you are using. The option only available in MS Visio 2007 -- **Professional Edition**.

Then you proceed the below steps.


1. On the File menu, point to New, point to Database, and then click Database Model Diagram. 2. On the Database menu, click Reverse Engineer. 3. On the first screen of the Reverse Engineer Wizard, do the following: • Select the Microsoft Office Visio database driver for your database management system (DBMS). If you have not already associated the Visio database driver with a particular 32-bit ODBC data source, do so now. • Select the data source of the database you're updating. If you have not already created a data source for the existing database, do so now. Note When you create a new source, its name is added to the Data Sources list. • When you are satisfied with your settings, click Next. 4. Follow the instructions in any driver-specific dialog boxes. For example, in the Connect Data Source dialog box, type a user name and password, and then click OK. 5. Select the check boxes for the type of information you want to extract, and then click Next. 6. Select the check boxes for the tables (and views, if any) that you want to extract, or click Select All to extract them all, and then click Next. 7. If you selected the Stored Procedures check box in step 5, select the procedures that you want to extract, or click Select All to extract them all, and then click Next. 8. Select whether you want the reverse engineered items added automatically to the current page. 9. Review your selections to verify that you are extracting the information you want, and then click Finish. The wizard extracts the selected information and displays notes about the extraction process in the Output window. 10. Create a diagram of your model by • Dragging the tables you want to view from the Tables and Views window onto the drawing page. • Selecting a table, and then on the Database menu, clicking Show Related Tables to view the tables related to the selected table.

FAQ about Sharepoint

What is Microsoft Windows SharePoint Services? How is it related to Microsoft Office SharePoint Server 2007?

Windows SharePoint Services is the solution that enables you to create Web sites for information sharing and document collaboration. Windows SharePoint Services -- a key piece of the information worker infrastructure delivered in Microsoft Windows Server 2003ice system and other desktop applications, and it serves as a platform for application development.

Office SharePoint Server 2007 builds on top of Windows SharePoint Services 3.0 to provide additional capabilities including collaboration, portal, search, enterprise content management, business process and forms, and business intelligence.
[edit]
What is Microsoft SharePoint Portal Server?

SharePoint Portal Server is a portal server that connects people, teams, and knowledge across business processes. SharePoint Portal Server integrates information from various systems into one secure solution through single sign-on and enterprise application integration capabilities. It provides flexible deployment and management tools, and facilitates end-to-end collaboration through data aggregation, organization, and searching. SharePoint Portal Server also enables users to quickly find relevant information through customization and personalization of portal content and layout as well as through audience targeting.
[edit]
What is Microsoft Windows Services?

Microsoft Windows Services is the engine that allows administrators to create Web sites for information sharing and document collaboration. Windows SharePoint Services provides additional functionality to the Microsoft Office System and other desktop applications, as well as serving as a plat form for application development. SharePoint sites provide communities for team collaboration, enabling users to work together on documents, tasks, and projects. The environment for easy and flexible deployment, administration, and application development.
[edit]
What is the relationship between Microsoft SharePoint Portal Server and Microsoft Windows Services?

Microsoft SharePoint Products and Technologies (including SharePoint Portal Server and Windows SharePoint Services) deliver highly scalable collaboration solutions with flexible deployment and management tools. Windows SharePoint Services provides sites for team collaboration, while Share Point Portal Server connects these sites, people, and business processes—facilitating knowledge sharing and smart organizations. SharePoint Portal Server also extends the capabilities of Windows SharePoint Services by providing organizational and management tools for SharePoint sites, and by enabling teams to publish information to the entire organization.
[edit]
Who is Office SharePoint Server 2007 designed for?

SharePoint is fundamentally designed for information workers, but it is designed in such a way that it assists a wide spectrum of users and support staff. Key stakeholders are:

* business users,
* business administrators,
* IT administrators,
* IT developers.

The true beauty of SharePoint is the way that conduct of tasks can be devolved to the lowest possible level:

* many tasks can be achieved by business users without IT support;
* if a business user cannot perform a function, then in many cases a business administrator can assist;
* in the unlikely even that a business administrator cannot perform the task, then there is a large world-wide community that has developed thousands of 'add-ins' and web-parts that can be easily installed by an IT administrator;
* in the even more unlikely event that a ready-made 'add-in' is not available, then SharePoint provides a highly structured environment for developers.

SharePoint also provides a framework which is designed to simplify IT development and ongoing administration, in the first instance developers should endeavour to:

* develop as a web-part in order to preserve all other site functionality without losing the ability for business users to maintain the site;
* if the desired functionality cannot be developed as a web-part, then SharePoint provides a range of other (reversible) development options;
* the option for business users to reset components to the 'site definition' is invaluable and great caution should be exercised when making changes that alter components at this level;
* generally, (perhaps only as a last resort) is it rarely necessary to customise SharePoint in such a way that the full set of default functionality is altered.

[edit]
What are the main benefits of Office SharePoint Server 2007?

Office SharePoint Server 2007 provides a single integrated platform to manage intranet, extranet, and Internet applications across the enterprise.

* Business users gain greater control over the storage, security, distribution, and management of their electronic content, with tools that are easy to use and tightly integrated into familiar, everyday applications.
* Organizations can accelerate shared business processes with customers and partners across organizational boundaries using InfoPath Forms Services–driven solutions.
* Information workers can find information and people efficiently and easily through the facilitated information-sharing functionality and simplified content publishing. In addition, access to back-end data is achieved easily through a browser, and views into this data can be personalized.
* Administrators have powerful tools at their fingertips that ease deployment, management, and system administration, so they can spend more time on strategic tasks.
* Developers have a rich platform to build a new class of applications, called Office Business Applications, that combine powerful developer functionality with the flexibility and ease of deployment of Office SharePoint Server 2007. Through the use of out-of-the-box application services, developers can build richer applications with less code.

[edit]
How does SharePoint empower business users?

SharePoint is a set of powerful technologies that provide a large range of functions to users and administrators without the need to engage IT or developers. Once the basic SharePoint service is deployed, users can self-serve with a minimum of IT support.

* By default, all users can personalise their user experience, this includes such things as adding, removing or updating web-parts on any web-part page. These user changes can then be saved as a personal view. This is particularly useful because it allows users to create pages which contain the information that is relevant to them and it allows users to hide information (eg information that does not relate to their department or role).
* By default, all users can also create custom personal views in SharePoint. This is particularly helpful for large lists of information and gives users the ability to filter large lists of information to only show the information that is relevant to them, perhaps their department or division.

SharePoint also empowers users at the administration level. It is normal for users to be given the ability to alter "site settings", this is done by nominating one or more users to have "Full Control" of the user experience for any site. A user with "Full Control" can add additional web-parts, customise web-parts by adding metadata, and change the default view for all users. In effect, a user with "Full Control" over a site can create a rich user experience for the group of users that are using the particular site without any IT support or development skills.

It is also common for selected expert users to be appointed as "Site Collection Administrators" in order to facilitate the management of multiple sites which are called a site collection. The "Site Collection Administration" function also allows selected users to view all deleted items across an entire site, as well as turn on or off global features.

All of the functions listed above can normally be managed by business users and do not require IT support. No coding is required. All of these functions are managed by SharePoint through the SharePoint user interface. Thus, because there is no coding, there is no requirement for change control, testing or development protocols. A change log is still suggested.

For this reason, SharePoint is ideal for work-teams or project-teams that need to collaborate on a defined task. SharePoint gives the business user/ or team the ability to create a "site" that is highly customised for their particular needs without any need for IT support or development tools.

Indeed, all of the functionality listed above can generally be supported without the need for significant levels of governance. Some central governance is normally suggested, in order to do such things as maintain some control over different site collections, to maintain user groups, to share common infrastructure and to ensure that sites are managed through their lifecycle.

However,.. if (and many would say only if) the standard set of functions is insufficient, and additional functionality is required, then SharePoint provides a very strong set of tools and an excellent framework for developers. The beauty of SharePoint is that it is only at this point that IT support is really required.

And even then, many companies will find that the only IT support they require is to install "add-ons" from the SharePoint user community to their SharePoint server. Deployment of additional web-parts or "add-ons" generally requires specialist server administrator skills to deploy.

Business users can achieve a lot in SharePoint without writing a line of code or using development tools like Microsoft SharePoint Designer or similar development tools.
[edit]
What is the difference between Microsoft Office SharePoint Server 2007 for Internet sites and Microsoft Office SharePoint Server 2007?

Microsoft Office SharePoint Server 2007 for Internet sites and Microsoft Office SharePoint Server 2007 have identical feature functionality. While the feature functionality is similar, the usage rights are different.

If you are creating an Internet, or Extranet, facing website, it is recommended that you use Microsoft Office SharePoint Server 2007 for Internet sites which does not require the purchase client access licenses. Websites hosted using an “Internet sites” edition can only be used for Internet facing websites and all content, information, and applications must be accessible to non-employees. Websites hosted using an “Internet sites” edition cannot be accessed by employees creating, sharing, or collaborating on content which is solely for internal use only, such as an Intranet Portal scenario. See the previous section on licensing for more information on the usage scenarios.
[edit]
What suites of the 2007 Microsoft Office system work with Office SharePoint Server 2007?

Office Outlook 2007 provides bidirectional offline synchronization with SharePoint document libraries, discussion groups, contacts, calendars, and tasks.

Microsoft Office Groove 2007, included as part of Microsoft Office Enterprise 2007, will enable bidirectional offline synchronization with SharePoint document libraries.

Features such as the document panel and the ability to publish to Excel Services will only be enabled when using Microsoft Office Professional Plus 2007or Office Enterprise 2007.

Excel Services will only work with documents saved in the new Office Excel 2007 file format (XLSX).
[edit]
How do I invite users to join a Windows SharePoint Services Site? Is the site secure?

SharePoint-based Web sites can be password-protected to restrict access to registered users, who are invited to join via e-mail. In addition, the site administrator can restrict certain members' roles by assigning different permission levels to view post and edit.
[edit]
Can I post any kind of document?

You can post documents in many formats, including .pdf, .htm and .doc. In addition, if you are using Microsoft Office XP, you can save documents directly to your Windows SharePoint Services site.
[edit]
Can I download information directly from a SharePoint site to a personal digital assistant (PDA)?

No you cannot. However, you can exchange contact information lists with Microsoft Outlook.
[edit]
How long does it take to set up the initial team Web site?

It only takes a few minutes to create a complete Web site. Preformatted forms let you and your team members contribute to the site by filling out lists. Standard forms include announcements, events, contacts, tasks, surveys, discussions and links.
[edit]
Can I create custom templates?

Yes you can. You can have templates for business plans, doctor's office, lawyer's office etc.
[edit]
How can I make my site public? By default, all sites are created private.

If you want your site to be a public Web site, enable anonymous access for the entire site. Then you can give out your URL to anybody in your business card, e-mail or any other marketing material. The URL for your Web site will be: http:// yoursitename.wss.bcentral.com

Hence, please take special care to name your site. These Web sites are ideal for information and knowledge intensive sites and/or sites where you need to have shared Web workspace. Remember: Under each parent Web site, you can create up to 10 sub-sites each with unique permissions, settings and security rights.
[edit]
How do the sub sites work?

You can create a sub site for various categories. For example:

* Departments - finance, marketing, IT
* Products - electrical, mechanical, hydraulics
* Projects - Trey Research, Department of Transportation, FDA
* Team - Retention team, BPR team
* Clients - new clients, old clients
* Suppliers - Supplier 1, Supplier 2, Supplier 3
* Customers - Customer A, Customer B, Customer C
* Real estate - property A, property B

The URLs for each will be, for example:

* http://yoursitename.wss.bcentral.com/finance
* http://yoursitename.wss.bcentral.com/marketing

You can keep track of permissions for each team separately so that access is restricted while maintaining global access to the parent site.
[edit]
How do I make my site non-restricted?

If you want your site to have anonymous access enabled (i.e., you want to treat it like any site on the Internet that does not ask you to provide a user name and password to see the content of the site), follow these simple steps:

1. Login as an administrator
2. Click on site settings
3. Click on Go to Site Administration
4. Click on Manage anonymous access
5. Choose one of the three conditions on what Anonymous users can access:

*
o Entire Web site
o Lists and libraries
o Nothing

Default condition is nothing; your site has restricted access. The default conditions allow you to create a secure site for your Web site.
[edit]
Can I get domain name for my Web site?

Unfortunately, no. At this point, we don't offer domain names for SharePoint sites. But very soon we will be making this available for all our SharePoint site customers. Please keep checking this page for further update on this. Meanwhile, we suggest you go ahead and set up your site and create content for it.
[edit]
What are picture libraries?

Picture libraries allow you to access a photo album and view it as a slide show or thumbnails or a film strip. You can have separate folder for each event, category, etc
[edit]
What are the advantages of a hosted SharePoint vs. one that is on an in-house server?

* No hardware investment, i.e. lower costs
* No software to download - ready to start from the word go
* No IT resources - Anyone who has used a Web program like Hotmail can use it
* Faster deployment

[edit]
Can I ask users outside of my organization to participate in my Windows SharePoint Services site?

Yes. You can manage this process using the Administration Site Settings. Simply add users via their e-mail alias and assign permissions such as Reader or Contributor.
[edit]
Are there any IT requirements or downloads required to set up my SharePoint site?

No. You do not need to download any code or plan for any IT support. Simply complete the on-line signup process and provide us your current and correct email address. Once you have successfully signed up and your site has been provisioned, we will send a confirmation to the email address you provided.
[edit]
I am located outside of the United States. Are there any restrictions or requirements for accessing the Windows SharePoint Services?

No. There are no system or bandwidth limitations for international trial users. Additionally language packs have been installed which allow users to set up sub-webs in languages other than English. These include: Arabic, Danish, Dutch, Finnish, French, German, Hebrew, Italian, Japanese, Polish, Portuguese (Brazilian), Spanish and Swedish.
[edit]
Are there any browser recommendations?

Yes. Microsoft recommends using the following browsers for viewing and editing Windows SharePoint Services sites: Microsoft Internet Explorer 5.01 with Service Pack 2, Microsoft Internet Explorer 5.5 with Service Pack 2, Internet Explorer 6, Netscape Navigator 6.2 or later.


[edit]
What security levels are assigned to users?

Security levels are assigned by the administrator who is adding the user. There are four levels by default and additional levels can be composed as necessary.

* Reader - Has read-only access to the Web site.
* Contributor - Can add content to existing document libraries and lists.
* Web Designer - Can create lists and document libraries and customize pages in the Web site.
* Administrator - Has full control of the Web site.

[edit]
How secure are Windows SharePoint Services sites hosted by Microsoft?

Microsoft Windows SharePoint Services Technical security measures provide firewall protection, intrusion detection, and web-publishing rules. The Microsoft operation center team tests and deploys software updates in order to maintain the highest level of security and software reliability. Software hot-fixes and service packs are tested and deployed based on their priority and level of risk. Security related hot-fixes are rapidly deployed into the environment to address current threats. A comprehensive software validation activity ensures software stability through regression testing prior to deployment.
[edit]
What is the difference between an Internet and an intranet site?

An internet site is a normal site that anyone on the internet can access (e.g., www.msn.com, www.microsoft.com, etc.). You can set up a site for your company that can be accessed by anyone without any user name and password. The internet is used for public presence and a primary marketing tool managed typically by web programmers and a system administrator.

An intranet (or internal network), though hosted on a Web site, can only be accessed by people who are members of a specific network. They need to have a login and password that was assigned to them when they were added to the site by the site administrator. The intranet is commonly used as an internal tool for giving employees access to company information. Content is driven by business relevance, business rules and has increasingly become a common tool in larger organizations. An intranet is becoming more and more the preferred method for employees to interact with each other and the central departments in an organization, whether or not the organization has a Web presence.
[edit]
What is a workspace?

A site or workspace is when you want a new place for collaborating on Web pages, lists and document libraries. For example, you might create a site to manage a new team or project, collaborate on a document or prepare for a meeting.
[edit]
What are the various kinds of roles the users can have?

A user can be assigned one of the following roles

* Reader - Has read-only access to the Web site.
* Contributor - Can add content to existing document libraries and lists.
* Web Designer - Can create lists and document libraries and customize pages in the Web site.
* Administrator - Has full control of the Web site.

[edit]
Can more than one person use the same login?

If the users sharing that login will have the same permissions and there is no fear of them sharing a password, then yes. Otherwise, this is discouraged.
[edit]
How customizable is the user-to-user access?

User permissions apply to an entire Web, not to documents themselves. However, you can have additional sub webs that can optionally have their own permissions. Each user can be given any of four default roles. Additional roles can be defined by the administrator.
[edit]
Can each user have access to their own calendar?

Yes there are two ways to do this,

* by creating a calendar for each user, or
* by creating a calendar with a view for each user

[edit]
How many files can I upload?

There is no restriction in place except that any storage consumed beyond that provided by the base offering may have an additional monthly charge associated with them.
[edit]
What types of files can I upload / post to the site?

The only files restricted are those ending with the following extensions: .asa, .asp, .ida, .idc, .idq. Microsoft reserves the right to add additional file types to this listing at any time. Also, no content that violates the terms of service may be uploaded or posted to the site.
[edit]
Can SharePoint be linked to an external data source?

SharePoint data can be opened with Access and Excel as an external data source. Thus, SharePoint can be referenced as an external data source. SharePoint itself cannot reference an external data source.

But 3rd pary software can do this for you: http://www.layer2.de/en/products/pages/sharepoint-business-data-list-connector.aspx
[edit]
Can SharePoint be linked to a SQL database?

SharePoint 2007 Portal Server (MOSS2K7) allows connections to SQL based datasources via the Business Data Catalog (BDC). The BDC also allows connecting to data via Web Services. Or you can link lists directly qith sql queries in the list settings using the BDLC found here: http://bit.ly/p30tJ .
[edit]
Can I customize my Windows SharePoint Services site?

YES! Windows SharePoint Services makes updating sites and their content from the browser easier then ever.

SharePoint includes tools that let you create custom lists, calendars, page views, etc. You can apply a theme; add List, Survey and Document Library Web Parts to a page; create personal views; change logos; connect Web Parts and more.

To fully customize your site, you can use Microsoft FrontPage 2003. Specifically, you can use FrontPage themes and shared borders, and also use FrontPage to create photo galleries and top ten lists, utilize standard usage reports, and integrate automatic Web content.
[edit]
Will Microsoft Office SharePoint Server 2007 run on a 64-bit version of Microsoft Windows?

Windows SharePoint Services 3.0, Office SharePoint Server 2007, Office Forms Server 2007, and Office SharePoint Server 2007 for Search will support 64-bit versions of Windows Server 2003.
[edit]
How Office SharePoint Server 2007 can help you?

Office SharePoint Server 2007 can help us:

Manage content and streamline processes. Comprehensively manage and control unstructured content like Microsoft Office documents, Web pages, Portable Document Format file (PDF) files, and e-mail messages. Streamline business processes that are a drain on organizational productivity.

Improve business insight. Monitor your business, enable better-informed decisions, and respond proactively to business events.

Find and share information more simply. Find information and expertise wherever they are located. Share knowledge and simplify working with others within and across organizational boundaries.

Empower IT to make a strategic impact. Increase responsiveness of IT to business needs and reduce the number of platforms that have to be maintained by supporting all the intranet, extranet, and Web applications across the enterprise with one integrated platform.

Office SharePoint Server 2007 capabilities can help improve organizational effectiveness by connecting people, processes, and information.

Office SharePoint Server 2007 provides these capabilities in an integrated server offering, so your organization doesn't have to integrate fragmented technology solutions itself.
[edit]
What are the features that the portal components of Office SharePoint Server 2007 include?

The portal components of Office SharePoint Server 2007 include features that are especially useful for designing, deploying, and managing enterprise intranet portals, corporate Internet Web sites, and divisional portal sites. The portal components make it easier to connect to people within the organization who have the right skills, knowledge, and project experience.
[edit]
What are the advanced features of MOSS 2007?

* User Interface (UI) and navigation enhancements
* Document management enhancements
* The new Workflow engine
* Office 2007 Integration
* New Web Parts
* New Site-type templates
* Enhancements to List technology
* Web Content Management
* Business Data Catalog
* Search enhancements
* Report Center
* Records Management
* Business Intelligence and Excel Server
* Forms Server and InfoPath
* The “Features” feature
* Alternate authentication providers and Forms-based authentication

[edit]
What are the features of the new Content management in Office SharePoint 2007?

The new and enhanced content management features in Office SharePoint Server 2007 fall within three areas:

* Document management
* Records management
* Web content management

Office SharePoint Server 2007 builds on the core document management functionality provided by Windows SharePoint Services 3.0, including check in and check out, versioning, metadata, and role-based granular access controls. Organizations can use this functionality to deliver enhanced authoring, business document processing, Web content management and publishing, records management, policy management, and support for multilingual publishing.
[edit]
Does a SharePoint Web site include search functionality?

Yes. SharePoint Team Services provides a powerful text-based search feature that helps you find documents and information fast.
[edit]
Write the features of the search component of Office SharePoint Server 2007?

The search component of Office SharePoint Server 2007 has been significantly enhanced by this release of SharePoint Products and Technologies. New features provide:

* A consistent and familiar search experience.
* Increased relevance of search results.
* New functions to search for people and expertise.
* Ability to index and search data in line-of-business applications and
* Improved manageability and extensibility.

[edit]
What are the benefits of Microsoft Office SharePoint Server 2007?

* Provide a simple, familiar, and consistent user experience.
* Boost employee productivity by simplifying everyday business activities.
* Help meet regulatory requirements through comprehensive control over content.
* Effectively manage and repurpose content to gain increased business value.
* Simplify organization-wide access to both structured and unstructured information across disparate systems.
* Connect people with information and expertise.
* Accelerate shared business processes across organizational boundaries.
* Share business data without divulging sensitive information.
* Enable people to make better-informed decisions by presenting business-critical information in one central location.
* Provide a single, integrated platform to manage intranet, extranet, and Internet applications across the enterprise.

[edit]
Will SharePoint Portal Server and Team Services ever merge?

The products will come together because they are both developed by the Office team.
[edit]
What does partial trust mean the Web Part developer?

If an assembly is installed into the BIN directory, the code must be ensured that provides error handling in the event that required permissions are not available. Otherwise, unhandled security exceptions may cause the Web Part to fail and may affect page rendering on the page where the Web Part appears.
[edit]
How can I raise the trust level for assemblies installed in the BIN directory?

Windows SharePoint Services can use any of the following three options from ASP.NET and the CLR to provide assemblies installed in the BIN directory with sufficient permissions. The following table outlines the implications and requirements for each option.

Option Pros Cons

Increase the trust level for the entire virtual server. For more information, see "Setting the trust level for a virtual server" Easy to implement.

In a development environment, increasing the trust level allows you to test an assembly with increased permissions while allowing you to recompile assemblies directly into the BIN directory without resetting IIS. This option is least secure.

This option affects all assemblies used by the virtual server. There is no guarantee the destination server has the required trust level. Therefore, Web Parts may not work once installed on the destination server.

Create a custom policy file for your assemblies. For more information, see "How do I create a custom policy file?" Recommended approach.

This option is most secure.

An assembly can operate with a unique policy that meets the minimum permission requirements for the assembly.

By creating a custom security policy, you can ensure the destination server can run your Web Parts.

Requires the most configuration of all three options. Install your assemblies in the GAC

Easy to implement. This grants Full trust to your assembly without affecting the trust level of assemblies installed in the BIN directory.

This option is less secure.

Assemblies installed in the GAC are available to all virtual servers and applications on a server running Windows SharePoint Services. This could represent a potential security risk as it potentially grants a higher level of permission to your assembly across a larger scope than necessary

In a development environment, you must reset IIS every time you recompile assemblies.

Licensing issues may arise due to the global availability of your assembly.
[edit]
Does SharePoint work with NFS?

Yes and no. It can crawl documents on an NFS volume, but the sharepoint database or logs cannot be stored there.
[edit]
How is SharePoint Portal Server different from the Site Server?

Site Server has search capabilities but these are more advanced using SharePoint. SPS uses digital dashboard technology which provides a nice interface for creating web parts and showing them on dashboards (pages). SS doesn't have anything as advanced as that. The biggest difference would be SPS document management features which also integrate with web folders and MS Office.
[edit]
What would you like to see in the next version of SharePoint?

A few suggestions:

1. SPS and STS on same machine
2. Tree view of Categories and Folders
3. General Discussion Web Part
4. Personalization of Dashboards
5. Role Customization
6. Email to say WHY a document has been rejected for Approval
7. More ways to customize the interface
8. Backup and restore an individual Workspaces
9. Filter for Visio
10. Better way to track activity on SPS
11. Ability to Save as from Adobe to space on My Network Places

[edit]
Why Sharepoint is not a viable solution for enterprise wide deployments?

Planning an enterprise deployment using SharePoint features is a very difficult task unless you can establish a Service Oriented Architecture, using AD for managing security with well defined roles based information access(EISA). Sounds reasonable, although it seems difficult to deploy with the tools limitations in document storage.

Document management does not scale beyond a single server, but scales great within a single server. For example, a quad Xeon machine with 4GB of RAM works great for a document management server that has about 900,000 - 1,000,000 document, but if you need to store 50,000,000 document and want to have them all in one single workspace then it does not scale at all. If you need a scenario like this, you need to plan your deployment right and it should scale for you, it just does not right out of the box. If you are using your server as a portal and search server most for the most part it scales great. You can have many different servers crawl content sources and have separate servers searching and serving the content.

If you have < 750,000 documents per server and fewer than 4 content sources and fewer than 50,000 users, SPS should scale just fine for your needs with the proper planning.
[edit]
What are the actual advantages of SharePoint Portal Services (SPS) over SharePoint Team Services (STS)?

SharePoint Portal Services (SPS) has MUCH better document management. It has check-in, check-out, versioning, approval, publishing, subscriptions, categories, etc. STS does not have these features, or they are very scaled back. SharePoint Portal Services (SPS) has a better search engine, and can crawl multiple content sources. STS cannot. STS is easier to manage and much better for a team environment where there is not much Document Management going on. SPS is better for an organization, or where Document Management is crucial.
[edit]
How Does SharePoint work?

The browser sends a DAV packet to IIS asking to perform a document check in. PKMDASL.DLL, an ISAPI DLL, parses the packet and sees that it has the proprietary INVOKE command. Because of the existence of this command, the packet is passed off to msdmserv.exe, who in turn processes the packet and uses EXOLEDB to access the WSS, perform the operation and send the results back to the user in the form of XML.
[edit]
How do I open an older version of a document?

Normally, all previous versions are located in the shadow, so if you right click a published document from within the web folders, go to properties and then the third tab, versions you can view older versions.

If you want to do this in code:

strURL = "url of the last published version"
Set oVersion = New PKMCDO.KnowledgeVersion
Set prmRs = oVersion.VersionHistory(strURL)
Set oVersion = Nothing

prmRS will contain a recordset, which contains the url to the old versions in the shadow.
[edit]
Why do the workspace virtual directories show the error “stop sign” symbol in the IIS snap-in?

If World Wide Web Publishing Service (W3SVC) starts before Microsoft Exchange Information Store (MSExchangeIS), “stop sign” symbols appear under the Default Web Site folder of the Internet Information Services console in Microsoft Management Console (MMC).

There is a dependency between the local paths of the SharePoint Portal Server virtual directories and the MSExchangeIS. You must start MSExchangeIS first, followed by W3SVC.

Complete the following steps to prevent the stop signs from appearing each time you restart:

1. Change the Startup type for W3SVC to Manual.
2. Restart the server. The MSExchangeIS service starts automatically.
3. Start W3SVC.

[edit]
What newsgroups are available?

There are two,

* microsoft.public.sharepoint.portalserver and
* microsoft.public.sharepoint.portalserver.development.

[edit]
What is SharePoint from a Technical Perspective?

Technically SharePoint illustrates neatly what Microsoft's .net strategy is all about: integrating Windows with the Web. Microsoft has previously made accessing stuff on a PC easier, (Windows) then on a network (NT) and now on the web (.NET). SharePoint is an application written to let a user access a web accessible directory tree called the Web Storage System.

SharePoint was written with a set of technologies that allow the programmer to pass data, functions, parameters over HTTP, the web's medium. These are XML, XSL and SOAP, to name a few I understand the basics of!

To the user it looks easy, like Hotmail, but every time they click a button or a link, a lot has to happen behind the scenes to do what they want to do quickly and powerfully. Not as easy as you might think, but SharePoint does it for you. Accessing this Web storage system and the server itself is also done using technologies like ADO, CDO, PKMCDO, LDAP, DDSC, ADSC. More on these later. SharePoint is a great example of how the Internet Platform can be extended and integrated into an existing well adopted technology, Windows.
[edit]
What is SharePoint from an Administration Perspective?

Administering SharePoint mainly consists of setting it up, which is much easier than you expect, adding the content, which can be just dragging and dropping in whole directory structures and files, and then organizing the files better by giving them categories or other metadata. This is done either through the Web interface or through the SharePoint Client: a program what means you can access SharePoint as a Web folder and then right-click files to select options like "edit profile". Or add files by dragging them in individually or in bulk.

Setting the security is also important, using NT accounts, either NT4 or Active Directory (or both in mixed mode) you can give users access to files/folders the same way as you do in standard Windows. Users can be grouped and the groups given access privileges to help manage this better. Also SharePoint has 3 Roles that a User or Group can be given on a particular item. Readers can see the item (i.e. document/file or folder) but not change it, Authors can see and edit items and coordinators can set security privileges for the part of the system they have control over. Thus, you could set 12 different coordinators for 12 different folder trees, and they could manage who can do what within that area only.
[edit]
What is SharePoint from a Users Perspective?

From a Users perspective SharePoint is a way of making documents and folders on the Windows platform accessible over the web. The user visits the SharePoint Portal web page, and from there they can add documents, change documents & delete documents. Through this Portal, these documents are now available for discussion, collaboration, versioning and being managed through a workflow. Hence the name "Share-Point". Details about the document can be saved too, such as: who wrote it, when, for whom, its size, and version, category or target audience. These can then be used to find the document through SharePoint's Search facility. Even documents not "in" SharePoint can be included in the search engine's index so they become part of the portal. All in all, it's a great way to get stuff up on the web for users with average technical skills, and for administrators to manage the content.
[edit]
What are the various Sharepoint 2003 and Exchange integration points?
[edit]
Link to Outlook

This is a button on contacts or events lists that lets Outlook 2003 add a pst file named Sharepoint Folders and it links to the data on the site. It’s read-only, but you could make the home page for that PST be the Sharepoint site for easier viewing. The link to outlook feature seems more to be where some can public a calendar, but not want too much collaboration. For example, a holiday schedule, company meeting schedule, etc, can be made available for people to be able to view from Outlook without having to go to a web browser. Another nice thing about OL2K3 is that you can compare these calendars with others side by side.
[edit]
Searching Public Folders

With SPS you can index Exchange’s public folders with the search engine so that all that precious public folder content is searchable. You’ll want to look at content sources and indexing in Sharepoint administration.
[edit]
Displaying Public Folders in a web part

Since exchange web-enables public folders, you can create a web part that displays that content. IE, http://exchangeserver/Public/IT/Helpdesk will display the IT/Helpdesk public folder via OWA. So you add the Page Viewer web part to a page and point it at that URL. The key here is to add ?cmd=contents to the end of the url if you don’t want the navigator pane on the left.
[edit]
Smart web parts

Some of the web parts that come with SPS allow you to add a web part to a page that actually takes the users outlook info (calendar, inbox, contacts, tasks) and put them into the page.

The SmartPart Web Part project template for Visual Studio allows developers to create quickly a project which contains the base infrastructure to:

* write a web user control (ASCX)
* wrap the user control in a SmartPart instance
* generate a SharePoint Solution file (WSP) for easy deployment
* generate a setup package for a wizard driven installation

[edit]
Can SharePoint compare two document versions?

"In Word 2003, you can compare documents side by side. Open two documents. Then, from the Window menu of one of them, select the Compare Side By Side command. If you have only two documents open, the command will automatically choose to compare them. If you have three or more documents open, you'll have to select which document to compare with the current file.

A floating toolbar with two buttons will open. If the button on the left is selected, Word will scroll both documents at the same time. Press the button on the right side of the toolbar to return to where the cursor was located when you started comparing."
[edit]
What are the integration differences between SPS 2003 and the various Office versions?

SPS webpage can detect you have installed the Office 2003 and run local dll to implement some SPS function, e.g. multi-file upload only works when you have office 2003 installed.

Integration with Office XP is gone.

You will get guys telling you that you can integrate with SPSv2 if you install a backwards compatible document library - but that’s really just putting a bit of SPS 2001 on the server.

Believe me, check-in, check-out, which are themselves very basic, are not available from inside Office XP, or even from the context menu in Windows Explorer.

The ONLY option you have is to use the web interface to check-in or check-out.

Friday, February 11, 2011

FAQ about Windows Forms (.NET)

How can I programmatically maximize or minimize a form?


The Brushes Sample shows you how to use four different brushes in several shapes. Below is a code snippet showing how to use hatched and gradient brushes.

Rectangle rect = new Rectangle(35, 190, 100, 100);
LinearGradientBrush brush2 = new LinearGradientBrush(rect,
Color.DarkOrange, Color.Aquamarine,
LinearGradientMode.ForwardDiagonal);
g.FillEllipse(brush2, 35, 190, 100, 100);

HatchBrush brush1 = new HatchBrush(HatchStyle.DiagonalCross,
Color.DarkOrange, Color.Aquamarine);
g.FillEllipse(brush1, 35, 190, 100, 100);





How can I display a pop up a confirmation dialog when the user closes the form?


You can listen to the Form's Closing event, where you can display a MessageBox as show below:
[C#]
private void Form1_Closing(object sender, System.ComponentModel.CancelEventArgs e)
{
if (MessageBox.Show("Do you want to close the application?", "Close Application", MessageBoxButtons.YesNo) == DialogResult.No)
e.Cancel = true;

}
[VB.NET]
Private Sub Form1_Closing(ByVal sender As Object, ByVal e As System.ComponentModel.CancelEventArgs)
If MessageBox.Show("Do you want to close the application?","Close Application",MessageBoxButtons.YesNo) = DialogResult.No Then
e.Cancel = True
End If

End Sub



How can I center my form?


You can set the Form's StartPosition property to CenterScreen to achieve this.




How do I prevent users from resizing a form?


You can prevent the users from resizing a form by setting the FormBorderStyle to FixedDialog and setting the MaximizeBox property to false.



How do I programmatically set an image as Form's Icon ?


You could do so as shown in the code below :
[C#]
Form form1 = new Form();
Bitmap bmp = imageList1.Images[index] as Bitmap;
form1.Icon = Icon.FromHandle(bmp.GetHicon());

[VB.NET]
Dim form1 As Form = New Form()
Dim bmp As Bitmap = imageList1.Images(index) as Bitmap
form1.Icon = Icon.FromHandle(bmp.GetHicon())



How can I add items to the System Menu of a form.


To do this, you can use use iterop to access the GetSystemMenu and AppendMenu Win32 APIs. You also need to override the form's WndProc method to catch and act on the menu message. This idea was posted in the Microsoft newsgroups by Lion Shi.



How can I have a form with no title bar, but yet keep the resizing borders?


Set your form's Text and ControlBox properties.
myForm.Text = "";
myForm.ControlBox = false;




How can I tell if a form is closed from the controlbox (system menu) or from a call to Form.Close?


One way to do this is to override the form's WndProc method and check for WM_SYSCOMMAND and SC_CLOSE. Looking for WM_CLOSE in the override is not sufficient as WM_CLOSE is seen in both cases. A sample is available for download (C#, VB).
public const int SC_CLOSE = 0xF060;
public const int WM_SYSCOMMAND = 0x0112;

//_closeClick is a bool member of the form initially set false...
// It can be tested in the Closing event to see how the closing came about.

protected override void WndProc(ref System.Windows.Forms.Message m)
{
if(m.Msg == WM_SYSCOMMAND && (int)m.WParam == SC_CLOSE)
this._closeClick = true;

base.WndProc(ref m);
}





I have two forms. How can I access a textbox on one form from the other form?


One way to do this is to make the TextBox either a public property or a public field. Then you will be able to access it through the instance of its parent form. So, if TextBox1 is a public member of FormA and myFormA is an instance of FormA, then you can use code such as
[VB.NET]
Dim strValue as String = myFormA.TextBox1.Text

[C#]
string strValue = myFormA.TextBox1.Text;

anywhere myFormA is known.





How do I create a non-modal top level form that always stays on top of all the app's windows (like the VS.Net find dialog)?


Make your main form the "Owner" of the form in question. Refer to Form.Owner in class reference for more information.

[C#]
findReplaceDialog.Owner = this; // Your main form.
findReplaceDialog.TopLevel = false;
[VB.Net]
findReplaceDialog.Owner = Me ' Your main form.
findReplaceDialog.TopLevel = False




How can I display a form that is 'TopMost' for only my application, but not other applications?


The idea is to create the 'bound' table in your dataset, and then add an extra 'unbound' column. The steps are to derive a custom columnstyle that overrides Paint where you calculate and draw the unbound value. You can also override Edit to prevent the user from selecting your unbound column. Then to get your datagrid to use this special column style, you create a tablestyle and add the column styles to it in the order you want the columns to appear in the datagrid. Here are code snippets that derive the column and use the derived column.

// custom column style that is an unbound column
public class DataGridUnboundColumn : DataGridTextBoxColumn
{
protected override void Edit(System.Windows.Forms.CurrencyManager source, int rowNum, System.Drawing.Rectangle bounds, bool readOnly, string instantText, bool cellIsVisible)
{
//do not allow the unbound cell to become active
if(this.MappingName == "UnBound")
return;

base.Edit(source, rowNum, bounds, readOnly, instantText, cellIsVisible);
}

protected override void Paint(System.Drawing.Graphics g, System.Drawing.Rectangle bounds, System.Windows.Forms.CurrencyManager source, int rowNum, System.Drawing.Brush backBrush, System.Drawing.Brush foreBrush, bool alignToRight)
{

//clear the cell
g.FillRectangle(new SolidBrush(Color.White), bounds);

//compute & draw the value
//string s = string.Format("{0} row", rowNum);
// col 0 + 2 chars from col 1
DataGrid parent = this.DataGridTableStyle.DataGrid;
string s = parent[rowNum, 0].ToString() + ((parent[rowNum, 1].ToString())+ " ").Substring(0,2);
Font font = new Font("Arial", 8.25f);
g.DrawString(s, font, new SolidBrush(Color.Black), bounds.X, bounds.Y);
font.Dispose();

}
}


//code that uses this unbound column
private void Form1_Load(object sender, System.EventArgs e)
{
// Set the connection and sql strings
// assumes your mdb file is in your root
string connString = @"Provider=Microsoft.JET.OLEDB.4.0;data source=C:\northwind.mdb";
string sqlString = "SELECT * FROM customers";

OleDbDataAdapter dataAdapter = null;
DataSet _dataSet = null;

try
{
// Connection object
OleDbConnection connection = new OleDbConnection(connString);

// Create data adapter object
dataAdapter = new OleDbDataAdapter(sqlString, connection);

// Create a dataset object and fill with data using data adapter's Fill method
_dataSet = new DataSet();
dataAdapter.Fill(_dataSet, "customers");
connection.Close();
}
catch(Exception ex)
{
MessageBox.Show("Problem with DB access-\n\n connection: "
+ connString + "\r\n\r\n query: " + sqlString
+ "\r\n\r\n\r\n" + ex.ToString());
this.Close();
return;
}

// Create a table style that will hold the new column style
// that we set and also tie it to our customer's table from our DB
DataGridTableStyle tableStyle = new DataGridTableStyle();
tableStyle.MappingName = "customers";

// since the dataset has things like field name and number of columns,
// we will use those to create new columnstyles for the columns in our DB table
int numCols = _dataSet.Tables["customers"].Columns.Count;

//add an extra column at the end of our customers table
_dataSet.Tables["customers"].Columns.Add("Unbound");

DataGridTextBoxColumn aColumnTextColumn ;
for(int i = 0; i < numCols; ++i) { aColumnTextColumn = new DataGridTextBoxColumn(); aColumnTextColumn.HeaderText = _dataSet.Tables["customers"].Columns[i].ColumnName; aColumnTextColumn.MappingName = _dataSet.Tables["customers"].Columns[i].ColumnName; tableStyle.GridColumnStyles.Add(aColumnTextColumn); //display the extra column after column 1. if( i == 1) { DataGridUnboundColumn unboundColStyle = new DataGridUnboundColumn(); unboundColStyle.HeaderText = "UnBound"; unboundColStyle.MappingName = "UnBound"; tableStyle.GridColumnStyles.Add(unboundColStyle); } } // make the dataGrid use our new tablestyle and bind it to our table dataGrid1.TableStyles.Clear(); dataGrid1.TableStyles.Add(tableStyle); dataGrid1.DataSource = _dataSet.Tables["customers"]; } } How do I automatically resize the Form when the screen resolution changes between design-time and runtime? The framework automatically resizes the form if the current Font size during runtime is different from the font size in design-time. It however doesn't auto size when the resolution changes. But it should be easy for you to accomplish. You could derive a custom Form, provide a "ScreenResolutionBase" property that could return the current screen resolution (Screen.PrimarScreen.Bounds will give you this). This value will get serialized in code during design time. Then during runtime in the Form's OnLoad you could check for the current screen resolution and resize the Form appropriately. How can I ensure that my form will always be on the desktop? To set or control the location of the form using desktop coordinates, you can use the SetDeskTopLocation property. You can do this by setting the child form's TopMost to False and setting its Owner property to the Main Form. [C#] this.SetDesktopLocation(1,1); [VB.NET] Me.SetDesktopLocation(1,1) How can I restrict or control the size of my form? You can restrict the size of a form by setting it's MaximumSize and MinimumSize properties. This will help you control the maximum and minimum size the form can be resized to. Also note that WindowState property of the form plays a part in how the form can be resized. [C#] //Minimum width = 300, Minimum height= 300 this.MinimumSize = new Size(300, 300); //Maximum width = 800, Maximum height= unlimited this.MaximumSize = new Size(800, int.MaxValue); [VB.NET] 'Minimum width = 300, Minimum height= 300 Me.MinimumSize = New Size(300, 300) 'Maximum width = 800, Maximum height= unlimited Me.MaximumSize = New Size(800, Integer.MaxValue) How can I prevent a form from being shown in the taskbar? You need to set the form's ShowInTaskbar property to False to prevent it from being displayed in the Windows taskbar. [C#] this.ShowInTaskbar = false; [VB.NET] Me.ShowInTaskbar = False How do I prevent a user from moving a form at run time? The following code snippet (posted in the Windows Forms FAQ forums) shows how you can prevent a user from moving a form at run time: [C#] protected override void WndProc(ref Message m) { const int WM_NCLBUTTONDOWN = 161; const int WM_SYSCOMMAND = 274; const int HTCAPTION = 2; const int SC_MOVE = 61456; if((m.Msg == WM_SYSCOMMAND) && (m.WParam.ToInt32() == SC_MOVE)) { return; } if((m.Msg == WM_NCLBUTTONDOWN) && (m.WParam.ToInt32() == HTCAPTION)) { return; } base.WndProc (ref m); } [VB.NET] Protected Overrides Sub WndProc(ByRef m As Message) const Integer WM_NCLBUTTONDOWN = 161 const Integer WM_SYSCOMMAND = 274 const Integer HTCAPTION = 2 const Integer SC_MOVE = 61456 If (m.Msg = WM_SYSCOMMAND) &&(m.WParam.ToInt32() = SC_MOVE) Then Return End If If (m.Msg = WM_NCLBUTTONDOWN) &&(m.WParam.ToInt32() = HTCAPTION) Then Return End If MyBase.WndProc( m) End Sub How can I create a non rectangular form? This MSDN article titled Shaped Windows Forms and Controls in Visual Studio .NET shows how you can create non rectangular forms.




How can I make my form cover the whole screen including the TaskBar?


The following code snippet demonstrates how you can make your form cover the whole screen including the Windows Taskbar.
[C#]
// Prevent form from being resized.
this.FormBorderStyle = FormBorderStyle.FixedSingle;
// Get the screen bounds
Rectangle formrect = Screen.GetBounds(this);
// Set the form's location and size
this.Location = formrect.Location;
this.Size = formrect.Size;

[VB.NET]
' Prevent form from being resized.
Me.FormBorderStyle = FormBorderStyle.FixedSingle
' Get the screen bounds
Dim formrect As Rectangle = Screen.GetBounds(Me)
' Set the form's location and size
Me.Location = formrect.Location
Me.Size = formrect.Size







How can I move a Borderless form?


This code snippet shows how you can move a borderless form.
[C#]
public const int WM_NCLBUTTONDOWN = 0xA1;
public const int HTCAPTION = 0x2;
[DllImport("User32.dll")]
public static extern bool ReleaseCapture();
[DllImport("User32.dll")]
public static extern int SendMessage(IntPtr hWnd, int Msg, int wParam, int lParam);

private void Form1_MouseDown(object sender, System.Windows.Forms.MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
ReleaseCapture();
SendMessage(Handle, WM_NCLBUTTONDOWN, HTCAPTION, 0);
}
}






How do I force a Windows Form application to exit?


Your main form is an object of type System.Windows.Forms.Form. Use its Close method to exit the application. If you wish to Exit from a Form's constructor, this will not work. A workaround is to set a boolean flag that you can later check in the Form's Load method to call Close if required.

Another way is to use the Application.Exit() method.



How do I set the default button for a form?


Set the form's AcceptButton property. You can do this either through the designer, or through code such as
Form1.AcceptButton = button1;



How do I get an HWND for a form?


See the Control.Handle property which returns the HWND. Be careful if you pass this handle to some Win32 API as Windows Forms controls do their own handle management so they may recreate the handle which would leave this HWND dangling.



How can I detect if the user clicks into another window from my modal dialog?


Use the Form.Deactivate event:
this.Deactivate += new EventHandle(OnDeactivate);
//...

private void OnDeactivate(object s, EventArgs e)
{
this.Close();
}




How do I create a form with no border?


Use the Form.FormBorderStyle property to control a form's border.
public void InitMyForm()
{
// Adds a label to the form.
Label label1 = new Label();
label1.Location = new System.Drawing.Point(80,80);
label1.Name = "label1";
label1.Size = new System.Drawing.Size(132,80);
label1.Text = "Start Position Information";
this.Controls.Add(label1);

// Changes the border to Fixed3D.
FormBorderStyle = FormBorderStyle.Fixed3D;

// Displays the border information.
label1.Text = "The border is " + FormBorderStyle;
}

(From the .NET Framework SDK documentation)




How do I prevent a Form from closing when the user clicks on the close button on the form's system menu?


Handle the form's Closing event.
private void Form1_Closing(object sender, System.ComponentModel.CancelEventArgs e)
{
if( NotOkToClose() )
e.Cancel = true; //don't close
}




How do I display a splash screen type form, one with only client area (no border or titlebar)?


public void CreateMyBorderlessWindow()
{
this.FormBorderStyle = FormBorderStyle.None;
this.MaximizeBox = false;
this.MinimizeBox = false;
this.StartPosition = FormStartPosition.CenterScreen;
this.ControlBox = false;
}





How do I get the window handle (HWND) of my form or control?


Use the Control.Handle property.




How can I make sure I don't open a second instance modeless dialog that is already opened from my main form?


There are a several of ways to do this. Here are a few:

1) Insert a carriage return-linefeed, "\r\n", between your lines.
textBox1.Text = "This is line 1.\r\nThis is line 2";
// or textBox1.Text = stringvar1 + "\r\n" + stringvar2;

2) Use the Environment.NewLine property. This property is normally set to "\r\n".
textBox1.Text = "This is line 1." + Environment.NewLine + "This is line 2";

3) Use the Lines property of the TextBox. Make sure you populate your array before you set the property.
string[] arr = new string[2];
arr[0] = "this is line1";
arr[1] = "this is line 2";

textBox3.Lines = arr;








Is there a way to halt a screen from painting until all the controls on the form are initialized?


Shawn Burke responded to this question in a posting on microsoft.public.dotnet.framework.windowsforms newsgroup. There is not currently a way to do this built into the framework, but WM_SETREDRAW will do what you're looking for. It can't be called recursively, so here's code for a property you can add to your form to handle it.

private const int WM_SETREDRAW = 0xB;

[DllImport("User32")]
private static extern bool SendMessage(IntPtr hWnd, int msg, int wParam, int lParam);

private bool FreezePainting
{
get { return paintFrozen > 0; }
set {
if (value && IsHandleCreated && this.Visible)
{
if (0 == paintFrozen++)
{
SendMessage(Handle, WM_SETREDRAW, 0, 0);
}
}
if (!value)
{
if (paintFrozen == 0)
{
return;
}

if (0 == --paintFrozen)
{
SendMessage(Handle, WM_SETREDRAW, 1, 0);
Invalidate(true);
}
}
}
}




How do I return values from a form?


Add public properties to your form. Then these properties can be accessed by any object that creates an instance of your form.



How can I easily manage whether controls on my form are readonly or not?


One way is to place all the controls into a single GroupBox and then use the GroupBox.Enabled property to manage whether the controls are editable or not.






The controls that I've try to add to my form at runtime don't show up. What's wrong?


Make sure you implemented and executed code similar to the InitializeComponent method that VS adds to your Windows Forms project for controls added during design time. Recall that InitializeComponent() is called from your Forms constructor to create the controls, size, position and show the controls, and finally add the controls to the form's Controls collection. So, your code at runtime should also implement these same steps. In particular, don't forget the this.Controls.AddRange call that adds your new controls to the form's Controls collection.





How to make a form transparent?


The opacity property enables you to specify a level of transparency for the form and its child controls.

The TransparencyKey property will let you make the form transparent while keeping it's child controls visible (provided they have a different BackColor).

See the .NET documentation for Form.Opacity for differences between Opacity and TransparencyKey properties.
Opacity only works with Windows 2000 and later.





How can I create an instance of a Form class just from knowing its name in a string?


You can use the System.Reflection.Assembly.CreateInstance method to create a form from its name. Below is a code snippet. The name in the textbox has to be the full name including its namespace. So if there is a class named Form2 in namespace MyCompanyName, then the textbox would contain MyCompanyName.Form2. This snippet also assumes that the class is defined in the current executing assembly. If not, you would have to create an instance of the assembly that contains the class instead of calling the static method GetExecutingAssembly. As noted on this board, using reflection in this manner might affect performance.

[C#]
try
{
Assembly tempAssembly = Assembly.GetExecutingAssembly();
// if class is located in another DLL or EXE, use something like
// Assembly tempAssembly = Assembly.LoadFrom("myDLL.DLL");
// or
// Assembly tempAssembly = Assembly.LoadFrom("myEXE.exe");

Form frm1 = (Form) tempAssembly.CreateInstance(textBox1.Text);// as Form;
frm1.Show();
}
catch(Exception ex)
{
MessageBox.Show("Error creating: "+ textBox1.Text);
}

[VB.NET]
textBox1.Text = "MyNameSpace.Form2"
......

Try
Dim tempAssembly As System.Reflection.Assembly = System.Reflection.Assembly.GetExecutingAssembly()

' if class is located in another DLL or EXE, use something like
' tempAssembly = Assembly.LoadFrom("myDLL.DLL")
' or
' tempAssembly = Assembly.LoadFrom("myEXE.exe")

Dim frm1 As Form = CType(tempAssembly.CreateInstance(textBox1.Text), Form) ' as Form;
frm1.Show()
Catch ex As Exception
MessageBox.Show("Error creating: " + ex.ToString())
End Try



I don't want to have the Close box on my form's title bar. How do I remove this system menu box?


Set the property Form.ControlBox to false.




How do I change my application's icon?


In the Solution Explorer window, you'll see a file called app.ico in your project. This file contains your application icon. You can change this to a different file in the project properties screen which you see by right-clicking the project node in the Solution Explorer, and selecting Properties..

Thursday, February 3, 2011

Java Synchronization

The Java programming language supports multiple threads, using a monitor construction for synchronization. In the Java language, a method can be declared as synchronized.Threads communicate primarily by sharing access to fields and the objects reference fields refer to. This form of communication is extremely efficient, but makes two kinds of errors possible: thread interference and memory consistency errors. The tool needed to prevent these errors is synchronization.
A built-in mechanism ensures that only one Java thread can execute an object's synchronized methods at a time. The mechanism also allows threads to wait for resources to become available, and allows a thread that makes a resource available to notify other threads that are waiting for the resource. This web page describes this mechanism and its use. But first, we need to look at an example that illustrates why synchronization is needed.
The Bounded Buffer Problem

In the Bounded Buffers problem, there are two kinds of processes or threads: producers and consumers. Producers take buffers from a queue of empty buffers, put content into the buffers, and place the buffers into a queue of full buffers. Consumers take buffers from a queue of full buffers, do something with the buffers' contents, and place the buffers back onto the queue of empty buffers. Each of the buffer queues has a bounded capacity for buffers. Processes communicating through a pipe or communicating through mailboxes are examples of the Bounded Buffers problem.

There is generally only one queue of empty buffers, maintained by the operating system. It provides all buffers for processes or threads. There can be multiple producers, consumers, and queues of full buffers. The queues of full buffers usually have a small capacity, on the order of 10 buffers. We generally only need to consider a single queue of full buffers at a time. The following picture illustrates the flow of buffers.

Figure 1. Buffer flow in the Bounded Buffers Problem.
A First Solution

When we have a good solution to the Bounded Buffers problem, the coordination between producers and consumers will be controlled by two BufferQueue objects representing the queue of empty buffers and the queue of full buffers. The following code is an implementation of a BufferQueue class that works well in a single-threaded environment.
Testing the First Solution

We are limited in the kind of testing we can do on this first version of the BufferQueue class. There is no good way of making producers wait for empty buffers or making consumers wait for full buffers. So we will only use producers. Initially the queue of empty buffers has 10 buffers and the queue of full buffers has none. We first run a single producer that moves buffers from the queue of empty buffers to the queue of full buffers as long as the queue of empty buffers is not empty. The producer kills time for 20 milliseconds on the average after removing a buffer from the queue of empty buffers and kills time for 20 milliseconds on the average after putting the buffer on the queue of full buffers.

Here is the log for this kind of test.

0001: Producer 1 got Buffer 0 from BufferQueue empty.
0042: Producer 1 removed Buffer 0 from BufferQueue empty.
0068: Producer 1 got Buffer 1 from BufferQueue empty.
0087: Producer 1 removed Buffer 1 from BufferQueue empty.
0134: Producer 1 got Buffer 2 from BufferQueue empty.
0140: Producer 1 removed Buffer 2 from BufferQueue empty.
0173: Producer 1 got Buffer 3 from BufferQueue empty.
0222: Producer 1 removed Buffer 3 from BufferQueue empty.
0251: Producer 1 got Buffer 4 from BufferQueue empty.
0276: Producer 1 removed Buffer 4 from BufferQueue empty.
0294: Producer 1 got Buffer 5 from BufferQueue empty.
0298: Producer 1 removed Buffer 5 from BufferQueue empty.
0316: Producer 1 got Buffer 6 from BufferQueue empty.
0335: Producer 1 removed Buffer 6 from BufferQueue empty.
0380: Producer 1 got Buffer 7 from BufferQueue empty.
0390: Producer 1 removed Buffer 7 from BufferQueue empty.
0423: Producer 1 got Buffer 8 from BufferQueue empty.
0438: Producer 1 removed Buffer 8 from BufferQueue empty.
0464: Producer 1 got Buffer 9 from BufferQueue empty.
0532: Producer 1 removed Buffer 9 from BufferQueue empty.

As you can see, the queue of empty buffers appears to be working correctly.

Now let's try the same test with two producers. Here is the log.

0001: Producer 1 got Buffer 0 from BufferQueue empty.
0004: Producer 2 got Buffer 0 from BufferQueue empty.
0018: Producer 2 removed Buffer 0 from BufferQueue empty.
0050: Producer 2 got Buffer 1 from BufferQueue empty.
0059: Producer 1 removed Buffer 1 from BufferQueue empty.
0063: Producer 2 removed Buffer 2 from BufferQueue empty.
0064: Producer 1 got Buffer 3 from BufferQueue empty.
0086: Producer 1 removed Buffer 3 from BufferQueue empty.
0098: Producer 1 got Buffer 4 from BufferQueue empty.
0110: Producer 2 got Buffer 4 from BufferQueue empty.
0114: Producer 2 removed Buffer 4 from BufferQueue empty.
0120: Producer 1 removed Buffer 5 from BufferQueue empty.
0146: Producer 1 got Buffer 6 from BufferQueue empty.
0161: Producer 1 removed Buffer 6 from BufferQueue empty.
0167: Producer 1 got Buffer 7 from BufferQueue empty.
0174: Producer 1 removed Buffer 7 from BufferQueue empty.
0177: Producer 2 got Buffer 8 from BufferQueue empty.
0184: Producer 1 got Buffer 8 from BufferQueue empty.
0200: Producer 1 removed Buffer 8 from BufferQueue empty.
0202: Producer 2 removed Buffer 9 from BufferQueue empty.

If you look at the "got Buffer" reports, you can see that some of the buffers were gotten twice (Buffer 0, for example) and others weren't gotten at all (Buffer 2, for example).
A Second Solution

The first solution has some obvious problems in a multithreaded environment. First of all, it makes no provision for making a thread wait. To get the BufferQueue class tested, we needed to get rid of the consumers, who need to wait for a full buffer. Second, multiple threads that both read and modify shared data can make a mess of the data.

Part of the problem is the interface for the BufferQueue class. The fact that the functionality of the getBuffer() and removeBuffer() methods are separated causes trouble whenever one process does a getBuffer() in between another process's getBuffer() and removeBuffer() - both processes get the same buffer. If the first process did a removeBuffer() between another process's getBuffer() and removeBuffer() then the second buffer to be removed will never have been gotten.

When a data structure is modified, you usually need to get local information about the structure, then modify it. You cannot do this correctly if the structure is modified in between these two steps. When you deal with multiple threads, there are usually operations that have to be executed atomically. That is, the operations have to be performed completely without the possibility of another thread trying to make modifications at the same time.

To fix our BufferQueue, we must start by modifying its methods. We need to combine the getBuffer() and removeBuffer() functionality. So we combine them into a takeBuffer() method that removes and returns a buffer. While we're at it, we may as well get rid of the isEmpty() and isFull() methods. The boolean values that they return can easily change before they are used. We thus end up with the second version of BufferQueue.java.

This version of the BufferQueue class cannot properly be tested since there is no way of properly stopping a producer when the queue of empty buffers is empty. If we did come up with a way of doing that would it work? Yes, for a while, but eventually it would fail. Since a thread swith can occur at any time, we do not have any guarantee that takeBuffer() and putBuffer() are executed atomically. As a matter of fact, these methods execute so fast relative to the time between thread switches that failure would probably occur only once every few hundred thousand operations. Imagine examining logs that big to try to figure out what is going wrong. Problems that show up rarely are much harder to troubleshoot than problems that occur frequently.
Correctly Solving Synchronization Problems

A correct solution to a synchronization problem requires the following.

* atomic method execution that gives threads mutually exclusive access to bookkeeping data,
* a mechanism for waiting until an operation can be performed, and
* a mechanism for notifying other threads of a change in state.

The first two needs have been discussed earlier. The third is a consequence of the second. In the Bounded Buffers problem, for example, consumers must wait until a producer has put a buffer onto the queue of full buffers. That means that there must be something in the putBuffer() method that wakes up threads that are waiting.

A monitor is a convenient mechanism that tackles addresses these needs. In order to understand the monitor concept, let's take a look at how monitors are implemented in Java.
Java's Implementation of Monitors

Any object in Java is a monitor if some of its methods are declared with the synchronized keyword. As a monitor, there are three mechanisms for addressing the needs described above.

* Atomic method execution that gives threads mutually exclusive access to bookkeeping data - The synchronized keyword:
When this keyword is placed before a method's return type, threads that invoke the method must acquire a lock on the receiving object. Only one thread can hold this lock at a time. This thread is then the object's lock holder. Any other thread that sends a message to the object invoking a synchronized method becomes a lock waiter.

* A mechanism for waiting until an operation can be performed - The wait() method:
An object with synchronized methods has a wait set. The wait() method can only be invoked by the object's lock holder. When the lock holder invokes the wait() method it is placed into the object's wait set. If a thread other than the lock holder invokes the wait() method it will cause an IllegalMonitorStateException to be thrown.

* A mechanism for notifying other threads of a change in state - The notifyAll() method:
This method wakes up all threads in the wait set. Since more than one thread may be woken up, waiting threads usually need to check again to see if they can accomplish their objective. The notifyAll() method also throws an IllegalMonitorStateException if invoked by a thread other than the lock holder.

A Properly Synchronized BufferQueue

In order to properly synchronize a BufferQueue for the Bounded Buffers problem, the following changes need to be made.

* Declare takeBuffer() and putBuffer() synchronized. Put the keyword synchronized before the return types for the methods.

* Use a wait loop at the beginning of takeBuffer() and putBuffer(). This wait loop has the following form.

while (unable to proceed) {
try {
wait();
} catch(InterruptedException ex) {
}
}

The takeBuffer() method is unable to proceed when the count variable is 0. The putBuffer() method is unable to proceed when the count variable is equal to buffers.length.

* Invoke notifyAll() to wake up the wait set. Normally, this method is invoked at the end of a synchronized method. It should only be invoked when the change in state can make some thread in the wait set able to proceed. When the count variable is buffers.length - 1 at the end of the putBuffer() method then a thread that is waiting because the queue is full is able to proceed. When the count variable is equal to 1 at the end of the takeBuffer() method then a thread that is waiting because the queue is empty is able to proceed.

Execution of the Properly Synchronized Solution

The following table shows the monitor state for the queue of full buffers. For this example, each producer fills one buffer, puts it onto the queue of full buffers, then terminates. Each consumer gets one buffer from the queue of full buffers, consumes it, then terminates. At the start, there are two consumers and two producers, and the queue of full buffers is empty. All threads are attempting to access the queue sumultaneously.

In this table, count is the number of buffers in the queue, lh is its lock holder, lw is its lock waiters, and ws is its wait set.

Consumer Producer full BufferQueue runable
A B C D count lh lw ws threads
takeBuffer takeBuffer putBuffer putBuffer 0 - - - A, B, C, D
runs blocks blocks blocks | A B, C, D A
wait | - - A B, C, D
resumes blocks blocks | B C, D | B
wait | - - A, B C, D
resumes blocks | C D | C
add Buffer 1 | | | |
notifyAll | | A, B, D - |
returns | - - A, B, D
resumes blocks blocks | A B, D A
take buffer 0 | | |
returns | - - B, D
resumes blocks | B D B
wait | - - B D
resumes | D | |
add buffer 1 | | |
notifyAll | | B - |
returns | - - B
resumes | B |
take buffer 0 | |
returns | - |