Sharepoint Interview Questions

Leave a comment

1. What Do you know about SharePoint Object Model?
Ans. In Sharepoint Object model there are two Important namespaces.
The Microsoft.Office.Server namespace is the root namespace of all Office Server objects and Microsoft.SharePoint is the root namespace for all WSS objects.

The Chart Below illustrates some of the key classes contained in each of these namespaces, as well as to which functional area they belong.

Document Libraries (Microsoft.SharePoint)
SPDocumentLibrary , SPPictureLibrary

Business Data Catalog (Microsoft.Office.Server.ApplicationRegistry.Administration)
EntityCollection , ApplicationRegistry

Features (Microsoft.SharePoint)
SPFeatureDefinition, SPFeatureScope, SPElementDefinition, SPFeature, SPFeatureProperty

Sites (Microsoft.SharePoint)
SPSite, SPSiteAdministration, SPSiteCollection, SPWeb

Meetings (Microsoft.SharePoint.Meetings)
SPMeeting, MtgUtility

User Profiles (Microsoft.Office.Server.UserProfiles)
UserProfile, UserProfileManager

Solutions (Microsoft.SharePoint.Administration)
SPsolution, SPFeatureReceiver, SPSolutionCollection

Lists (Microsoft.SharePoint)
SPList, SPListItem, SPListItemCollection

2. Can you develop webparts and other SharePoint solutions at your local machine?

Ans.In order to run and debug sharePoint solutions, the project must reside on the server which has Windows sharePoint services installed. However, you can reference the Microsoft.SharePoint dll in your project at your local, but you won’t be able to run it.

 

3. How do you debug SharePoint Webparts?
Ans.
To debug SharePoint webpart (or any solution) you can simply drag and drop your complied .dll in GAC and recycle the app pool. You can also run upgrade solution command from stsadm.

4. How would you retrieve large number of Items form the list ?
Ans. If you have to retrieve a large number of Items and also need a better performance then you should use one of the methods below :

1. Using SPQuery

2. Using PortalSiteMapProvider Class

Lets see the examples for both the methods :

Our Query – Query to get all the Items in a list where Category is “Sp2007″

SPQuery -

// Get SiteColl
SPSite curSite = new SPSite(“http://myPortal”);

//Get Web Application
SPWeb curWeb = curSite.OpenWeb();

// Create a SPQuery Object
SPQuery curQry = new SPQuery();

// Write the query
curQry.Query = “<Where><Eq><FieldRef Name=’Category’/>
<Value Type=’Text’>SP2007 </Value></Eq></Where>”;

// Set the Row Limit
curQry.RowLimit = 100;

//Get the List
SPList curList = curWeb.Lists(new Guid(“myListGUID”));

//Get the Items using Query
SPListItemCollection curItems = curList.GetItems(curQry);

// Enumerate the resulting items
foreach (SPListItem curItem in curItems)
{

string ResultItemTitle = curItem["Title"].ToString();

}

PortalSiteMapProvider class -

The class includes a method called GetCachedListItemsByQuery that retrieves data from a list based on an SPQuery object that is provided as a parameter to the method call.
The method then looks in its cache to see if the items already exist. If they do, the method returns the cached results, and if not, it queries the list, stores the results in cache and returns them from the method call.

// Get Current Web
SPWeb curWeb = SPControl.GetContextWeb(HttpContext.Current);

//Create the Query
SPQuery curQry = new SPQuery();
curQry.Query = “<Where><Eq><FieldRef Name=\’Category\’/><Value Type=\’Text\’>SP2007</Value></Eq></Where>”;

// Get Portal Map Provider
PortalSiteMapProvider ps = PortalSiteMapProvider.WebSiteMapProvider;

PortalWebSiteMapNode pNode = TryCast (ps.FindSiteMapNode (curWeb.ServerRelativeUrl), PortalWebSiteMapNode);

// Get the items
pItems = ps.GetCachedListItemsByQuery(pNode, “myListName_NotID”, curQry, curWeb);

// Enumerate all resulting Items
foreach (PortalListItemSiteMapNode curItem in pItems)
{
string ResultItemTitle = curItem["Title"].ToString();
}

5. What is impersonation, and when would you use impersonation?

Ans. Impersonation can basically provide the functionality of executing something in the context of a different identity, for example assigning an account to users with anonymous access. You would use impersonation in order to access resources on behalf of the user with a different account, that normally, that wouldn’t be able to access or execute something.

6. How Do you implement Impersonation in ShrePoint.
Ans. By Using RunWithElevatedPrivileges method provided by SPSecurity class.

The SPSecurity class provides a method (RunWithElevatedPrivileges) that allows you to run a subset of code in the context of an account with higher privileges than the current user.
The premise is that you wrap the RunWithElevatedPrivileges method around your code. And also In certain circumstances, such as when working with Web forms, you may also need to set the AllowSafeUpdates method to true to temporarily turn off security validation within your code. If you use this technique, it is imperative that you set the AllowSafeUpdates method back to false to avoid any potential security risks.

Code example

{
SPSite mySite = SPContext.Current.Site;
SPWeb myWeb = mySite.OpenWeb();

//Using RunWithElevatedPrivileges

SPSecurity.RunWithElevatedPrivileges(delegate()
{
// Get references to the site collection and site for the current context.
// The using statement makes sures these references are disposed properly.

using (SPSite siteCollection = new SPSite(mySite.ID))
{

using (SPWeb web = siteCollection.OpenWeb(myWeb.ID))
{

web.AllowUnsafeUpdates = true;

try
{
//Your code
}

web.AllowUnsafeUpdates = false;

//siteCollection = null;
//web = null;

}

7. What is the performance impact of RunWithElevatedPrivileges?
Ans. RunWithElevatedPrivileges creates a new thread with the App Pool’s credentials, blocking your current thread until it finishes.


8. How will you add Code behind to a Custom Applictaion Page or a Layout Page in SharePoint?
Ans.
You do not deploy a code behind file with your custom Layouts page. Instead, you can have the page inherit from the complied dll of the solution to access the code behind.

9. What is the difference between a Site Definition and a Site Template?
Ans. Site Definitions are stored on the hard drive of the SharePoint front end servers. They are used by the SharePoint application to generate the sites users can create. Site Templates are created by users as a copy of a site they have configured and modified so that they do not have to recreate lists, libraries, views and columns every time they need a new instance of a site.

10. Why do you use Feature Receivers?
Ans.
Feature Receivers are used to execute any code on Activation\Deactivation of a Feature. You can use it for various purposes.

11. Can you give a example where feature receivers are used.
Ans
. You can use it to assign an event receiver feature to a specific type of list or can write a code in a feature receivers Deactivate method to remove a webpart from webpart gallery.

12. Where do you deploy the additional files used in your webpart, like css or javascript files, and how do you use them in your WebPart?
Ans.
You can deploy the css or javascript files in _layouts folder in SharePoint’s 12 hive. To use them in your webpart, you need to first register them to your webpart page and then specify a virtual path for the file for e.g. _layouts\MyCSS.css .See example below

Button Testbutton;
Image img;
string imagePath;

// Referring External Javascript
ClientScriptManager cs = Page.ClientScript;
// Include the required javascript file.
if (!cs.IsClientScriptIncludeRegistered(“jsfile”))
cs.RegisterClientScriptInclude(this.GetType(), “jsfile”, “/_wpresources/MyWP/1.0.0.0_9f4da00116c38ec5/jsfile.js”);

Test :
Testbutton= new Button();
Testbutton.Text = “Click me”;
Testbutton.OnClientClick = “jsfile_Function()”; // specify function name here
this.Controls.Add(Testbutton);

// Refering External CSS
Microsoft.SharePoint.WebControls.CssLink cssLink = new Microsoft.SharePoint.WebControls.CssLink();
cssLink.DefaultUrl = “/_wpresources/MyWP/1.0.0.0_9f4da00116c38ec5/styles.css”;
this.Page.Header.Controls.Add(cssLink);

// Using External Image
imagePath = “/_wpresources/MyWP/1.0.0.0_9f4da00116c38ec5/Image.jpg”;
img.ImageUrl = imagePath;
img.ID = “image1″;

this.Controls.Add(mybutton);
this.Controls.Add(img);
13: When should you dispose SPWeb and SPSite objects?
Ans. According to the best Practices you should always dispose them if you have created them in your code. You can dispose them in Finally block or you can use the “Using” clause, so that they gets disposed when not required. If you are using SPContext then you need not dispose the spsite or spweb objects.

14. What are the best practices for SharePoint development.
Ans.
Some of the best practices are:

1. You should always dispose SPsite and SPWeb objects, once you refer them in your code. Using the “Using” clause is recommended.

2. Use RunwithelevatePrivilages to avoid errors for end users.

3. Try writing your errors to SharePoint error logs (ULS Logs). Since it’s a bad idea to fill-up event log for your production environment.

4. Use SPQuery instead of foreach loop while retrieving Items from the list.

5. Deploy additional files used in your webpart to 12 hive. Use your solution package to drop the files in 12 hive. Also, make sure that all the references (for e.g. Css or .js files) get removed when the solution is retracted.
15. What is the main difference between using SPListItem.Update() and SPListItem.SystemUpdate()?

Ans. Using SystemUpdate() will not create a new version and will also retain timestamps.

16. When do you use SPSiteDataQuery ?
Ans. You can use SPSiteDataQuery when you need to extract data from more than one list\library in your site colletcion. The data is extracted on the basis of the query you write and is
returened as a Datatable. You can also specify the GUID for the lists\libraries you want to query against.

17. How do you create a Custom action for an item in a list ?
Ans. This can be done by adding a new feature into SharePoint. You would need to use customaction tag in your elements.xml file and will have to set various properties like imageurl or UrlAction for your customaction. You can later add this feature into sharepoint using stsadm install feature command.

18. How would you bind this CustomAction to a specific list ?
Ans. To do this you can either create a new list type(again a feature) and use the listtype number for the new list in your RegistrationType property of the Customaction. The CustomAction will then show up only for the items of this list type. or You can create a new content type and then use that content type’s id in your cutsomaction to bind the custom action to items of just that content type. Add the new content type to the list where you need this customaction.

19. How will you deploy an existing asp.net webapplication or website in SharePoint?
Ans.
You would need to wrap the web application in a solution package in order to deploy it in 12 hive or say ShraePoint. It is recommended to create a feature first, and then wrap everything in a Solution package.

20. How will you cancel a deployment from central admin -> solution managment, if its stuck at “deploying” or “Error”.
Ans.
You can either try to force execute timer jobs using execadmsvcjobs command or can cancel the dpeloyment using stsadm command stsadm –o cancaldeployment –id {GUID} command. The Id here would be GUID of the timer or deployment job. You can get the Id from stsadm enumdeployment command. This will display all the deployments which are process or are stuck with Error.

21. How do make an existing non-publishing site Publishing?
Ans.
You can simply activate the SharePoint Publishing Feature for the Site, you want to make publishing.

22. Can you name some of the tools used for SharePoint Administration?
Ans.
Axceler’s ControlPoint, Nintex Workflow 2007, DocAve

 

23. What are Application Pages in SharePoint?
Ans.
Unlike site pages (for example, default.aspx), a custom application page is deployed once per Web server and cannot be customized on a site-by-site basis. Application pages are based in the virtual _layouts directory. In addition, they are compiled into a single assembly DLL.
A good example of an Application Page is the default Site Settings page: every site has one, and it’s not customizable on a per site basis (although the contents can be different for sites).
With application pages, you can also add inline code. With site pages, you cannot add inline code.

24. What is Authentication and Authorization?
Ans . An authentication system is how you identify yourself to the computer. The goal behind an authentication system is to verify that the user is actually who they say they are.
Once the system knows who the user is through authentication, authorization is how the system decides what the user can do.

25. How do you deploy a User Control in SharePoint ?
Ans. You deploy your User Control either by a Custom webpart, which will simply load the control on the page or can use tools like SmartPart, which is again a webpart to load user control on the page. User Control can be deployed using a custom solution package for the webapplication or you can also the control in the webpart solution package so that it gets deployed in _controlstemplate folder.

26. Which is faster a WebPart or a User Control?
Ans. A WebPart renders faster than a User Control. A User Control in SharePoint is usually loaded by a webpart which adds an overhead. User Controls however, gives you an Interface to add controls and styles.

27. What SharePoint Databases are Created during the standard Install?
Ans. During standard install, the following databases are created :

SharePoint_AdminContent
SharePoint_Config
WWS_Search_SERVERNAME%_%GUID_3%
SharedServicesContent_%GUID_4%
SharedServices1_DB_%GUID_5%
SharedServices1_Search_DB_%
GUID_6%WSS_Content_%GUID_7%

28. What are content types?
Ans. A content type is a flexible and reusable WSS type definition (or we can a template) that defines the columns and behavior for an item in a list or a document in a document library. For example, you can create a content type for a leave approval document with a unique set of columns, an event handler, and its own document template and attach it with document library/libraries.

29. Can a content type have receivers associated with it?
Ans.
Yes, a content type can have an event receiver associated with it, either inheriting from the SPListEventReciever base class for list level events, or inheriting from the SPItemEventReciever base class. Whenever the content type is instantiated, it will be subject to the event receivers that are associated with it.

30. What two files are typically (this is kept generally) included when developing a content type, and what is the purpose of each?

Ans. There is generally the main content type file that holds things like the content type ID, name, group, description, and version. There is also the ContentType.Fields file which contains the fields to include in the content type that has the ID, Type, Name, DisplayName, StaticName, Hidden, Required, and Sealed elements. They are related by the FieldRefs element in the main content type file.

31. What is an ancestral type and what does it have to do with content types?

Ans. An ancestral type is the base type that the content type is deriving from, such as Document (0×0101). The ancestral type will define the metadata fields that are included with the custom content type.

32. Can a list definition be derived from a custom content type?

Ans. Yes, a list definition can derive from a content type which can be seen in the schema.XML of the list definition in the element.

33. Can you add a Cutsom Http Handler in SharePoint ?
Ans.
Yes, a Custom httphandler can be deployed in _layouts folder in SharePoint. Also, we need to be register the handler in the webapp’s webconfig file.

34. While creating a Web part, which is the ideal location to Initialize my new controls?
Ans. Override the CreateChildControls method to include your new controls. You can control the exact rendering of your controls by calling the .Render method in the web parts Render method.

35. How do you return SharePoint List items using SharePoint web services?
Ans. In order to retrieve list items from a SharePoint list through Web Services, you should use the lists.asmx web service by establishing a web reference in Visual Studio. The lists.asmx exposes the GetListItems method, which will allow the return of the full content of the list in an XML node. It will take parameters like the GUID of the name of the list you are querying against, the GUID of the view you are going to query, etc.

36. How Do you deploy Files in 12 hive when using wspbuilder or vsewss?
Ans.Typically, you can add these files in the 12 hive folder structure in your project. In Vsewss however, you will have to create this structure manually.

37. What files gets created on a file system, when a Site collection is created ?
Ans.
Windows SharePoint Services does not create any files or folders on the file system when the site collection or sites are created; everything is created in the content database. The Pages for the site collection are created as instances in the content database. These instances refer to the actual file on the file system.

38. What are Customized(unghosted) and Uncustomized(ghosted) Files in SharePoint ?
Ans.
There are two types of Pages in SharePoint; site pages (also known as content pages) and application pages.

Uncustomized :

When you create a new SharePoint site in a site collection, Windows SharePoint Services provisions instances of files into the content database that resides on the file system. That means if you create a new Site “xyz” of type Team Site(or Team sIte Definition), an instance of the Team Site Definition( Which resides on the File System), i.e. “xyz” gets created in the Content database. So, When ASP.NET receives a request for the file, it first finds the file in the content database. This entry in the content database tells ASP.NET that the file is actually based on a file on the file system and therefore, ASP.NET retrieves the source of the file on the file system when it constructs the page.

Customized :

A customized file is one in which the source of the file lives exclusively in the site collection’s content database. This happens When you modify the file in any way through the SharePoint API, or by SharePoint Designer 2007,which uses the SharePoint API via RPC and Web service calls to change files in sites. So, When the file is requested, ASP.NET first finds the file in the content database. The entry in the database tells ASP.NET whether the file is customized or uncustomized. If it is customized, it contains the source of the file, which is used by ASP.NET in the page contraction phase.

 

39. What is a SharePoint site definition

Ans. SharePoint site definitions are the core set of functionality from which SharePoint site are built from, building from the SiteTemplates directory in the SharePoint 12 hive. Site definitions allow several sites to inherit from a core set of files on the file system, although appear to have unique pages, thereby increasing performance and allowing changes that happen to a site propagate to all sites that inherit from a site definition.

40. What are event receivers?
Ans.
Event receivers are classes that inherit from the SpItemEventReciever or SPListEventReciever base class (both of which derive out of the abstract base class SPEventRecieverBase), and provide the option of responding to events as they occur within SharePoint, such as adding an item or deleting an item.

41. When would you use an event receiver?
Ans.
Since event receivers respond to events, you could use a receiver for something as simple as canceling an action, such as deleting a document library by using the Cancel property. This would essentially prevent users from deleting any documents if you wanted to maintain retention of stored data.

42. If I wanted to restrict the deletion of the documents from a document library, how would I go about it?
Ans.
You would create a event receiver for that list/library and implement the ItemDeleting method. Simply, set: properties.Cancel= true and display a friendly message using Properties.Message(“How can u delete this… Its not your stuff!”);
43. What is the difference between an asynchronous and synchronous event receivers?
Ans.
An asynchronous event occurs after an action has taken place, and a synchronous event occurs before an action has take place. For example, an asynchronous event is ItemAdded, and its sister synchronous event is ItemAdding

 

44. What base class do event receivers inherit from?

Ans. Event receivers either inherit from the SPListEventReciever base class or the SPItemEventReciever base class, both which derive from the abstract base class SPEventReceiverBase.

45. How could you append a string to the title of a site when it is provisioned?

Ans. In the OnActivated event:

PLAIN TEXT

C#:

  1. SPWeb site = siteCollection.RootWeb;
  2. site.Title += “interview”;
  3. site.Update();

46. Can an event receiver be deployed through a SharePoint feature?

Ans. Yes.

47. How do you Increase trust level for a single WebPart in the WebConfig file.
Ans.
To list a Web Part with Full Permissions within your Web Application while still retaining a WSS_Minimal permission set for all other Web Parts, You need to create a Custom policy file. This file will be then referenced in SharePoint Web.config file and will allow your specific webpart to be of Full trust.
Steps :
1. Make a copy of the WSS_Minimal.Config file from the 12\Config folder and paste it into the same folder renaming it to Custom_WSS_Minimal.Config. Now, edit the Custom_WSS_Minimal.Config file using NotePad. Obtain the Public Key Token for the Web Part assembly that you want to deploy, using the following command: sn –Tp filename.dll. Create a new entry in your Custom_WSS_Minimal.Config file for your WebPart. Save the File.
Finally, Create a new TrustLevel element for your config file in the Web.Config called Custom_WSS_Minimal that points to your custom file in the 12\config folder. Recycle the Application Pool and You’re Done.

48. How does Windows SharePoint Services help render the Webapplictaion in ShrePoint?
Ans.When a new web applictaion is created via Central Admin, Windows SharePoint Services creates a new Web application in IIS. Then the WSS, loads the custom HTTP application and replaces all installed HTTP handlers and modules with Windows SharePoint Services–specific ones. These handlers and modules essentially tell IIS to route all file requests through the ASP.NET 2.0 pipeline. This is because most files in a SharePoint site are stored in a Microsoft SQL Server database.

49. How would you pass user credentials while using SharePoint WebService from your Web Part or application.
Ans.
The web service needs credentials to be set before making calls.

Examples:

listService.UseDefaultCredentials = true; // use currently logged on user

listService.Credentials = new System.Net.NetworkCredential(“user”, “pass”, “domain”); // use specified user

50. How would you remove a webapart from the WebPart gallery? Does it get removed with Webpart retraction?
Ans.
No, Webpart does not get removed from the WebPart gallery on retraction. You can write a feature receiver on Featuredeactivating method to remove the empty webpart from the gallery.

51. What is a SharePoint Feature? Features are installed at what scope
Ans. A SharePoint Feature is a functional component that can be activated and deactivate at various scopes throughout a SharePoint instances, scope of which are defined as
1. Farm level 2. Web Application level 3. Site level 4. Web level
Features have their own receiver architecture, which allow you to trap events such as when a feature is Installing, Uninstalling, Activated, or Deactivated.

 

52. What files are used to define a feature?

Ans. The two files that are used to define a feature are the feature.xml and manifest file. The feature XML file defines the actual feature and will make SharePoint aware of the installed feature. The manifest file contains details about the feature such as functionality.

53. How the introduction of features has changed the concept of site definitions ?

Ans. SharePoint features are important when understanding the architecture of site definitions, since the ONET.XML file has been vastly truncated since it has several feature stapled on it.

54. What types of SharePoint assets can be deployed with a SharePoint feature?

Ans. Features can do a lot. For example, you could deploy Simple site customizations,Custom site navigation,WebParts,pages,list types,list instances,event handlers,workflows,custom actions

55. What type of components can be created or deployed as a feature?
Ans.
We can create menu commands, Custom Actions,page templates, page instances, list definitions, list instances,event handlers,webparts and workflows as feature.

56. How Do you bind a Drop-Down Listbox with a Column in SharePoint List ?
Ans.
Method 1 : You can get a datatable for all items in the list and add that table to a data set. Finally, specify the dataset table as datasource for dropdown listbox.

Method 2 : You can also use SPDatasource in your aspx or design page.

57. How Does SharePoint work?
Ans.
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.

58. What is CAML, and why would you use it?

Ans. CAML stands for Collaborative Application Markup Language. CAML is an XML based language which provides data constructs that build up the SharePoint fields, view, and is used for table definition during site provisioning. CAML is responsible for rending data and the resulting HTML that is output to the user in SharePoint. CAML can be used for a variety of circumstances, overall is used to query, build and customize SharePoint based sites. A general use would be building a CAML query in a SharePoint WebPart in order to retrieve values from a SharePoint list.

59. Can you display\add a Custom aspx or WebApplication Page in SharePoint Context ?

Ans.You need to make some modification in the aspx file to display it in SharePoint Context. Firstly, add the references for various sharepoint assemblies on the Page. Then wrap the Code in PlaceHolderMain contentPlaceholder, so that it gets displayed as a content page. Lastly, add a reference to SharePoint Master Page in aspx file and swicth it in Code behind if needed.

60. What are the two base classes a WebPart you are going to use within SharePoint 2007 can inherit from?

Ans. There are two base classes that a WebPart which is going to be consumed by SharePoint can inherit from, either the SharePoint WebPart Base class or the ASP.NET 2.0 WebPart base class. When inheriting from the SharePoint WebPart Base class your derived WebPart class will inherit from Microsoft.SharePoint.WebPartPages.WebPart. When inheriting from the ASP.NET 2.0 WebPart base class your derived WebPart class will inherit from System.Web.UI.WebControls.WebParts.WebPart. It is considered good practice to use the ASP.NET WebPart base class since the old base class is meant for backwards compatibility with previous version of SharePoint, however there are four exception when it is better to leverage functionality from the SharePoint WebPart base class:

Cross page connections

Connections between Web Parts that are outside of a Web Part zone

Client-side connections (Web Part Page Services Component)

Data caching infrastructure

61. What are the differences between the two base classes and what are the inherit benefits of using one over another?

Ans. The difference is the Microsoft.SharePoint.WebPartPages.WebPart base class is meant for backward compatibility with previous versions of SharePoint. The benefit of using the SharePoint WebPart base class is it supported:

Cross page connections

Connections between Web Parts that are outside of a Web Part zone

Client-side connections (Web Part Page Services Component)

Data caching infrastructure

ASP.NET 2.0 WebParts are generally considered better to use because SharePoint is built upon the ASP.NET 2.0 web architecture. Inheriting from the ASP.NET 2.0 base class offers you features that inherit to ASP.NET 2.0, such as embedding resources as opposed to use ClassResources for deployment of said types.

62. What is the GAC?

Ans. The GAC stands for the global assembly cache. It is the machine wide code cache which will give custom binaries place into the full trust code group for SharePoint. Certain SharePoint assets, such as Feature Receivers need full trust to run correctly, and therefore are put into the GAC. You should always try to avoid deployment to the GAC as much as possible since it will possibly allow development code to do more than it was intended to do.

63. What is strong naming (signing) a WebPart assembly file mean?

Ans. Signing an assembly with a strong name (a.k.a strong naming) uses a cryptographic key pair that gives a unique identity to a component that is being built. This identity can then be referred throughout the rest of the environment. In order to install assemblies into the GAC, they must be strongly named. After signing, the binary will have a public key token identifier which can be use to register the component in various other places on the server.

64. What are safe controls, and what type of information, is placed in that element in a SharePoint web.config file?

Ans. When you deploy a WebPart to SharePoint, you must first make it as a safe control to use within SharePoint in the web.config file. Entries made in the safe controls element of SharePoint are encountered by the SharePointHandler object and will be loaded in the SharePoint environment properly, those not will not be loaded and will throw an error.

In the generic safe control entry (this is general, there could be more), there is generally the Assembly name, the namespace, the public key token numeric, the typename, and the safe declaration (whether it is safe or not). There are other optional elements.

65. What is the CreateChildControls() method? How can you use it to do something simple like displaying a Label control?

Ans. The CreateChildControls method in WebParts is used to notify the WebPart that there are children controls that should be output for rendering. Basically, it will add any child ASP.NET controls that are called instantiating each control with its relevant properties set, wire any relevant event handlers to the control, etc. Then the add method of the control class will add the control to the controls collection. In the relevant WebPart render method, the EnsureChildControls method can be called (or set to false if no child controls should be called) to ensure that the CreateChildControls method is run. When using CreateChildControls it implies that your WebPart contains a composition of child controls.

In order to create something like a label control in Create, you would create a new label control using the new keyword, set the various properties of the control like Visible=True and ForeColor = Color.Red, and then use Controls.Add(myLabelControl) to add the control to the controls collection. Then you can declare EnsureChildControls in the Render method of the WebPart.

66. What does the RenderContents method do in an ASP.NET 2.0 WebPart?

Ans. The render contents method will render the WebPart content to the writer, usually an HtmlTextWriter since WebParts will output to an HTML stream. RenderContents is used to tell how the controls that are going to be displayed in the WebPart should be rendered on the page.

67. Difference between CreateChildControls and the RenderContents method.

Ans. The CreateChildControls method is used to add controls to the WebPart, and the RenderContents method is used to tell the page framework how to render the control into HTML to display on a page.

68. What is the WebPartManager sealed class? What is its purpose?

Ans. The WebPartManager sealed class is responsible for managing everything occurring on a WebPart page, such as the WebParts (controls), events, and misc. functionality that will occur in WebPartZones. For example, the WebPartManager is responsible for the functionality that is provided when you are working with moving a WebPart from WebPartZone to WebPartZone. It is known as the “the central class of the Web Part Control Set.”

69. how many WebPartManager controls should be on a page?

Ans. In order to have WebParts on a page there has to be just one WebPartManager control to manage all the WebParts on the page.

70. What is a SPSite and SPWeb object, and what is the difference between each of the objects?

Ans. The SPSite object represents a collection of sites (site collection [a top level sites and all its subsites]). The SPWeb object represents an instance SharePoint Web, and SPWeb object contains things like the actual content. A SPSite object contains the various subsites and the information regarding them.

71.  How would you go about getting a reference to a site?

Ans.

PLAIN TEXT

C#:

  1. oSPSite = new  SPSite(“http:/server”);
  2.  
  3. oSPWeb = oSPSite.OpenWeb();

72. What does a SPWebApplication object represent?

Ans. The SPWebApplication objects represents a SharePoint Web Application, which essentially is an IIS virtual server. Using the class you can instigate high level operations, such as getting all the features of an entire Web Application instance, or doing high level creation operations like creating new Web Applications through code.

73. Would you use SPWebApplication to get information like the SMTP address of the SharePoint site?

Ans. Yes, since this is a Web Application level setting. You would iterate through each SPWebApplication in the SPWebApplication collection, and then use the appropriate property calls (OutboundMailServiceInstance) in order to return settings regarding the mail service such as the SMTP address.

74.  Are there other ways to send emails from SharePoint?

Ans. Yes, there is. You can use the SendMail method from the SPutility class to send simple emails, however it is not as robust as using the System.Net.Mail functionality since it doesn’t allow things like setting priorities on the email.

75. How do you connect (reference) to a SharePoint list, and how do you insert a new List Item?

Ans.

PLAIN TEXT

C#:

  1. using(SPSite mySite = new SPSite(“yourserver”))
  2. {
  3. using(SPWeb myWeb = mySite.OpenWeb())
  4. {
  5. SPList interviewList = myWeb.Lists["listtoinsert"];
  6. SPListItem newItem = interviewList.Items.Add();
  7.  
  8. newItem["interview"] = “interview”;
  9. newItem.Update();
  10. }
  11. }

76. How would you loop using SPList through all SharePont List items, assuming you know the name (in a string value) of the list you want to iterate through, and already have all the site code written?

Ans.

PLAIN TEXT

C#:

  1. SPList interviewList = myWeb.Lists["listtoiterate"];
  2. foreach (SPListItem interview  in interviewList)
  3. {
  4. // Do Something
  5. }

77. When retrieving List items using SharePoint Web Services, how do you specify explicit credentials to be passed to access the list items?

In order to specify explicit credentials with a Web Service, you generally instantiate the web service, and then using the credentials properties of the Web Service object you use the System.Net.NetworkCredential class to specify the username, password, and domain that you wish to pass when making the web service call and operations.

78. When you should state the credentials in code?

Ans. You must state the credentials you are going to pass to the web service before you call any of the methods of the web service, otherwise the call will fail.

79. What is the IDesignTimeHtmlProvider interface, and when can you use it in WebParts?

Ans. The IDesignTimeHtmlProvider interface uses the function GetDesignTimeHtml() which can contain your relevant render methods. It was helpful to use in 2003 since it allowed your WebPart to have a preview while a page was edited in FrontPage with the Webpart on it, because the GetDesignTimeHtml() method contains the HTML for the designer to render.

80. What are WebPart properties, and what are some of the attributes you see when declaring WebPart properties in code?

Ans. WebPart properties are just like ASP.NET control properties, they are used to interact with and specify attributes that should be applied to a WebPart by a user. Some of the attributes you see with ASP.NET 2.0 properties are WebDescription, WebDisplayName, Category, Personalizable, and WebBrowsable. Although most of these properties come from the System.Web.UI.WebControls.WebParts class, ones like Category come out of System.ComponentModel namespace.

81.  Why are properties important in WebPart development, and how have you exploited them in past development projects? What must each custom property have?

Ans. Properties are important because WebParts allow levels of personalization for each user. WebPart properties make it possible for a user to interact, adjust, and increase overall experience value with the programmatic assets that you develop without having the need to use an external editor or right any code. A very simple example of exploiting a property would be something like allowing the user to change the text on the WebPart design interface so that they can display whatever string of text they desire.

Each custom property that you have must have the appropriate get and set accessor methods.

82. What are ClassResources? How do you reference and deploy resources with an ASP.NET 2.0 WebPart?

Ans. ClassResources are used when inheriting from the SharePoint.WebPart.WebPartPages.WebPart base class, and are defined in the SharePoint solution file as things that should be stored in the wpresources directory on the server. It is a helpful directory to use in order to deploy custom images. In ASP.NET 2.0, typically things such as images are referenced by embedding them as resources within an assembly. The good part about ClassResources is they can help to eliminate recompiles to change small interface adjustments or alterations to external JavaScript files.

83.  What is a SharePoint Solution File? How does it differ from WebPart .cab files in legacy development? What does it contain?

Ans. A SharePoint solution file is essentially a .cabinet file with all a developers ustom componets suffixed with a .wsp extension that aids in deployment. The big difference with SharePoint solution files is is that a solution:

allows deployment to all WFE’s in a farm

is highly manageable from the interface allowing deployment, retraction, and versioning

Can package all types of assets like site definitions, feature definitions (and associated components), Webparts, etc.

Can provide Code Access Security provisioning to avoid GAC deployments

84. What is a .ddf file and what does it have to do with SharePoint Solution creation?

Ans.  .ddf file is a data directive file and is used when building the SharePoint solution bundle specifying the source files and their destination locations. The important thing for someone to understand is that the .ddf file will be passed as a parameter to the MAKECAB utility to orchestrate construction of the SharePoint solution fiel.

85. What file does a SharePoint solution package use to orchestrate (describe) its packaged contents?

Ans. The solution Manifest.XML file.

86. What deployment mechanism can you use to instigate Code Access Security attributes for your WebParts?

Ans. SharePoint solution files can add in order to handle code access security deployment issues. This is done in the element in the SharePoint solution manifest.XML, which makes it easier to get assemblies the appropriate permissions in order to operate in the bin directory of the web application.

87. When creating a list definition, how can you create an instance of the list?

You can create a new instance of a list by creating an instance.XML file.

88. What is a Field Control?

Field controls are simple ASP.NET 2.0 server controls that provide the basic field functionality of SharePoint. They provide basic general functionality such as displaying or editing list data as it appears on SharePoint list pages.

89. What base class does custom Field Controls inherit from?

This varies. Generally, custom field controls inherit from the Microsoft.SharePoint.WebControls.BaseFieldControl namespace, but you can inherit from the default field controls.

90. How does one deploy new SharePoint site definitions so that they are made aware to the SharePoint system?

The best way to deploy site definitions in the SharePoint 2007 framework is to use a SharePoint solution file, so that the new site definition is automatically populated to all WFE’s in the SharePoint farm.

List of .NET Libraries

1 Comment

Dependency Injection/Inversion of Control

  1. Unity Framework – Microsoft
  2. StructureMap
  3. Castle Windsor
  4. NInject
  5. Spring Framework
  6. Autofac
  7. Managed Extensibility Framework

Logging

  1. Logging Application Block – Microsoft
  2. Log4Net – Apache
  3. Error Logging Modules and Handlers(ELMAH)
  4. NLog

Compression

  1. SharpZipLib
  2. DotNetZip
  3. YUI Compressor (CSS and JS compression/minification)

Ajax

  1. Ajax Control Toolkit – Microsoft
  2. AJAXNet Pro

Data Mapper

  1. XmlDataMapper
  2. AutoMapper

ORM

  1. NHibernate
  2. Castle ActiveRecord
  3. Subsonic
  4. XmlDataMapper

Charting/Graphics

  1. Microsoft Chart Controls for ASP.NET 3.5 SP1
  2. Microsoft Chart Controls for Winforms
  3. ZedGraph Charting
  4. NPlot – Charting for ASP.NET and WinForms

PDF Creators/Generators

  1. PDFsharp
  2. iTextSharp

Unit Testing/Mocking

  1. NUnit
  2. Rhino Mocks
  3. Moq
  4. TypeMock.Net
  5. xUnit.net
  6. mbUnit
  7. Machine.Specifications

Automated Web Testing

  1. Selenium
  2. Watin

URL Rewriting

  1. url rewriter
  2. UrlRewriting.Net
  3. Url Rewriter and Reverse Proxy – Managed Fusion

Controls

  1. Krypton – Free winform controls
  2. Source Grid – A Grid control
  3. Devexpress – free controls

Unclassified

  1. CSLA Framework – Business Objects Framework
  2. AForge.net – AI, computer vision, genetic algorithms, machine learning
  3. Enterprise Library 4.1 – Logging, Exception Management, Validation, Policy Injection
  4. File helpers library
  5. C5 Collections – Collections for .NET
  6. Quartz.NET – Enterprise Job Scheduler for .NET Platform
  7. MiscUtil – Utilities by Jon Skeet
  8. Lucene.net – Text indexing and searching
  9. Json.NET – Linq over JSON
  10. Flee – expression evaluator
  11. PostSharp – AOP
  12. IKVM – brings the extensive world of Java libraries to .NET.

New Site for sharing My Code Snipets

1 Comment

codesnipets.wordpress.com

codesnipets.wordpress.com

Silverlight 2 Reverse Countdown Timer Control

2 Comments

Silverlight 2 Reverse Countdown Timer Control

Silverlight 2 Reverse Countdown Timer Control

Created a very simple silverlight 2 reverse count down timer control.

Download the sourcecode here :

http://cid-d1697dec80818a03.skydrive.live.com/browse.aspx/Silverlight%202%20Applications

Calling WCF Service from Silveriight 2

1 Comment

Here is a quick example how you can call WCF Service using silverlight 2.

  1. Add a service reference in Silverlight Protject
  2. See Below for code example….

AService.AWSClient c = new A.AService.AWSClient();
c.ValidateLoginCompleted += new EventHandler<A.AService.ValidateLoginCompletedEventArgs>(c_ValidateLoginCompleted);
c.ValidateLoginAsync("admin", "password");

void c_ValidateLoginCompleted(object sender,A.AService.ValidateLoginCompletedEventArgs e)
{
AService.Player p = e.Result;
MessageBox.Show(p.sBirthDate.ToString());
}

Bad Habits as a Professional

4 Comments

Bad Habit: Missing deadlines.
What you think: “If it’s only a little late, it doesn’t mean anything.”
What it really says: Your colleagues and boss can’t count on you. 
What to do: Don’t view deadlines as negotiable. Remind yourself that people are counting on you to do your job well, which includes completing tasks on time. Even if you just barely missed the deadline and everything turned out OK, you probably caused your teammates a lot of anxiety and extra work, which they won’t forget.

 

Bad Habit: Dressing unprofessionally.
What you think: “I’m the office free spirit with a quirky sense of style!”
What it really says: You don’t take the job seriously.
What to do: You don’t have to be a boring dresser to be professional, but you shouldn’t look like you’re about to go clubbing or strutting down a runway. Take a cue from your co-workers to see what’s considered acceptable in the office.

 

Bad Habit: Not being punctual.
What you think: “As long as I get all my work in, nobody cares.”
What it really says: You think your time is more important than everybody else’s.
What to do: Stick to the schedule. Everyone in your office would like to sleep in a little or leave early, but they don’t because people rely on them to be on time.

 

Bad Habit: Checking your e-mail, playing games, shopping.
What you think: “I’m discreet.”
What it really says:  You’re not doing your job.
What to do: Keep the fun stuff to a minimum. Most employers don’t mind if you check your e-mail every once in awhile or read your favorite blog for a few minutes in the morning. They begin to care when you minimize that game of Scrabulous every time they walk by your desk. You’re being paid to work, not play.

 

Bad Habit: Gossiping.
What you think: “I’m just saying what I heard.”
What it really says: You can’t be trusted.
What to do: Sure, everybody gossips a little here and there, but it shouldn’t be your livelihood. Eventually you’ll gain a reputation for not keeping anything confidential –whether it’s a personal matter or work-related. Plus, your chattering could end up hurting somebody’s feelings or reputation.

 

Bad Habit: Being negative.
What you think: “Everybody complains.”
What it really says: You’re the person to avoid.
What to do: It’s natural to grumble about work once in awhile. If you gripe and moan when you’re asked to do anything, however, people will not only get annoyed, they’ll wonder why you don’t just quit. Keep in mind that work isn’t always fun; keep the complaints to a minimum.
 
Bad Habit: Trying to be everybody’s best friend.
What you think: “I’m just sociable.”
What it really says: You don’t know how to set boundaries.
What to do: It’s not uncommon for friendships to develop at work, but don’t expect it to happen with everybody. Unless you have reason to do otherwise, treat your superiors, colleagues and subordinates like professionals, not like drinking buddies.

 

Bad Habit: Burning bridges.
What you think: “I’ll never see them again.”
What it really says: You’re not a professional who thinks about the future.
What to do: As much as you dream of telling off your boss or co-workers after you’ve handed in your resignation, restrain yourself. People change jobs, companies merge – someone you dissed in the past may end up being your boss down the road.

 

Bad Habit: Always being the funny one.
What you think: “People love me.”
What it really says: You’re really annoying.
What to do: There’s nothing wrong with being funny – most people do like a good sense of humor. Just remember that not everybody wants to hear your sarcastic quips and “Godfather” impersonations every five minutes.

 

Bad Habit: Forgetting you have neighbors.
What you think: “I’m not as annoying as they are.”
What it really says: You’re inconsiderate.
What to do: Do unto your co-workers as you’d want them to do unto you. Your hour-long conference call on speakerphone is just as irksome to your cube mates as theirs are to you.

 

How do i Read Write Oracle CLOB data in ASP.NET or VB.NET ?

12 Comments

[KEYWORDS: ASP.NET READ WRITE CLOB DATA, VB.NET READ WRITE ORACLE CLOB DATA, ORACLE CLOB, CLOB, ORACLE CLOB READ WRITE]
Oracle has Varchar2 with max length of 4000 chars. If you need to sore more than that you have to use CLOB datatype
CLOB stores 4gb of chars. But remember, .NET Only supports string worth 2gb. so you need to handle the scenario
if you want to store 2+gb string into oracle.


Que: How do i Read Write Oracle CLOB data in ASP.NET or VB.NET ?
Ans:
It took me 2 days to come up with the simpletes method to read/write ORACLE CLOB data.
And I would like to share that with all you guys.

Step 1: Add a reference – Oracle.Dataaccess.dll ( found in ODP.NET )

Step 2: Imports following namespaces

Imports Oracle.DataAccess.Client
Imports Oracle.DataAccess.Types

Step 3: Create a connection string

Public ReadOnly connectionstring = "data source = oradb;user id = rmsoni;password=rmsoni99"</code>

Step 4: Create Following Public Methods

Public Sub ReadLOBData()
Dim con As New OracleConnection(connectionstring)
con.Open()</code></div>
<div><code>Dim sql As String = "select CLOBTEXTFIELD from TestCLOB where ID=1"
Dim cmd As OracleCommand = New OracleCommand(sql, con)
Dim dr As OracleDataReader = cmd.ExecuteReader()
dr.Read()
Dim blob As OracleClob = dr.GetOracleClob(0)</code></div>
<div><code>txtOutput.Text = blob.Value()</code></div>
<code>blob.Close()
dr.Close()
con.Close()
End Sub

Complete Source Code –

Public Sub WriteLOBData()
Dim connection As New OracleConnection(connectionstring)
connection.Open()

Dim strSQL As String = "INSERT INTO TestCLOB (ID,CLOBTEXTFIELD) VALUES (1,:TEXT_DATA) "
'Dim strsql As String = "UPDATE TestCLOB SET CLOBTEXTFIELD=:TEXTDATA where testid=1"
Dim paramData As New OracleParameter
paramData.Direction = ParameterDirection.Input
paramData.OracleDbType = OracleDbType.Clob
paramData.ParameterName = "TEXT_DATA"
paramData.Value = txtInput.Text

Dim cmd As New OracleCommand
cmd.Connection = connection
cmd.Parameters.Add(paramData)
cmd.CommandText = strSQL
cmd.ExecuteNonQuery()

paramData = Nothing
cmd = Nothing
connection.Close()
End Sub

That’s all you need for CLOB.
Enjoy.

Logging Events

Leave a comment

Logging Events 

Why do we need to Create EventLog ? 

No matter how well written and tested an application is, chances are high that there will be a bug or some unexpected behavior. Moreover, users typically aren’t developers and don’t use the same terminology that developers are accustomed to. It’s common to have users report problems using terminology that developers don’t recognize or understand. This communication gap makes bug verification a difficult process. And even when a bug can be verified, the circumstances that caused it might remain unknown. This reality makes identifying and fixing bugs difficult and can cause serious delays in repairing them.

Later versions of Windows such as Windows 2000, Windows XP, and Windows Server 2003 provide a mechanism to let applications log things that happen to them. This feature has many benefits. By using the event log, developers can record certain aspects of the state of an application, including serious errors. Essentially, developers can record just about anything that they think might be useful after the application is deployed. The ability to review significant events makes it much easier for support people to diagnose issues. A summary of the benefits of using Windows events and logging them are as follows:

§        Provide an easy mechanism to record specific items regarding an application’s state

§        Provide an easy mechanism to record situations that the developers consider to be out of the ordinary

§        Provide an easy mechanism for users to check on the state of applications that are running

Some Caveats about EvenLog  

§         Creating an EventLog object, writing to it, and passing it to code executing in a partial trust setting can be a huge security vulnerability. EventLog objects, including EventLogEntry objects and EventLogEntryCollection objects, should never be passed to less trusted code. This means any less trusted code, so it’s important to be cognizant of the security context these objects are executing in.

§         The EventLogPermission is required for many actions that use EventLog manipulation. Granting this permission to partially trusted code can open a serious security vulnerability. For example, mischievous code running in a partial trust environment with this permission granted could easily spoof other applications. It could, for example, shut down a critical antivirus or spyware-detection application yet make it appear as if it’s still running. The potential for mischief is unlimited.

§         Reading and logging events are relatively resource intensive in terms of disk utilization, system processor time, and other resources. EventLog objects can also get filled up, at which point attempts to write to them will cause exceptions to be thrown. EventLog objects should be used as necessary, but judiciously as well.

  Avoid EventLog objects in partial trust environments  

Use of EventLog objects in a partial trust environment can cause serious security holes and should be avoided if at all possible. 

Creating and Deleting an Event Log

To create an event log, the .NET Framework provides the EventLog class. To use it, the Source property needs to be specified and a message needs to be written, as shown in the following code, which requires the System.Diagnostics namespace:

' VB
Public Shared Sub CreateEventLog()
    Dim DemoLog As New EventLog("Chap10Demo")
    DemoLog.Source = "Chap10Demo"
DemoLog.WriteEntry("CreateEventLog called", EventLogEntryType.Information)
End Sub
 
// C#
public static void CreateEventLog()
   {
     EventLog DemoLog = new EventLog("Chap10Demo");
     DemoLog.Source = "Chap10Demo";
DemoLog.WriteEntry("CreateEventLog called", EventLogEntryType.Information);
   }

After you create an EventLog object and specify its source (which, by the way, can all be done in one of the overloaded constructors), information about the object should be visible from the Windows Event Viewer.

Deleting an event log is equally simple. You may want, for example, to delete the log that you just created as part of this exercise. To remove the demonstration log, use the Delete method of EventLog in code like the following:

' VB
Public Shared Sub DeleteEventLog()
EventLog.Delete ("Chap10Demo")
End Sub
 
// C#
Public static void DeleteEventLog()
{
EventLog.Delete("Chap10Demo");
}

Just be sure you don’t delete a log with valuable information by using this method!

Writing to an Event Log

Now that you have the code in place to create the log, it’s time to use it. Only one small enhancement needs to be made to the code sample you just created to get it to write to the event log:

' VB
Public Shared Sub CreateEventLog()
    Dim DemoLog As New EventLog("Chap10Demo")
    DemoLog.Source = "Chap10Demo"
DemoLog.WriteEntry("CreateEventLog called",          EventLogEntryType.Information)
End Sub
 
// C#
public static void CreateEventLog()
   {
     EventLog DemoLog = new EventLog("Chap10Demo");
     DemoLog.Source = "Chap10Demo";
DemoLog.WriteEntry("CreateEventLog called",          EventLogEntryType.Information);
   }

In this example, the WriteEntry method looks rather simple. However, there are 10 overloads for it. As is the case with many overloaded constructors, the minimal construction can be used and then you can set all necessary properties. Or you can specify all the information you need in the constructor. Although doing everything in the overload is typically considered more elegant and straightforward, you might encounter situations in which this approach won’t work well with the rest of your code. For example, you might not know the rest of the values that you intend to record.

To make the point a little clearer, here are each of the overloads in action:

' VB
Public Shared Sub CreateEventLog()
    Dim DemoLog As New EventLog("Chap10Demo")
    DemoLog.Source = "Chap10Demo"
DemoLog.WriteEntry("CreateEventLog called",          EventLogEntryType.Information)
End Sub
 
// C#
public static void CreateEventLog()
   {
     EventLog DemoLog = new EventLog("Chap10Demo");
      DemoLog.Source = "Chap10Demo";
DemoLog.WriteEntry("CreateEventLog called",          EventLogEntryType.Information);
   }

The following example shows how to use an overload to add an event ID:

' VB
Public Shared Sub CreateEventLog()
    Dim DemoLog As New EventLog("Security")
    DemoLog.Source = "Chap10Demo"
DemoLog.WriteEntry("CreateEventLog called",          EventLogEntryType.Information, 100)
End Sub
 
// C#
public static void CreateEventLog()
   {
     EventLog DemoLog = new EventLog("Security");
     DemoLog.Source = "Chap10Demo";
DemoLog.WriteEntry("CreateEventLog called",          EventLogEntryType.Information, 100);
    }
 

In addition to reading custom logs, the EventLog object also gives developers the ability to read from and write to built-in event logs. The built-in logs are the Application, Security, and System logs. Even though you might have a specified log for your application, you might want to take advantage of the built-in logs. Assume for a second that you have an ASP.NET Web application that authenticates users. Assume further that you have code in place to detect attempted SQL injection attacks. Developers of an application can do little about attempted attacks (other than ensuring that the code prevents them from being successful), but security administrators will be very interested in this type of activity, even when it is unsuccessful. Therefore it makes sense to write such events to the built-in Security log, where security personnel will be sure to see it.

 ( Meaning of SQL Injection – SQL injection attacks are hack attempts made through an application that trusts user input. The attacker uses special characters to change the nature of the input in order to embed SQL-database commands. Depending on what an attacker is allowed to do, he or she might be able to completely take over the database, as well as destroy it.)

Following are examples of how to write to each of the built-in logs. Remember that you must have permission to write to those logs.

Use the following code to write to the Application log:

‘ VB

Public Shared Sub WriteToApplicationEventLog()
Dim DemoLog As New EventLog("Application")
DemoLog.Source = "DemoApp"
DemoLog.WriteEntry("Written to Application Log", EventLogEntryType.Information)
End Sub
 
// C#
public static void WriteToApplicationEventLog()
 {
   EventLog DemoLog = new EventLog("Application");
   DemoLog.Source = "DemoApp";
   DemoLog.WriteEntry("Written to Application Log",EventLogEntryType.Information);
}
 

Use the following code to write to the Security log:

' VB
Public Shared Sub WriteToSecurityEventLog()
Dim DemoLog As New EventLog("Security")
DemoLog.Source = "DemoApp"
DemoLog.WriteEntry("A Sql Injection Attack just occurred fromIP Address 100.000.00.0", EventLogEntryType.Information)
End Sub
// C#
public static void WriteToSecurityEventLog()
{
  EventLog DemoLog = new EventLog("Security");
  DemoLog.Source = "DemoApp";
  DemoLog.WriteEntry("A Sql Injection Attack just occurred fromIP Address 100.000.00.0", EventLogEntryType.Warning);
}

Use the following code to write to the System log:

' VB
Public Shared Sub WriteToSystemEventLog()
Dim DemoLog As New EventLog("System")
DemoLog.Source = "DemoApp"
DemoLog.WriteEntry("A DemoService Restarted due to reboot", EventLogEntryType.Information)
End Sub
// C#
public static void WriteToSystemEventLog()
 {
   EventLog DemoLog = new EventLog("System");
  DemoLog.Source = "DemoApp";
  DemoLog.WriteEntry("A DemoService Restarted due to reboot",
EventLogEntryType.Information);
}

Reading from an Event Log

At this point, an event log has been created and data has been written to it. The EventLog object has an Entries property. This property is an instance of the EventLogEntryCollection and contains EventLogEntry objects. After you have an instance of yourEventLog class, you can easily iterate through the log entries, as illustrated by thefollowing code:

' VB
Public Shared Sub ReadEventLog()
     Dim DemoLog As New EventLog()
     DemoLog.Log = "Chap10Demo"
     For Each DemoEntry As EventLogEntry In DemoLog.Entries
       Console.WriteLine(DemoEntry.Source + ": " + DemoEntry.Message)
     Next
End Sub
 
// C#
public static void ReadEventLog()
   {
     EventLog DemoLog = new EventLog();
     DemoLog.Log = "Chap10Demo";
     foreach (EventLogEntry DemoEntry in DemoLog.Entries)
     {
      Console.WriteLine(DemoEntry.Source + ":" + DemoEntry.Message);
     }
   }
 
The only real task left to address is clearing a log. This method for doing this is one of the simplest methods to use. All you need to do is call the Clear method of the EventLog instance:
' VB
Public Shared Sub ClearEventLog()
        Dim LogDemo As New EventLog("Chap10Demo")
        LogDemo.Source = "DemoApp"
        LogDemo.Clear()
End Sub
 
// C#
public static void ClearEventLog()
   {
     EventLog LogDemo = new EventLog("Chap10Demo");
     LogDemo.Source = "DemoApp";
     LogDemo.Clear();
   }
 

If you use the ReadEventLog method after calling ClearEventLog, you should see no log entries. If you see any entries—other than entries that might have been written by another piece of code in the interim—something has failed.


Download   logging events.doc

Oracle Interview Questions

Leave a comment

1. What are the components of Physical database structure of Oracle Database?
ORACLE database is comprised of three types of files. One or more Data files, two are more Redo Log files, and one or more Control files


2. What are the components of Logical database structure of ORACLE database?
Tablespaces and the Database’s Schema Objects.


3. What is a Tablespace?
A database is divided into Logical Storage Unit called tablespaces. A tablespace is used to grouped related logical structures together.

 
4. What is SYSTEM tablespace and When is it Created?
Every ORACLE database contains a tablespace named SYSTEM, which is automatically created when the database is created. The SYSTEM tablespace always contains the data dictionary tables for the entire database.


5. Explain the relationship among Database, Tablespace and Data file
Each databases logically divided into one or more tablespaces One or more data files are explicitly created for each tablespace.

6. What is schema?
A schema is collection of database objects of a User.

 
7. What are Schema Objects ?
Schema objects are the logical structures that directly refer to the database’s data. Schema objects include tables, views, sequences, synonyms, indexes, clusters, database triggers, procedures, functions packages and database links.



8. Can objects of the same Schema reside in different tablespaces.?
Yes.


9. Can a Tablespace hold objects from different Schemes ?
Yes.


1
0. what is Table ?
A table is the basic unit of data storage in an ORACLE database. The tables of a database hold all of the user accessible data. Table data is stored in rows and columns.

 
11. What is a View ?
A view is a virtual table. Every view has a Query attached to it. (The Query is a SELECT statement that identifies the columns and rows of the table(s) the view uses.)


12. Do View contain Data ?

Views do not contain or store data.



13. Can a View based on another View ?
Yes.


14. What are the advantages of Views ?
Provide an additional level of table security, by restricting access to a predetermined set of rows and columns of a table.
Hide data complexity.
Simplify commands for the user.
Present the data in a different perpecetive from that of the base table.
Store complex queries.

15. What is a Sequence ?
A sequence generates a serial list of unique numbers for numerical columns of a database’s tables.

16. What is a Synonym ?
A synonym is an alias for a table, view, sequence or program unit.



17. What are the type of Synonyms?
There are two types of Synonyms Private and Public.


18. What is a Private Synonyms ?
A Private Synonyms can be accessed only by the owner.
 


19. What is a Public Synonyms ?
A Public synonyms can be accessed by any user on the database.


20. What are synonyms used for ?
Synonyms are used to: Mask the real name and owner of an object.
Provide public access to an object
Provide location transparency for tables, views or program units of a remote database.
Simplify the SQL statements for database users.



21. What is an Index ?
An Index is an optional structure associated with a table to have direct access to rows, which can be created to increase the performance of data retrieval. Index can be created on one or more columns of a table.


22. How are Indexes Update ?
Indexes are automatically maintained and used by ORACLE. Changes to table data are automatically incorporated into all relevant indexes.

 
23. What are Clusters?
Clusters are groups of one or more tables physically stores together to share common columns and are often used together.



24. What is cluster Key?
The related columns of the tables in a cluster are called the Cluster Key.


25. What is Index Cluster ?
A Cluster with an index on the Cluster Key.


26. What is Hash Cluster ?
A row is stored in a hash cluster based on the result of applying a hash function to the row’s cluster key value. All rows with the same hash key value are stores together on disk.


27. When can Hash Cluster used ?
Hash clusters are better choice when a table is often queried with equality queries. For such queries the specified cluster key value is hashed. The resulting hash key value points directly to the area on disk that stores the specified rows.

 
28. What is Database Link ?
A database link is a named object that describes a “path” from one database to another.

29. What are the types of Database Links ?
Private Database Link, Public Database Link & Network Database Link.

30. What is Private Database Link ?
Private database link is created on behalf of a specific user. A private database link can be used only when the owner of the link specifies a global object name in a SQL statement or in the definition of the owner’s views or procedures.


31. What is Public Database Link ?
Public database link is created for the special user group PUBLIC. A public database link can be used when any user in the associated database specifies a global object name in a SQL statement or object definition.

 
32. What is Network Database link ?
Network database link is created and managed by a network domain service. A network database link can be used when any user of any database in the network specifies a global object name in a SQL statement or object definition.



33. What is Data Block ?

ORACLE database’s data is stored in data blocks. One data block corresponds to a specific number of bytes of physical database space on disk.


34. How to define Data Block size ?

A data block size is specified for each ORACLE database when the database is created. A database users and allocated free database space in ORACLE datablocks. Block size is specified in INIT.ORA file and cann’t be changed latter.


35. What is Row Chaining ?

In Circumstances, all of the data for a row in a table may not be able to fit in the same data block. When this occurs , the data for the row is stored in a chain of data block (one or more) reserved for that segment.

36. What is an Extent ?
An Extent is a specific number of contiguous data blocks, obtained in a single allocation, used to store a specific type of information.

37. What is a Segment ?
A segment is a set of extents allocated for a certain logical structure.

38. What are the different type of Segments ?
Data Segment, Index Segment, Rollback Segment and Temporary Segment.

39. What is a Data Segment ?
Each Non-clustered table has a data segment. All of the table’s data is stored in the extents of its data segment. Each cluster has a data segment. The data of every table in the cluster is stored in the cluster’s data segment.

40. What is an Index Segment ?
Each Index has an Index segment that stores all of its data.

41. What is Rollback Segment ?
A Database contains one or more Rollback Segments to temporarily store “undo” information.

42. What are the uses of Rollback Segment ?
Rollback Segments are used :
To generate read-consistent database information during database recovery to rollback uncommitted transactions for users.


43. What is a Temporary Segment ?

Temporary segments are created by ORACLE when a SQL statement needs a temporary work area to complete execution. When the statement finishes execution, the temporary segment extents are released to the system for future use.

44. What is a Data File ?
Every ORACLE database has one or more physical data files. A database’s data files contain all the database data. The data of logical database structures such as tables and indexes is physically stored in the data files allocated for a database.

45. What are the Characteristics of Data Files ?
A data file can be associated with only one database. Once created a data file can’t change size.
One or more data files form a logical unit of database storage called a table space.

46. What is a Redo Log?
The set of Redo Log files for a database is collectively known as the database’s redo log.


47. What is the function of Redo Log ?

The Primary function of the redo log is to record all changes made to data.


48. What is the use of Redo Log Information ?

The Information in a redo log file is used only to recover the database from a system or media failure prevents database data from being written to a database’s data files.


49. What does a Control file Contain ?

A Control file records the physical structure of the database. It contains the following information.
Database Name
Names and locations of a database’s files and redolog files.
Time stamp of database creation.

50. What is the use of Control File ?
When an instance of an ORACLE database is started, its control file is used to identify the database and redo log files that must be opened for database operation to proceed. It is also used in database recovery.  

51. What is a Data Dictionary ?
The data dictionary of an ORACLE database is a set of tables and views that are used as a read-only reference about the database.
It stores information about both the logical and physical structure of the database, the valid users of an ORACLE database, integrity constraints defined for tables in the database and space allocated for a schema object and how much of it is being used.


52. What is an Integrity Constrains ?
An integrity constraint is a declarative way to define a business rule for a column of a table.



53. Can an Integrity Constraint be enforced on a table if some existing table data does not satisfy the constraint ?

No.


54. Describe the different type of Integrity Constraints supported by ORACLE ?
NOT NULL Constraint – Disallows NULLs in a table’s column.
UNIQUE Constraint – Disallows duplicate values in a column or set of columns.
PRIMARY KEY Constraint – Disallows duplicate values and NULLs in a column or set of columns.
FOREIGN KEY Constrain – Require each value in a column or set of columns match a value in a related table’s UNIQUE or PRIMARY KEY.
CHECK Constraint – Disallows values that do not satisfy the logical expression of the constraint.


55. What is difference between UNIQUE constraint and PRIMARY KEY constraint ?
A column defined as UNIQUE can contain NULLs while a column defined as PRIMARY KEY can’t contain Nulls.


56. Describe Referential Integrity ?
A rule defined on a column (or set of columns) in one table that allows the insert or update of a row only if the value for the column or set of columns (the dependent value) matches a value in a column of a related table (the referenced value). It also specifies the type of data manipulation allowed on referenced data and the action to be performed on dependent data as a result of any action on referenced data.
 


 
57. What are the Referential actions supported by FOREIGN KEY integrity constraint ?
UPDATE and DELETE Restrict – A referential integrity rule that disallows the update or deletion of referenced data.
DELETE Cascade – When a referenced row is deleted all associated dependent rows are deleted.



58. What is self-referential integrity constraint ?
If a foreign key reference a parent key of the same table is called self-referential integrity constraint.


59. What are the Limitations of a CHECK Constraint ?
The condition must be a Boolean expression evaluated using the values in the row being inserted or updated and can’t contain subqueries, sequence, the SYSDATE,UID,USER or USERENV SQL functions, or the pseudo columns LEVEL or ROWNUM.

60. What is the maximum number of CHECK constraints that can be defined on a column ?
No Limit.


Downloan basic-oracle-questions.doc

Basic InterviewQuestions for PL/SQL

25 Comments

1. What is PL/SQL ?
Ans.
PL/SQL is a procedural language that has both interactive SQL and procedural programming language constructs such as iteration, conditional branching.


2. What is the basic structure of PL/SQL ?
Ans.
PL/SQL uses block structure as its basic structure. Anonymous blocks or nested blocks can be used in PL/SQL.


3. What are the components of a PL/SQL block ?
Ans.
A set of related declarations and procedural statements is called block.


4. What are the components of a PL/SQL Block ?
Ans.
Declarative part, Executable part and Exception part.
Datatypes PL/SQL


5. What are the datatypes a available in PL/SQL ?
Ans.
Some scalar data types such as NUMBER, VARCHAR2, DATE, CHAR, LONG, BOOLEAN.
Some composite data types such as RECORD & TABLE.


6. What are % TYPE and % ROWTYPE ? What are the advantages of using these over datatypes?
Ans.
% TYPE provides the data type of a variable or a database column to that variable.
% ROWTYPE provides the record type that represents a entire row of a table or view or columns selected in the cursor.
The advantages are :
I. Need not know about variable’s data type
ii. If the database definition of a column in a table changes, the data type of a variable changes accordingly.


7. What is difference between % ROWTYPE and TYPE RECORD ?
Ans.
% ROWTYPE is to be used whenever query returns a entire row of a table or view.
TYPE rec RECORD is to be used whenever query returns columns of different
table or views and variables.
E.g. TYPE r_emp is RECORD (eno emp.empno% type,ename emp ename %type
);
e_rec emp% ROWTYPE
cursor c1 is select empno,deptno from emp;
e_rec c1 %ROWTYPE.
 
8. What is PL/SQL table ?
Ans.
Objects of type TABLE are called “PL/SQL tables”, which are modeled as (but not the same as) database tables, PL/SQL tables use a primary PL/SQL tables can have one column and a primary key.

9. What is a cursor ? Why Cursor is required ?
Ans.
Cursor is a named private SQL area from where information can be accessed. Cursors are required to process rows individually for queries returning multiple rows.

10. Explain the two type of Cursors ?
There are two types of cursors, Implicit Cursor and Explicit Cursor.
PL/SQL uses Implicit Cursors for queries.
User defined cursors are called Explicit Cursors. They can be declared and used.

11. What are the PL/SQL Statements used in cursor processing ?
Ans.
DECLARE CURSOR cursor name, OPEN cursor name, FETCH cursor name INTO or Record types, CLOSE cursor name.

12. What are the cursor attributes used in PL/SQL ?
Ans.
%ISOPEN – to check whether cursor is open or not
% ROWCOUNT – number of rows fetched/updated/deleted.
% FOUND – to check whether cursor has fetched any row. True if rows are fetched.
% NOT FOUND – to check whether cursor has fetched any row. True if no rows are fetched.
These attributes are proceeded with SQL for Implicit Cursors and with Cursor name for Explicit Cursors.

13. What is a cursor for loop ?
Ans.
Cursor for loop implicitly declares %ROWTYPE as loop index, opens a cursor, fetches rows of values from active set into fields in the record and closes
when all the records have been processed.
eg. FOR emp_rec IN C1 LOOP
salary_total := salary_total +emp_rec sal;
END LOOP;

14. What will happen after commit statement ?
Ans.
Cursor C1 is
Select empno,
ename from emp;
Begin
open C1; loop
Fetch C1 into
eno.ename;
Exit When
C1 %notfound;—–
commit;
end loop;
end;
The cursor having query as SELECT …. FOR UPDATE gets closed after COMMIT/ROLLBACK.
The cursor having query as SELECT…. does not get closed even after COMMIT/ROLLBACK.

15. Explain the usage of WHERE CURRENT OF clause in cursors ?
Ans.
WHERE CURRENT OF clause in an UPDATE, DELETE statement refers to the latest row fetched from a cursor.

16. What is a database trigger ? Name some usages of database trigger ?
Ans.
Database trigger is stored PL/SQL program unit associated with a specific database table. Usages are Audit data modifications, Log events transparently, Enforce complex business rules Derive column values automatically, Implement complex security authorizations. Maintain replicate tables.

17. How many types of database triggers can be specified on a table ? What are they ?
Ans.
Insert Update Delete
Before Row o.k. o.k. o.k.
After Row o.k. o.k. o.k.
Before Statement o.k. o.k. o.k.
After Statement o.k. o.k. o.k.
If FOR EACH ROW clause is specified, then the trigger for each Row affected by the statement.
If WHEN clause is specified, the trigger fires according to the returned boolean value.


18. Is it possible to use Transaction control Statements such a ROLLBACK or COMMIT in Database Trigger ? Why ?
Ans.
It is not possible. As triggers are defined for each table, if you use COMMIT of ROLLBACK in a trigger, it affects logical transaction processing.


19. What are two virtual tables available during database trigger execution ?
Ans.
The table columns are referred as OLD.column_name and NEW.column_name.
For triggers related to INSERT only NEW.column_name values only available.
For triggers related to UPDATE only OLD.column_name NEW.column_name values only available.
For triggers related to DELETE only OLD.column_name values only available.


20. What happens if a procedure that updates a column of table X is called in a database trigger of the same table ?
Ans.
Mutation of table occurs.


21. What is an Exception ? What are types of Exception ?
Ans.
Exception is the error handling part of PL/SQL block. The types are Predefined and user_defined. Some of Predefined exceptions are.
CURSOR_ALREADY_OPEN
DUP_VAL_ON_INDEX
NO_DATA_FOUND
TOO_MANY_ROWS
INVALID_CURSOR
INVALID_NUMBER
LOGON_DENIED
NOT_LOGGED_ON
PROGRAM-ERROR
STORAGE_ERROR
TIMEOUT_ON_RESOURCE
VALUE_ERROR
ZERO_DIVIDE
OTHERS.


22. What is Pragma EXECPTION_INIT ? Explain the usage ?
Ans. The PRAGMA EXECPTION_INIT tells the complier to associate an exception with an oracle error. To get an error message of a specific oracle error.
e.g. PRAGMA EXCEPTION_INIT (exception name, oracle error number)


23. What is Raise_application_error ?
Ans.
Raise_application_error is a procedure of package DBMS_STANDARD which allows to issue an user_defined error messages from stored sub-program or database trigger.


24. What are the return values of functions SQLCODE and SQLERRM ?
Ans.
SQLCODE returns the latest code of the error that has occurred.
SQLERRM returns the relevant error message of the SQLCODE.

25. Where the Pre_defined_exceptions are stored ?
Ans.
In the standard package.

26. What is a stored procedure ?
Ans.
A stored procedure is a sequence of statements that perform specific function.

27. What is difference between a PROCEDURE & FUNCTION ?
Ans.
A FUNCTION always returns a value using the return statement.
A PROCEDURE may return one or more values through parameters or may not return at all.

28. What are advantages fo Stored Procedures ?
Ans. Extensibility, Modularity, Reusability, Maintainability and one time compilation.

29. What are the modes of parameters that can be passed to a procedure ?
Ans.
IN, OUT, IN-OUT parameters.

30. What are the two parts of a procedure ?
Ans.
Procedure Specification and Procedure Body.

31. Give the structure of the procedure ?
Ans.
PROCEDURE name (parameter list…..)
is
local variable declarations
BEGIN
Executable statements.
Exception.
exception handlers
end;

32. Give the structure of the function ?
Ans.
FUNCTION name (argument list …..) Return datatype is
local variable declarations
Begin
executable statements
Exception
execution handlers
End;

33. Explain how procedures and functions are called in a PL/SQL block ?
Ans.
Function is called as part of an expression.
sal := calculate_sal (‘a822′);
procedure is called as a PL/SQL statement
calculate_bonus (‘A822′);

34. What is Overloading of procedures ?
Ans.
The Same procedure name is repeated with parameters of different datatypes and parameters in different positions, varying number of parameters is called overloading of procedures.
e.g. DBMS_OUTPUT put_line

35. What is a package ? What are the advantages of packages ?
Ans.
Package is a database object that groups logically related procedures.
The advantages of packages are Modularity, Easier Application Design, Information. Hiding,. reusability and Better Performance.

36.What are two parts of package ?
Ans.
The two parts of package are PACKAGE SPECIFICATION & PACKAGE BODY.
Package Specification contains declarations that are global to the packages and local to the schema.
Package Body contains actual procedures and local declaration of the procedures and cursor declarations.

37. What is difference between a Cursor declared in a procedure and Cursor declared in a package specification ?
Ans.
A cursor declared in a package specification is global and can be accessed by other procedures or procedures in a package.
A cursor declared in a procedure is local to the procedure that can not be accessed by other procedures.

38. Name the tables where characteristics of Package, procedure and functions are stored ?
Ans.
User_objects, User_Source and User_error 


 Download in word document -   pl-sql-interview-questions.doc

Older Entries

Follow

Get every new post delivered to your Inbox.