Thursday, December 13, 2007

Properties in C#

Properties , As there are lot of things going on in my life regarding hike in Bangalore properties ,…..

Here I am trying to understand properties in C#

properties are nothing but natural extension of data fields

Here is an simple example which explain diff between code using properties and not using properties .

With out using properties

using System;
class MyClass
{
private int x;
public void SetX(int i)
{
x = i;
}
public int GetX()
{
return x;
}
}
class MyClient
{
public static void Main()
{
MyClass mc = new MyClass();
mc.SetX(10);
int xVal = mc.GetX();
Console.WriteLine(xVal);//Displays 10
}
}

Syntax for properties


{
get
{
}
set
{
}
}

Where can be private, public, protected or internal. The can be any valid C# type. Note that the first part of the syntax looks quite similar to a field declaration and second part consists of a get accessor and a set accessor.

If we use properties, the code sample will be

using System;
class MyClass
{
private int x;
public int propertyValue
{
get
{
return x;
}
set
{
x = value;
}
}
}
class MyClient
{
public static void Main()
{

MyClass mc = new MyClass();
mc.propertyValue = 10;
int xVal = mc.propertyValue;
Console.WriteLine(xVal);//Displays 10
}
}

mc.propertyValue = 10; // calls set accessor of the property propertyValue, and pass 10 as value of the standard field 'value'.
This is used for setting value for the data member x.
.

For more info you can visit this link

http://www.c-sharpcorner.com/UploadFile/rajeshvs/PropertiesInCS11122005001040AM/PropertiesInCS.aspx

Thursday, December 6, 2007

Cast Conversion

I am not talking about Cast conversion in C#

Its a cast conversion which is happening in India,..

I belive everyone has rights to follow there owne religions....,

But , In India there are some mechinaries which are converting poor Hindus in to christinas by saying " we will give better life" .

But , I feel its exploitaions ,...

I had a freind who is basically from Ooty, and he is a christian,.... While talking with him , I got to know one surprising thing.

He said his father was converted christian and mother was brahmin Hindu ,..and they have to face lot of problems because of Intercast clashes...

and he is telling Even thoe he like Hinduism very much he cant convert from Christian to Hindu ,..because once the christian community of them came to know that you are not coming to church or not following rules they will not even give a small piece of place to burry you after your death,..

and also, he said like In hindues there is no rule that to follow hinduism you have to come to temple or you have to do any particular thing,..
with out becoming hindu also you can always follow Hindu's way of life,..
so he is celebrating all Hindu festival and also going for church ..

There may be many people in india who may be living with these type of clashes,..

As a Hindu I certainily like Hinduism but it doesnt mean that I have to hate Muslim relegions and christianity,...
Same way I excepect Muslim and christians should not say Hinduism is wrong..

I personally ,...Completly oppose converting people from one religion to another,..

and I personally feel people who convert like that may not be having there owne mind set ,..

All religions say live your life happily and join god after your death ,..so whatever religion you follow,..How you live in life will matter ,...





Thursday, November 29, 2007

Iframe in html

I was behind Iframe this morning,

I was not having any task today,..we had kannada rajyotsava celebration in office,..

I got a good article which explained me Iframe with Ex.

Iframes is also defined as an "Inline Frame". Inline Frames are those frames that are embedded in any part of the main page. It made its debut way back when Microsoft had released 'Internet Explorer v.3.0'. In the initial stages the usefulness of Iframes where limited to local applications which were compatible to the Microsoft browser.

I feel, simply we can say using Iframe, I can open many page in a single main page..

and whatever function we perform on that Iframe will effect only on that particular Iframe and it will not effect the page.


For more details visit
Iframa example link

Tuesday, November 27, 2007

ASP.NET AJAX Overview

I was doing R & D on how efficiently we can load data in grid view and i figured out one Asynchronous method to load data,...using Ajax here is a note on that..

What is Ajax ?


•AJAX (Asynchronous JavaScript and XML), or Ajax, is a web development technique used for creating interactive web applications


• exchange small amounts of data with the server behind the scenes so that the entire web page does not have to be reloaded each time the user requests a change


Before going though Asp.net Ajax let me tell you some defnition of Server controls

The following list describes the most frequently used ASP.NET AJAX server controls



ScriptManager


•Manages script resources for client components, partial-page rendering, localization,
globalization, and custom user scripts. The ScriptManager control is required in order to use the UpdatePanel, UpdateProgress, and Timer controls.


UpdatePanel


Enables you to refresh selected parts of the page, instead of refreshing the whole page by using a synchronous postback.



UpdateProgress


•Provides status information about partial-page updates in UpdatePanel controls.


Timer


•Performs postbacks at defined intervals. You can use the Timer control to post the whole page, or use it together with the UpdatePanel control to perform partial-page updates at a defined interval.

Code Sample
-- This code is need to execute script

-- This is the panel, all the controls inside this panel will get updated asynchronously











-->



-- This will say what to trigger




--- This will perform when the updation is in progress



---------------

---- This is the link button where u say apply filter


---- This code will fire asynchronously

protected void lbFilter_Click(object sender, EventArgs e)
{
FillGridView( txtName.Text );
}


private void FillGridView( string filter )
{
gridViewPersons.DataSource = get dataset ;
gridViewPersons.DataBind();
}



For more details see this
http://msdn2.microsoft.com/en-us/library/bb398874(VS.90).aspx

This code will load the grid with out refreshing page ,..

But, still i am not sure how this will improve performence,..
Will it take more time to load data,..
What happens if i click on other button when this process is executing,..
Need to figure out ..........








Wednesday, November 21, 2007

Scan web page by url with HttpWebRequest method

Scan the web page with HttpWebRequest

After deploying code and html pages to palladium group we found so many broken links in pages, which has become a big problem to rework...SO, .. i create a console application which will run in back end and get the content of of all url and check the url whether its working or not by getting the response ,.. and if it is not working send the mail to content developers .

This is the method to scan url

private string GetContent(string url )
{
try
{
// Place the web request to the server by specifying the URL
wReq = (HttpWebRequest)WebRequest.Create(url);
// No need for a persistant connection
wReq.KeepAlive = false;
wResp = (HttpWebResponse)wReq.GetResponse();
// Display the header of the response
// wResp.Headers.ToString();
// Get a stream to read the body of the response
rStream = wResp.GetResponseStream();
// Needed for looping through the buffer int bufCount = 0;
// Buffer in which we're going to store data coming from the server
byte[] byteBuf = new byte[1024];
// Loop as long as there's data in the buffer
string myOutPut = string.Empty ;
do
{
// Fill the buffer with data
bufCount = rStream.Read(byteBuf, 0, byteBuf.Length);
if (bufCount != 0)
{
// Transform the bytes into ASCII text and append to the textbox
myOutPut += System.Text.Encoding.ASCII.GetString(byteBuf, 0, bufCount);
}
}
while (bufCount > 0);
if(myOutPut.IndexOf("corp.thepalladiumgroup") != -1)
{
return "This Content contains corp.thepalladiumgroup link ";
}
}
catch (Exception ex)
{
if (ex.Message.IndexOf("404") != -1 )
{
return " Error 404 found : Details - " + ex.Message ;
}
else if ( ex.Message.IndexOf("500") != -1)
{
return " Error 500 found : Detais - " + ex.Message ;
}
else
{
return "General Exception : " + ex.Message ;
}
}
return "" ;
}

In actual code I am storing all the url in config ,.. get the items in config ,..loop with all url items and check resoponse , if any error send mail ...

Wednesday, November 14, 2007

Trip to BR Hills

On Saturday 10 th of Novemver 2007 we have gone to Biligiri Rangana Betta ( BR Hills) with my friends Kytha , and Ravi ,…other friends who are supposed come, escaped but trip did not cancel..
We decided to go to BR Hills via T Narasipur – Yalandur , we left mandya around 11 Am and we reached BR Hills at 4 PM its about 120 Km from Mandya.

Few things about BR Hills

The Biligiri Rangaswamy Temple wildlife sanctuary (BRT), is a little gem of astonishing bio-diversity. It spreads over an area of 540 Sq. km and is located between 110 43I and 120 08I N latitudes and 770 01I and 770 15I East longitude. Located at the eastern most edge of the
Western ghats, BRT is considered as biogeographic bridge between the Western and the Eastern ghats. The hills are in the Yelandur taluk of Chamarajanagar district of Karnataka. The hills are contiguous with the Satyamangalam range southwards, in the Erode district of Tamil Nadu. The area is 90 km from Mysore and 180 km from Bangalore. It is connected by road, one from Yelandur and the other via Chamarajanagar. The hills are located at the easternmost edge of the Western Ghats and support diverse flora and fauna in view of the various habitat types supported. A wildlife sanctuary of 322.4 km² was created around the temple on 27 June 1974, and enlarged to 539.52 km² on 14 January 1987. The sanctuary derives its name “Biligiri” either from the white rock face that constitutes the major hill crowned with the temple of Lord Rangaswamy, or from the white mist and the silver clouds that cover these lofty hills for a greater of the year. BRT has an amazing diversity of vegetation types such as scrub, dry and moist deciduous, evergreen, sholas and high-altitude grasslands. This diversity of forest types supports a rich variety of fauna, avi-fauna, insects and butterflies. BRT is also known for its many endemic species of plants including valuable medicinal ones. BR Hills constitute a live link between the Eastern Ghats and Western Ghats facilitating an active exchange of gene pools between them. Thus this sanctuary serves as an important biological bridge for the biota of the entire Deccan plateau. BR hills along with the Male-Madeshwara (MM Hills) range are a distinctly unusual mountain range running north-south amidst the plains of Bangalore-(~900 m) Mysore-(~600m) and Krishnagiri-(~450 m) surfaces. The peaks of these lofty ranges rise as high as 1800 m (BR hills 1400 to 1800 m; MM Hills 1000 to 1200 m). The highest hill is Kattari Betta, at 1800 MSL. Biogeographically, BRT sanctuary is very uniquely located. Between 11° and 12° N along its north-south running chain. Western Ghats projects itself in a north-easterly direction and meets the splintered hills of the Eastern Ghats at 78° E. This unique extension of Western Ghats constitutes a live bridge between the Eastern and Western Ghats with the sanctuary located almost in the middle of this bridge. Thus, the biota of BRT sanctuary can be expected to be predominantly of Western Ghats in nature with significant proportion of eastern elements as well.

For more details visit
http://en.wikipedia.org/wiki/Biligirirangan_Hills

After visiting temple we went in search of Lodge,..then we saw board aboout Jungle Resort Lodge in K.Gudi its about 20 Kms from BR Hills,.
We decided to go there but after traveling few Km my friends are afraid to move forward, because the forest is very dense and we not seeing any vehicle form long time in that road. So we turned back and while coming we saw A school Vivekananda Residential Insitution
I need to talk about this institute , this was headed by Dr. Sudharshan and its giving educations to tribal childrens ,..


When we are searching room there we found one person who is from Mandya working as teacher there ,..and He helped a lot in all the way ,.. his name is Sundaresh..

At last we got a room there ,..we drink coffe in Sundaresh house and wathched Etv news in dish Tv ,the speciality of news is ..Mr Yediurappa was about to become CM,..after a long fight…
We had dinner in Biligiri dharshin and came back to room ,..i was roaming in ground till mid night,. ,..
And morning we wake up and went inside jungle ,..we went to K Gudi but could not able to see any animals but we saw one old Temple “Kyatheswara” in K Gudi ,..and my friend kyatha is very happy that he found his Family gods Temple,..He said a story about there ancestors who have moved from Chamraj nagar to bangalore ,..The story is very intresting “ Once the Palegara of that place wanted to marry a girl in this village it seems and the elders did not agree to that,..and they shifted from Chanmraj nagar to Mandya in the night ,..leaving all there properties in that village and while coming they got a lake in between and they prayed god that if they reach safely they will name For helder son as “Kyathe gowda” and for younger son “Boregowda” and still you can see these familys in the place of Shivalli,Panakanalli,villages..near Mandya “

After K Gudi we saw .the view point which is really a fantastic place ,..we can see nice picture of mountains view from there…

While coming we came via Kollegal – mallavalli – Mandya

BR Hills was a nice place for treckking,..Bird watching,.If you plan to go there plan for at least 2 days…

Monday, November 5, 2007

Learn Kannada

we are celeberating our kannada rajyotsava ,..

I feel it is limitted to only for certain region, certain people ,..u can see only auto drivers have the passion of celebration,..
may be as we become more educated,..we loose the joy of celebrating these type of functions,..


The only way to keep our language is,( its not only for kannada,..for all indian language like Tamil, Telugu,Malayalam,..)
Talk only in your mother tounge in the Home,with ur wife,relatives,..and ecourage ur childrens to talk in there mother tounge..

Few words about Kannada,...

Kannada is a Dravidian language spoken primarily in Karnataka State in South India, and has a literature that dates from the ninth century. It has a population of 35,346,000 speakers, and is spoken not only in Karnataka, but to some extent in the neighboring states of Andhra Pradesh, Tamil Nadu, and Maharashtra. The literacy rate in Kannada is estimated to be about 60%. Kannada is written with its own script, which is similar to the script used also for Telugu. The Kannada script is also used for writing Tulu.

This is for non Kannadiga's,

Here are some common kannada words which we use everyday ,.which may help you in proper communication.

It is arranged like this pattren,..
English
Kannada


I
Nanu
He
Avanu
She
Avalu
You
Neenu
It
Adu
This
Idu
That
Adu
A
vandhu
Mother
Thaayi/amma
Father
Appa/thandhe.
Come(You come)
Baa
Came
Baandha(male) /Bandhalu(female)
Will come
Baaruthare
Sit
Kuthko/ Kulithuko
Walk
Nadee
Eat
Thinnu
Drink
Kudee
Win
Gellu
Go
Hogu/Horadu
Run
Odu
I go
Nanu hoguthene
He goes
Avanu hoguthane
He eats an apple
Avanu sebu(apple) thinuthane
He is eating an apple
Avanu sebu thinnuthidhane
He ate an apple
Avanu sebu thindhanu
I saw the film last week
Nanu hodha wara picture/ chalanachitra nodidhenu
She came by bus yesterday
Avalu ninne businalli bandhalu
They went to the mosque
Avaru masidhi/darga ge hodharu
He slept the whole night
Avanu eedi raatri malaghidhanu
He wrote well in the examination
Avanu pariksheyalli chennaghi madidhanu/

Avanu pariksheyalli chennaghi baredhanu
He has eaten
Avanu thindhidhane
He will eat
Avanu thinnuthane
He will go
Avanu hoguthane
He will come
Avanu baruthane
What is your name?
Ninna hesarenu?/ Ninna hesaru yenu?
What
Yenu?
Your
Ninna
Name
Hesaru
What did you do?
Neenu yenu maduthiya?
What should I do?
Nanu yenu madabeku?
What can I do?
Nanu yenu madabhahudhu?/ nanu yenu madaballe
What are the questions?
Yenu prashnegalu?
What were the questions?
Yenu prashnegaliddhavu?
What is the last question?
Koneya prashne yenu?
What is written in the letter?
Pattradhalli/Kaagadhadalli yenu baredhidhe?
What you had been told?
Ninege yenu hellalaghithu?
What will be the answer?
Uttara yenirabhahudhu?
Why did you come?
Neenu yaake bandhe?
Why did you sleep?
Neenu yaake malaghidhe?
Why did you tell him to go?
Neenu avanige yakee hoghalikke hellidhe?
Why did he bring the bag?
Avanu yaake cheela thandhanu?
Why did she pay the money?
Avalu yakee dhuddu kottalu?
Why did they sit there?
Avaru alli yakee kootharu?
Why do you drive the car?
Neenu gaadi yakee biduthiya?/

Neenu yakee gaadi chalayisuthiya?
Why are they late for the meeting?
Avaru meetingige yaake thadavadharu?
How did you come?
Neenu hege bandhe?
How did you sleep?
Neenu hege malaghidhe?
How did you drive?
Neenu hege gaadi chalayisidhe?.
How did you write?
Neenu hege baredhe?
How many apples are there in my hand?
Nanna kaiyalli yestu sebu idde?
How many did you take?
Neenu yestu thagedhukonde?
How much did he pay you?
Avanu ninage yestu hana kottanu?
How much distance to go?
Yestu doora hoghabheku?
How was the journey yesterday?
Ninneya prayana heghithu?
Which way did you come?
Neenu yaava daariyalli bandhe?
Which is your favourite colour?
Ninna istavadha banna yavudhu?/

ninege yava banna ista?
In which room did you sleep?
Neenu yava koneyalli malaghidhe?
Which story did you tell?
Neenu yava khathe helidhe?
Which is the sweetest fruit?
Yallakintha saviyatha hannu yavudhu?
Which is the best newspaper in Hindi?
Hindiya yava patrike sarvashresta?
Which Indian state has the largest population?Bharatha deshada yava rajyadalli jasti janasankye?

Where did you come from?
Neenu yellindha bandhe?/ ninna ooru yavadhu?
Where did you sleep?
Neenu yelli malaghidhe?
Where is the manager’s cabin?
Managerina kone yavudhu?
Where should I go?
Nanu yellige hogabeku?
Whom should I contact?
Nanu yaranna samparkisabeku?
Is it a book?
Idu pustakava?/ idu pustaka naa?
It is a book
Ide pustaka/ ide pustaka
Is it the answer?
Idu uttarana?
It is the answer
Ide uttara
Will you come with me?
Neenu nanna joteghe baaruthiya?
I shall come with you.
Naanu ninna jotege barythene
Will you give me your pen?
Ninna pennu/ kalam nanage koduthiya?
Yes, of course.
Avashyavaghi koduthene
Do you love me?
Neenu nannannu preethisuthiya?
Yes, I love you.
Hovadhu naanu ninna preethisuthene
Can you give me your pen?
Nanege ninna penana kodabhahudha?/

Ninna kalam nanaghe koduthiya?
Can you lift the box?
Neenu dabbiyanna yethe balliya?/

Ninindha dabbi yathellu sadhyava?
Can you write the exam?
Ninindha parikshe bariyalu sadyana?
Did you have your lunch?
Oota madhidheya?/ oota aayitha?
How are you?
Hegiddhiya?/ Neenu heghiddhiya?
I am fine
Nanu chenagiddene.
Happy Kannada Rajyotsava,....

Tuesday, October 23, 2007

Journey to Hoysala temples in Mandya

Jounrney to old Hoysala tempels in Mandya.


Check the picture here
http://picasaweb.google.com/praveen.kulakarni/MandyaTrip

The journey begin from Mandya in My New car Turbo DLG..
My freinds as come from Bangalore to Mandya in bus and later joined me in Mandya.

our journey begin at 9 from Mandya on 21st OCt Sunday 2007,
Started with Tiffin in Shivalli(Dudha) near Mandya and went to Melkote



MELUKOTE:

Yoga Narasimha Temple:
After driving up a few narrow winding streets we reached the parking place at the foot of the hill.We reached Melukote at 10.30 am. On the top of the hill there is a temple of Yoga Narasimha. To reach here you have to take big steps( half way you can go by vehicles . There are around 30 to 40 steps to reach temple. Temple is 1,777 mtr above from the sea level. After reaching the temple we could able to see a beautiful nature surrounding. It is a 1000year old temple and here we could not find that beautiful architecture still is looks good.We spent 30min in the temple.

AKKA TANGI KOLA:
This KOLA(pond) is near to the temple.There are two ponds in one pond there is dirty water(in Akka kola) and in another pond there is clean water(TANGI kola). We asked the reason for this to one old lady she told "The younger sister was willing to build a pound but elder sister was not interested for this. At last both built a different ponds, in younger sister's pond there was a clean water but in elder sister's pond dirty water because she was not interested for this". The main thing is we could able to differentiate both pond water.

Tiru Narayana:
Then we head in to the town there a big Tiru Narayana temple. We parked the car and started walking towards the temple, on the way we got a beautiful KALYANI (water pond surrounded by steps). Here people were taking bath and praying to god. After that we entered to temple, this is a large temple surrounded by an open veranda in side that there were so many beautiful carved pillars. We spent some time there and took many photographs. I asked Praveen "how was they able to do this type of design in stone?" He gave a smile and replied they were intelligent.
Now its 12 noon, we left for the Hosaholalu its nearly 27km from here near K.R.Pete.



Hosaholalu:

We reached K.R.Pete at 12.45 and had lunch and started driving towards Hosahoralu. It is trikuta (three shrined) Lakshminarayana temple. Here the temple was closed and we could able to see only from the outside. The outer wall is with the beauties of deities made up of stone. Here i surprised by seeing this sculptures. It is worth going here. And again I asked the same question to praveen "how was they able to do this type of design in stone?" and got the same reply.We spent more than 45min here.
Praveen explained me some sculptures meaning. Before this i never used to enjoy in temple but this time i enjoyed and got to know so many things. Thanks to Praveen.

Govindanahalli:


This was our main destiny to see, whole journey started to see this panchalingeswara temple...

Its nealy 15km from the K.R.Pete . Its difficult to reach here by bus and we did't see a single board to show the way.Here we had to struggle little bit to reach here.

On the way we saw an accident between bike and Maruthi Omni ,..just a small hit from bike caused lot of damage to maruthi omni car,..The bike person head has come out and the child sitting inside maruthi got fractured..

So,..started driving carefully.......

We reached the temple by 2.30 and here also temple was closed. Its a very big temple panchkuta (five shrined) Shiva temple. In the entrance two Veera bhadhreshwara sculpture and opposite to the main entrance a beautiful sculpture Nandi. We spent 20min by seeing out side the temple after that one lady came and opened the door of the temple. Inside the temple there are mainly five Lingu's situated with the different names and there are number of lined carved pillars and as usual so many sculptures on the wall.

One thing which i wanted to tell is,.. we should give proper publicity to these type of places,..

till we come here we never thought it will be such a nice place with cool atmosphere,...

Govt. and also the people should give proper publicity and help to preserve these old temples....


From here we started journey back to Bangalore at around 3.15pm. On the way to mandya we stopped in AALE MANE(the place to prepare jaggery) near Bedara Halli pandava pura distict. HeY.. we had a mugs of nice sugercane juice and fresh jaggery(it will be in jelly state).

Even thoe I had these alemane experence many times in my child days , its a different exp for my bangalore fnds,..
Even I enjoyed a lot ....

Please see the pics in this URl
Picture of trip

Friday, October 19, 2007

What is UDDI

Note On UDDI


What is UDDI

Web service standards have made outstanding progress. However, let's take a quick step backwards to examine an older standard called Universal Description, Discovery and Integration of Web services (UDDI).

The UDDI specification defines a SOAP-based Web service for locating Web services and programmable resources on a network. It offers a foundation for sharing information about internal services across the enterprise and public services on the Internet.1


UDDI Programming Model

XML Web Services has been the toast of the .NET Framework, however Web Services are not a .NET invention – they were available before .NET. So why are they so popular under .NET? Because the set of tools available under Microsoft .NET Framework lets the developer build sophisticated Web Services with little difficulty. Developers are embracing Web Services at an exponential rate under the .NET framework. With this popularity increase, UDDI is emerging as the preferred mechanism to discover the Web Services. This article is aimed at advanced users familiar with UDDI so I will be skipping the introductory lessons and dive into UDDI details from the start. In the second half of this article we will put our knowledge into use by building an ASP.NET UDDI browser using web forms.



We will first explore the UDDI data structures, then we will investigate the UDDI API version 2.0, this is the most recent version of the UDDI API. The best place to find more technical details on UDDI is www.uddi.org.

UDDI API Data Structures

UDDI has 4 main data structures.
All the information is stored as predefined XML formats. First we will try to understand the responsibilities of each structure. Then we will learn how these structures work together to create UDDI.
Business information ( businessEntity XML Format)
Service Information ( businessService XML Format)
Binding Information ( bindingTemplate XML Format)
Specifications for the services offered ( tModels XML Format)

businessEntity Data Structure

You only need a businessEntity element to publish data within a UDDI repository. The other data elements are optional. During the discovery phase, the businessEntity element serves as a handle to retrieve pertinent information about a company.


businessService Data Structure

Service information deals with technical and business descriptions. Each Web Service has one or more technical web descriptions. These technical descriptions include information to communicate with clients. Those could be:
URLs, addresses to communicate to child Web Services.
Configuration options on the host web server.
Prerequisite Web Services that should run before this Web Service.
Load Balancing information on the host web server.


bindingTemplate Data Structure
The information about invoking a Web Service is documented in a XML structure called bindingTemplate.. The bindingTemplate"binds" technical and business data to a Web Service. So what information do we bind? We need to know all the technical information for seamless integration of the Web Service. Here are some of those questions if we implement a Web Service to handle purchase orders.
We need to know the format of our purchase orders?
Are they in a specific XML format geared towards online transactions? (eg. OBI – Open Buying on Internet)


What are the required security implications to access purchase orders?
In order to integrate the Web Service we need to answer all these questions, therefore we need XML structures to represent this information inside the Web Service bindings. These structures are commonly referred to as "tModel".

tModel Data Structure
This is probably the most interesting data structure. UDDI draws a distinction between abstraction and implementation with its concept of tModels. The tModel structure, short for "Technology Model", represents technical fingerprints, interfaces and abstract types of metadata. Binding templates are the concrete implementation of one or more tModels. Inside a binding template, one registers the access point for a particular implementation of a tModel. tModels can be published separately from the binding templates that reference them.
Each tModel also gets a unique identifier, this will enable other applications to refer to it, these tModels make up bindingTemplate structures. The tModels represent all the integration information to consume a Web Service. The different service providers can easily build a software product to consume the Web Service as long as the tModels are compatible.


check this link for more details
http://www.microsoft.com/windowsserver2003/technologies/idm/uddi/default.mspx


Friday, October 12, 2007

Differences between using web controls and using HTML controls in dotnet application

This is a note on differences between using web controls and using HTML controls in dotnet application,which I feel more useful and sharing with you all.

The confusion that I had, and I think some of you may also have, is that why provide two type of controls that almost provide similar functionality, i.e. that both the controls are executed on the server side , both the controls are providing nearly similar events and have similar usage when creating forms or other pages. All this is true that both controls are nearly similar, but they have a vast difference that exists between them. The ASP .NET Server Controls are more rich in functionality as compared to their HTML Server Control counterparts. Let's take a look at some other differences that exist between these controls.

1. Control Abstraction:A HTML Server Control has similar abstraction with its corresponding HTML tag and offers no abstraction.ASP .NET Server Controls have higher level of abstraction. An output of an ASP .NET server control can be the result of many HTML tags that combine together to produce that control and its events.

2. Object Model:The HTML Server Controls follow the HTML-centric object model.ASP .NET Server Controls have an object model different from the traditional HTML and even provide a set of properties and methods that can change the outlook and behavior of the controls.


3. Browser Compatibility:The HTML Server Controls have no mechanism of identifying the capabilities of the client browser accessing the current page.ASP .NET Server Controls can however detect the target browser's capabilities and render themselves accordingly.


Despite the differences you can still use these controls together by mixing them in an ASPX form or page. These controls can also be used together in the build up of user controls that you can design according your requirements and needs. As far as the question which control to use when? is concerned, I would say that its up to you to decide that what you are comfortable with and what you can handle easily. If you want to convert your existing HTML based template pages to ASPX based pages then it would be better for you to convert the tagged HTML controls within them to HTML Server Controls as this would only require you to add the runat="server" attribute to them. If preparing new ASPX based template pages that you want to easily target browsers according to their capabilities, e.g. a page that can have the same view on a mobile phone as it has on the Internet Explorer, would require you to use the ASP .NET Server Controls.


I am listing some difference between these two types of controls, If you find any other point please add to this

1. Server Controls Trigger Server side events. Where as HTML controls only trigger client side events.
2. State ManagementServer Controls provides State Management - Data entered in a control is maintained across requests.State Management in HTML Controls can be achieved using Page-level scripts.
3. AdaptationServer controls automatically detects & adapts display appropriately.HTML Controls - No automatic detection is possible.
4. PropertiesServer controls - Provides a good set of properties that can be manipulated from server side code.HTML Controls - It has the basic set of HTML attributes attached to each element.
5.server control inherits from System.Web.UI.Webcontrols but html not

Wednesday, September 12, 2007

Impersonation in SharePoint 2007 using Elevated privileges

When I was working with giving permission for the logged in user to access data from BDC , I found so many articles which talks about Impersonation ...

when Searching more for simpler method i got a method which helps in
Executing code with elevated privileges .

The code goes like this

SPSecurity.CodeToRunElevated elevatedMethod = new SPSecurity.CodeToRunElevated(pullUserData);
SPSecurity.RunWithElevatedPrivileges(elevatedMethod);


where pullUserData() is a void method which gets data from BDC.


private void pullUserData()
{
string userName = getUserName(); // "domain\\b" ;
userprofile.UserProfileService myuser = new UserProfileService();
userprofile.PropertyData[] userprop = null;

// here userprofile is web service method
http://localhost/_vti_bin/userprofileservice.asmx

myuser.Credentials = System.Net.CredentialCache.DefaultCredentials;
myuser.PreAuthenticate = true;
long test = myuser.GetUserProfileCount();
userprop = myuser.GetUserProfileByName(userName);

for (int i = 0; i < userprop.Length; i++)
{
if (userprop[i].Name != null)
{
if (userprop[i].Name.Trim().ToLower() == gblAttribute.Trim().ToLower())
{

if (userprop[i].Values[0] != null)
{
gblResult = userprop[i].Values[0].Value.ToString();

}

}
}
}

}


Friday, August 31, 2007

Get BDC Data In Sharepoint with Web Service

Get the Users from Business Data Catalog (BDC) programmatically

I got a chance to work in getting users from BDC in sharepoint.

Initially I tryed by getting users from UserInformationList using CAML query
after that I got web service things which made my job easy


The BDC allows you to create a XML metadata file describing a database or web service to SharePoint so that SharePoint can query this data source to make its data available within the portal. Once registered in your SharePoint environment this data can be displayed in the Business Data web parts (described later in this posting) or as lookup information for list/library columns (and column templates).


user this Web service Interface to get user profiles

http://localhost/_vti_bin/userprofileservice.asmx


The below code will give me User data from particular user


public string getUserValuesfromBDC(string attribute)

{ string myvalues = string.Empty;

try
{




string userName = getUserName(); // "VMTPG\\b" ;

userprofile.UserProfileService myuser = new UserProfileService();
userprofile.PropertyData[] userprop = null;

myuser.Credentials = System.Net.CredentialCache.DefaultCredentials;
long test = myuser.GetUserProfileCount();
userprop = myuser.GetUserProfileByName(userName);
for (int i = 0; i <>

{
if (userprop[i].Name != null)

{
if (userprop[i].Name.Trim().ToLower() == attribute.Trim().ToLower())

{
try
{
if (userprop[i].Values[0] != null)
{
myvalues = userprop[i].Values[0].Value.ToString();
return myvalues;

}
}
catch { }

}
}
}


}
catch

{ }

return myvalues;
}





To Get All Users as Data Set


protected void Button1_Click(object sender, EventArgs e)
{

GridView1.AutoGenerateColumns = true ;
GridView1.DataSource = getAllUserValuesfromBDC();
GridView1.DataBind();

}


public DataSet getAllUserValuesfromBDC()
{
string myvalues = string.Empty;
string fieldname = string.Empty;

DataSet ds = new DataSet();
try
{
DataTable mydt = new DataTable();

userinfo.UserProfileService myuser = new UserProfileService();
userinfo.PropertyData[] userprop = null;
userinfo.GetUserProfileByIndexResult myindx = null;

myuser.Credentials = System.Net.CredentialCache.DefaultCredentials;
long userCount = myuser.GetUserProfileCount();
int uCount = Convert.ToInt32(userCount);


// To add column to the data table
myindx = myuser.GetUserProfileByIndex(0);
if (myindx != null)
{
for (int m = 0; m < myindx.UserProfile.Length; m++)
{
try
{
if (myindx.UserProfile[m].Name != null)
{
mydt.Columns.Add(myindx.UserProfile[m].Name);
}
}
catch{}
}
}


// To add the Row value to Table
for (int k = 0; k < userCount; k++)
{
myindx = myuser.GetUserProfileByIndex(k);
DataRow dr = mydt.NewRow();

if (myindx != null)
{
for (int m = 0; m < myindx.UserProfile.Length; m++)
{
try
{
if (myindx.UserProfile[m].Name != null && myindx.UserProfile[m].Values[0].Value != null)
{
dr[myindx.UserProfile[m].Name] = myindx.UserProfile[m].Values[0].Value;
}
}
catch
{
}
}
mydt.Rows.Add(dr);
}
}
ds.Tables.Add(mydt);

}
catch
{

}
return ds;
}


Hope this will be more user full

Thursday, August 30, 2007

How to Get Survey Data from Sharepoint

Get the Survey data of Site in sharepoint

SPWeb web = SPContext.Current.Web;

string parentUrl = SPContext.Current.Web.Site.RootWeb.Url;


string currentURL = Survey List Url;

SPSite site = new SPSite(currentURL);
SPWebCollection spcollection = site.AllWebs;
string inputsite = p_strUrl ;

SPListCollection myweblist

html += "

";
for (int k = 0; k < spcollection.Count; k++)
{
if (inputsite.ToLower().Trim() == spcollection.Names[k].ToLower().Trim())
{
myweblist = spcollection[k].Lists;
for (int i = 0; i < myweblist.Count; i++)
{
if (myweblist[i].BaseType.ToString() == "Survey")
{
Assignmentvalue = myweblist[i].Title;

string urlAssignmentvalue = myweblist[i].DefaultViewUrl ;

html += "";

}
}
}
}
html += "
>" + Assignmentvalue + "
";

How to Get Discussion Board Data from Share point

Get the data of DiscussionCategory using SPQuery


Get the SpWeb

SPWeb web = SPContext.Current.Web;

using ( web = site.OpenWeb())
{

SPQuery query = new SPQuery();

discussionBoardUrl is the url which points to Discussion Board Exist

SPList list = web.GetListFromUrl(discussionBoardUrl);


Query the SpList to get Item Collection


string qLess = string.Empty;
qLess +=
" ";


query.Query = qLess;


SPListItemCollection listCollection = list.GetItems(query);
string subject = string.Empty;
string category = string.Empty;
litDiscussion.ID = "discussionBoard";

Loop with Each ITem In List Collection

string html = "";

ArrayList arrCategory = new ArrayList();
foreach (SPListItem listItem in listCollection)
{
string lcategory = listItem.GetFormattedValue("DiscussionCategory");
if (arrCategory != null && listCollection.Count > 0 && !arrCategory.Contains(lcategory.ToLower().Trim()))
arrCategory.Add(lcategory.Trim());

}


html = "

";
html += "";


int count = 0;

for (int k = 0; k < arrCategory.Count; k++ )
{
category = arrCategory[k].ToString() ;
html += "

";


foreach (SPListItem listItem in listCollection)
{
string lcategory = listItem.GetFormattedValue("DiscussionCategory");

Arranging Category under that Discussion topics

if (arrCategory[k].ToString().ToLower().Trim() == lcategory.ToLower().Trim())
{
count = count + 1;
string last = listItem.GetFormattedValue("Last Updated");
subject = listItem.GetFormattedValue("Subject");
html += "

";


}

if (count >= displayCount)
{
break;
}
}
html += "";
if (count >= displayCount)
{
break;
}
}
html += "

Discussion Board

" + category + "

> " + subject + "
";
litDiscussion.Text = html;

Monday, July 23, 2007

My notes on MOSS 2007

This notes is created to give training for my juniors on basic overview on sharepoint .



What is portal

Portal is a web application that gathers information from various desperate sources to share the information among the users .

The portals has the following significant features
· collabaration
· security
· personalization
· customization
· search , etc

Site which are not portals are called vertical portal or Vortals

Windows share point services 3.0 is free licensing it has less feature compare to Moss 2007


Ghost able – stored in content database

Un ghost able – stored in hard disk


Web part

Web part is a custom control , created by a developer and deployed on to the share point site with the extension dwp or webpart(recommended) .

Web part zone

Web part zone is a logical area created by the designer on a web part page where the web part can be dropped.

Web part page

Page, which contain web parts.

There are two type of deployment

· stand alone Installation (Deployment ) – Everything is there in the same system .
· web form Installation ( Web garden) -
A Web garden is an application pool that is configured with more than one worker process. (Web gardens are to be distinguished from Web farms, which use multiple servers for a Web site.)






Hierarchy
Central administration


site administrator


Top-level sites

Top level site 1 - Top level site 2

Role

Administrator – can create sites, content, users, application, manage forms.

Designer – can create manage content and design of the website

Contributor – can only contribute to existing content .

Reader – no other permission except view.


Feature

Feature are new innovation in Moss 2007 these are plug gable component which actually modifies the structure, layout programming capability of share point site .


Sample code which display a simple html web part page

using System.Configuration ;
using Microsoft.SharePoint .WebPartPages ;
using Microsoft.SharePoint;


namespace tpg.SFO
{
public class SFO : WebPart
{
#region Controls Initialization
protected Literal litContent = new Literal();
protected Label lblMessage = new Label();
protected Panel pnlHtml = new Panel();
public string currentURL = string.Empty;
//private tpg.ConfigurationReader.Configurations configReader = new tpg.ConfigurationReader.Configurations();
//Load the xslt file from the specified location
Configurations config = new Configurations();
tpg.CustomMessages.CustomMessages custommessage = new tpg.CustomMessages.CustomMessages();
#endregion

protected override void RenderWebPart(System.Web.UI.HtmlTextWriter writer)
{
base.RenderWebPart(writer);
}
///
/// Create Input controls which is needed to capture the data
///

protected override void CreateChildControls()
{

litContent.Text = "";
SPWeb web = SPContext.Current.Web ;
currentURL = web.Url ;


litContent.Text = CreateHtmlContent();
this.pnlHtml.Controls.Add(litContent);
this.Controls.Add(pnlHtml);

}



///
/// Build a HTML file which display a static page
///

public string CreateHtmlContent()
{
string htmlContent = string.Empty ;
try
{
// some html Content ;

}
catch (Exception ex)
{
ShowMessage(custommessage.getMessage("general_error"));
}
return htmlContent;

}
///
/// get redirect location from config
///

private string getUrl(string info)
{
string url = string.Empty;
SPWeb web = SPContext.Current.Web;
currentURL = web.Url;
string configValue = string.Empty;
try
{
configValue = config.getConfigurationValue(info, "value");
}
catch { }
configValue = configValue + "?CId=" + info + "&AId=302 ";
url = currentURL + configValue;
return url;


}
///
/// get redirect location from config
///

private string getImagepath()
{
string imagePath = string.Empty;
imagePath = config.getConfigurationValue("pentagon", "value");
return imagePath;

}



///

///
/// This is to show normal messages.
///

///
private void ShowMessage(string message)
{
lblMessage.Text = message;
lblMessage.CssClass = "error";
this.Controls.Add(lblMessage);
}

}
}





Additional notes


Microsoft Office SharePoint Portal Server 2003 (the current release) is a Web Portal which belongs to the Microsoft Office family. It is a collaborative portal application based on the Windows SharePoint Services platform, a free component of Windows Server 2003. Windows SharePoint Services offers online publishing of standard file formats. It also has version control, document approval and a basic search facility

Microsoft Office SharePoint Server 2007, commonly abbreviated to MOSS, is the successor to Microsoft Office SharePoint Portal Server 2003. It has a large range of new features not in the previous version.
MOSS is a licensed enterprise extension to version 3.0 of the no-cost Windows SharePoint Services platform - a component available for Windows Server 2003. Its main strength is enabling an organization’s information to be organized and aggregated in one central, web-based application. It can be configured to return separate content for Intranet, Extranet and Internet locations. The primary areas of investment that Microsoft has made over the previous version are Excel Services, Infopath Forms Services, the Business Data Catalog, Enterprise Search, web content management, more specialized document management, records management, web 2.0 collaboration functionality like blogs and wikis, delivery of information stored in SharePoint via RSS, PowerPoint Slide Libraries, and the ability to take content and lists offline with Outlook 2007 and Microsoft Access.

One of the weaknesses of the tool is its own ease of use. Administrators may be tempted to start one port 80 and build a single site collection with sub-sites underneath, exposed to the company as a home page and sub-pages. Though this makes logical sense for a large organization or one with bespoke portals using custom Web Parts or Forms Server, it can cause problems. All the sites in a site collection will be stored in the same database, which can become too large to effectively back-up. Moreover, bespoke development using the same Web Application and Application pool can bring a company-wide internet down.

When designing a large implementation it makes sense to break distinct areas of the organization in to their own portal with their own Web Applications.
MOSS 2007 also allows content types and document libraries to have information management policies, which allows the triggering of workflow or deletion after a certain fixed event or time period, helping to reduce many of the size-growth problems of earlier versions.

Monday, July 16, 2007

pagination in datagrid webpart in sharepoint

The Best way to bind datagrid with the Pagination property and Edit and update command .


I was stuck in Adding pagination property to datagrid which was created under sharepoint webparts .

The Next pagination is working but Prev Pagination is not working. I tryed with somany ways but not able to find out .

Atlast I rearranged the code which handle viewstate properly ..

This is the code which works properly ...

public class TestHOF : WebPart
{

// To get the data from databse
public static DataSet getData()
{
DataSet ds = new DataSet();

return ds;
}
//======================================================================
///
/// Method to get connection string from web.config
///

//======================================================================
public static string GetConnectionstring()
{
string connStr = string.Empty;
try
{
connStr = ConfigurationManager.ConnectionStrings["ConnectionString"].ToString();
}
catch
{


}

return connStr;
}

private MyDataGrid grid;

private bool DynamicColumnsAdded
{
get
{
object o = ViewState["DynamicColumnsAdded"];
if (o != null)
{
return (bool)o;
}
return false;
}
set
{
ViewState["DynamicColumnsAdded"] = value;
}
}

protected override void CreateChildControls()
{
grid = new MyDataGrid();
grid.ID = "DataGridInsideWebPart";
grid.AllowPaging = true;
grid.PageSize = 5;
grid.PagerStyle.Mode = PagerMode.NextPrev;
grid.PagerStyle.NextPageText = "Next";
grid.PagerStyle.PrevPageText = "Prev";
grid.ItemCommand += new DataGridCommandEventHandler(this.LanguageGrid_ItemCommand);
grid.UpdateCommand += new DataGridCommandEventHandler(this.LanguageGrid_UpdateCommand);
grid.PageIndexChanged += new DataGridPageChangedEventHandler(grid_PageIndexChanged);
grid.AutoGenerateColumns = false;

this.Controls.Add(grid);
ChildControlsCreated = true;
}

void grid_PageIndexChanged(object source, DataGridPageChangedEventArgs e)
{
//throw new Exception("The method or operation is not implemented.");
grid.CurrentPageIndex = e.NewPageIndex;
grid.DataSource = getHOFMembersData();
grid.DataBind();
}

protected override void OnLoad(EventArgs e)
{
EnsureChildControls();
if (!DynamicColumnsAdded)
{
AddColumns();
}
if (!Page.IsPostBack)
{
grid.DataSource = getData() ;
grid.DataBind();
}
base.OnLoad(e);

}

public void LanguageGrid_ItemCommand(Object sender, DataGridCommandEventArgs e)
{
if (e.CommandName == "Edit")
{
Page.Response.Write("Edit:" + e.Item.ItemIndex);
this.LanguageGrid_EditItem(sender, e);
}
if (e.CommandName == "Update")
{
Page.Response.Write("Update:" + e.Item.ItemIndex);
this.LanguageGrid_UpdateCommand(sender, e);
}
}

public void LanguageGrid_EditItem(Object sender, DataGridCommandEventArgs e)
{
grid.EditItemIndex = e.Item.ItemIndex;
grid.DataBind(); // Refreshes the grid
}

public void LanguageGrid_UpdateCommand(Object sender, DataGridCommandEventArgs e)
{
string language = e.Item.Cells[0].Text;
grid.EditItemIndex = -1;
grid.DataBind();
}

protected override void LoadViewState(object savedState)
{
EnsureChildControls();
object[] stateArr = (object[])savedState;
base.LoadViewState(stateArr[0]);
grid.LoadDGViewState(stateArr[1]);
if (DynamicColumnsAdded)
{
AddColumns();
}
}

protected override object SaveViewState()
{
object[] state = new object[2];
state[0] = base.SaveViewState();
state[1] = grid.SaveDGViewState();
return state;
}

private void AddColumns()
{
BoundColumn languages = new BoundColumn();
languages.DataField = "CategoryId";
languages.HeaderText = "CategoryId";

EditCommandColumn edit = new EditCommandColumn();
edit.ButtonType = ButtonColumnType.LinkButton;
edit.EditText = "Edit";
edit.UpdateText = "Update";
grid.Columns.Add(languages);
grid.Columns.Add(edit);

DynamicColumnsAdded = true;
}

private class MyDataGrid : DataGrid
{
public void LoadDGViewState(object state)
{
this.LoadViewState(state);
}

public object SaveDGViewState()
{
return this.SaveViewState();
}
}






}

Thursday, July 12, 2007

WebService in Sharepoint

One of the majour part which I have worked in my project is connecting webpart and web service.

May be this article will give a an Idea of how we can Add a asmx page into sharepoint
and also how to use the existing web service in Share point .


1) Create an ASP.NET Web service in Microsoft Visual Studio 2005.
Create a class library within the Web service that defines the programming logic for the Web service.


Create a strong name for the class library:
add your assembly to the global assembly cache (GAC),
Open TestFiles.asmx page Remove the CodeBehind attribute and Add the class
<%@ WebService Language="C#" Class="Files,clsUploadService, Version=1.0.0.0, Culture=neutral, PublicKeyToken=c741d2e07f0e3abc" %>


where "Files" represents the class name that you provide in Files.cs and " clsUploadService, Version=1.0.0.0, Culture=neutral, PublicKeyToken=c741d2e07f0e3abc" is the one which we get from Reflector.exe ( this procedure is similar to the process of getting assembly name )

2) Generate and edit a static discovery file and a Web Services Description Language (WSDL) file.
To provide discovery and description for your custom Web service, you must create a .disco file and a .wsdl file
In Windows Explorer, copy the TestFiles.asmx file of your Web service to \\ Program Files\Common Files\Microsoft Shared\web server extensions\12\TEMPLATE\LAYOUTS.
Disco.exe at the command promp ( from Microsoft tools - command) disco http: // mytestwebsite:4704 / _layouts/TestFiles.asmx
( mytestwebsite:4704 is the server name ) after this open the wsdl and disco files with this link
http://mytestwebsite:4704/_layouts/TestFiles.asmx?disco
http://mytestwebsite:4704/_layouts/TestFiles.asmx?wsdl
save both file as aspx files TestFilesdisco.aspx and TestFilesWSDL.aspx
In both file replace with
<%@ Page Language="C#" Inherits="System.Web.UI.Page" %>
<%@ Assembly Name="Microsoft.SharePoint, Version=12.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
<%@ Import Namespace="Microsoft.SharePoint.Utilities" %>
<%@ Import Namespace="Microsoft.SharePoint" %>
<% Response.ContentType = "text/xml"; %>



3) replaces literal paths with code generated paths
in disco file
docRef=<% SPHttpUtility.AddQuote(SPHttpUtility.HtmlEncode(SPWeb.OriginalBaseUrl(Request)),Response.Output); %>
xmlns="http://schemas.xmlsoap.org/disco/scl/" />

xmlns:q1="http://tempuri.org/" binding="q1:HelloWorld" xmlns="http://schemas.xmlsoap.org/disco/soap/" />

xmlns:q2="http://tempuri.org/" binding="q2:ServiceSoap12" xmlns="http://schemas.xmlsoap.org/disco/soap/" />

in WSDL file
/>


4) Copying the Web Service Files to the _vti_bin Directory
The _vti_bin virtual directory maps physically to the Local_Drive:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\12\ISAPI directory, which contains the default Web service files used in Windows SharePoint Services. Copy the new MyCustomWebServicewsdl.aspx and MyCustomWebServicedisco.aspx files, and also the MyCustomWebService.asmx file, to the ISAPI folder.
To verify navigate to http://mytestwebsite:4704/_vti_bin/TestFiles.asmx.

5 ) Add the New Web Service in spdisco.aspx

To make your Web service discoverable in Visual Studio as a Web service alongside the default Windows SharePoint Services Web services, open the spdisco.aspx file located in \Program Files\Common Files\Microsoft Shared\Web Server Extensions\12\ISAPI and add the following code, specifying the .asmx file for your Web service.

docRef=<% SPHttpUtility.AddQuote(SPHttpUtility.HtmlEncode(spWeb.Url + "/_vti_bin/ TestFiles.asmx"), Response.Output); %>
xmlns=" http://schemas.xmlsoap.org/disco/scl/ " />

xmlns="http://schemas.xmlsoap.org/disco/" />

To create web part which connects to WebService ( TestWebpartServices ) and returns data
add a web reference to http://mytestwebsite:4704/_vti_bin/TestFiles.asmx. and name that has mytestwebsite
public class TestWebpartServices : WebPart
{
private mytestwebsite.Files file = new global::TestWebpartServices.mytestwebsite.Files();
protected override void RenderContents(System.Web.UI.HtmlTextWriter writer)
{

file.PreAuthenticate = true;
file.Credentials = CredentialCache.DefaultCredentials;
writer.Write(file.HelloWorld());
}
}
and after this create web Part from this dll and Import this in application you can see a message "Hello World" .

when I was creating web service application in 2005 we dont have any option to edit the proxy class .i.e reference.cs file will not create .. but if we do this with the class project we can see reference.cs file




MOSS 2007 Training

Microsoft® Office SharePoint® Server 2007

I got a chance to undergo training on MOSS 2007 , since our client Palladiume USA wanted to shift to sharepoint portal .

The Training was conducted by Mr Gurjit , It was about 1 week .

Windows SharePoint Services is a versatile technology included in Microsoft Windows Server 2003 that enables organizations and business units of all sizes to increase the efficiency of business processes and improve team productivity.

Wednesday, May 9, 2007

Understanding Stored procedure

Understanding Stored procedure

Writing Stored Procedures doesn't have to be hard Normally, you would call a database with a query like:
Select column1, column2 From Table1


To make this into a stored procedure, you simple execute this code:

CREATE PROCEDURE sp_myStoredProcedure
AS
Select column1, column2 From Table1
Go


To execute the stored procedure. You can simply call it by name like this

Exec sp_myStoredProcedure


Let me go for little complex things now

Select column1, column2 From Table1 Where column1 = ‘1’ and column2 = ‘secondthing’
The stored procedure we can write is

CREATE PROCEDURE sp_myStoredProcedure @myInput int , @mysecondInput Varchar(1000)ASSelect column1, column2 From Table1Where column1 = @myInput and column2 = @ mysecondInput
Go

Exec sp_myStoredProcedure ‘1’ , ‘secondthing’

Stored procedure To check whether record exist or not If doesnot exist go for Insertion

CREATE procedure Sp_InsertLogin
@username varchar(100) ,
@password varchar(100)

As
declare @RollbackRequired int
set @RollbackRequired = 0

BEGIN TRANSACTION INSERTLOGIN
declare @count int
select @count = Count(username) from users where username = @username and password = @password
--If record doesnot exist go for inserting it.
if (@count = 0)
Insert into users (username , password , Active ,IsAdmin)values (@username , @password , '0','0')
--Check for error, If error occurred go for rollback
if @@Error <> 0
begin
set @RollbackRequired = 1
goto End_Transaction
end
End_Transaction:
IF @RollbackRequired = 1
BEGIN
ROLLBACK TRAN INSERTLOGIN
RETURN -1
END
ELSE
BEGIN
COMMIT TRAN INSERTLOGIN
RETURN 0
END


To execure this call

Exec InsertLogin ‘raj’ , ‘password’



About CURSORS

CURSORS are very similar to an ADO recordset

I chose the FAST_FORWARD option to optimize performance because it creates a forward only, read only cursor
Be aware that CURSORS are somewhat resource intensive. So use it when necessary but always look for a better way.
Also remember to CLOSE and DEALLOCATE your CURSORS as soon as possible to free up resources. Here's the code sample:

To display Course detail and course id records from coursedetail tabel

Create procedure Sp_CourseDetail
As
declare @cname varchar(50) , @cid varchar(50)
declare @mycursor cursor
set @mycursor = CURSOR FAST_FORWARD

for
select coursename , courseId from coursedetail

Open @mycursor
fetch next from @mycursor into
@cname , @cid

while @@fetch_status = 0
begin
print @cname
print @cid
fetch next from @mycursor into
@cname , @cid
end

close @mycursor
deallocate @mycursor

Go

exec Sp_CourseDetail


C-Sharp Code sample to execute Storred procedure


conn.ConnectionString = GetConnection() ;
conn.Open() ;
strSql = "Exec InsertLogin ‘raj’ , ‘password’ " ;
SqlCommand cmd = new SqlCommand(strSql ,conn) ;
cmd.ExecuteNonQuery() ;

My notes on c#

Methods of Navigation and Data Transfer
1. Sessions (data transfer only)
2. Response.Redirect
3. Server.Transfer
4. Server.Execute

1. Sessions : The traditional method which could contain almost any object and could be retrieved on any page during the session of a user. Limitation : If there is a large amount of data involved then using Sessions will considerably slow down your system, or heavyweight objects, such as DataSets.

2. Response.Redirect : This is primarily a navigation technique rather than a data transfer one. But you could append your data with the Page name in order to transfer your data. Like, Response.Redirect(“TestPage.aspx?TextBox1=” & textBox1.text). Frankly speaking this isn’t such a good technique. What if you put 20 text fields and some more dropdownlists etc. on your forms ? In such a situation, I surely wouldn’t use Response.Redirect to transfer data. e.g., Response.Redirect(“NextPage.aspx?Text1=” & textbox1.text & ”&Text2=” & textbox2.text)

3. Server.Transfer : This is one of the two technique offered by ASP.NET to transfer data. Server.Transfer transfers the user to a new page but retains values of ViewState and QueryString of the previous page. While using Server.Transfer you must keep few things in mind. Firstly, Server.Transfer can only be used between WebForms. Second, when using it make sure you set the EnableViewStateMac of the source webpage to False to disable hashing. e.g., Server.Transfer(“TargetPage.aspx”, True) The first parameter is obviously a Target Page where you want to transfer. The second parameter is PreserveForm which could be set to True or False. True will let you preserve the information for the next page.

4 Server.Execute : This method merges two form’s data into one form. As opposed to Server.Transfer which finishes dealing with one form before moving on to the next, Server.Execute processes a second form without leaving the the first one.
Server.Execute("Transfer.aspx", swrTarget) Label2.Text = swrTarget.ToString You only need to write Server.Execute(“TargetPage.aspx”) to get it working. Using this command, the next page’s content will be displayed right on top of the current page. But if you supply the second parameter - which is an object of the StringWriter class - then the output will go to this object and you can assign this output to any object. In my example I’m assigning to a label (label2). You are able to show your target page anywhere you want.

Note :

Response.Redirect(http://www.google.com) will work
but Server.Transfer(http://www.google.com) will not work

----------------------------------- End of this topic ----------------------------------------------

Operators

Unary Operators
unary operators affect a single expression. In many instances, the unary operators enable operations with simpler syntax than a comparable binary operation. The unary operators include + (plus), - (minus), ++ (increment), -- (decrement), ! (logical negation), and ~ (bitwise complement).

Binary Operators
Binary operators are those operators that work with two operands. For example, a common binary expression would be a + b —the addition operator (+) surrounded by two operands. The binary operators are further subdivided into arithmetic, relational, logical, and assignment operators.


Operator Overloading In C#
All unary and binary operators have pre-defined implementations, that are automatically available in any expressions. In addition to this pre-defined implementations, user defined implementations can also be introduced in C#. The mechanism of giving a special meaning to a standard C# operator with respect to a user defined data type such as classes or structures is known as operator overloading. Remember that it is not possible to overload all operators in C#.
The following table shows the operators and their overloadability in C#.

Operators

+, -, *, /, %, &, , <<, >> All C# binary operators can be overloaded.
+, -, !, ~, ++, --, true, false All C# unary operators can be overloaded.
==, !=, <, >, <= , >= All relational operators can be overloaded, but only as pairs.
&&, They can't be overloaded
() (Conversion operator) They can't be overloaded
+=, -=, *=, /=, %= These compound assignment operators can be overloaded.
But in C#, these operators are automatically overloaded when the respective binary operator is overloaded.

=, . , ?:, ->, new, is, as, sizeof These operators can't be overloaded

Note :
· A special function called operator function is used for overloading purpose.
· These special function or method must be public and static.
· They can take only value arguments.
· The ref and out parameters are not allowed as arguments to operator functions.
public static return_type operator op (argument list)