Zieglers

Just little about C#, .NET, SQL Server, SharePoint and SAP

Archive for the ‘C#’ Category

about C# Programming Language…

How to create a Visual Studio Item Template

Posted by zieglers on June 24, 2010

BACKGROUND:A number of predefined project and project item templates are installed when you install Visual Studio. You can use one of the many project templates to create the basic project container and a preliminary set of items for your application, class, control, or library. You can also use one of the many project item templates to create, for example, a Windows Forms application or a Web Forms page to customize as you develop your application.
 

In addition to the installed templates that are available in the New Project and Add New Item dialog boxes, you can access templates that you have created.

MOTIVATION:Developers are lazy. I don’t mean that in a bad way, but in the same way that a smart horse is a lazy horse. Developers just don’t stand for repeating the same tasks without finding a way to automate them. I count myself among the lazy developers. I’m quite willing to spend time figuring out how to automate those repetitive tasks that I find myself doing often.

Visual Studio provides enough extensibility points that I’ve made a new rule for myself: If I do the same task twice, I figure out how to automate it.

In this post, I’ll try to show you ‘How to create an Item Template‘ for your Visual Studio project.

This will allow you to take advantage of C#’s Item Templates to automate tasks that you find yourself having to perform on a regular basis.

DEMO:

Now, let’s assume we have an ‘Application Pages’ project. We’ve been creating some app pages for a while and now we’d like to automate this process.

Since creating an app page requires a number of steps, we don’t want to perform those steps again and again, so it’s time for an app page template for our project.

Before creating your item template, get your code in a position where it can be used as a template once it’s been generated by template. This means include all the tasks you repeat and only leave page specific code / logic. For that part of the code, simply you can use a comment saying: // YOUR CODE GOES HERE.

Ok, say you have your project item (you’ll create your template from) ready.

First, we start Export Template wizard from File menu.

Then, we choose Template Type. In our case, it’s ‘Item Template‘.

Next, we select the item we’d like to export as an item template.

Then, we select item references to include with our item.

Finally we name our item template, provide a custom icon for it if you want and a description.

Once you click finish, your item template will be generated. Solution and Item templates in Visual Studio are in ZIP format.

Now, let’s create an application page by using item template we’ve just created. For this, simply go to your project, right click where you want to add a new app page and select new item.

Select item template just created.

Provide a name for your app page and click Add. That’s all! Now a new app page has been created using your Item Template.

This concludes our post on ‘How to create an Item Template‘. Remember to give a second thought while coding, in case you find yourselves doing same thing more than once or twice, it might be a good candidate for an item template.

Zieglers

Posted in .NET Framework, C#, IT Stuff, SharePoint | Tagged: , , , | Leave a Comment »

Dynamically creating form controls in SharePoint

Posted by zieglers on April 8, 2010

While doing SharePoint development, occasionally we find ourselves in situations that we need to create controls dynamically based on some user selection, querystring parameter, … etc.

Here I provide you a code snippet which you can use in custom SharePoint application pages or web parts. This code is basically,

  • creating an HTML table
  • looping thru some fields (those can be SPListItem fields or any collection you want based on which you’ll generate controls dynamically)
  • creating a SPContext based on item
  • creating FieldLabel and FormField objects using SPContext (This allows controls to be created based on their rendering and item context. For example, say Title field is string, textbox control will be created or Start Date is DateTime, then textbox with calendar control will be created.)  This means you don’t need to worry about which type of control you need to create.
  • adding FieldLabel and FormField to table rows.
  • finally adding constructed table to some other control before rendering, say to a panel.

You can download code snippet, CreateControls method, here: Creating Dynamic SharePoint Form Controls

zieglers

Posted in C#, IT Stuff, SharePoint | Tagged: , , , , , , , , | Leave a Comment »

Virtual vs. Abstract Classes

Posted by zieglers on March 25, 2010

Here is a brief comparison of VIRTUAL and ABSTRACT classes:

————–

The virtual keyword is used to modify a method, property, indexer or event declaration, and allow it to be overridden in a derived class.

The abstract modifier can be used with classes, methods, properties, indexers, and events. Use the abstract modifier in a class declaration to indicate that a class is intended only to be a base class of other classes. Members marked as abstract, or included in an abstract class, must be implemented by classes that derive from the abstract class.

Abstract classes have the following features:
- An abstract class cannot be instantiated.
- An abstract class may contain abstract methods and accessors.
- It is not possible to modify an abstract class with the sealed (C# Reference) modifier, which means that the class cannot be inherited.
- A non-abstract class derived from an abstract class must include actual implementations of all inherited abstract methods and accessors.

In general, virtual does not work on classes.
It is only for a class method, property, indexer or event declaration to have the possibility, to override them in a derived class.
An abstract class can’t be initiated and can more interpretated as a template of a class, which has to be derived to create an instance of it. 
————–

Zieglers

Posted in .NET Framework, C#, IT Stuff | Tagged: , , , , , | 1 Comment »

Featured Employee Web Part – AJAX Enabled

Posted by zieglers on February 18, 2009

Abstract: This document explains how to develop AJAX Enabled Featured Employee Web Part for SharePoint 2007. This web part displays a random employee profile after every 5 seconds using ASP.NET AJAX Technology.

Introduction

In this article, I’ll try to explain how to implement AJAX enabled “Featured Employee” web part. Actually what I mean by featured employee is any user profile which exists in SharePoint Shared Services user profiles list.

In most of the projects I worked, clients were asking for a web part which sort of displays or searches based on user profile info stored in Active Directory. I’ll try to show how to implement “Employee Directory Search” web part in another article. For this one, I’ll focus on just displaying employee info.

Let me mention some features of this web part. First of all, this web part will be changing displayed profile every 5 seconds using ASP.NET AJAX 1.0. Profiles will be displayed in a random fashion. Also, there is going to be a Department property to limit displayed profiles to a certain department of the company.

Department

Before we start, I’d like to show you how “Featured Employee” web part will look like once we are done. (After every 5 seconds, displayed profile will be randomly changed.)

Featured Employees

Design

Design of this web part can be divided into some sub sections as follows:

1. Implementing Featured Employee web part without AJAX capability

a. Get a list of user profiles and keep them in a collection

b. Filter user profiles based on following properties

i. Department (This is our first criteria. If user belongs to the department specified by web part properties pane, then include this user to “Displayable” collection)

ii. Photo Exists (Don’t display profiles w/o photo)

iii. Visible (If this additional ‘Visible’ Boolean property is true in user’s profile, then display this profile)

c. Randomly select only one employee profile

d. Display UI using control template

 

2. Adding AJAX capability

a. Enable SharePoint site for AJAX

i. Install ASP.NET AJAX 1.0

ii. Add necessary Web.Config entries

iii. Add Script Manager to master page

b. Create an Update Panel

c. Create a Timer and Event Handler for re-displaying profiles after each 5 sec.

d. Add code implemented in subsection 1 above to Update Panel.

First we will implement this web part as it will only display different employee profiles after every page load. Then, we will extend this functionality using AJAX.

Now, let’s start with the implementation of sub section 1.

Implementation

Implementing Featured Employee web part without AJAX capability

Get a list of user profiles and keep them in a collection

UserProfileManager profileManager = new UserProfileManager(ServerContext.Current);

Filter user profiles based on following properties

i. Department (This is our first criteria. If user belongs to the department specified by web part properties pane, then include this user to “Displayable” collection)

Department User Profile Property

ii. Photo Exists (Don’t display profiles w/o photo)

Picture

iii. Visible (If this additional ‘Visible’ Boolean property is true in user’s profile, then display this profile)

Visible Property

private void FillDataListWithUserData(BaseDataList list)

{

// Get max number for randomazition

int max = 0;

ArrayList upc = new ArrayList();

 

foreach (UserProfile profile in profileManager)

// In order to show employee profile in web part,

// there should be a department value and this profile should be flagged as visible

if (Parse<String>(profile["Department"]) != null

&& Parse<Boolean>(profile["VisibleInFaceBook"])

&& Department == Parse<String>(profile["Department"]))

{

// Add qualified user profile to list

upc.Add(profile);

max++;

}

 

}

Randomly select only one employee profile

// Generate a random index

Random random = new Random();

int randomIdx = random.Next(0, max);

 

int i = 0;

foreach (UserProfile profile in upc)

if (i == randomIdx)

{

users.Add(new FaceBookUser()

{

Name = Parse<String>(profile["PreferredName"]),

FirstName = Parse<String>(profile["FirstName"]),

LastName = Parse<String>(profile["LastName"]),

Department = Parse<String>(profile["Department"]),

Office = Parse<String>(profile["Office"]),

Photo = Parse<String>(profile["PictureURL"]),

AboutMe = Parse<String>(profile["AboutMe"]),

Title = Parse<String>(profile["Title"]),

MySiteUrl = Parse<String>(profile["PersonalSpace"]),

HireDate = Parse<DateTime>(profile["SPS-HireDate"])

});

break;

}

else

i++;

}

 

Display UI using control template

protected override string DeterminateView()

{

return @”~/_controltemplates/FaceBookWebPartControl.ascx”;

}

Adding AJAX capability

Enable SharePoint site for AJAX

i. Download & Install ASP.NET AJAX 1.0

Can be downloaded from Microsoft Download Center: http://www.microsoft.com/downloads/details.aspx?FamilyID=ca9d90fa-e8c9-42e3-aa19-08e2c027f5d6&displaylang=en

ii. Add necessary Web.Config entries

You can follow the post I wrote in my blog for that:

http://zieglers.wordpress.com/2009/02/02/webconfig-entries-for-enabling-ajax-for-sharepoint-2007/

iii. Add Script Manager to master page

Add the following entry to the master page of the page which hosts Featured Employee web part:

<asp:ScriptManager runat=”server” ID=”ScriptManager1″></asp:ScriptManager>

ScriptManager in master page

Create an Update Panel

Now, we need an Update Panel in which contents of the web part will be displayed.

protected override void CreateChildControls()

{

base.CreateChildControls();

this.EnsureUpdatePanelFixups();

UpdatePanel up = new UpdatePanel();

up.ID = “UpdatePanel1″;

up.ChildrenAsTriggers = true;

up.UpdateMode = UpdatePanelUpdateMode.Conditional;

this.Controls.Add(up);

up.ContentTemplateContainer.Controls.Add(this.lstEmployeesList);

}

Note above that we add lstEmployeeList DataList to update panel container. This list is holding employee profiles to be displayed.

Create a Timer and Event Handler for re-displaying profiles after each 5 sec.

We also need a timer to fire the event which will be changing displayed profile after every 5 seconds.

Timer timer = new Timer();

timer.Interval = 5000;

timer.Tick += new EventHandler<EventArgs>(HandleButtonClick);

up.ContentTemplateContainer.Controls.Add(timer);

Display Employee Profile Event Handler

So, this timer will call HandleButtonClick event handler every 5 seconds and will change displayed profile. It does nothing but calls FillDataWithUserData to get lstEmployeeList DataList filled with new employee profile.

private void HandleButtonClick(object sender, EventArgs eventArgs)

{

using (SPWeb web = SPContext.Current.Site.OpenWeb())

{

// Change displayed user profile each time clock ticks

FillDataListWithUserData(lstEmployeesList);

}

}

Helper Code

This implementation makes use of some helper code.

Our first helper class is actually a base web part class. (BaseWebPart.cs)

Second helper class is just an entity class to hold some employee profile information. (FaceBookUser.cs)

Helper classes

Conclusion

As a result, we have an AJAX enabled web part displaying random employee profiles every 5 sec. from a selected department. This web part can be used at internal department sites of companies. It can also be useful for pages such as “contact us”, “board of directors”, “primary client contacts”… etc.

 

Posted in C#, IT Stuff, SharePoint | Tagged: , , , | Leave a Comment »

Using CreateUserWizard in MOSS Web Parts

Posted by zieglers on September 14, 2008

Using CreateUserWizard in normal ASP.NET .aspx pages can be very straightforward. However when you want to use it in web parts for MOSS, definitely there are some little details that you need to know to make it functional as expected.

First problem I had was related to MembershipProvider property. I provided AspNetSqlProvider as my provider name for that property value, and I get the ‘unexpected error’ page.. When I removed it, everything seemed to work ok. It was working all good for another sample project that i developed to test the usage of Form Authentication with CreateUserWizard.

Then, I realized that without providing MembershipProvider property, control was functioning as expected. This was because CreateUserWizard control, when membership info not provided, was inheriting this property’s value from the current MOSS web site’s web.config. So, if you want to use this control in a user control loader as a MOSS web part, you don’t need to provide MembershipProvider property.

Second problem that you may face, once the user is created successfully and page is redirected to the one you provided in ContinueDestinationPageUrl property, the page is being loaded with the recently created user’s credentials. Since you haven’t added this new user to your MOSS site, you’ll get Access Denied error. So, in order to resolve this issue, you need to set LoginCreatedUser property of the control to false, so that page is loaded with the original user’s credentials, not with the one’s recently created.

Also, if you want to check out a nice sample code on Login, Role and Profile usage in ASP.NET 2.0, you might want to read this post as well: http://weblogs.asp.net/scottgu/archive/2005/10/18/427754.aspx

zieglers

Posted in .NET Framework, C#, IT Stuff, SharePoint | Tagged: , , , | Leave a Comment »

Exam 70-547: PRO: Designing and Developing Web-Based Applications by Using the Microsoft .NET Framework

Posted by zieglers on November 21, 2007

 WebEye

Today I passed Exam 70-547 : PRO: Designing and Developing Web-Based Applications by Using the Microsoft .NET Framework with a score of 1000/1000 :) There are 40 questions in the exam, no simulations. I even didn’t get any drag & drop question.

 … to be completed …

Posted in .NET Framework, C#, IT Stuff | 11 Comments »

IT Sertifikasyonu ve Brainbench

Posted by zieglers on October 13, 2006

 Brainbench

Ne zamandir yazilim sektorunde calisan bi insan olarak ( simdilik sadece 4 sene :) ) deginmek istedigim bir konu var: Sertifika!

Yerine gore hicbir ise yaramayan, yerine gore de hersey olan bir kagit parcasi aslinda. Ama is gorusmelerindeki etkisi yadsinamaz. Isverenler genelde, ise alicaklari kisinin teknik bilgi yeterliligini bazi sertifikalari almis olup olmamasiyla olcuyorlar. Tabii bu ilk planda olan bir hadise, yani karsilikli gorusmeye cagirmadan once. Isverenin onunde 100 tane cv varsa bunlari belli bir sayiya indirebilmek icin agirlikli olarak sertifikaya onem veriyor. Daha sonra gorusmeye cagiriyor, diyelim ki 10 tanesini. Sonra bunlardan 3 tanesini ise aliyor. Sonra isinma sureci geciyor ise alinan arkadaslarin. Isveren bir bakiyor – bircok degiskene bagli olmakla beraber – calisaninin performansi hic de bekledigi gibi degil… :-|

Suana kadar 50′den fazla is gorusmesine girmis bir kisi olarak sunu rahatlikla soyleyebilirim ki isverenlerin %90′nin ‘Pre-Hiring’ testten haberi yok. Yani belli bir kisiyi ise almadan once, ona yapmasi icin web uzerinden atanan coktan secmeli testler… :)

Bu testlerin kisiye verdigi not ile o kisinin is verimi arasindaki korelasyon neredeyse +1 seviyesinde. Cunku bu testlerin belli basli ozellikleri var.

1. Zaman sinirlamasi: Her soru mesela 2-3 dakika (sinavina gore degisiyor tabii). Boylelikle kem kum edecek vaktiniz olmuyor. Google mi? Kullanin tabii. O bile bi sinav aslinda basli basina. Onunuzdeki soruyu okuyup anlayip, onu ne gibi bir phrase’le arayacaginiza karar verip, onu Google’da arayip cevabi cat diye bulabiliyorsaniz zaten sorun yok. Isverenin de sizden bekledigi asagi yukari bu. Efektif arastirmaci ruhun uygulamaya dokuldugunu gormek hangi isverenin yuzunu guldurmez?!? :)

2. Sonuclarin isverene gitmesi: Sinav bitiminde sonuclarinizi goremiyorsunuz. Sinav sonucu ayrintili bir sekilde isverene gidiyor, yani sinavi size yollayan kisiye.. He he he, yusuf yusuf olayi yani.. :) Siz sinavi yaptiktan sonra yaa acaba n’oldu diye kumru gibi dusunurken, sonucun ne oldugunu isverenin sizi birkac gun sonra geri aramasindan :) ya da aramamasindan :( anliyorsunuz… Eger aramadiysa ve de sizin o teknik konu hakkinda baska bir sertifikaniz varsa, kendinizi kandirmadan artik o sertifikaya siz de ‘ufurukten’ gozuyle bakabilirsiniz. :)

3. Nerde durdugunuzu gorebilmek (see where you stand): Aldiginiz skorla dunyada ya da kendi ulkenizde kacinci sirada oldugunuzu gorebilirsiniz (ayni sinavi alan kisiler arasinda tabii). Bunun icin personal assessment sinavi almis olmaniz gerekiyor.

4. Sorularin zorluk derecesi: Sorulari hic kucumsemeyin. Ayrica dump mump da bosuna aramayin, bulamazsiniz!!! :D Mesela Microsoft sinavlarinda bile dump’i cikmamis bir sinavi ilk alanlardan olmakla, dump’i cikali asirlar olmus sinavlari almak arasinda ucurum var isverenin gozunde; her ne kadar siz o sertifikayi almis olsaniz da…

Uzun lafin kisasi sertifika onemli, hem de cok ama hakkiyla alinirsa… Iste size ‘beyninizin hakkiyla’ sertifika alabileceginiz bir site: www.brainbench.com

Bircok free test mevcut, mesela C#, ASP.NET, .NET Framework. Simdi ben developer’im diyorsaniz, girin alin bence. Hem birbirini tamamlayan 3 sertifikaniz olsun, hem de bu post’a sinavi aldiktan sonra reply atin ki ben de sevineyim yazdigim sey bir ise yaradi diye… :)

Posted in C# | 1 Comment »

 
Follow

Get every new post delivered to your Inbox.

Join 49 other followers