15 Kasım 2008 Cumartesi

ASP.NET kontrollerinde 'could not be set on property' hatası

Birçoğumuz, kendimize ait kontrolleri oluştururuz. Oluşturduğumuz kontrolleri projelerimize ekler kullanırız. Ancak bazen hiç karşılaşmadığımız, saatlerimizi belki gecelerimizi harcayacağımız problemler ile karşılaşırız ( ben gibi :) ). Ben de bir projemde kolaylık sağlaması adına bir kontrol geliştirmek istedim. Kontrol, bir kişinin yada nesnenin bilgilerini girerken resim bilgisini görsel olarak tutmak ve seçilecek resmi, modal bir pencereden bizim belirlediğimiz bir path altından listeleyen bizim de bu listelenen resimlerden seçim yapıp bizim resim kontrolümüzde gözükmesini sağlıyor. Böylece url den kurtulmuş, kullanıcı da ne seçtiğini görsel olarak görmüş olucak.

Ancak asıl bloğa konu olan, yazdığım bu kontrolü sayfaya eklediğimde problem yok, herhangi bir property'i set etmek istediğimde 'XXXX:XXX' could not be set on property 'xxx' designer'da hatası ile karşılaştım. Bu hata, kontrolün içinde bulunduğu updatepanel yada grid gibi kontrollerin de designer'da hata vermesine neden oluyordu. Sonunda sorunun çözümünü buldum, çözümü de "Developing Microsoft ASP.NET Server Control and Components" isimli kitabın yardımıyla buldum tesadüfen.

Soruna neden olan ToolboxData("<{0}:XXX runat="server"> ")] attribute :)
sanırım assembly dosyasına [assembly: TagPrefix(namespace, TagPrefix)] attribute'ü ile kullandığımdan bir sorun oluşturdu anlamadım :), ancak ToolboxData attribute'ünü çıkardığımda sorun çözüldü :). Ama halen sizde bu sorun devam ediyorsa, kontrolünüzün render methodlarını gözden geçirin, örn. Page.ClientScript.GetPostBackEventReference(this, "")); yerine Page.GetPostBackEventReference(this, ""));
gibi bi tanımlama yaptıysanız, compiler size bu kullanımın yerine yeni kullanım şeklini kullanmanızı söyler. Bu tarz bi durum varsa düzeltiniz. Çünkü render methodundaki herhangi bir durum da bu hatayı almanıza neden olur.
başka bir problem ve konu ile görüşmek üzere...

13 Haziran 2008 Cuma

Access is denied. (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED))

Bu hataya, yakalanmayan yoktur sanırım, özellikle
Doc Lib'ler üzerinde yetki seviyesi düşük kullanıcaların login olduğu portal üzerinde bir item güncelleme,silme yada kendi yetkisini aşan işlemlerde "
Access is denied. (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED))" hatasını alırız. Bu bence çok can sıkıcı bir durum. Bu problemin çözümü için hemen aklınıza
SPSecurity.RunWithElevatedPrivileges
methodu gelebilir, ancak buna o kadar güvenmeyin. Çünkü karşılaştığım problem üzerinde hiçbir faydası olmadı.
Problem şuydu:


Birkaç zorunlu alana sahip Document Library listemde upload yaptığımda, upload işleminden sonra çıkan edit ekranında zorunlu alanları doldurmadan cancel işlemi yaptığımızda upload yapılan dosya Check-Out olarak listede duruyor. İlginç olan bir konu da bu check-out olarak kalan item'ın
admin haklarına sahip kullanıcalar tarafından da görülemiyor olması. Yazdım custom bir yapı ile cancel dediği anda callback methodu çağırıp silme işlemini gerçekleştiriyorum. Ancak siz bu silme işlemlerini
SPSecurity.RunWithElevatedPrivileges ile yapsanız bile item görülemediği için silinemiyor çünkü item yok :), (ha siz bu şekilde silebilirseniz bana da söyleyin ancak yukarda yazdığım işlemler seviyesinde).


Çözüm için:


ImpersonationUtility
 imp = 
ImpersonationUtility
.ImpersonateAdmin();
 kodunu kullanıp, yetkileri olmayan kullanıcı yerine admin haklarına sahip olan kullanıcı ile işlemleri yaptırıyorum, ancak yukarda ifade ettiğim gibi admin olsa bile cancel işleminden sonraki check-out olan item'ın görülmediğinden (ki sadece onu oluşturan user görebiliyor ve kod ile erişebiliyor), admin hakları ile listenin rollerini değiştirip geçici olarak üzerindeki hakları silip(daha sonra silme işlemi tamamlanınca bu hakları geri vermek üzere bunları bir generic list içerisinde tutuyorum) bu kullanıcıya item silme hakkını veriyorum. Silme işlemini gerçekleştiriyorum ve generic listemdeki hakları tekrar geri veriyorum ve mutlu son böylece item silinebiliyor.







2 Haziran 2008 Pazartesi

Retaining Attachment functionality when using the Custom List Form control in SharePoint 2007 or WSS 3.0

(Kaynak: Marc Davis' Blog)

Sharepoint ile oluşturduğumuz Custom List Formlarda(Insert->Sharepoint Controls->Custom List Form) en büyük problemimiz attachment desteği olmamasıdır. Bir dosya attach etmek istediğimizde "This form was customized not working with attachement." hata mesajını alırız. Sorun, custom list form oluştuğunda attachment için gereken upload kontrolü ve html yapısı oluşmaması. Bu mesaj'ın kaynağı "C:\Program Files\Common Files\Microsoft Shared\web server extensions\12\TEMPLATE\LAYOUTS\1033\FORM.js" javascript dosyasıdır. Hata mesajını burada arattığımızda

function ShowPartAttachment()
{
if (document.getElementById("part1")==null ||
typeof(document.getElementById("part1"))=="undefined")
{
var L_FormMissingPart1_Text= "This form was customized not working with attachement.";
alert(L_FormMissingPart1_Text);
return;
}
document.getElementById("part1").style.display="none";
document.getElementById("partAttachment").style.display="block";
GetAttachElement(FileuploadString+FileUploadIndex).focus();
}


karşımıza javacript fonksiyonu çıkar. Burada "part1" id'sine sahip html objesi aranmakta ancak bulunamadığı için de hata uyarısı gelmektedir. Bazı forumlarda bu ID'ye sahip bir "span" oluşturulup sayfadaki orjinal webpart içeri alındığında ve webpartın içine de Sharepoint attachment kontrolü konduğunda çözülebileceği söyleniyor ancak olmuyor bu sadece client tarafta çalışıyor ancak herhangi bir attachment gerçekleşmiyor.
Bu problemi, bir çoğumuz kendi custom çalışmalarımız ile birşekilde çözmeye çalışırız. Bazı forumlarda da buna benzer örnekleri görmek mümkün. Örneğin kendim de bir çözüm buldum taki newform.aspx karşıma bir problem çıkartana kadar. Yazdığım bir webpart ile attachmet için gereken tabloyu oluşturup, newform.aspx içerisinde de bu html yapıyı tutacak bir Literal kontrolü kullandım. Webpartı da id'i "part1" olan bir span içerisine aldım, span tagını kapattıktan sonra da attachment için html kodlarını koydum (bunları custom olmayan bir listenin sayfanın kaynak kodlarına baktığımızda görürüz, IEDeveloper Toolbar ile de bu id'yi arattığınızda bulacaksınız, default'ta gözükmez (display=none),display değerini block yaptığınızda gözükecektir.) Beni terleten sorun, newform.aspx' henüz herhangi bir liste Item'ı oluşmaması. Bunun dışında tüm fonksiyonlar gayet iyi çalışıyordu. Ancak bu sorunu aşamadım.
Çözüm olarak en son yukarda kaynak olarak belirttiğim adreste mevcut, ne yapılması gerektiği adım adım açıklanmış. Uyguladım bizzat, çalışıyor. Bu konuda yardıma ihtiyacınız olursa, adresim (masallah.ozen@hotmail.com).

Ha bide dosya attach ederken web.config dosyanızaki maximum değeri baz alın, yada bu değeri arttırın,

29 Mayıs 2008 Perşembe

HOWTO: Debugging JavaScript using "debugger;"

(Kaynak: HOWTO: Debugging JavaScript using "debugger;" )

There are a lot of developers who write custom JavaScript or need to debug pre-written JavaScript, yet do not know that they can debug it in Visual Studio 2005. This is a fairly simple process.
Visual Studio offers the developer the ability to utilize the IDE to debug, just like you would debug if you are debugging .NET code. How? Very simple, the "debugger;" key word.
How It Works
First, you must enable script debugging in Internet Explorer (we will get that in a minute, first lets look at some code).
To debug: Write your JavaScript and place the "debugger" keyword where ever you want the code to break into debugging. The JavaScript interpreter hits this keyword and halts execution and returns the control back to the IDE. This is like setting a breakpoint inside of Visual Studio.

Response.Filter : Çıktıyı Filitrelemek

(Kaynak: Oğuz Yağmur'un Günlüğü)
Bazen bir aspx sayfasının çıktısı üzerinde işlemler yapmak isteyebilirisiniz. Örneğin sayfadaki yasaklı kelimelerin - genelde forumlarda ihtiyaç duyulur :) - düzenlenmesi, ya da bazı bilindik kelimeler üzerinde işlem yapmak isteyebiliriz. Mesela ben sayfamda BT Akademi ve oğuz kelimelerine rastladığımda ilgili kelimelerin yerine sanki linki verilmiş gibi yer almasını isteyebilirim. Bu durumda yapmamız gereken çıktının - Response - Filter özelliğinden yararlanmak. Filter özelliğini - property- incelediğimizde aslında bunun bir Stream nesnesi olduğunu görürüz. Bu durumda yapmamız gereken görüntülenmesini istediğimiz çıktıyı kendimiz oluşturmak. Bunu da kendi Filter - aslında Stream'dan türemiş bir class oluşturmak - nesnemizi oluşturup Response.Filter özelliğine bu kendi nesnemizi vermekten ibaret.

Stream sınıfı abstract bir class olduğundan abstract - özet kelimesini pek sevmesem de Türkçe'de başka kelime anlamını tam veremiyor- olarak bildirilmiş metodlarını kendi sınıfımızda uygulamamız - implement - gerekiyor. Bunları ekteki dosyadan inceleyebilirsiniz. Asıl üzerinde durulması gereken konu ise bu oluşturduğumuz sınıfın Write(...) metodu. Bu metod içinde sayfamızda görünmesini istediğimiz çıktıyı kendimizin oluşturması.

19 Nisan 2008 Cumartesi

CUSTOM CULTURE

(Kaynak: http://www.yazilimuzmani.com/Articles/Details.aspx?aId=1000001031)

CUSTOM CULTURE

CultureAndRegionInfoBuilder classını kullanabilmek için uylamaya Sysglobl.dll in reference edilmesi gerekmektedir. Kişisel bir bölgesel ayar olusturabilmek için tüm yapmanız gereken CultureAndRegionInfoBuilder classının instance nı yaratarak var olan bir bölgesel ayar secmek ve CultureAndRegionModifiers degeri belirtmek..

CultureAndRegionModifiers Enum ları

Neutral =Bölgesel ayar değilde sadece var olan bir kültürü kullanmak istendiğinde.

None =Var olan kültürün min özelliğini kullanarak yeni bir kultur olusturmak istendiğinde.

Replacement=Var olan bir kültür ün özellikleri degiştirilmek istendiğinde.

Basit bir örnek asağıda gösterilmiştir.

CultureAndRegionInfoBuilder Demo=

new CultureAndRegionInfoBuilder("en-US",

CultureAndRegionModifiers.Neutral);

CultureInfo Culture = new CultureInfo("tr-TR");

RegionInfo Region = new RegionInfo("TR");

CultureAndRegionInfoBuilder Demo =

new CultureAndRegionInfoBuilder("tr_TR",

CultureAndRegionModifiers.Neutral);

Demo.LoadDataFromCultureInfo(Culture);

Demo.LoadDataFromRegionInfo(Region);

Simdi bir uygulamayla kendi kişisel bölgesel ayar ‘ımızı yaratalım..

private void button1_Click(object sender, EventArgs e)

{

CultureInfo usCulture = new CultureInfo("tr-TR");

RegionInfo usRegion = new RegionInfo("TR");

CultureAndRegionInfoBuilder demo =

new CultureAndRegionInfoBuilder("deneme",

CultureAndRegionModifiers.None );

demo.LoadDataFromCultureInfo(usCulture);

demo.LoadDataFromRegionInfo(usRegion);

//Parasal değer ve ondalık sayılarda virgülden sonra gelecek rakam sayısını belirlediğimiz kod bloğu

NumberFormatInfo numberInfo = new NumberFormatInfo();

numberInfo.CurrencySymbol = "%";

numberInfo.CurrencyDecimalDigits = 4;

demo.NumberFormat = numberInfo;

//Haftanın günlerini ve Tarih formatını belirleyen kod bloğu

DateTimeFormatInfo dateInfo = new DateTimeFormatInfo();

dateInfo.DateSeparator = ".";

dateInfo.DayNames = new String[] { "ilkGün", "ikinciGün",

"ÜcüncüGün", "DördüncüGün", "BeşinciGün", "AltıncıGün", "YedinciGün" };

dateInfo.ShortTimePattern = "mm-yyyy-dd";

demoBuilder.GregorianDateTimeFormat=dateInfo ;

demo.Register();

}

private void button12_Click(object sender, EventArgs e)

{

CultureInfo user = new CultureInfo("deneme");

RegionInfo regi = new RegionInfo("deneme");

textBox1.Text = user.DateTimeFormat.ShortTimePattern.ToString();

textBox2.Text = user.NumberFormat.PercentDecimalSeparator.ToString();

textBox3.Text = regi.CurrencySymbol.ToString();

textBox4.Text = user.NumberFormat.PercentDecimalDigits.ToString();

//user.DateTimeFormat.da

textBox5.Text = (100000).ToString("C");

String[] Günler = user.DateTimeFormat.DayNames ;

foreach (String Gün in Günler)

{

listBox1.Items.Add(Gün );

}

}

Sonuç Aşağıdaki Şekilde olacaktır...

Olusturduğumuz kişisel bölgesel ayarı Register yaptığımızda iki işlem gerceklesir bunlardan birincisi

C:\WINDOWS\Globalization klasörüne xx.nlp isimli bir dosya olusturur.İkinci işlem ise Registry de HKEY_LOCAL_MACHINE\System\CurrentControlSet\Control\Nls\IetfLanguage

Altına yeni bir key oluşturur...Biz olusturduğumuz kişisel bölgesel ayarı

Unregister methoduna tabi tutarak silebiliriz..Bu silme işleminde makinanın yaptığı işlem sadece olusturulan dosyanın adını değistirmekir..

CultureAndRegionInfoBuilder.Unregister("deneme");

Register ederek olusturduğumuz bu uygulamayı baska projelerde kullanabilmemiz için onu kaydetmeliyiz..Kaydetme işlemini iki şekilde yapabiliriz..

1. demo.Save(“c:\\xxx.ldml”);

(LDML= Locale Data Markup Language)

2. demo.Save(“c:\\xxx.xml”);

İnternet te olusturulmuz bir cok Kişisel Bölgesel ayar bulabilmeniz ve uygulamalarınızda kullanabilmeniz mümkündür.

Var olan bir Kişisel Bölgesel ayar ı uygulamanızda kullanmak için CultureAndRegionInfoBuilder clasının CreateFromLdml methodunu kullanmalısınız

CultureAndRegionInfoBuilder demo = CultureAndRegionInfoBuilder.CreateFromLdml(“deneme.ldml”);

Demo.Register();

yada

CultureAndRegionInfoBuilder demo = CultureAndRegionInfoBuilder.CreateFromLdml(“deneme.xml”);

Demo.Register();

GLOBALIZATION

(Kaynak: http://www.yazilimuzmani.com/Articles/Details.aspx?aId=1000001030)

GLOBALIZATION

Günümüzde yapılan uygulamaların kullanım bölgeleri hızla çoğalmakta.Ulkeler arasında

Ø Tarih formatları(dd/MM/YYYY),

Ø Parasal semboller(YTL,$),

Ø Dil,

Ø Rakam Formatları (100,00 YTL)

Farklılık gösterdiğinden dolayı bir uygulama diğer bir ülkede kullanılırken sorun çıkarabilmektedir.

Yapılan bir uygulamaları bölgelere,ülkelere göre uyarlamak ,O bölgeye uygun bi şekilde yapmaktan daha maliyetli olmaktadır. .Net Framework yazılımcılara bu konuda yardımcı olabilmek için System.Globalization namespace sini gelişmiştir

System.Globalization namespace sinde baslıca

· CultureInfo

· RegionInfo

· DateTimeFormatInfo

· NumberFormatInfo

Class ları bulunmaktadır...Bu makale dizisinde tüm bu class lara örneklerle değineceğim..

CultureInfo sınıfı bize uygulamanın çalıştırıldığı platformun kültürel dili,yazı ve rakam formatı,tarih formatı gibi bilgileri verir.

Bir platformun Bölgesel ayarlarını aşağıdaki şekilde öğrenebiliriz (CurrentCulture).

private void button1_Click(object sender, EventArgs e)

{

CultureInfo UsersCulture = Thread.CurrentThread.CurrentCulture;

textBox1.Text ="The current culture of this application is : " +UsersCulture.Name;

textBox2.Text ="The Display Name of this application is : " +UsersCulture.DisplayName;

textBox3.Text ="The Native Name of this application is : " + UsersCulture.NativeName;

textBox4.Text ="The ISO Abbreviation of this application is : " +UsersCulture.TwoLetterISOLanguageName;

}

CultureInfo sınıfının GetCultures method unu kullanarak tüm bölgesel ayar adlarını görebiliriz.Bu method CultureType türünde bir değişken istemektedir.

CultureTypes

AllCultures : Tüm kültür isimleri

FrameworkCultures : .Net Framework deki tüm bölgesel ayar isimleri (Framework 2.0 ile gelen özellik)

InstalledWin32Cultures : Windows işletim sistemindeki tüm bölgesel ayar isimleri

ReplacementCultures : Var olan bir kültürü editleyerek kullanıcının oluşturduğu bölgesel ayar isimleri (Framework 2.0 ile gelen özellik)

Specific Cultures : Ülkeye ait specific bölgesel ayar isimleri

UserCustom Cultures : Kullanıcı Tarafından yaratılmış olan bölgesel ayar isimleri (Framework 2.0 ile gelen özellik)

WindowsOnly Cultures : .Net Frameworkte olmayıp windos ta olan bölgesel ayar isimleri (Framework 2.0 ile gelen özellik)

foreach (CultureInfo UsersCulture in

CultureInfo.GetCultures(CultureTypes.AllCultures ))

{

comboBox1.Items.Add (UsersCulture.Name);

}

Örnek Olarak Yazdığınız uygulamanın bir kısmında çalışanlara verilen maaşı gösterdiniz..Türkiye’de olduğumuz için bu para miktarının sonunda YTL yazmalı bunu yapabilmenin ilk yolu şudur.

tbMaas.Text = "YTL100,000.00";

Ancak bu yolla yapılan bir code bloğu eger sizin yaptığınız uygulama yurtdısında kullanılacaksa yada para birimi olarak Euro kullanılacaksa tüm kodları degiştirmeniz gerekecek ve dolayısıyla size sorun yaşatacaktır(Hard Coding).. .

tbMaas.Text = (100000).ToString("C");

Codebloğunu kullanarak yaptığımızda sistemin Culture değerini çekerek otomatik olarak kullanılan para degerini ve hatta kurus degeri için virgülden sonra kaç değer konulacağını ayarlayacaktır...

CultureInfo Classının DateTimeFormat propertisini kullanarak uygulamada geçerli olan bölgesel ayarın gün lerini listeleyebiliriz.

CultureInfo UsersCulture = new CultureInfo("tr-TR");

String[] Days = UsersCulture.DateTimeFormat.DayNames;

foreach (String Day in Days)

{

listBox1.Items.Add("Day Names for " + UsersCulture.Name + " : " + Day);

}

Aşağıdaki uygulamada yine CultureInfo Classının DateTimeFormat propertisini kullanarak uygulamada geçerli olan bölgesel ayarın ay isimlerini listelenişi gösterilmektedir.

CultureInfo UsersCulture = Thread.CurrentThread.CurrentCulture;

String[] Months = UsersCulture.DateTimeFormat.MonthNames;

foreach (String Month in Months)

{

listBox1.Items.Add("Month Names for " + UsersCulture.Name + " : " + Month);

}

Aşağıdaki uygulamada CultureInfo Classının DateTimeFormat propertisini kullanarak uygulamada geçerli olan bölgesel ayarın parasal değeri,tarih formatı,ayraç ve kuruş degeri için virgülen sonra kac değer geleceğinin listelenişi gösterilmektedir

CultureInfo UsersCulture = Thread.CurrentThread.CurrentCulture;

textBox1.Text = (UsersCulture.Name + "CurrencySymbol : "

+ UsersCulture.NumberFormat.CurrencySymbol);

textBox2.Text = ("NumberDecimalSymbol : "

+ UsersCulture.NumberFormat.CurrencyDecimalSeparator );

textBox3.Text ="DateFormat :" + UsersCulture.DateTimeFormat.ShortDatePattern.ToString();

textBox4.Text = "CurrencyDecimalDigits :" + UsersCulture.NumberFormat.CurrencyDecimalDigits.ToString() ;

Aşağıda Uygulamada kullanılan, geçerli olan bir bölgesel ayarı Spanish/Venezuela Bölgesel ayarına degiştirmek için.. gerekli olan code bloğu gösterilmektedir..

CultureInfo UsersCulture = Thread.CurrentThread.CurrentCulture;

MessageBox.Show("The current culture of this application is : "

+ UsersCulture.Name);

//

Thread.CurrentThread.CurrentCulture = new CultureInfo("es-VE");

MessageBox.Show("The current culture of this application is : "

+ Thread.CurrentThread.CurrentCulture);

İsletim sisteminizde gecerli olan Bölgesel ayarları gözlemleyip, degiştirebilmenizin bir diğer yolu aşagıda gösterilmiştir..

Start/Settings/ControlPanel/Regional and Language Options

CultureInfo class ında sınıfının LCID (Local ID)ve Name olarak iki özellige bulunmaktadır.

private void button1_Click(object sender, EventArgs e)

{

CultureInfo UsersCulture = Thread.CurrentThread.CurrentCulture;

MessageBox.Show(UsersCulture.LCID.ToString());

MessageBox.Show(UsersCulture.Name);

}

Yukarıdaki örnekte geriye dönen her iki değerde aynı Bölgesel Ayar verilerine erişmemizi şağlayacaktır..

RegionInfo class’ı, CultureInfo class ‘ının nazaran Bir ülke yada bölge hakkında daha specific ,bilgileri barındırır.

RegionInfo class’ının kullanımı aşagıdaki örnekte gösterilmiştir..

private void button1_Click(object sender, EventArgs e)

{

CultureInfo UsersCulture = Thread.CurrentThread.CurrentCulture ;

RegionInfo DemoRegion = new RegionInfo(UsersCulture.LCID );

//RegionInfo DemoRegion = new RegionInfo("tr-TR");

textBox1.Text = ("English Name: " + DemoRegion.EnglishName);

textBox2.Text = ("Display Name: " + DemoRegion.DisplayName);

textBox3.Text = ("Currency Symbol: " + DemoRegion.CurrencySymbol);

textBox4.Text = DemoRegion.CurrencyNativeName.ToString();

textBox5.Text = DemoRegion.ISOCurrencySymbol.ToString();

textBox13.Text = DemoRegion.NativeName.ToString();

}

Su ana kadar yapılan uygulamalarda var olan Bölgesel ayarları kullandık; Framework 2.0 la gelen UserCustom Cultures ile bunların dısında kendi kişisel bölgesel ayarlarımızı oluşturabiliriz..Kendimize özgü bir takvim,tarih formatı.... ve hatta bu Kişisel Bölgesel Ayarları diğer uygulamalarımızdada kullanılabilir bir hala getirebiliriz.

31 Mart 2008 Pazartesi

CryptoCollaboration For SharePoint 2007

(Source / Details: http://www.codeplex.com/CryptoCollaboration)

Project Description
CryptoCollaboration for SharePoint 2007 (works for both Microsoft Office Server 2007 as well as Windows SharePoint Services 3.0) presents a native end-to-end encryption solution targeted at SharePoint lists and their related metadata.

One of the largest tribulations that exists within current collaboration systems is the reliance on making objects security aware based solely on provided principle attributes, characteristically noticed in SharePoint through its indigenous options for security trimming the interface. While this is certainly a method that promotes some level of privacy, security, and data integrity, it does not account for data storage while information is considered in a transitional state. Furthermore, this is amplified by the fact that numerous industry regulations require that when organizational data is stored in a system as SharePoint, that it is not directly callable in plain text, however promotes a secondary layer of privacy

CryptoCollaboration is broken up into two primary segments, the CryptoCollaboration Encryption Engine (CEE) and its related SharePoint interface components. The CEE is called directly from the ECB (Edit Content Block) menu provided by the native SharePoint ListFormWebPart (your orthodox SharePoint list interface), pooling all the fields that are considered encryption worthy and encrypting or decrypting them based on user interaction. Since there are current limitations to the fields out of an arbitrary list item that can be harvested (field types such as URL’s demand that certain formats be used and therefore cannot be subject to encryption operations).

Once the encryption / decryption operations are triggered, the CEE will encrypt / decrypt the stored fields with an algorithm that the user selects out of the interface (currently supported encryption algorithms are RC2, Rijndael (AES), Triple DES, or BlowFish). All code that the CEE leverages is CLS-Compliant and 100% managed.

Adam Buenz
http://sharepointsecurity.com

Code Access Security for SharePoint 2007 Web Part Developers

(Kaynak: http://www.brettlonsdale.com/spblog/Lists/Posts/Post.aspx?ID=4)

Setting up SharePoint 2007 Code Access Security

In addition to my WhitePaper (Code Access Security for Administrators) I would like to explain how to setup Code Access Security for Web Part developers in SharePoint 2007.

20 Mart 2008 Perşembe

Walkthrough: Creating a Basic ASP.NET AJAX-enabled Web Part

// Kaynak
http://msdn2.microsoft.com/en-us/library/bb861877.aspx
//

This walkthrough describes the steps for creating a basic ASP.NET AJAX-enabled Web Part that you can add to your Web Part page. The example creates a SayHello Web Part that derives from the ASP.NET 2.0 WebPart (in the System.Web.UI.WebControls.WebParts in the ASP.NET Class Library) for use in a Windows SharePoint Services 3.0 Web site.

Note:
For more information about ASP.NET Web Parts, see ASP.NET Web Parts Overview and Introducing Web Part Controls.


Prerequisites
Windows SharePoint Services 3.0

Visual Studio 2005

Step 1: Create a Web Part Project
To create an AJAX-enabled Web Part control, you start by creating a class library project in the class library in Visual Studio 2005.

To create an ASP.NET Web Part project in Visual Studio 2005
Start Visual Studio 2005.

On the File menu, point to New, and then click Project.

In Project Types, under Visual Basic or C#, select Windows.

In the Templates pane, select Class Library.

Type Sample.SayHello as the project name.

Step 2: Rename the base class and add required namespaces
After you create the project, a blank class file is displayed. You can change the default class name of Class1 to easily identify your new Web Part. In a class library project, only a few namespaces are included. You need to add two required namespaces and references to their assemblies. You must also derive the base class from System.Web.UI.WebControls.WebParts.WebPart. Then, you need to add two global variables to update the user interface (UI).

To add namespace references and shared UI components
Rename the default class by selecting Class1.cs in Solution Explorer, right-click, click Rename, and type SayHelloWebPart as the file name.

On the Project menu, click Add Reference.

In the Add Reference dialog on the .NET tab, select System.Web.Extensions and click OK.

Repeat steps 2 and 3 for the System.Web namespace.

In the references area of the class file, add a reference to System.Web.UI.WebControls and create two private variables for the UI, as shown in the following code:

C# Copy Codeusing System;
using System.Text;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
namespace Sample.SayHello
{
public class SayHelloWebPart : WebPart
{
private Label displayName;
private TextBox inputName;
}
}


Visual Basic Copy CodeImports System
Imports System.Text
Imports System.Web.UI
Imports System.Web.UI.WebControlsImports System.Web.UI.WebControls.WebParts
Public Class SayHelloWebPart
Inherits WebPart
Private displayName As Label
Private inputName as TextBox
End Class

You have now created a basic structure for the Web Part.

Step 3: Override CreateChildControls and create a button event handler.
After configuring the new class to act as a Web Part, you must override the CreateChildControls method to build the UI. You must also add a button handler to refresh the display data.

To override CreateChildControls and create a button event handler
In the SayHelloWebPart.cs file, copy and paste the following code to override the CreateChildControls method:

C# Copy Codeprotected override void CreateChildControls()
{
base.CreateChildControls();

//Fix for the UpdatePanel postback behaviour.
EnsurePanelFix();

LinkButton sayHello = new LinkButton();
UpdatePanel refreshName = new UpdatePanel();
ScriptManager scriptHandler = new ScriptManager();
displayName = new Label();
inputName = new TextBox();

//Set up control properties.
this.displayName.ID = "displayName";
this.displayName.Text = "Hello!";
this.inputName.ID = "inputName";
sayHello.ID = "sayHello";
sayHello.Text = "Say Hello";
scriptHandler.ID = "scriptHandler";
refreshName.ID = "refreshName";
refreshName.UpdateMode = UpdatePanelUpdateMode.Conditional;
refreshName.ChildrenAsTriggers = true;

//Add the EventHandler to the Button.
sayHello.Click += new EventHandler(ClickHandler);

//Add the user interface (UI) controls to the UpdatePanel.
refreshName.ContentTemplateContainer.Controls.Add(this.inputName);
refreshName.ContentTemplateContainer.Controls.Add(sayHello);
refreshName.ContentTemplateContainer.Controls.Add(this.displayName);

//The ScriptManager control must be added first.
this.Controls.Add(scriptHandler);
this.Controls.Add(refreshName);
}


Visual Basic Copy CodeProtected Overrides Sub CreateChildControls()
MyBase.CreateChildControls()

'Fix for the UpdatePanel postback behaviour.
EnsurePanelFix()

Dim sayHello As New LinkButton
Dim refreshName As New UpdatePanel
Dim scriptHandler As New ScriptManager
displayName = New Label
inputName = New TextBox

'Set up control properties.
Me.displayName.ID = "displayName"
Me.displayName.Text = "Hello!"
Me.inputName.ID = "inputName"
sayHello.ID = "sayHello"
sayHello.Text = "Say Hello"
scriptHandler.ID = "scriptHandler"
refreshName.ID = "refreshName"
refreshName.UpdateMode = UpdatePanelUpdateMode.Conditional
refreshName.ChildrenAsTriggers = True

'Add the EventHandler to the Button.
AddHandler sayHello.Click, _
New EventHandler(AddressOf ClickHandler)

'Add the user interface (UI) controsl to the UpdatePanel

refreshName.ContentTemplateContainer.Controls.Add(Me.displayName)
refreshName.ContentTemplateContainer.Controls.Add(Me.inputName)
refreshName.ContentTemplateContainer.Controls.Add(sayHello)

'The ScriptManager must be added first.
Me.Controls.Add(scriptHandler)
Me.Controls.Add(refreshName)
End Sub

Then, in the SayHelloWebPart.cs file, copy and paste the following code:

C# Copy Codeprivate void ClickHandler(object sender, EventArgs args)
{
this.displayName.Text = "Hello, "
+ this.inputName.Text.ToString() + ".";
}


Visual Basic Copy CodePrivate Sub ClickHandler(ByVal sender As Object, _
ByVal args As EventArgs)
Me.displayName.Text = "Hello, " & Me.inputName.Text & "!"
End Sub

Now you have created the basic UI and button handling event.

For ASP.NET controls that use the JavaScript _doPostBack() function to commit changes, a regular full-page postback event may occur even when the Web Part is inside an UpdatePanel control. Windows SharePoint Services 3.0 and ASP.NET AJAX cache certain form actions, which can cause a conflict between SharePoint and ASP.NET AJAX. To change this behavior, you must add code to scripts that are running in Windows SharePoint Services 3.0.

Step 4: Modify Windows SharePoint Services 3.0 scripts to change doPostBack() behavior
To modify scripts to ensure proper doPostBack() behavior
In the SayHelloWebPart.cs file, copy and paste the following code:

C# Copy Codeprivate void EnsurePanelFix()
{
if (this.Page.Form != null)
{
String fixupScript = @"
_spBodyOnLoadFunctionNames.push(""_initFormActionAjax"");
function _initFormActionAjax()
{
if (_spEscapedFormAction == document.forms[0].action)
{
document.forms[0]._initialAction =
document.forms[0].action;
}
}
var RestoreToOriginalFormActionCore =
RestoreToOriginalFormAction;
RestoreToOriginalFormAction = function()
{
if (_spOriginalFormAction != null)
{
RestoreToOriginalFormActionCore();
document.forms[0]._initialAction =
document.forms[0].action;
}
}";
ScriptManager.RegisterStartupScript(this,
typeof(SayHelloWebPart), "UpdatePanelFixup",
fixupScript, true);
}
}


Visual Basic Copy CodePrivate Sub EnsurePanelFix()
If Me.Page.Form IsNot Nothing Then
Dim fixupScript As New StringBuilder()

With fixupScript
.AppendLine("_spBodyOnLoadFunctionNames.push" & _
"(""_initFormActionAjax"");")
.AppendLine("function _initFormActionAjax()")
.AppendLine("{")
.AppendLine("if (_spEscapedFormAction == " & _
"document.forms[0].action)")
.AppendLine("{")
.AppendLine("document.forms[0]._initialAction = " & _
document.forms[0].action;")
.AppendLine("}")
.AppendLine("}")
.AppendLine("var RestoreToOriginalFormActionCore = " & _
RestoreToOriginalFormAction;")
.AppendLine("RestoreToOriginalFormAction = function()")
.AppendLine("{")
.AppendLine(" if (_spOriginalFormAction != null)")
.AppendLine(" {")
.AppendLine(" RestoreToOriginalFormActionCore();")
.AppendLine(" document.forms[0]._initialAction = " & _
"document.forms[0].action;")
.AppendLine(" }")
.AppendLine("}")
End With
ScriptManager.RegisterStartupScript(Me, _
GetType(SayHelloWebPart), "UpdatePanelFixup", _
fixupScript.ToString(), True)
End If
End Sub

Now you have modified the scripts to ensure proper postback handling.

After you've added all of your code to your Web Part project, you can build your sample Web Part and deploy it. For more information about deploying a Web Part, see Walkthrough: Creating a Basic Web Part.

See Also
Other Resources
Solutions and Web Part Packages


Tags : Add a tag Add Cancel
Community Content
Add Community Content

Avoiding Stack Overflows jsum | Edit | Show History
Please Wait
I encountered an issue when I tried to add webparts of differing types into the same web part page - the result was a stack overflow causing IE to abruptly terminate.

The problem arises when the script defined in the EnsurePanelFix method above, is inserted more than once into a page. The execution of the first script block is harmless. The execution of any subsequent block however, eventually results in a stack overflow. The reason is that the subsequent assignment to RestoreToOriginalFormActionCore is from the newly defined RestoreToOriginalFormAction (defined in the frist script block), and not the original RestoreToOriginalFormAction method.

In the subsequent execution of the script block, RestoreToOriginalFormActionCore and RestoreToOriginalFormAction are made equivalent, so the RestoreToOriginalFormAction method becomes infinately recursive.

var RestoreToOriginalFormActionCore = RestoreToOriginalFormAction; RestoreToOriginalFormAction = function() { if (_spOriginalFormAction != null) { RestoreToOriginalFormActionCore();
There are a number of ways around this, (that I can think of) but none of them are ideal. The first is to ensure that only one script block is inserted into the page, no matter how many types of your web parts are added to the page. This is done by modifying the call to RegisterStartUpScript. I found that it is the combination of the type parameter and key parameter together that determines whether the script is inserted. So I just created a base web part (MyBasePart), and used that type as the type parameter. typeof(object) also worked; I assume you can use any type that you want.

ScriptManager.RegisterStartupScript(this, typeof(MyBasePart), "UpdatePanelFixup",fixupScript, true);
Well this works if you publish all of the webparts that go into the page, but there will be issues if you also want to use web parts published by others, because depending on what type/key they used, you might still end up with more than one script block in your page. So the solution that I'm using for the time being is to define RestoreToOriginalFormAction based on what it is originally. (But this will break if the definition of RestoreToOriginalFormAction in WSS changes)

String fixupScript = @" if (typeof(_spBodyOnLoadFunctionNames) !== 'undefined'){ _spBodyOnLoadFunctionNames.push(""_initFormActionAjax""); function _initFormActionAjax() { if (_spEscapedFormAction == document.forms[0].action){ document.forms[0]._initialAction = document.forms[0].action; } } RestoreToOriginalFormAction = function() { if (_spOriginalFormAction != null) { if (_spEscapedFormAction==document.forms[0].action){ document.forms[0].action=_spOriginalFormAction; } _spOriginalFormAction=null; _spEscapedFormAction=null; document.forms[0]._initialAction = document.forms[0].action; } }; }";
I used the VS script debugger to find the original definition of RestoreToOriginalFormAction and incorporated it into the above code block. The new definition simply adds one line at the end:

document.forms[0]._initialAction = document.forms[0].action;
I removed the call to RestoreToOriginalFormActionCore. This is important because if a third party web part appears in the page after yours and again redefines the RestoreToOriginalFormAction method, there is still no possibility for recursion. i.e. RestoreToOriginalFormAction will become:

RestoreToOriginalFormAction = function() { if (_spOriginalFormAction != null) { RestoreToOriginalFormActionCore(); document.forms[0]._initialAction = document.forms[0].action; } }";
But RestoreToOriginalFormActionCore is our function, which is not recursive. The only side effect is that

document.forms[0]._initialAction = document.forms[0].action;
will be called twice in succession, but that should be harmless.

Naturally, all bets are off if you want to use your web parts with more than one web part from elsewhere.
Tags:


Please Wait
Tags : Add a tag Add Cancel
This code is causing a regular postback HotmailUser ... Noelle Mallory - MSFT | Edit | Show History
Please Wait
I've downloaded this code and built a WebPart using it with no changes. I deployed the WebPart to my MOSS 2007 site collection, and added it to a page. Clicking the LinkButton causes a full postback each time with the whole page refreshing. There's no partial rendering of the Label control.

How can I get around this?

I even tried both 1.0 and 3.5 versions of System.Web.Extensions.

Thanks.

[WolfyUK] Have you followed the steps at http://msdn2.microsoft.com/en-us/library/bb861898.aspx to configure WSS 3.0 SP1 for AJAX-enabled Web Parts?

[Noelle Mallory - MSFT] Please post questions to the MSDN Forums at http://forums.microsoft.com/msdn. You will likely get a quicker response through the forum than through the Community Content.



Tags:


Please Wait
Tags : postback (x) Add a tag Add Cancel
Multiple AJAX-enabled SharePoint Web Parts using this example WolfyUK ... kjkj3jf | Edit | Show History
Please Wait
I too have encountered issues when using this sample code in WSS 3.0 SP1 with ASP.NET AJAX Extensions 1.0.

Similar to the JavaScript overflow issues identified by jsum, you are only allowed one ScriptManager per ASP.NET page. This means that a check will need to somehow be made to see if a ScriptManager is already present on the SharePoint page before another is added by the AJAX-enabled Web Part. I haven't quite figured out the best way to achieve this yet, but catching the System.InvalidOperationException that is thrown when the second or subsequent ScriptsdddddddfsdfsdfsdfManagers are added to the Page seems to be a temporary workaround. Tags:


Please Wait
Tags : ajax (x) asp.net (x) scriptmanager (x) wss (x) Add a tag Add Cancel
Page Title gets changed when the ajax method is invoked Tragen | Edit | Show History
Please Wait
So I used the same type of architecture as listed here. However, whenever I click the method that performs the ajax call the page title gets changed to illegiable characters. Any idea why this would happen? Tags:


Please Wait
Tags : Add a tag Add Cancel
RE: Page Title gets changed when the ajax method is invoked Neil I | Edit | Show History
Please Wait
Tragen: It appears to be related to using Publishing Webs. If you try it on a regular site it'll probably work. I haven't been able to determine a workaround for that yet. If you do find one, post it here.

Redirect Reference (IIS 6.0)

// Kaynak
http://www.microsoft.com/technet/prodtechnol/WindowsServer2003/Library/IIS/41c238b2-1188-488f-bf2d-464383b1bb08.mspx?mfr=true
///

Redirecting a client request is one way to ensure that users get the correct page, if your site is under construction or has changed identity. You can redirect client requests to a directory on the same Web server or to a different URL.

Configuring URL and Wildcard Redirection
You can configure redirection to a URL and wildcard redirection programmatically. Redirection variables and flags allow you to specify targets and behavior by changing the HttpRedirect metabase property.

The following example shows the format of a simple redirection string.

http://DestinationURL[,Flag[s]]

Where DestinationURL can include the following redirect variables to pass portions of the original URL with the destination URL. You can use more than one variable in a single redirection string.


Variable Description Example
$S
Passes the suffix of the requested URL to the new URL. The suffix is the portion of the original URL that remains after the redirected URL is substituted.

If the EXACT_DESTINATION flag is not set, the resulting destination URL will have the name of the requested file appended as a folder name, as well as the file name itself.
If the virtual directory that is mapped to the following Web site:

http://fabrikam/Scripts

is configured to be redirected to the following exact URL:

http://fabrikam/NewScripts$S

A new request for the following URL:

http://fabrikam/Scripts/Program.exe

Would be redirected automatically to the following URL:

http://fabrikam/NewScripts/Program.exe

$P
Passes parameters (such as querystring parameters) in the original URL to the new URL, without the question mark (?).
If the virtual directory that is mapped to the following Web site:

http://fabrikam/Scripts

is configured to be redirected to the following URL:

http://fabrikam/NewScripts$P

A new request for the following URL:

http://fabrikam/Scripts/File.asp?var1=5&var2=6

Would be redirected automatically to the following URL:

http://fabrikam/NewScriptsvar1=5&var2=6

$Q
Passes parameters (such as querystring parameters) in the original URL to the new URL, including the question mark (?).
If the virtual directory that is mapped to the following Web site:

http://fabrikam/Scripts

is configured to be redirected to the following exact URL:

http://fabrikam/NewScripts$S$Q

A new request for the following URL:

http://fabrikam/Scripts/File.asp?var1=5&var2=6

Would be redirected automatically to the following URL:

http://fabrikam/NewScripts/File.asp?var1=5&var2=6

$V
Passes the requested URL, without the server name and without any parameters. To include parameters, use the $P or $Q variable with the $V variable.

If the EXACT_DESTINATION flag is not set, the resulting destination URL will have the name of the requested file appended as a folder name, as well as the file name itself.
If the virtual directory that is mapped to the following Web site:

http://fabrikam/Scripts

is configured to be redirected to the following exact URL:

http://contoso$V

A new request for the following URL:

http://fabrikam/Scripts/File.asp

Would be redirected automatically to the following URL:

http://contoso/Scripts/File.asp


Redirection Using Wildcards
You can use redirect wildcards to match any number of characters in the original URL. Begin the destination URL with an asterisk (*) and a semicolon (;), and separate pairs of wildcard characters and destination URLs with a semicolon. The following example shows the format of a redirection string that uses wildcards.

*; Wildcard1; Destination1[; Wildcard2; Destination2][, Flags]

Where WildcardN can include an asterisk (*) to match any number of characters in the original URL and pass them to DestinationN by using the $0 through $9 variables defined in the following table.


"Variable" "Description" "Example"
$0 through $9
Passes the portion of the requested URL that matches the indicted wildcard character. Wildcards must start at $0 for each Wildcard;Destination set. The EXACT_DESTINATION flag must be appended to the redirection string.
If the virtual directory that is mapped to the following Web site:

http://fabrikam/Scripts

is configured with the following redirection string:

*; /Scripts/*_in.asp; /NewScripts/$0.dll; /Scripts/*_out.asp; http://contoso/NewScripts/$0.dll

A new request for the following URLs:

http://fabrikam/Scripts/data_in.asp

http://fabrikam/Scripts/data_out.asp

Would be redirected automatically to the following respective URLs:

http://fabrikam/NewScripts/data.dll

http://contoso/NewScripts/data.dll

!
Does not allow a redirect.

This variable is useful when you want to exempt files or subdirectories from redirection when a parent directory is configured to be redirected.
If the virtual directory that is mapped to the following Web site:

http://fabrikam/Scripts

is configured to be redirected, but the following Web site:

http://fabrikam/Scripts/Commerce/Accounts

needs to be exempt, programmatically set the redirection string for the exempted folder to the following

*;!



For example, to redirect all requests for /Scripts/Filename.stm to a single file called Default.stm, and to redirect all requests for /Scripts /Filename.htm to a single file called Default.htm, use the following redirect request for the /Scripts virtual directory:

*;Filename.stm;/Default.stm/Filename.htm;/Default.htm

Using Redirection Flags
The following flags augment redirect strings of either URL or wildcard format. More than one flag is allowed. Flags are appended programmatically to the redirection string in HttpRedirect, or configured by selecting check boxes in IIS Manager.


Flag User Interface Check Box Description
EXACT_DESTINATION
The exact URL entered above
Indicates that the value provided for the destination should be considered an absolute target location.

CHILD_ONLY
A directory below this one
Alerts IIS that redirection should occur only once because the destination is in a subdirectory of the original URL. This flag avoids loops. Also, this flag instructs IIS to redirect requests only if they are to subfolders or files of the original URL.

PERMANENT
A permanent redirection for this resource
Indicates that this redirection is permanent for this resource.

TEMPORARY
Clear the A permanent redirection for this resource check box"
Indicates that this redirection is temporary for this resource.

Accessing SharePoint List Data as XML

//////
http://www.sharepointblogs.com/dwise/archive/2008/01.aspx
///////

The other day, I found myself in need of a way to access SharePoint list data as XML but the only method available to me was a simple http GET. This is not too bad, but what can I get from SharePoint via GET? RSS is too limited and scraping the page is too painful and error-prone to even contemplate.

It turns out that there is an option available in 2007 that was carried forward from SharePoint 2003 / FrontPage days: owssvr.dll. But this isn't some forgotten FrontPage artifact, it is still a central part of SharePoint. In fact, if you pull up a list view and then view the source looking for owssvr.dll, you will see that this is the mechanism behind both the Export to Spreadsheet and Open with Access options on the list Actions menu.

How It Works
Simply put together a URL like this:

http://MyServer/[site]/_vti_bin/owssvr.dll?Cmd=Display&List={listGuid}&XMLDATA=TRUE

This will only return the fields that are defined on the default view of the list. If you need specific fields then you need to create a view with those fields and pass the View ID as well, like this:

http://.../owssvr.dll?Cmd=Display&List={listGuid}&view={viewGuid}&XMLDATA=TRUE


Specifying Fields to be Returned
There is also a Query parameter that lets you specify which fields are to be included in the resulting XML, regardless of how the view is defined. For example, if you wanted just to bring back the Title and Status Fields, you would add the field names separated by spaces (URL Encoded, of course) like "&Query=Title%20Status". If you want to return all fields, use an asterisk (*) instead of field names.

http://.../owssvr.dll?Cmd=Display&List={listGuid}&query=Title%20Status&XMLDATA=TRUE


Filtering Data
Regardless of whether you pass a view or use the default it will still use the filter defined by that view. Not bad, but you can trim this data even more by including a filter of your own using the FilterFieldn and FilterValuen arguments in the querystring. These are the same values that are passed when you use the filter options in the column headers of a view which makes it pretty easy to track down exactly what needs to be passed. Simply pull up the view that is your starting point and use the column filters to create your desired filter. Once you have it, grab all of the FilterField and FilterValue items from the querystring and add them on to yours.

http://.../owssvr.dll?Cmd=Display&List={listGuid}&query=Title%20Status&XMLDATA=TRUE&FilterField1=Status&FilterValue1=In%20Progress

For a full list of what can be done with this technique, check out the URL Protocol or the older Using the URL Protocol on MSDN.

Free MOSS/WSS 2007 Web Part - Hide Controls via JavaScript

http://www.cleverworkarounds.com/category/sharepoint/

Note: version 0.2 posted with minor bugfix 15th March 08!

This is my small contribution to the SharePoint world. It is a web part that once added to a web part page, allows you to customise the display by adding JavaScript to selectively hide controls on the page . Ever needed to hide a field from display/edit for a certain audience? Well here is a way do it without requiring SharePoint Designer and having to break a page from it’s site definition (unghosting).

Before and after shots below (look ma - no top button!)



To fully understand what is being done here, I suggest you read my series of articles on the use of JavaScript in SharePoint. Part 3 in particular will show you how to safely add this web part to pages with editing disabled (NewForm.aspx, EditForm.aspx and DispForm.aspx)

The full series can be found here: Part 1, Part 2, Part 3, Part 4, Part 5 and Part 6.

Kudos to Jeremy Thake for feedback and some code contribution. Despite being seriously metrosexual, he is otherwise otherwise very cool :-P.

Now two important warnings:

Warning 1: This is an alpha quality release and I may never touch it again So you very likely *will* break it. If there is enough interest, I am happy to pop it on codeplex

Warning 2: This web part should NOT be considered as a security measure and thus used in any security sensitive scenario (such as an extranet or WCM site). JavaScript by its very nature can be trivially interfered with and thus other methods (server side) should be employed in these scenarios to prevent interference at the browser.

You can download by reading the disclaimer and clicking the button below..

THIS CODE IS PROVIDED UNDER THIS LICENSE ON AN “AS IS” BASIS, WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, WITHOUT LIMITATION, WARRANTIES THAT THE COVERED CODE IS FREE OF DEFECTS, MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE OR NON-INFRINGING. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE COVERED CODE IS WITH YOU. SHOULD ANY COVERED CODE PROVE DEFECTIVE IN ANY RESPECT, YOU (NOT THE INITIAL DEVELOPER OR ANY OTHER CONTRIBUTOR) ASSUME THE COST OF ANY NECESSARY SERVICING, REPAIR OR CORRECTION. THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS LICENSE. NO USE OF ANY COVERED CODE IS AUTHORIZED HEREUNDER EXCEPT UNDER THIS DISCLAIMER

Use at your own risk!



To install perform the following commands

stsadm.exe” -o addsolution -filename CleverWorkAroundsHideFields.wsp
stsadm.exe” -o execadmsvcjobs
stsadm.exe” -o deploysolution -name CleverWorkAroundsHideFields.wsp -immediate -allowgacdeployment -allcontenturls
stsadm.exe” -o execadmsvcjobs
To remove/reinstall perform the following commands

stsadm.exe” -o retractsolution -name CleverWorkAroundsHideFields.wsp -immediate -allcontenturls
stsadm.exe” -o execadmsvcjobs
stsadm.exe” -o deletesolution -name CleverWorkAroundsHideFields.wsp
stsadm.exe” -o execadmsvcjobs
stsadm.exe” -o addsolution -filename CleverWorkAroundsHideFields.wsp
stsadm.exe” -o execadmsvcjobs
stsadm.exe” -o deploysolution -name CleverWorkAroundsHideFields.wsp -immediate -allowgacdeployment -allcontenturls
stsadm.exe” -o execadmsvcjobs

12 Mart 2008 Çarşamba

Adding web parts programmatically in SharePoint

The code to accomplish this is quite easy, basically there are two scenarios: you add a web part that is displaying data for a list, or you add any other web part (e.g. a custom web part or a 3rd party web part like the SmartPart). The code for the first scenario is:

using Microsoft.SharePoint;

using Microsoft.SharePoint.WebPartPages;

// Get a reference to a web and a list
SPSite site = new SPSite("http://localhost:8000");
SPWeb web = site.OpenWeb();
SPList list = web.Lists["Contacts"];

// Instantiate the web part
ListViewWebPart wp = new ListViewWebPart();
wp.ZoneID = "Left";
wp.ListName = list.ID.ToString("B").ToUpper();
wp.ViewGuid = list.DefaultView.ID.ToString("B").ToUpper();

// Get the web part collection
SPWebPartCollection coll =
web.GetWebPartCollection("default.aspx",
Storage.Shared);

// Add the web part
coll.Add(wp);

First you get a reference to the SPWeb in which you want to add the web part, and to the list you want to use (in this example the Contacts list). Next you create an instance of the ListViewWebPart class, in which you can set the ZoneID, the ListName and the ViewGuid. This is the tricky part, the ListName property should contain the ID of your list (a GUID), not the name of your list!! But the ListName property is of the type string, so you need to convert the List GUID to a string using .ToString(“B”).ToUpper(). The same goes for the ViewGuid. Finally you need to get a reference to the WebPartCollection for the page in which you want to add the web part (in this example the home page, being default.aspx). Now you can add the web part using the Add method.

For the second scenario, the code is as follows:

// Get a reference to a web and a list

SPSite site = new SPSite("http://localhost:8000");
SPWeb web = site.OpenWeb();

// Get the web part collection
SPWebPartCollection coll =
web.GetWebPartCollection("default.aspx",
Storage.Shared);

string dwp = @"
http://www.w3.org/2001/XMLSchema"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns=""http://schemas.microsoft.com/WebPart/v2"">
SmartPart List 1.0.0.0 Left
SmartPart, Version=1.0.0.0, Culture=neutral,
PublicKeyToken=dd064a5b12b5277a

SmartPart.UserControlWebpart

~\UserControls
"
;

coll.Add(dwp);
The first section is the same, get a reference to your site and the WebPartCollection (you don’t need a reference to a list). Next you need to build a XML string containing the information about the web part you want to add. The contents of that string are the same as the DWP file that you need to create to use your custom web parts. A trick to figure out what needs to be in there (especially if you want to specify values for some properties) is to put the web part on a page (using the web interface), and choose “Export” from the dropdown menu of the web part. This will save the contents of the DWP in a file. Finally you can add the web part by calling the Add method of the WebPartCollection and using the dwp string as a parameter.


I have recently had to come up with a way to programmatically add a Web Part to a large number of existing publishing pages. It took me a little while to find the exact way to do it, so I thought I would post the source code here.

Attached is the C# code that will iterate over a bunch of pages in a bunch of sites, and then add a doclib Web Part on all those pages, in a specific Web Part Zone. The meat of the code is this:
SPSite mySiteCollection = new SPSite("http://sharepoint");
SPWeb w = mySiteCollection.AllWebs["/whatever"];
SPFile f = w.GetFile("Pages/Page.aspx");
SPLimitedWebPartManager wpm = f.GetLimitedWebPartManager(PersonalizationScope.Shared);
SPList l = w.Lists["Documents"];
ListViewWebPart wp = new ListViewWebPart();
wp.ListName = l.ID.ToString("B").ToUpper();
wp.ViewGuid = l.DefaultView.ID.ToString("B").ToUpper();
wpm.AddWebPart(wp, "Zone 1", 1);
f.Publish("Added Web Part");
f.Approve("Web Part addition approved");

This bit of code uses an SPLimitedWebPartManager to add the ListViewWebPart to the "Zone 1" Web Part Zone. The page is then published and approved.

Kaynak:
http://blogs.msdn.com/tconte/archive/2007/01/18/programmatically-adding-web-parts-to-a-page.aspx

18 Ocak 2008 Cuma

Javascript ile sadece numerik girişi kontrolü

http://www.webmasterworld.com/javascript/3519735.हतं

adresindeki

/** * A helpful link: http://www.quirksmode.org/js/keys.html * The event will have two different properties: * keyCode: the actual keyboard key the user pressed * charCode: the ASCII value of the resulting character * * onkeypress events register in different properties for each of the * browsers, some in the charCode, others in the keyCode. And some * will not register keyboard movement keys whatsoever so the * onkeypress event will not even be fired at all. With onkeydown/up * the keyCode always holds the key code. * // +-----------------------------------------------------------------------+ * For instance, a lower case 'a' and an upper case 'A' have the same * keyCode because the user presses the same key, but a different charCode * because the resulting character is different. Explorer and Opera do not * support charCode. However, they give the character information in the * keyCode, but only onkeypress. Onkeydown/up keyCode contains the key info. * * Some general definitions of onkeypress events: * ------------------------------------------------ * character: numeric value of keyboard character key (alphanumeric, etc.) * movement: numeric value of keyboard "movement" key (up, delete, etc.) * * The following table shows which event property will be populated for two * of the major browsers. Windows onkeypress will not register movement * keys so the event would be undefined. * * Event event.charCode event.keyCode * --------- -------------- ------------- * character Mozilla Windows * movement Mozilla * * character keys: * ------------------- * 44 Comma * 46 Period * 48-57 Digits 0-9 * movement keys: * ------------------- * 8 Backspace * 9 Tab * 32 Space * 33 Page Up * 34 Page Down * 35 End * 36 Home * 37 Arrow Left * 38 Arrow Up * 39 Arrow Right * 40 Arrow Down * 46 Delete * 48-57 Digits 0-9 */ function checkMoneyOnlyMillions(elm, desc, msg) { desc = (desc)? desc : elm.name msg = (msg)? false : true var reMoneyOnly = /^\d{0,9}(\.\d{0,2})?$/ if (elm.value &&!reMoneyOnly.test(elm.value)) { if (msg) { alert('The ' + desc + ' accepts monetary values only, up to the millions with two decimal places (123456789.12).') elm.focus() elm.select() } return false } return true } function checkNumbersOnly(elm, desc, msg) { desc = (desc)? desc : elm.name msg = (msg)? false : true var reNumbersOnly = /[^\d]/ if (elm.value &&!reNumbersOnly.test(elm.value)) { if (msg) { alert('This field accepts decimal numbers only.') elm.focus() } return false } return true } function numOnly(evt) { evt = (evt)? evt : ((window.event)? window.event : "") if (evt) { var charCode = (evt.charCode)? evt.charCode : evt.keyCode // Backspace (8), tab (9), space (32), page up/down (33-34), end (35), home (36), arrow keys (37-40), delete (Mozilla.event.keyCode=46), digits 0-9 (48-57) // MSIE movement keys do not register a keyCode event (the evt.which property will be 'undefined'; Mozilla registers 0) if ((charCode!= 8 && charCode!= 9) && charCode <> 40 && charCode <> 57) { window.status = "This field accepts numbers only." return false } } window.status = "" return true } function moneyOnly(evt) { evt = (evt)? evt : ((window.event)? window.event : "") if (evt) { // evt.which and evt.charCode are undefined in Windows, evt.keyCode is the keyboard character value in Windows (keyboard movement keys do not trigger an onkeypress event!) // evt.which is the keyboard character value in Mozilla, evt.keyCode is the keyboard movement keys in Mozilla var charCode = (evt.charCode)? evt.charCode : evt.keyCode if (charCode!= 46 &&!numOnly(evt)) { window.status = "This field accepts monetary values only." return false } window.status = "" return true } }