Saturday, 31 May 2014

ExecuteOrDelayUntilScriptLoaded error


After this statement i am getting error..
Solution:
Make sure you added
<script type="text/javascript" src="/_layouts/sp.core.js"></script>
<script type="text/javascript" src="/_layouts/sp.js"></script>
<script type="text/javascript" src="/_layouts/SP.UI.Dialog.js"></script>
<script type="text/javascript" src="/_layouts/sp.runtime.js"></script>
<script type="text/javascript" src="/_layouts/SP.Taxonomy.js"></script>

Enable Windows Authentication for anonymous IIS web site

You need to check that Windows Authentication is enabled for your IIS web site. You have to perform this task to all crawl servers.
For IIS 7:
1. Click Start -> Administrative Tools -> Internet Information Services (IIS) Manager
2. Click Sites
3. Select your anonymous site
4. Double-click Authentication under IIS-section in the Features View
5. Select Windows Authentication and click Enable from the Actions-pane on the right side of the window

K2 Blackpearl Error for ASP.Net IIS web site

Add below code in web.config

<configuration>
   <system.web>
      <identity impersonate="true"/>
   </system.web>
</configuration>

What is the only sport played on the moon

Golf

It was in 1971 that Apollo 14 set off for the moon. There were 3 astronauts on board including the sneaky Alan Shepard. Shepard had managed to smuggle a ball and golf club head inside his spacesuit! Just before Apollo 14 was set to leave the moon, Shepard played 2 shots. According to him, the ball flew ‘miles and miles and miles’. In reality, it travelled just a few hundred yards. Not bad when you’re wearing a super stiff suit! And thanks to Shepard it’s nailed in history, Golf is the first sport to have been played on the moon.

Windows power shell ISE Enable


Start-->In search programs and files-->Type
Turn Windows features on or off
Open it
You will get new window
Under features Summary
Click Add Featres
Select Windows PowerShell Integrated Scripting Environment
Click Install

SharePoint Start Excel service

Navigate to the following folder:
C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\BIN
Run the following command:
PSConfig.exe -cmd upgrade -inplace b2b -force -cmd applicationcontent -install -cmd installfeatures

Javascript replace

var x="<div><a onclick='hello()' href='#' </a></div>";
var start = x.indexOf('<a');
var end = x.indexOf('</a>')+4 ;
var final = x.slice (start,end) ;
x = x.replace(final,'hello');

K2 Out of Office

Site Actions–>K2 Site Settings–>Management Console–>Management Console–>Out of Office Users–>Actions–>Add User
Select Out of Office option.

Read a file in Asp.net Using StreamReader

System.IO.StreamReader sr = new System.IO.StreamReader("/1.txt");
string line;
while (sr.Peek() != -1)
{
line = sr.ReadLine();
Response.Write(Server.HtmlEncode(line) + "
");
}

Friday, 30 May 2014

showModalDialog add maximize minimize


window.showModalDialog("www.bing.com",null,"dialogHeight:600px;dialogWidth:1000px;maximize:1;minimize:1;center:yes");
---
window.showModalDialog(path,null,
"dialogHeight:600px;dialogWidth:1000px;maximize:1;minimize:1;center:yes");
SharePoint 
var options = {
title: "Hi",
width: 1100,
height: 900,
url: path};
SP.UI.ModalDialog.showModalDialog(options);

How to remove Temporary Internet Files


Open IE browser
Click on Tools
Internet options
Under General
Click on Settings
Click on View files
The path will be:
C:\Users\UserName\AppData\Local\Microsoft\Windows\Temporary Internet Files
You can delete it.

jquery reference error $ is not defined


Add below script:
<script src="//code.jquery.com/jquery-1.10.2.js"></script>

SCRIPT5007: Unable to get property 'showModalDialog' of undefined or null reference


You will get above error in SharePoint 2013 or SharePoint Online.
Solution:
Try below code
SP.SOD.execute('sp.ui.dialog.js', 'SP.UI.ModalDialog.showModalDialog', options);
Instead of
SP.UI.ModalDialog.showModalDialog(options);

Thursday, 29 May 2014

The remote server returned an error: (403) Forbidden

The remote server returned an error: (403) Forbidden
Troubleshooting Exceptions: System.Net.WebException
Root Cause: You might have missing SPO Authentication
Solution:

 Check this method in below code: SPOAuthe
 clientContext = SPOAuthe(clientContext);



Now your code should work..

microsoft.sharepoint.client.serverUnauthorizedaccessexception

Open AppManifest file
search for AllowAppOnlyPolicy
that value should be true
AllowAppOnlyPolicy="true"
Save
Problem should resolve

Wednesday, 28 May 2014

How to change default File Upload size in SharePoint

How to change default File Upload size in SharePoint?
1. Central Administration > Application Management > Web Application General Settings
2. Here we can find "Maximum Upload Size" field, please change this value from 50 MB to 300 MB.
Sharepoint
How to change default File Upload size in SharePoint
change default File Upload size
File Upload size
Maximum Upload Size

Update a File in Sharepoint Document Library from .Net

Check Duplicate Document in Sharepoint Document LibraryCheck Duplicate Document in Sharepoint Document Library


public bool checkDocumentList(string strFileName)
{
SPSite siteCollection = null;
SPWeb topLevelSite = null;
bool blnFound = false;
string strDocLibraryLink = System.Configuration.ConfigurationManager.AppSettings["SPDocumentLibrary"].ToString();//"http://*********/Documents/";
siteCollection = new SPSite(strDocLibraryLink);
topLevelSite = siteCollection.AllWebs[ConfigurationManager.AppSettings["TopLevelSite"].ToString()];// siteCollection.AllWebs["Corporate/DealDesk"];
SPList list = topLevelSite.Lists["Documents"]; //topLevelSite.Lists["Approved Documents"];
foreach (SPListItem item in list.Items)
{
if (strFileName.Equals(Convert.ToString(item["File Name"])))
{
blnFound = true;
break;
}
}
siteCollection.Dispose();
topLevelSite.Dispose();
return blnFound;
}
Check Duplicate Document
Check Duplicate Document Sharepoint Document Library
Object model code
Sharepoint Object model code
Sharepoint

Checkout a document in SharePoint using Object Model Code

SPSite siteCollection = null;
SPWeb topLevelSite = null;
string strDocLibraryLink = System.Configuration.ConfigurationManager.AppSettings["SPDocumentLibrary"].ToString();//"http://*******/Documents/"; siteCollection = new SPSite(strDocLibraryLink);
topLevelSite = siteCollection.AllWebs[ConfigurationManager.AppSettings["TopLevelSite"].ToString()];// siteCollection.AllWebs["Corporate/DealDesk"];
SPList list = topLevelSite.Lists["Documents"]; //topLevelSite.Lists["Approved Documents"];
foreach (SPListItem item in list.Items)
{
if (Convert.ToString(item["Document Number"]).Equals(strDocNumber))//It should be document ID. We need to add. lnkDocumentId
{
SPFileName.CheckOut(true, Convert.ToString(System.DateTime.Now));
}
}

Check Sharepoint User Role through Object Model Code

protected bool CheckUserRole()
{
bool blStatus=true;
SPSite siteCollection = null;
SPWeb topLevelSite = null;
SPList list = null;
string strRoleName = string.Empty;
try
{
siteCollection = new SPSite(System.Configuration.ConfigurationManager.AppSettings["SPDocumentLibrary"]);
topLevelSite = siteCollection.OpenWeb();
SPRoleDefinitionBindingCollection usersRoles = topLevelSite.AllRolesForCurrentUser;
//Full Control
SPRoleDefinition roleDefinition0 = topLevelSite.RoleDefinitions[0];
//Design
SPRoleDefinition roleDefinition1 = topLevelSite.RoleDefinitions[1];
//"Contribute"
SPRoleDefinition roleDefinition2 = topLevelSite.RoleDefinitions[2];
//"Read"
SPRoleDefinition roleDefinition3 = topLevelSite.RoleDefinitions[3];
//"Limited Access"
SPRoleDefinition roleDefinition4 = topLevelSite.RoleDefinitions[4];
//"View Only"
SPRoleDefinition roleDefinition5 = topLevelSite.RoleDefinitions[5];
if (usersRoles.Contains(roleDefinition0))
{
strRoleName=topLevelSite.RoleDefinitions[0].Name;
}
else if (usersRoles.Contains(roleDefinition1))
{
strRoleName=topLevelSite.RoleDefinitions[1].Name;
}
else if (usersRoles.Contains(roleDefinition2))
{
strRoleName=topLevelSite.RoleDefinitions[2].Name;
}
else if (usersRoles.Contains(roleDefinition3))
{
strRoleName=topLevelSite.RoleDefinitions[3].Name;
}
else if (usersRoles.Contains(roleDefinition4))
{
strRoleName=topLevelSite.RoleDefinitions[4].Name;
}
else if (usersRoles.Contains(roleDefinition5))
{
strRoleName=topLevelSite.RoleDefinitions[5].Name;
}
if ((strRoleName == "Read") || (strRoleName == "Limited Access") || (strRoleName == "View Only"))
{
blStatus = false;
}
else
{
blStatus = true;
}
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
finally
{
topLevelSite.AllowUnsafeUpdates = false;
siteCollection.AllowUnsafeUpdates = false;
siteCollection.Dispose();
topLevelSite.Dispose();
}
return blStatus;
}

Tuesday, 27 May 2014

Managed Metadata Navigation in SharePoint 2013


If you have more than one Site Collections and want to manage one
Enable SharePoint Publishing infrastructure under Site Collection
Enable Managed Navigation in site level
Go to Term store of site collection and configure Terms.
stite settings--site collection features--
Enable SharePoint Publishing infrastructure
site settings--navigation
you can find golbal navigation(Top) and current navigation(left)
select managed navigation option...
in the same page you can find "managed navigation term set"
click on create term set..
click ok
no if you go to home page..you will not see any links...
now we will add terms..then you wil see links
go to site settings
Click on term store management
you can find a group with name as site collection name
expand..
you will see one group...click on group
(you can create your own group...then select this group under site settings--navigation--"managed navigation term set")
right side you will see general tab
click on general tab
check "use this term set for site navigation". save
in the left side group right click..select create term. enter name and press enter
select term
in the right side you will see navigation tab
under navigation node type
select the radio button for simple link..
click on browse. select any page from pages library
save
now you will see top nav and left nav
you can repeat term creation ...
you can apply same page or different page for each term...
if you want to use this navigation in another site collection
Access Term Store in different Site collection
Copy the Site collection url of the term store which you want to access in different site.
Open term store of the target site collection
Ex:https://SP2013/MySiteCollection/_layouts/15/termstoremanager.aspx
Click on the Term set group under System
You can find: Site Collection Access
Paste the site collection url, which you want get term stores in this site collection







Monday, 26 May 2014

item.Update(); and item.SystemUpdate(false);

SPList list = web.Lists["myList"];
SPListItem item = list.Items[0];
item["myField"] = "my value";
item.Update();
list.Update();
This code works perfect for end-user scenarios. It creates automatically new version of list item as Update method is called. I needed no new versions and therefore this solution wasn't great help for me. I found list item's method SystemUpdate. The following code is same as the previous one but instead of Update it uses SystemUpdate.
SPList list = web.Lists["myList"];
SPListItem item = list.Items[0];
item["myField"] = "my value";
item.SystemUpdate(false);
list.Update();
SystemUpdate method avoids SharePoint 2007 to change modified date and modifier fields. Argument false tells that no new versions are expected. SystemUpdate solved my problem perfectly well.

Diff between item.attachment.addnow() and item.attachment.add()


addnow() no need of item.update()
add() need to call item.update() method
Ex:attachmentCollection.Add(fileUpload.FileName, attachmentContent);
//no need of Update
attachmentCollection.AddNow(fileUpload.FileName, attachmentContent);
item.update();//Need update

Trust level in SharePoint

Trust level in SharePoint
You can specify a level of trust that corresponds to a predefined set of permissions forASP.NET applications. By default, ASP.NET defines the following trust levels:
Full
High
Medium
Low
Minimal
With the exception of the Full trust level, all trust levels grant only partial trust to the application folder of a virtual server instance. For more information on the ASP.NET trust levels, see Code Access Security for ASP.NET.
Additionally, Windows SharePoint Services defines two trust levels of its own:
WSS_Minimal
WSS_Medium
The trust levels extend the Minimal and Medium trust levels of ASP.NET for Windows SharePoint Services. The trust levels are defined in security policy files, wss_minimaltrust.config and wss_mediumtrust.config. By default, Windows SharePoint Services stores these files in the following location:
local_drive:\Program Files\Common Files\Microsoft Shared\web server extensions\60\config
By default, when you extend a virtual server with Windows SharePoint Services, Windows SharePoint Services sets the trust level to WSS_Minimal. This helps provide a secure trust level in which assemblies operate with the smallest set of permissions required for code to execute.

SharePoint Designer Soap Server Error


Error: soap:ServerServer was unable to process request. —> A Web Part or Web Form Control on this Web Part Page cannot be displayed or imported because it is not registered as safe on this site. You may not be able to open this page in an HTML editor that is compatible with Microsoft Windows SharePoint Services, such as Microsoft Office SharePoint Designer. To fix this page, contact the site administrator to have the Web Part or Web Form Control configured as safe. You can also remove the Web Part or Web Form Control from the page by using the Web Parts Maintenance Page. If you have the necessary permissions, you can use this page to disable Web Parts temporarily or remove personal settings. For more information, contact your site administrator.
Root Cause:
Some of the web part which you have deployed is causing some problem.
Solution:
you have to remove that webpart..other wise, it will consume some resources and slow down page loads.
How to see unused web parts..
Open IE
http://SP2010/SitePages/Home.aspx?contents=1
here SP2010 is my sharepoint server, change this based on your server name
Once you open above url, it will redirect to one page, where you can see all unused webparts,
this is "Web Part Page Maintenance" page.
Now you can select check box and click on delete
now try to open your site in sharepoint designer...
It will work..

Valid Date regularexpressionvalidator

regularexpressionvalidator cssclass="SuccessErrorText" id="RegularExpressionValidator2"
runat="server" controltovalidate="txtRequestedImplementationDate" font-names="Verdana"
font-size="X-Small" setfocusonerror="True" display="Dynamic" errormessage="Please Enter Valid Date"
validationgroup="Save"
validationexpression="^(?:(?:0?[13578]|1[02])|(?:0?[469]|11)(?!\/31)|(?:0?2)(?:(?!\/3[01]|\/29\/(?:
(?:0[^48]|[13579][^26]|[2468][^048])00|(?:\d{2}(?:0[^48]|[13579][^26]|[2468][^048]))))))\/(?:0?[1-9]
|[12][0-9]|3[01])\/\d{4}$"

SharePoint 2010 for End Users


SharePoint 2010 helps you and your team work better, faster, and smarter. Access the right people and information at the
right time to make better decisions and get the job done. Plus, work comfortably and confidently in SharePoint 2010 with a
familiar interface and direct connections to Microsoft Office.
Benefits
Work Better Together
​Connect with your colleagues in new and creative ways. Easily find and work with people who have the right skills,
expertise, and shared interests.
Work Faster
​Quickly become more productive. SharePoint 2010 works seamlessly with technologies you currently use, including
Microsoft Office, Microsoft Exchange Server, and Microsoft Unified Communications.
Work Smarter
​Make better business decisions. Easily find the right business information—regardless of who created it, what format it’s in,
or where it lives.
Ref:http://sharepoint.microsoft.com/en-us/product/benefits/End-User/Pages/default.aspx

SharePoint 2010 Benefits for Developers

SharePoint 2010 Benefits for Developers
With SharePoint 2010, you and your development team can build custom applications and components to rapidly respond to
business needs. With familiar tools, it’s easy to create Web Parts, external content types, and workflow activities for use in
SharePoint solutions. A full set of extensibility APIs also lets you customize your SharePoint implementations. What’s more,
you can count on community support and training opportunities to help you do your work in SharePoint quickly and
effectively.
Ref:http://sharepoint.microsoft.com/en-us/product/benefits/developer/Pages/default.aspx

Search In Sharepoint

1-SharePoint Items (Documents, Tasks, and Events etc.) :
Can be acheived using OOB MOSS Search, content sources, custom scopes & managed properties will do the job and more...
2- SalesForce Items (Chatter Discussions, Documents etc.) :
I Don't know a lot about SaleForce; but in general; there is a bunch of options to search external sources outside SharePoint like Federal search, BDC, etc...
3-Exchange Mailboxes Items (Emails, attachments etc.)
This can be achieved using 2 different approches:
i-Add a content source "http:///exchange/" or "http:///exchange/user_alias", but please be aware that users will only get serch results from their mailboxes, except for exchange admins will be able to get results from any mailbox
ii-There is some third party connectors that provide more features for this like the BA Insight exchange mail box connector for shsrepoint; I haven't try it before; but give the trial version a try & et's see !!
4- Network Shared Folder items
This can be achieved using OOB SharePoint search
-Regarding merging search results from all sources in one view while using icons for highlighting the origin; this can be achieved using the SharePoint search object model
-For complex queries & scenarios; I believe FAST (comes with the SharePoint 2010) will do the job.

Igate Asp.Net Interview


1) What is the difference b/w WCF and classic asmx web services?
2) How do you deployed the Web service what are the pages needed?
3) Are you implemented Ajax? Then Microsoft Ajax toolkit or own Ajax?
4) Do you Used JSON?
5) What is the Difference B/W JQuery and Ajax?
6) What is the difference B/W Sting and String Builder?
7) What is the Difference B/W Dataset and data reader?
8) How do you use data Adapter with Dataset and data reader?
9) What is the major Difference B/W MVC ans classic ASP.NET Application?

Wipro .Net Interview


1)Temp Table Vs Global Table
2)Fault Contracts in WCF
3)Waht is clustered index and use
4) Delagate and Multi Cast Delegate
5)Deep Copy and Shell Copy Diff
6) MVP Vs MVC
7)Factory Pattern
8) Singleton
9) If U Use singleyon there is no problem when using threading
10)What is Statis constructor
11)How The Request will be handled in MVC b/w "M","V","C"?
12) What is the difference B/W Server.Transfer() and response.Redirect()?
13) J- Query
14)Application Domain
15)Serialization and why we use
16)How do we get all the methods and properties in a object in runtime
17)Application Pooling
18) Which Namespace you will use to get the metada data of DLL
19)once you requested from Home.aspx then how many times Http Handler will call and http modules will called

SQL Server importing XML files

CREATE TABLE XmlImportTest
(
xmlFileName VARCHAR(300),
xml_data xml
)
GO
DECLARE @xmlFileName VARCHAR(300)
SELECT @xmlFileName = 'c:\TestXml.xml'
-- dynamic sql is just so we can use @xmlFileName variable in OPENROWSET
EXEC('
INSERT INTO XmlImportTest(xmlFileName, xml_data)
SELECT ''' + @xmlFileName + ''', xmlData
FROM
(
SELECT *
FROM OPENROWSET (BULK ''' + @xmlFileName + ''' , SINGLE_BLOB) AS XMLDATA
) AS FileImport (XMLDATA)
')
GO
SELECT * FROM XmlImportTest
DROP TABLE XmlImportTest
Ref:http://weblogs.sqlteam.com/mladenp/archive/2007/06/18/60235.aspx

Saturday, 24 May 2014

What are the main problems, if i increase the number of sites in single site collection


1.Database Problem: If i add more sites in a single site collection, content database of that site collection will increase...
At one point of time database may be corrupted.
If there are any daily jobs which take database backup..it will effect because of the size...and restore also will get effected..
2.Groups: If we add more sites to one site collection then each site will have it's own groups...it will increase...site collection administrator will have tough time to manage all these groups..
3.Changes: If there is any change in the root level site permissions...it will effect to all sites...
If we change any content type of site column it will effect to all sites..
4.Recycle bin: Each site will have recycle bin and Site Collection have one recycle bin. If any site admin delete the data first it will go to site recycle bin...if site admin removes from site recycle bin, it will move to site collection recycle bin. At one point all deleted files will come to Site collection recycle bin, it will be very difficult to site collection administrator to handle all these...

Like this we will get more problems if we add more sites in single site collection. It will always best practice to create new site collections and add sites to that..

Friday, 23 May 2014

Steps Install WSP file Using PowerShell

Deploying WSP
=====================
Open PowerShell and Run as Administrator
C:\Windows\System32\WindowsPowerShell\v1.0\PowerShell.exe
Batch File Name.: DeployWSP.bat
—————————————————————
@Set SiteURL=”http://SP2010:1234/mysite”
Echo “Deploying My WSP”
C:\Windows\System32\WindowsPowerShell\v1.0\PowerShell.exe Set-ExecutionPolicy RemoteSigned; .\WSPFOlder\DeployWSP.ps1 -SiteURL %SiteURL%
PowerShell Script Name:DeployWSP.ps1
————————————————————————–
Param
(
[string]$SiteURL = $null
)
write-host “Adding Snapin”
Add-PsSnapin Microsoft.SharePoint.PowerShell
write-host “Added”
$site=new-object Microsoft.SharePoint.SPSite($SiteURL);
$web=$site.RootWeb;
write-host “Installing WSP”
Add-SPSolution .\WSPFOlde\MyFeature.wsp
Start-Sleep -s 100
Install-SPSolution -Identity MyFeature.wsp -GACDeployment -force
Start-Sleep -s 100
write-host “Installtion of WSP Done.”
write-host “Removing Snapin”
Remove-PsSnapin Microsoft.SharePoint.PowerShell
write-host “Removed”
=======================================================================================================================================================================
Undeploying WSP
=====================
Batch File Name:UndeployWSP.bat
———————————————————————–
@Set SiteURL=”http://SP2010:1234/mysite”
Echo “Undeploying My WSP”
C:\Windows\System32\WindowsPowerShell\v1.0\PowerShell.exe Set-ExecutionPolicy RemoteSigned; .\WSPFOlder\UndeployingWSP.ps1 -SiteURL %SiteURL%
PowerShell Script Name:UndeployingWSP.ps1
————————————————————————————
Param
(
[string]$SiteURL=$null
)
write-host “Adding Snapin”
Add-PsSnapin Microsoft.SharePoint.PowerShell
write-host “Added”
write-host “Undeploying My WSP.”
Uninstall-SPSolution -identity MyFeature.wsp -Confirm:$false
Start-Sleep -s 100
Remove-SPSolution -identity MyFeature.wsp -Confirm:$false
Start-Sleep -s 100
write-host “My WSP Uninstalled.”
write-host “Removing Snapin”
Remove-PsSnapin Microsoft.SharePoint.PowerShell
write-host “Removed”
======================================================================================================================================================================
Sharepoint 2010 wsp installation and uninstallation
Install wsp
Add New Wsp
—————–
Add-SPSolution “D:\MySPSolution.wsp“
Install-SPSolution –Identity MySPSolution.wsp –WebApplication http://sp2010 –GACDeployment
Update wsp
————-
Update-SPSolution –Identity MySPSolution.wsp –LiteralPath “D:\MySPSolution.wsp” –GacDeployment
unInstall wsp
Uninstall-SPSolution –Identity MySPSolution.wsp –WebApplication http://sp2010
Remove-SPSolution–Identity MySPSolution.wsp
==========================================================================================================================================================================
WSP Depoyment Using STSADM Commands
————————————————————
Open Command Prampt
Go to this path: C:\Program Files\Common Files\Microsoft Shared\web server extensions\12\BIN
Install:
stsadm -o addsolution -filename c:\Mysolution.wsp
stsadm -o deploysolution -name Mysolution.wsp -local -allowGacDeployment -force -url http://Server:3333/
Uninstall:
stsadm -o retractsolution -name Mysolution.wsp -immediate -allcontenturls
stsadm -o execadmsvcjobs
stsadm -o deletesolution -name Mysolution.wsp -override
stsadm -o execadmsvcjobs

The property or field XXXXX has not been initialized. It has not been requested or the request has not been executed. It may need to be explicitly requested

The property or field 'PathOfTerm' has not been initialized. It has not been requested or the request has not been executed. It may need to be explicitly requested
Root Cause: PathOfTerm is not included in the contentx.

objterms = termSet.GetAllTerms();
clientContext.Load(objterms,objtermColl => objtermColl.Include(termNew => termNew.Id,termNew => termNew.Name,termNew => termNew.PathOfTerm));

Thursday, 22 May 2014

Read Excel using C#

public  DataTable objSheetTable;
string strpath=@”C:\myexcel.xlsx”;
OleDbConnection oledbConn = new OleDbConnection(@”Provider=Microsoft.ACE.OLEDB.12.0;Data Source=” + strpath + “;Extended Properties=’Excel 12.0;HDR=YES;IMEX=1;’;”);
oledbConn.Open();
objSheetTable = new DataTable();
objSheetTable = oledbConn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
int intSheetCount = objSheetTable.Rows.Count;
for (int intSheet = 0; intSheet < 0; intSheet++)
{
dt = new DataTable();
OleDbCommand cmd = new OleDbCommand(“SELECT * FROM [" + objSheetTable.Rows[intSheet][2].ToString() + “]”, oledbConn);
OleDbDataAdapter oleda = new OleDbDataAdapter(cmd);
oleda.Fill(dt);
//Read all rows values based on column..
foreach (DataRow row in dt.Rows)
{
string c1 = row[0].ToString();
strinf c2 = row[1].ToString();
}
}

The property or field 'Id' has not been initialized. It has not been requested or the request has not been executed. It may need to be explicitly requested

The property or field 'Id' has not been initialized. It has not been requested or the request has not been executed. It may need to be explicitly requested
You are missing
ctx.Load(objname);
ctx.ExecuteQuery();

Sharepoint list item using client object model

Create New Item
string siteUrl = "http://sp2013";
ctx ctx = new ctx(siteUrl);
List oList = ctx.Web.Lists.GetByTitle("MyList");
ListItemCreationInformation lstCre = new ListItemCreationInformation();
ListItem oListItem = oList.AddItem(lstCre);
oListItem["Title"] = "Hello World";
oListItem.Update();
ctx.ExecuteQuery();


Update List Item
string siteUrl = "http://sp2013";
ctx ctx = new ctx(siteUrl);
List oList = ctx.Web.Lists.GetByTitle("MyList");
ListItem oListItem = oList.GetItemById(5);
oListItem["Title"] = "Hello World Updated!!!";
oListItem.Update();
ctx.ExecuteQuery();
Delete List Item
string siteUrl = "http://sp2013";
ctx ctx = new ctx(siteUrl);
List oList = ctx.Web.Lists.GetByTitle("MyList");
ListItem oListItem = oList.GetItemById();
oListItem.DeleteObject();
ctx.ExecuteQuery();

console application c# .exe is missing


Search in this folder
ProjectName\bin\Debug
Or
ProjectName\bin\Release

Friday, 16 May 2014

Get WebApplication Name Using GUID

Get WebApplication Name Using GUID

Add-PSSnapin Microsoft.SharePoint.PowerShell

$url = "http://SERVER/sites/MyWebApp"
$site = Get-SPWeb ($url)
foreach ($web in $site.Site.AllWebs)
{
if ($web.Url.StartsWith($url))
{
Write-Host ($web.Name + "|" + $web.Url + "|" + $web.Id)
}
}
Now you will get Name and GUID, just check with GUID corresponding name.

Thursday, 15 May 2014

Retrieve SharePoint List Data and bind this to a dropdownlist



if (!Page.IsPostBack)
        {
            using (SPSite site = new ("http://SP2013"))
            {
                using (SPWeb web = site.OpenWeb())
                {
                    SPList list = web.Lists["NameOfYourList"];
                    dropSite.DataSource = list.Items;
                    dropSite.DataValueField = "Title";
                    dropSite.DataTextField = "Title";
                    dropSite.DataBind();
                }
            }
        }

Sharepoint Read Large List

Sharepoint Best practice
using (SPSite site = new SPSite("http://SERVER:42204/Lists/"))
{
using (SPWeb web = site.OpenWeb())
{
SPList tasksList = web.Lists["Announcements"];
System.Data.DataTable dt;
int i = 0;
dt = tasksList.Items.GetDataTable();
foreach (System.Data.DataRow dr in dt.Rows)
{
Console.WriteLine(dr["Title"].ToString());
i++;
}
Console.WriteLine(i);
}
}

Sharepoint read list items using ClientContext

Create a SharePoint page.
Add Content editor web part
Open notepad
Add below content

Upload in to SharePoint.
Copy the file location (URL)
Edit Content editor web part
Provide url which you get from above step in "Content Link" section.
Save.

Give full read access to default content access account


You should have a dedicated domain account that is used as a default content access account. This is important since this account is used by the crawler in any of the servers in your farm that has been assigned as crawl servers.
Default content access account needs to have Full Read-permissions to the SharePoint web application you are crawling.
1. Open SharePoint 2010 Central Administration
2. Click Manage web applications under Application Management-section
3. Select your web application's row
4. Click User Policy from the ribbon
5. Click Add Users
6. Click Next
7. Input your default content access account to Users-box
8. Select Full Read under Permissions
9. Click Finish

To develop Silver Light Application which support Coded UI test what are the prerequisite?


1. VS 2010 Ultimate
2. Visual Studio 2010 Feature Pack 2 (http://msdn.microsoft.com/en-us/vstudio/ff655021)
3. Silverlight 4 Developer runtime.(http://www.microsoft.com/downloads/en/confirmation.aspx?FamilyID=b3deb194-ca86-4fb6-a716-
b67c2604a139&displayLang=en)
4. Install http://go.microsoft.com/fwlink/?LinkId=146060
Why we have to Install Visual Studio Feature Pack 2.
Ans) To get coded UI test option in Silver light application to find out control names in the UI we have to develop siverlight application with Visual Studio Feature Pack 2. So that we can get the control ids to use in Coded Ui testing.

Get Attachments from SharePoint


using System;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using Microsoft.SharePoint;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
GridView1.DataSource = ShowSPListAttachments(“1?, “http://SERVER:PORT/sites/NAME/”, “LISTNAME”, “TestList2010?, “TestList2010?, “http://SERVER:PORT/sites/NAME/LISTNAME/Lists/TestList2010/”);
GridView1.DataBind();
}
private DataTable ShowSPListAttachments(string listItemID, string spSiteCollection, string spTopLevelSite, string spListName, string spListSubFolderName, string spListAttachmentLocation)
{
SPSite spSite = null;
SPWeb spWeb = null;
SPList spList = null;
SPListItem spListItem = null;
SPAttachmentCollection spAttachmentCollection = null;
SPFolder spFolder = null;
DataTable dtAttachments = new DataTable();
string fileName = string.Empty;
int docID = 0;
try
{
SPSecurity.RunWithElevatedPrivileges(delegate()
{
using (spSite = new SPSite(spSiteCollection))
{
using (spWeb = spSite.OpenWeb())
{
using (spWeb = spSite.AllWebs[spTopLevelSite]) { }
}
//spWeb = spSite.AllWebs[spTopLevelSite];
//spSite.OpenWeb();
}
});
spWeb.AllowUnsafeUpdates = true;
spList = spWeb.Lists[spListName];
spListItem = spList.GetItemById(int.Parse(listItemID));
spAttachmentCollection = spListItem.Attachments;
DataColumn dc;
dc = new DataColumn(“FileName”, typeof(string));
dtAttachments.Columns.Add(dc);
dc = new DataColumn(“FilePath”, typeof(string));
dtAttachments.Columns.Add(dc);
if (spAttachmentCollection.Count > 0)
{
spFolder = spWeb.Folders["Lists"].SubFolders[spListSubFolderName].SubFolders["Attachments"].SubFolders[spListItem["ID"].ToString()];
HyperLink objHyperLink = null;
string FileExt = String.Empty;
foreach (SPFile objSPFile in spFolder.Files)
{
if (spFolder.Files.Count != 0)
{
fileName = spListAttachmentLocation + objSPFile.ToString().Replace(” “, “%20?);
objHyperLink = new HyperLink();
objHyperLink.NavigateUrl = fileName.Trim();
objHyperLink.Text = objSPFile.Name;
objHyperLink.ID = docID.ToString();
docID++;
FileExt = objSPFile.Name.ToString().Substring(objSPFile.Name.LastIndexOf(“.”) + 1);
if (string.Compare(FileExt.Trim().ToUpper(), “PDF”, true) == 0)
{
objHyperLink.Target = “_blank”;
}
dtAttachments.Rows.Add(objHyperLink.Text, objHyperLink.NavigateUrl);
FileExt = string.Empty;
}
}
}
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
finally
{
if (spWeb != null)
{
spWeb.AllowUnsafeUpdates = false;
spWeb.Dispose();
spWeb = null;
}
if (spSite != null)
{
spSite.Dispose();
spSite = null;
}
spList = null;
spListItem = null;
spAttachmentCollection = null;
spFolder = null;
}
return dtAttachments;
}
}

SharePoint Client Object Model get Look up field

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.SharePoint.Client;
using Microsoft.SharePoint;
namespace SPLookUpPOC
{
class Program
{
static void Main(string[] args)
{
string strWeburl = "http://MyServer/sites/MyWebSite";
ClientContext ObjContext = new ClientContext(strWeburl);
List Objlist = ObjContext.Web.Lists.GetByTitle("MyList");
CamlQuery ObjQuery = new CamlQuery();
ObjQuery.ViewXml = @"<View Scope='RecursiveAll'/>";
ListItemCollection objListColl = Objlist.GetItems(ObjQuery);
ObjContext.Load(objListColl);
ObjContext.ExecuteQuery();
//Now we can loop all columns from ListItemCollection..I am trying to find lookup column
string strID = string.Empty;
foreach (ListItem objItem in objListColl)
{
if (objItem["ID"] != null)
{
FieldLookupValue Objlf = (FieldLookupValue)objItem.FieldValues["ID"];
strID = Objlf.LookupId.ToString();
}
}
}
}
}

K2 Blockpearl Custom code

sourcecode.workflow.client
need to add above name space to use k2 API in asp.net
 
Declarations before PageLoad
SourceCode.Workflow.Client.Connection m_oConn = null;
//bp server from the web.config
private string m_strBPServer = System.Configuration.ConfigurationManager.AppSettings["WorkflowServer"];
 
Open the connection at the beginning of PageLoad
// open the connection
m_oConn.Open(m_strBPServer);
 
————————————————————
 
using (SourceCode.Workflow.Client.Connection con = new Connection())
{
con.open(“workflowserver”);
ProcessInstance pi = con.CreateProcessInstance(“workflowproject\\workflowprocess”); pi.DataFields["fieldname"].value = “value”;
con.StartProcessInstance(pi);
}

Upload file to SharePoint using PowerShell


$SPWebURL = “http://SP2013/sites/SiteCollA”
$MylibraryName = “MyDocumentLib”
$MyFilePath = “C:\file.docx”
$SPWeb = Get-SPWeb $SPWebURL
$List = $SPWeb.GetFolder($MylibraryName)
$Files = $List.Files
$FileName = $MyFilePath.Substring($MyFilePath.LastIndexOf("\")+1)
$File= Get-ChildItem $MyFilePath
$Files.Add($MylibraryName +"/" + $FileName,$File.OpenRead(),$false)
$SPweb.Dispose()

C# DataSet Print Columns and Rows

//DataSet ds=(DataSet)table;
DataTable table = results.Tables[0];
string strTable = string.Empty;
foreach (DataColumn dc in table.Columns)
{
//Console.Write("{0,15}", dc.ColumnName);
strTable += dc.ColumnName + " ";
}
//Console.Write(vbCrLf);
strTable += "vbCrLf";
// Display the data for each row. Loop through the rows first.
//DataRow dr;
foreach (DataRow dr in table.Rows)
{
// Then loop through the columns for the current row.
int i;
for (i = 1; i <= table.Columns.Count; i++)
{
//Console.Write("{0,15}", dr[i-1]);
strTable += dr[i - 1] + " ";
}
// Add a line break after every row
//Console.Write(vbCrLf);
strTable += "vbCrLf";
}
//End
string k = strTable;

Wednesday, 14 May 2014

Microsoft.SharePoint.WorkflowActions.dll

Microsoft.SharePoint.WorkflowActions.dll path

C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\ISAPI

Save a Site as a Template in SharePoint missing


Site Actions -> Site Settings -> Manage site features (under “Site Actions”)
“Deactivate” for “SharePoint Server Publishing”
Now go to :Site Actions -> Site Settings. You should now see “Save site as template” as an option
Solution path:
_catalogs/solutions/Forms/AllItems.aspx

If you still not able to see Save Site as template.
try this powershell command...

$oweb = Get-SPWeb http://sp2013

$oweb.SaveSiteAsTemplateEnabled = $true

$oweb.Update()

Error: Failed to communicate with WCF Service.


Root Cause:
Check your WCF Service application pool it might stopped
Check FAST Server admin account changing pssword.
Open FAST Search PowerShell and run below command.
Get-FASTSearchContentCollection.
Current Logged in Account Should be part of FASTSearchAdministrators group.
Whne yu install FAST Search this Group will "FASTSearchAdministrators"create.
Determine whether the FastSearchAdminAppPool administrative service is running.
Log on to the FAST Search Server 2010 server as a FAST Search Server 2010 user.
Click Start, point to Administrative Tools, and then click Internet Information Services (IIS) Manager.
Expand FAST_Search_server_name, and then expand Application Pools.
Right-click FastSearchAdminAppPool, and then click Properties.
If the service is stopped, click Start.

Determine whether the FASTSearchAdminServices site exists:
Log on to the FAST Search Server 2010 server as a FAST Search Server 2010 user
Click Start, point to Administrative Tools, and then click Internet Information Services (IIS) Manager.
Expand FAST_Search_server_name and then expand Sites.
Verify that the FASTSearchAdminServices site exists under Sites.

How to create foreign key in SQL


Create Table Emp
(
EId Int primary key,
EName varchar(20)
)
Create Table Leavedetails
(
LId int,
NoOfDays int,
Emp_ID int foreign key references Emp(EId)
)
Group By
Select EName, Sum(NoOfDays) NoOfDays from Emp
Inner Join Leavedetails on Emp.EId=Leavedetails.Emp_ID
Group By EName
The column names after Select statement, should be member of Group By or Aggregate function (SUm, Avg, Count), other wise you will get error.

Tuesday, 13 May 2014

telerik:RadDatePicker OnValueChanging

<script type="text/javascript">
        function ValueChanging(sender, args)
        {
            if (sender.get_dateFormat() == "MM/yyyy")
            {
                var selectedDay = sender.get_owner().get_calendar().get_selectedDates()[0][2];
                var value = args.get_newValue();
                var monthPlace = sender.get_dateFormatInfo().DateSlots["Month"];
                if (monthPlace == 1)
                {
                    args.set_newValue(selectedDay + "/" + value);
                }
                else
                {
                    var monthAndYear = value.split("/");
                    args.set_newValue(monthAndYear[0] + "/" + selectedDay + "/" + monthAndYear[1]);
                }
            }
        }
    </script>
 
    <telerik:RadDatePicker ID="RadDatePicker1" runat="server">
        <DateInput ID="DateInput1" DateFormat="MM/yyyy" runat="server"
            ClientEvents-OnValueChanging="ValueChanging" />
    </telerik:RadDatePicker>

Execute Class Libraray in SharePoint Server


1. Open Class Library
2. Build the solution
3.If you have and reference errors , solve the errors
4.If you want to get dlls from GAC
Go to Run
Type:
C:\windows\assembly\gac_msil
Now you can copy any dll.
5.Rebuild.After getting success.
6.Copy the source in to server , where you want to run this.
7.Open Command prompt. Run as Administrator
8.Go to your project folder and execute the exe. (If you want to change config files, change in server directly)
Ex: C:\Myproject>MyProject.exe

what is the meaning of ( object sender, System.EventArgs e )


Let' assume i have 2 button click events.
btnTestA.Click += new EventHandler(btnTest_Click);
btnTestB.Click += new EventHandler(btnTest_Click);
If use click on btnTestB, it will call btnTest_Click method.
Now i will write btnTest_Click
private void btnTest_Click(object sender, EventArgs e)
{
Button test = sender as Button;
// etc ...
}
How can i find user has cliecked on btnTestB
here is the solution...
object sender will able to find that
Button test = sender as Button;
the above code will give the exact button name, there sender will be usefull
The EventArgs portion is a way to pass extra information to the event handler. In the case above, EventArgs is a base class and no real extra information is passed. However, alot of events use a derivative of EventArgs, which contain extra information.

Get SPList Data

public DataTable getList()
{
SPSite siteCollection = null;
SPWeb topLevelSite = null;
SPListItemCollection myitems = null;
try
{
siteCollection = new SPSite("");
topLevelSite = siteCollection.AllWebs[""];
SPList list = topLevelSite.Lists[""];
myitems = list.Items;
//Get the Datatable for ALL the list items
dtNewItems = myitems.GetDataTable();
return dtNewItems;
}
catch (Exception ex)
{
throw ex;
}
}

Add new list row using Object Model is sharepoint list

private void updateSharePoint(NewSSP_SubmitBLLFields objNewSSP, stringstrNotifiers)
{ SPSite siteCollection = null;
SPWeb topLevelSite = null;


string strNewXRef = String.Empty;
bool blnNoError = true;
try
{
SPSecurity.RunWithElevatedPrivileges(delegate()
{
siteCollection = newSPSite(System.Configuration.ConfigurationManager.AppSettings["SPDocumentLibrary"].ToString());
topLevelSite = siteCollection.AllWebs[ConfigurationManager.AppSettings["TopLevelSite"].ToString()];
});
topLevelSite.AllowUnsafeUpdates = true;
SPList list = topLevelSite.Lists[ConfigurationManager.AppSettings["ListName"].ToString()];




// Create List Item
SPListItem objListItem = list.Items.Add();
objListItem["Title"] = objNewSSP.Title;
objListItem["SSP #"] = strRetSSPID.ToString();

string strUserName = Session["FullName"].ToString();
for (int i = 0; i 0)
{
objListItem["Estimated Completion Date"] = txtEstimateComplitionDate.Text;
}
objListItem["Request Date"] = DateTime.Today.ToShortDateString().ToString();
objListItem["Timing"] = txtTiming.Text;
objListItem["Cost"] = txtCost.Text;
objListItem["How Affect Product"] = txtHowAffectProduct.Text;





string strNList = string.Empty;
if (lstnotification.Items.Count > 0)
{

for (int i = 0; i < lstnotification.Items.Count; i++)
{

if(!string.IsNullOrEmpty(lstnotification.Items[i].ToString()))
{
strNList = lstnotification.Items[i].ToString() + ";";
}
}
objNewSSP.NotificationList = strNList.ToString();
objListItem["NotificationList"] = strNList;
}
objListItem.Update();
topLevelSite.AllowUnsafeUpdates = false;
UploadSSPFiles();
hdnDupTitle.Value = "Yes";
}





catch (Exception ex)
{
blnNoError = false;
lblMsg.Text = "Error " + ex.StackTrace.ToString() + " While Updating Sharepoint List";


// lblSuccessMsg.Text = "";
}
finally
{
if (blnNoError)
{
lblMsg.Text = "";

// lblSuccessMsg.Text = "Document has been reserved successfully";
txtComments.Enabled = false;
//btnSubmit.Enabled = false;
}
}
siteCollection.Dispose();
topLevelSite.Dispose();
if (blnNoError)
{

//Response.Redirect("Confirm.aspx?id=9&SSPID=" + strRetSSPID);
spnSSPID.InnerText = strRetSSPID.ToString();
ScriptManager.RegisterStartupScript(this, Page.GetType(), "","ShowDivLayer('shadow','divShowSSPID');", true);
}
}
http://www.infoitweb.com/Common/Articles.aspx?TypeID=11&ContentID=139

.dwp .webpart different

.dwp- Sharepoint Web parts-System.Web.UI.WebControls.WebParts.WebPart
 
Cross page connections
 
Connections between Web Parts that are outside of a zone
 
Client-side connections (Web Part Page Services Component)
 
Data caching infrastructure, including the ability to cache to the database
 
All above feature can’t do using Dot net web part.
 
.webparts- Dot net webparts-Microsoft.SharePoint.WebPartPages.WebPart

Generics in asp.net

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Collections.Generic;
namespace Test_n.G
{
public partial class WebForm1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
List names = new List();
names.Add("A");
names.Add("B");
names.Add("C");
lboxStrings.DataSource = names;
lboxStrings.DataBind();
string temp1 = names[2];
Customer c1 = new Customer("1", "A", "AA", "123-4567");
Customer c2 = new Customer("2", "B", "BB", "123-7823");
Customer c3 = new Customer("3", "C", "CC", "123-6383");
List customers = new List();
customers.Add(c1);
customers.Add(c2);
customers.Add(c3);
Customer c = customers[2];
customers[1] = c;
lboxCustomers.DataSource = customers;
lboxCustomers.DataBind();
Dictionary dict = new Dictionary();
dict.Add(c1.Id, c1);
dict.Add(c2.Id, c2);
lboxDictionary.DataSource = dict;
lboxDictionary.DataBind();
}
}
public abstract class AbstractEntity
{
private string _id;
public AbstractEntity(string id)
{
_id = id;
}
public string Id
{
get { return _id; }
set { _id = value; }
}
public abstract bool IsValid
{
get;
}
}
public class Customer : AbstractEntity
{
private string _firstName;
private string _lastName;
private string _phone;
public Customer(string id, string firstName, string lastName, string phone)
: base(id)
{
_firstName = firstName;
_lastName = lastName;
_phone = phone;
}
public string FirstName
{
get { return _firstName; }
set { _firstName = value; }
}
public string LastName
{
get { return _lastName; }
set { _lastName = value; }
}
public string Phone
{
get { return _phone; }
set { _phone = value; }
}
public string Name
{
get { return LastName + ", " + FirstName; }
}
public override bool IsValid
{
get
{
if (Id.Length > 0 && LastName.Length > 0)
return true;
else
return false;
}
}
public override string ToString()
{
return Id + "," + Name + "," + Phone;
}
}
}
--------------------
asp:ListBox ID="lboxStrings" runat="server"
asp:ListBox ID="lboxCustomers" runat="server"
DataTextField="Name"
DataValueField="Id"
asp:ListBox ID="lboxDictionary" runat="server"
DataTextField="Value"
DataValueField="Key"
----------------------------------
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Collections.Generic;
namespace Test_narayana.G
{
public partial class A : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
Author A1 = new Author(TextBox1.Text, TextBox2.Text, TextBox3.Text, "123-4567");
Author A2 = new Author("TTT", "B", "BB", "123-7823");
Author A3 = new Author("MS", "C", "CC", "123-6383");
Dictionary dict = new Dictionary();
dict.Add(A1.Id, A1);
dict.Add(A2.Id, A2);
dict.Add(A3.Id, A3);
lboxDictionary.DataSource = dict;
lboxDictionary.DataBind();
ReadDic(dict);
}
protected void ReadDic(Dictionary dict)
{
//Read Dictionary
foreach (KeyValuePair kv in dict)
{
Response.Write(kv.Key + ":" + kv.Value);
Author au = kv.Value;
Response.Write(au.Id);
Response.Write(au.ItemURL);
Response.Write(au.AuthorName);
Response.Write(au.searchKeyWord);
}
}
}
public abstract class AAbstractEntity
{
private string _id;
public AAbstractEntity(string id)
{
_id = id;
}
public string Id
{
get { return _id; }
set { _id = value; }
}
public abstract bool IsValid
{
get;
}
}
public class Author : AAbstractEntity
{
private string _ItemURL;
private string _AuthorName;
private string _searchKeyWord;
public Author(string id, string ItemURL, string AuthorName, string searchKeyWord)
: base(id)
{
_ItemURL = ItemURL;
_AuthorName = AuthorName;
_searchKeyWord = searchKeyWord;
}
public string ItemURL
{
get { return _ItemURL; }
set { _ItemURL = value; }
}
public string AuthorName
{
get { return _AuthorName; }
set { _AuthorName = value; }
}
public string searchKeyWord
{
get { return _searchKeyWord; }
set { _searchKeyWord = value; }
}
//public string Name
//{
// get { return AuthorName + ", " + ItemURL; }
//}
public override bool IsValid
{
get
{
if (Id.Length > 0 && AuthorName.Length > 0)
return true;
else
return false;
}
}
//public override string ToString()
//{
// return Id + "," + Name + "," + searchKeyWord;
//}
public override string ToString()
{
return Id + "," + AuthorName + ", " + ItemURL + "," + searchKeyWord;
}
}
}

SQL stored procedures

To get all stored procedures
exec sp_stored_procedures
DatabaseName.dbo.sp_stored_procedures
DatabaseName.dbo.sp_helptext StoredProcedureName
to get all information
SELECT * FROM sys.objects;
SQL Server 2005 To get all stored procedures
SELECT * FROM sys.procedures;

Monday, 12 May 2014

png hover styles in the same image

.mystyle
{
    background: transparent url('images1.png');
    height: 50px;
    width: 33px;
    vertical-align: middle;
    float:right;
}
.mystyle:hover
{
    background-position: 50px 33px;
}

How to see if string contains substring


if (strName.toLowerCase().indexOf("myproject") >= 0){
strName= strName.toLowerCase().replace("myproject", "");
}

Increase memory limit for remote shell


PS WSMan:\localhost\Shell> Get-Item .\MaxMemoryPerShellMB
PS WSMan:\localhost\Shell> set-item .\MaxMemoryPerShellMB 1024 -force

Javascript calling function through a variable


<script>
var foo = function () {
for (var i = 0; i < 10; i++) {
alert(i);
}
};
foo();
</script>

How to enable sharepoint feature using CSOM


public void ActivateFeature(string webFullUrl,Guid featureId,bool force,FeatureDefinitionScope featdefScope)
{
using (var ctx = new ClientContext(webFullUrl))
{
var features = ctx.Web.Features;
ctx.Load(features);
ctx.ExecuteQuery();
features.Add(featureId, force, featdefScope);
ctx.ExecuteQuery();
}
}

jQuery Templates

Using jQuery templates, we can define the out HTML structure using template, create a data source. Then bind the data source to template.
Please go through this site for more details.
http://www.borismoore.com/2010/09/introducing-jquery-templates-1-first.html

You can find below samples.
<script src="http://code.jquery.com/jquery.js" type="text/javascript"></script>
<!--Download tmpl "https://code.google.com/p/my-web-js/downloads/detail?name=jquery.tmpl.min.js&can=2&q="-->
<script src="jquery.tmpl.min.js" type="text/javascript"></script>
<script id="movieTemplate" type="text/x-jquery-tmpl">
<li>
<b>${Name}</b> (${ReleaseYear})
</li>
</script>
<ul id="results"></ul>
<script type="text/javascript">
var movies = [
{ Name: "The Red Violin", ReleaseYear: "1998" },
{ Name: "Eyes Wide Shut", ReleaseYear: "1999" },
{ Name: "The Inheritance", ReleaseYear: "1976" }
];
$("#movieTemplate").tmpl(movies)
.appendTo("#results");
</script>

Now i am going to change the data source and template...

<script src="http://code.jquery.com/jquery.js" type="text/javascript"></script>
<!--Download tmpl "https://code.google.com/p/my-web-js/downloads/detail?name=jquery.tmpl.min.js&can=2&q="-->
<script src="jquery.tmpl.min.js" type="text/javascript"></script>
<script id="movieTemplate" type="text/x-jquery-tmpl">
<li>
<b>{{html Name}}</b>
(<span style="color: Blue"> ${ReleaseYear}</span>) - Director: ${Director}
</li>
</script>
<ul id="results"></ul>
<script type="text/javascript">
var movies = [
{ Name: "The <strong style='color: red'>Red</strong> Violin", ReleaseYear: "1998", Director: "Francois Girard" },
{ Name: "Eyes Wide Shut", ReleaseYear: "1999", Director: "Stanley Kubrick" },
{ Name: "The Inheritance", ReleaseYear: "1976", Director: "Mauro Bolognini" }
];
$("#movieTemplate").tmpl(movies)
.appendTo("#results");
</script>

How can I change the order the list fields appear in 'add new item' form in SharePoint


If you are using content type
Go to Site Settings
Click on : Site Content Types
Select Your group, from Show Group.
Now you will able to see all content types..
Click on content type which you want to change
You can find: Column order : Click " Column order "
You will see all columns with sort order
You can change sort order..
Save


If you are using Column from List
Go to List
List Settings
Under "Views"
Click on Your view which you want to change the column order
You will see all columns with sort order.
Change order and Save

Powershell Script to clear Blob Cache


Write-Host -ForegroundColor White ” – Enabling SP PowerShell cmdlets…”
If ((Get-PsSnapin |?{$_.Name -eq “Microsoft.SharePoint.PowerShell”})-eq $null)
{
$PSSnapin = Add-PsSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue | Out-Null
}
$webAppall = Get-SPWebApplication
foreach ($_.URL in $webAppall) {
$webApp = Get-SPWebApplication $_.URL
[Microsoft.SharePoint.Publishing.PublishingCache]::FlushBlobCache($webApp)
Write-Host “Flushed the BLOB cache for:” $webApp
}


Feature: New to the WSSv3 Platform is a concept called Features.  These enable you to package chunks of functionality and allow this functionality to be turned on or off in a WSSv3 based site

Feature Stapler: Feature Stapling allows you to “staple” a Feature to a site definition without modifying it in any way.  This means you can add your feature to all sites created using that site definition

Feature Staplee: To create a staple you actually create another Feature that does the staple and called Feature Staplee.

Scenario:  You want to run some custom code whenever a site is created. (a typical use of the ExecuteURL property in V2)
Solution:  Build a Feature that has an Event Receiver defined on it; & have it catch the Feature activation event.  Run your custom code in there.  Then, use a Feature Staple to staple your Feature to the site definition


Saturday, 10 May 2014

SQL Server: Definition, Comparison and Difference between HAVING and WHERE Clause


SQL Having:
HAVING specifies a search condition for a group or an aggregate function used in SELECT statement.
HAVING can be used only with the SELECT statement. HAVING is typically used in a GROUP BY clause. When GROUP BY is not used, HAVING behaves like a WHERE clause.
A HAVING clause is like a WHERE clause, but applies only to groups as a whole, whereas the WHERE clause applies to individual rows. A query can contain both a WHERE clause and a HAVING clause. The WHERE clause is applied first to the individual rows in the tables . Only the rows that meet the conditions in the WHERE clause are grouped. The HAVING clause is then applied to the rows in the result set. Only the groups that meet the HAVING conditions appear in the query output. You can apply a HAVING clause only to columns that also appear in the GROUP BY clause or in an aggregate function.
Example of HAVING and WHERE in one query:
SELECT titles.pub_id, AVG(titles.price)
FROM titles INNER JOIN publishers
ON titles.pub_id = publishers.pub_id
WHERE publishers.state = 'CA'
GROUP BY titles.pub_id
HAVING AVG(titles.price) > 10
Sometimes you can specify the same set of rows using either a WHERE clause or a HAVING clause. In such cases, one method is not more or less efficient than the other. The optimizer always automatically analyzes each statement you enter and selects an efficient means of executing it. It is best to use the syntax that most clearly describes the desired result. In general, that means eliminating undesired rows in earlier clauses.

SQL Functions


Aggregate :It can apply on group of data
Ex: Sum(row1,r2,...)
Sum(ColumnName)
Aggregate will expect collection data as input
It will rerun single value as Output.
Ex: Sum, Max, MIn, Avg, Count and Count_Big
If you add any Aggregate function and any addtional columns in select statement, then you have to add group by
Ex: Select EName, Sum(LeaveDays) from Emp
Group By Ename
If you don't add Group By Ename then you will get error.
Select COUNT(*) from Emp --For small tables
Select COUNT_BIG(*) from EMP --Counts big data. Ex: if you have a table with more data like 50Cr
Scalar: Single Valued
Ex: UPPER('')
Scalar will expect single value as input
it will rerun based on number of rows.
Scalar functions
Ex:
Numeric
Date
String
System
MetaData
Date:
GetDate() --Current Server date and time
DateAdd(<Units>,<Number>,<DateValue>)
Ex:
Select DateAdd(d,10,GETDATE())
Select DateAdd(Month,10,GETDATE())
Select DateAdd(Year,-10,GETDATE())
DateDiff(<Units>,<FromDate>,<EndDate>)
EX:
Select DATEDIFF(d,<FromDate>,<EndDate>) as Diff from Table
Select DATEDIFF(Month,<FromDate>,<EndDate>) as Diff from Table
DatePart(<Units>,<Date>)
Ex:
Select DATEPART(month,getdate())
Select DATEPART(Year,getdate())
DateName(<Units>,<Date>)
Numeric Functions
--ABS(s)
:Absulute Value
Select ABS(-5)
O/p:5
--CEAILING(n)
It will return next higest value of integer
Select CEAILING(2.1)
O/P=3
Select CEAILING(-2.1)
O/P=-2
-EXP(n)
Ex: EXP(10)
It will give e power 10
--FLOOR(n)
It will return next lowest value of integer
--LOG(n)
It's base is e
--LOG10(n)
It's Base is 10
--PI()
--POwer(x,y)
--RAND()
It will return random value from 0 to 1
--ROUND(n,p)
ROUND(22.33,1) o/p: 22.3
ROUND(22.33,-1) o/p:20
--ROWCOUNT_BIG
Last executed query records count(Effected rows)
--select SQRT(9)
String Functions
----------------
--CHAR(Integer)
Select CHAR

--ASCII (Character)
Select ASCII('A')
Select ASCII('x')
--CHARINDEX(String1,String2)
Select CHARINDEX('n','India')
Select CHARINDEX('d','redmond')
if(CHARINDEX('red','redmond')>0)
Print 'Redmond'
else
Print 'Hi'
--LEFT(String,length)
Ex:
Select LEFT('India',3)
O/P: Ind
Select LEFT('India',5)
O/P: India
Select LEFT('India',8)
O/p: India
Select LEFT('India',0)
O/P:
--RIGHT(String,length)
Select RIGHT('India',3)
O/P: dia
--LEN(string)
Select LEN('India')
O/P: 5
Ex: Select LEN(Ename) from Emp
--LOWER(string)
select LOWER('INDIA')
O/P: india
--UPPER(string)
--LTRIM(String)
Select LTRIM(' India ')
O/p:'India '
--RTRIM(String)
Select RTRIM(' India ')
O/P:' India'
Select LTRIM(RTRIM(' India '))
O/P: 'India'
--REPLACE(string1,string2,string3)
Search for string2 in string1 and replace with string3
Ex: Select REPLACE('Banguloor','Ban','Man')
O/P: Manguloor
--REPLICATE(string,int)
select replicate('A',100)
--REVERSE(string)
Select REVERSE(Ename) from EMP
--STR(float,len,d)
Convert floating values to string
Ex: select STR(2.345,3)
--STUFF(str1,starting Charector,How Many chrectors,str2)
Select STUFF('Hyderabad IT place',10,0,' is Nice ')
O/p: Hyderabad Nice IT place
--SUBSTRING(str,Start,len)
Ex: select substring('Hyderabad IT place',7,3)
o/p:bad

the version of sql server data tools is not compatible with the database runtime components

Issues:
  1. SSDT September 2012 and previous SSDT releases are not compatible with this new version of DACFX.
  2. Packages created by this release of DACFx (and later) containing Selective XML Indexes (SXI) or packaged table data cannot be consumed by previous releases of DACFx and SSDT.
Solution
http://go.microsoft.com/fwlink/?LinkID=309459

Difference between View and Named Query in SQL


View: Valid Select query in SQL(In Data base level)
Named Query: Creating a View in Data Source View
EX: Create View <Name>
as
Select ....

SharePoint Display Template Hover click

SharePoint Display Template Hover click
Add below code in item template
var tileId=encodedId + "tile";
var containerId=encodedId + "container";
var featureinformation=$getItemValue(ctx, "Feature Information");
var linkMarkup="<a href='" + linkURL.value + "'><div class='cbs-sliding-details-preview-pane-link'>See more information</div></a>";
var contentMarkup="<div class='cbs-preview-pane-feature-details'>" + featureinformation.value + linkMarkup + "<\div>";
addPreviewPaneContentData([containerId,contentMarkup]);
============================
function addPreviewPaneContentData(newData){
previewPaneContentData.push(newData);
}
function setCurrentPaneId(newId){
curretntPanelId = newId;
}
function getCurrentPanelId(){
return(currentPanelId);
}
function previewpane_init() {
$('.cbs-sliding-details-container').click(tileClick);
$('.cbs-sliding-details-container').first().click();
}
function tileClick() {
if (previewPanelContentData != null)
{
for(var i=0; i<previewPanelContentData.length; i++)
{
if($(this.attr("id")==previewPanelContentData[i][0]){
$('#previewPanelHeroPanel').html(previewPanelContentData[i][1]);
break;
}
}
}
See below video from 40 min onwards..
http://channel9.msdn.com/Events/SharePoint-Conference/2012/SPC246

Friday, 9 May 2014

Open Print option javascript

<script>
function print()
{
javascript:(function(){win=open(%22about:blank%22,%20%22View%20DOM%20Source%22,%20%22menubar=no,
resizable=yes,status=no,toolbar=no%22);
win.document.write(%22<pre>%22%20+%20document.documentElement.outerHTML.split(%22&%22).
join(%22&amp;%22).split(%20%22<%22).join(%22&lt;%22).split(%22>%22).join(%22&gt;%22)%20+%20%22</pre>%22);win.focus();})()
}
</script>
<div><a id="print" onclick="return print();">Print</a></div>

BlobBuilder is not defined

var builder = new Blob(data);
builder.append(data);
var blob = builder.getBlob(mimetype || "application/octet-stream");

Replace above code with...
var blob = new Blob(['Hello...'], { type: 'text/css' });

CTS Interview

TCP Security, how to write security for your web services..
How to access SQL Datatabase using C# API
How to read DOM element using javascript
How to read DOM element using jquery
JSON Serilization
What are the pros and cons using Entity database
MVC framework, what are the advantage.
Interms of testing what are the advantages using MVC
Cross site scripting
Do u have used any framework for unit testing
multithreading in c#
c# threadpool
difference between agile and scrum
Refelecter
IE Developer toolbar
pros and cons of 2-tier and 3-tier architecture?

รข€™ html remove


Add below tag inside header.
<meta http-equiv='Content-Type' content='text/html; charset=utf-8'>

Custom Styles for Content Editor Web part in SharePoint 2013



First create your custom style definitions; you can use existing CSS which is linked to the master page or create new CSS file. Sample CSS:
.custom-rteStyle-Heading1
{-ms-name:"Custom Defined 1";
color:#FF0000;
font-size:30px;
font-family:"Gill Sans MT";
font-weight:bold;}
.custom-rteStyle-Heading2
{-ms-name:"Custom Defined 2";
color:#000000;
font-size:24px;
font-family:"Gill Sans MT";
font-weight:bold;}
Ensure that instances of content editor web part are set to use above style definition.
To do that, you can use below JavaScript in your masterpage or in script editor web part (if you want to run a quick test). Obviously if you want content editor web parts anywhere on the site inherit this style - use the script in the masterpage.
Below, also make sure you have a proper name for jQuery reference and CSS file which has your style definitions (my CSS reference is \_layouts\15\MyProject1\Styles.css, so make sure you use your own whether it's in the library or _layouts folder).
Add below code in Master Page.
< script src="http://code.jquery.com/jquery-1.10.2.min.js" type="text/javascript"></script>
< script type="text/javascript">
ExecuteOrDelayUntilScriptLoaded(function() {
$("div[RteRedirect]").each(function() {
var id = $(this).attr("RteRedirect"),
editSettings = $("#" + id);
if(editSettings.length > 0 && editSettings[0].PrefixStyleSheet != 'custom-rte')
{
editSettings[0]['PrefixStyleSheet'] = 'custom-rte';
editSettings[0]['StyleSheet'] = '\u002f_layouts\u002f15\u002fMyProject1\u002fStyles.css';
RTE.Canvas.fixRegion(id, false);
}
});
}, "sp.ribbon.js");
< /script>

jquery document ready

$(document).ready(function(){
//Write your code....
});
Example...
$(document).ready(function(){
$("button").click(function(){
$("p").slideToggle();
});
});

Java Interview Questions

1. What is JVM? Why is Java called the ‘Platform Independent Programming Language’?
JVM, or the Java Virtual Machine, is an interpreter which accepts ‘Bytecode’ and executes it.
Java has been termed as a ‘Platform Independent Language’ as it primarily works on the notion of ‘compile once, run everywhere’. Here’s a sequential step establishing the Platform independence feature in Java:
The Java Compiler outputs Non-Executable Codes called ‘Bytecode’.
Bytecode is a highly optimized set of computer instruction which could be executed by the Java Virtual Machine (JVM).
The translation into Bytecode makes a program easier to be executed across a wide range of platforms, since all we need is a JVM designed for that particular platform.
JVMs for various platforms might vary in configuration, those they would all understand the same set of Bytecode, thereby making the Java Program ‘Platform Independent’.
2. What is the Difference between JDK and JRE?
When asked typical Java Interview Questions most startup Java developers get confused with JDK and JRE. And eventually, they settle for ‘anything would do man, as long as my program runs!!’ Not quite right if you aspire to make a living and career out of Programming.
The “JDK” is the Java Development Kit. I.e., the JDK is bundle of software that you can use to develop Java based software.
The “JRE” is the Java Runtime Environment. I.e., the JRE is an implementation of the Java Virtual Machine which actually executes Java programs.
Typically, each JDK contains one (or more) JRE’s along with the various development tools like the Java source compilers, bundling and deployment tools, debuggers, development libraries, etc.
3. What does the ‘static’ keyword mean?
We are sure you must be well-acquainted with the Java Basics. Now that we are settled with the initial concepts, let’s look into the Language specific offerings.
Static variable is associated with a class and not objects of that class. For example:
public class ExplainStatic {
public static String name = "Look I am a static variable";
}
We have another class where-in we intend to access this static variable just defined.
public class Application {
public static void main(String[] args) {
System.out.println(ExplainStatic.name)
}
}
We don’t create object of the class ExplainStatic to access the static variable. We directly use the class name itself: ExplainStatic.name
4. What are the Data Types supported by Java? What is Autoboxing and Unboxing?
This is one of the most common and fundamental Java interview questions. This is something you should have right at your finger-tips when asked. The eight Primitive Data types supported by Java are:
Byte : 8-bit signed two’s complement integer. It has a minimum value of -128 and a maximum value of 127 (inclusive)
Short : 16-bit signed two’s complement integer. It has a minimum value of -32,768 and a maximum value of 32,767 (inclusive).
Int : 32-bit signed two’s complement integer. It has a minimum value of -2,147,483,648 and a maximum value of 2,147,483,647 (inclusive)
Long : 64-bit signed two’s complement integer. It has a minimum value of -9,223,372,036,854,775,808 and a maximum value of 9,223,372,036,854,775,807 (inclusive)
Float
Double
Autoboxing: The Java compiler brings about an automatic transformation of primitive type (int, float, double etc.) into their object equivalents or wrapper type (Integer, Float, Double,etc) for the ease of compilation.
Unboxing: The automatic transformation of wrapper types into their primitive equivalent is known as Unboxing.

5. What is the difference between STRINGBUFFER and STRING?
String object is immutable. i.e , the value stored in the String object cannot be changed. Consider the following code snippet:
String myString = “Hello”;
myString = myString + ” Guest”;
When you print the contents of myString the output will be “Hello Guest”. Although we made use of the same object (myString), internally a new object was created in the process. That’s a performance issue.
StringBuffer/StringBuilder objects are mutable: StringBuffer/StringBuilder objects are mutable; we can make changes to the value stored in the object. What this effectively means is that string operations such as append would be more efficient if performed using StringBuffer/StringBuilder objects than String objects.
String str = “Be Happy With Your Salary.''
str += “Because Increments are a myth";
StringBuffer strbuf = new StringBuffer();
strbuf.append(str);
System.out.println(strbuf);
The Output of the code snippet would be: Be Happy With Your Salary. Because Increments are a myth.


6. What is Function Over-Riding and Over-Loading in Java?
This is a very important concept in OOP (Object Oriented Programming) and is a must-know for every Java Programmer.
Over-Riding: An override is a type of function which occurs in a class which inherits from another class. An override function “replaces” a function inherited from the base class, but does so in such a way that it is called even when an instance of its class is pretending to be a different type through polymorphism. That probably was a little over the top. The code snippet below should explain things better.
public class Car {
public static void main (String [] args) {
Car a = new Car();
Car b = new Ferrari(); //Car ref, but a Ferrari object
a.start(); // Runs the Car version of start()
b.start(); // Runs the Ferrari version of start()
}
}
class Car {
public void start() {
System.out.println("This is a Generic start to any Car");
}
}
class Ferrari extends Car {
public void start() {
System.out.println("Lets start the Ferrari and go out for a cool Party.");
}
}
Over-Loading: Overloading is the action of defining multiple methods with the same name, but with different parameters. It is unrelated to either overriding or polymorphism. Functions in Java could be overloaded by two mechanisms ideally:
Varying the number of arguments.
Varying the Data Type.
class CalculateArea{
void Area(int length){System.out.println(length*2);}
void Area(int length , int width){System.out.println(length*width);}
public static void main(String args[]){
CalculateArea obj=new CalculateArea();
obj.Area(10); // Area of a Square
obj.Area(20,20); // Area of a Rectangle
}
}
7. What is Constructors, Constructor Overloading in Java and Copy-Constructor?
Constructors form the basics of OOPs, for starters.
Constructor: The sole purpose of having Constructors is to create an instance of a class. They are invoked while creating an object of a class. Here are a few salient features of Java Constructors:
Constructors can be public, private, or protected.
If a constructor with arguments has been defined in a class, you can no longer use a default no-argument constructor – you have to write one.
They are called only once when the class is being instantiated.
They must have the same name as the class itself.
They do not return a value and you do not have to specify the keyword void.
If you do not create a constructor for the class, Java helps you by using a so called default no-argument constructor.
public class Boss{
String name;
Boss(String input) { //This is the constructor
name = "Our Boss is also known as : " + input;
}
public static void main(String args[]) {
Boss p1 = new Boss("Super-Man");
}
}
Constructor overloading: passing different number and type of variables as arguments all of which are private variables of the class. Example snippet could be as follows:
public class Boss{
String name;
Boss(String input) { //This is the constructor
name = "Our Boss is also known as : " + input;
}
Boss() {
name = "Our Boss is a nice man. We don’t call him names.”;
}
public static void main(String args[]) {
Boss p1 = new Boss("Super-Man");
Boss p2 = new Boss();
}
}
Copy Constructor: A copy constructor is a type of constructor which constructs the object of the class from another object of the same class. The copy constructor accepts a reference to its own class as a parameter.
Note: Java Doesn’t support Copy Constructor. Nevertheless folks from C/C++ background often get confused when asked about Java Copy Constructors.
8. What is Java Exception Handling? What is the difference between Errors, Unchecked Exception and Checked Exception?
Anything that’s not Normal is an exception. Exceptions are the customary way in Java to indicate to a calling method that an abnormal condition has occurred.
In Java, exceptions are objects. When you throw an exception, you throw an object. You can’t throw just any object as an exception, however — only those objects whose classes descend from Throwable. Throwable serves as the base class for an entire family of classes, declared in java.lang, that your program can instantiate and throw. Here’s a hierarchical Exception class structure:
java 8
An Unchecked Exception inherits from RuntimeException (which extends from Exception). The JVM treats RuntimeException differently as there is no requirement for the application-code to deal with them explicitly.
A Checked Exception inherits from the Exception-class. The client code has to handle the checked exceptions either in a try-catch clause or has to be thrown for the Super class to catch the same. A Checked Exception thrown by a lower class (sub-class) enforces a contract on the invoking class (super-class) to catch or throw it.
Errors (members of the Error family) are usually thrown for more serious problems, such as OutOfMemoryError (OOM), that may not be so easy to handle.
Exception handling needs special attention while designing large applications. So we would suggest you to spend some time brushing up your Java skills.
9. What is the difference between Throw and Throws in Java Exception Handling (remember this queston?)
Throws: A throws clause lists the types of exceptions that a method might throw, thereby warning the invoking method – ‘Dude. You need to handle this list of exceptions I might throw.’ Except those of type Error or RuntimeException, all other Exceptions or any of their subclasses, must be declared in the throws clause, if the method in question doesn’t implement a try…catch block. It is therefore the onus of the next-on-top method to take care of the mess.
public void myMethod() throws PRException
{..}
This means the super function calling the function should be equipped to handle this exception.
public void Callee()
{
try{
myMethod();
}catch(PRException ex)
{
...handle Exception....
}
}
Using the Throw: If the user wants to throw an explicit Exception, often customized, we use the Throw. The Throw clause can be used in any part of code where you feel a specific exception needs to be thrown to the calling method.
try{
if(age>100){throw new AgeBarException(); //Customized ExceptioN
}else{
....}
}
}catch(AgeBarException ex){
...handle Exception.....
}
10. What is the Difference between byte stream and Character streams?
Every Java Programmer deals with File Operations. To generate User reports, send attachments through mails and spill out data files from Java programs. And a sound knowledge on File Operation becomes even more important while dealing with Java questions.
byte stream : For reading and writing binary data, byte stream is incorporated. Programs use byte streams to perform byte input and output.
Performing InputStream operations or OutputStream operations means generally having a loop that reads the input stream and writes the output stream one byte at a time.
You can use buffered I/O streams for an overhead reduction (overhead generated by each such request often triggers disk access, network activity, or some other operation that is relatively expensive).
Character streams: Character streams work with the characters rather than the byte. In Java, characters are stored by following the Unicode (allows a unique number for every character) conventions. In such kind of storage, characters become the platform independent, program independent, language independent.
11. What are FileInputStream and FileOutputStream ? Explain with an example to read and write into files.
mysql vs mysqliFileInputStream : It contains the input byte from a file and implements an input stream.
FileOutputStream : It uses for writing data to a file and also implements an output stream.
public class FileHandling {
public static void main(String [ ] args) throws IOException
{
FileInputStream inputStream = new FileInputStream ("Input.txt") ;
FileOutputStream outputStream = new FileOutputStream("Output.txt",true) ;
byte[] buffer = new byte[1024];
//For larger files we specify a buffer size which defines the chunks size for data
int bytesRead;
while ((bytesRead = inputStream.read(buffer)) != -1)
outputStream.write(buffer, 0, bytesRead);
inputStream.close() ;
outputStream.close() ;
}
}
12. What are FileReader and FileWriter ? Explain with an example to read and write into files.
FileReader : The FileReader class makes it possible to read the contents of a file as a stream of characters. It works much like the FileInputStream, except the FileInputStream reads bytes, whereas the FileReader reads characters. The FileReader is intended to read text, in other words. One character may correspond to one or more bytes depending on the character encoding scheme.The FileReader object also lets web applications asynchronously read the contents of files (or raw data buffers) stored on the user’s computer, using File or Blob objects to specify the file or data to read.
how to write betterFileWriter : This class is used to write to character files. Creation of a FileWriter is not dependent on the file already existing. FileWriter will create the file before opening it for output when you create the object. Its write() methods allow you to write character(s) or Strings to a file. FileWriters are usually wrapped by higher-level Writer objects such as BufferedWriters or PrintWriters, which provide better performance and higher-level, more flexible methods to write data.
Usage of FileWriter can be explained as follows :
File file = new File("fileWrite2.txt");
FileWriter fw = new FileWriter(file);
for(int i=0;i<10;i++){
fw.write("Soham is Just Awesome : "+i);
fw.flush();
}
fw.close();
Usage of FileWriter and FileReader used in conjunction is as follows:
int c;
FileReader fread = new FileReader("xanadu.txt");
FileWriter fwrite = new FileWriter("characteroutput.txt");
while ((c = fread.read()) != -1)
fwrite.write(c);
13. What is the difference between ArrayList and LinkedList ?
Please pay special attention as this is probably one of the most widely asked interview questions.
We aren’t going to state the properties of each in this question. What we are looking for are the differences. The prime areas where the two stand apart are as follows :
Arraylist Linklist
Random access. Sequential access.The control traverses from the first node to reach the indexed node.
Only objects can be added. The LinkedList is implemented using nodes linked to each other. Each node contains a previous node link, next node link, and value, which contains the actual data
14. Explain the difference between ITERATOR AND ENUMERATION INTERFACE with example.
Iterators allow the caller to remove elements from the underlying collection during the iteration with well-defined semantics.
Iterator actually adds one method that Enumeration doesn’t have: remove ().
14
Whereas in case of Enumeration:
14b
15. What is the use of the ‘SimpleDateFormat’ and how can you use it to display the current system date in ‘yyyy/MM/DD HH:mm:ss’ format?
SimpleDateFormat is one such concrete class which is widely used by Java developers for parsing and formatting of dates. This is also used to convert Dates to String and vice-versa.
Literally every Enterprise level Java Application invariably uses the SimpleDateFormat for handling user dates. We ofcourse aren’t expecting Java interviewees to be absolutely spectacular with the syntaxes. But a basic know-how of this class is mandatory.
public class CurrentSystemDate {
public static void main(String[] args) {
SimpleDateFormat sysForm = new SimpleDateFormat("yyyy/MM/DD HH:mm:ss");
Date curdate= new Date();
System.out.println(sysForm.format(curdate));
}
}
The best way to brush up your Java knowledge is to open up an eclipse and write loads of codes and sample programs. Get into the habit of remembering syntaxes and applying the best coding standards possible.