# Tuesday, February 23, 2010
protected void Page_Load(object sender, EventArgs e)
{

   StringBuilder strContent = new StringBuilder();

   try
   {
      using(EntitiesDataContext context = new EntitiesDataContext("http://sharepoint/Development"))
      {
         var q = from companie in context.Companies
                 select new
                 {
                    companie.Title
                 };

         strContent.Append("<table border=\"1\" cellpadding=\"3\" cellspacing=\"3\">");

         foreach (var companie in q)
         {
            strContent.Append("<tr><td>" + companie.Title + "</td></tr>");
         }

         strContent.Append("</table>");
      }
   }

   catch (Exception ex)
   {
      strContent.Append(ex.ToString());
   }

   mainDiv.InnerHtml = strContent.ToString();
}
You must create Entities.cs with SPMetal Utility. You can download sample project
LINQVisualWebPartSample.zip (124,08 KB)
posted on Tuesday, February 23, 2010 12:55:38 PM (GMT Standard Time, UTC+00:00)  #    Comments [0] Trackback
# Monday, February 22, 2010

In this sample you will create a Windows Application for retrieving Sharepoint lists. Step by step instructions :

  • Add a reference to the Client Object Model. You can find Microsoft.Sharepoint.Client.dll ve Microsoft.Sharepoint.Client.Runtime.dll in C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\ISAPI folder.
  • Drag a TextBox control onto Form1.
  • Drag a ListBox control onto Form1.
  • Drag a Button control onto Form1.
  • Add using statement to your project cs file

    using ClientOM = Microsoft.Sharepoint.Client;
  • Enter the following code in the button1_Click event to retrieve data.

    private void button1_Click(object sender, EventArgs e)
    {
        this.Cursor = Cursors.WaitCursor;
        listBox1.Items.Clear();
    
        using (ClientOM.ClientContext ctx = 
    new ClientOM.ClientContext(textBox1.Text))
        {
            ClientOM.Web site = ctx.Web;
            ctx.Load(site);
            ctx.Load(site.Lists);
            ctx.Load(site,
                x => x.Lists.Where(l => l.Title != null));
            ctx.ExecuteQuery();
            foreach (ClientOM.List list in site.Lists)
            {
                listBox1.Items.Add(list.Title);
            }
        }
        this.Cursor = Cursors.Default;
    }

Result :

posted on Monday, February 22, 2010 12:58:14 PM (GMT Standard Time, UTC+00:00)  #    Comments [0] Trackback

If you type SPSecurity, Visual Studio 2010's intellisense does not recognize it as a valid object, but once you type the entire line out, Visual Studio won't add the red underlined squiggle line indicating a syntax error. This is because when creating sandboxed solutions, you are still building against the full Sharepoint Object Model, but Visual Studio uses a different intellisense file to help the developer know which objects they will not have access to when the component runs in the sandboz.

Your sandboxed solution cannot include a reference to the SPSecurity type. If you use similar to following syntax

SPSecurity.RunWithElevated Priviliges(delegate
{
   //Your Code
});

You show the error like

posted on Monday, February 22, 2010 12:02:16 PM (GMT Standard Time, UTC+00:00)  #    Comments [0] Trackback

Before you can deploy sandboxed solutions to the Sharepoint Server, your server must be configured for this. To configure, open Sharepoint 2010 Central Administration site and choose System Settings > Services on Server. Locate Microsoft Sharepoint Foundation User Code Service and check its status. If it's stopped, click the start hyperlink.

Now, web can create our first sandboxed solution.

Step by step instructions :

  • Open Visual Studio 2010 and choose to create a new project. Pick Empty Project under Visual C# > Sharepoint > 2010 template group.
  • Name your project as "SandboxedWebPart"


  • Choose your debugging site URL and check "Deploy as a sandboxed solution".
  • In Visual Studio 2010 Solution Explorer right click the solution name and select Add > New Item. Add a Web Part to your project.
  • Expand features, right click Feature1 and choose View Designer. In the designer, verify the Scope. It should be set to site.


  • In WebPart1.cs, add the following code in CreateChildControls method

    protected override void CreateChildControls()
    {
        Label message = new Label();
        Controls.Add(message);
    
        Controls.Add(new WebControl(HtmlTextWriterTag.Br));
    
        Button testButton1 = new Button();
        testButton1.Text = "Test 1";
        testButton1.Click += delegate
        {
            message.Text = String.Format("This site contains {0} lists",
                SPContext.Current.Web.Lists.Count);
        };
        Controls.Add(testButton1);
    }
  • Then deploy it. (Right click solution name and select "Deploy")
  • To show your web part, open your browser and navigate to the site. On the ribbon, select Page tab and choose Edit Page. Select a web part zone and add your web part.
posted on Monday, February 22, 2010 11:46:46 AM (GMT Standard Time, UTC+00:00)  #    Comments [0] Trackback
# Thursday, February 11, 2010
posted on Thursday, February 11, 2010 6:53:15 AM (GMT Standard Time, UTC+00:00)  #    Comments [0] Trackback
# Friday, January 29, 2010

Required using statements

using Microsoft.SharePoint;
using Microsoft.Office.Server;
using Microsoft.Office.Server.UserProfiles;

Then sample code

try
{
   site = SPContext.Current.Site;
   ServerContext serverContext = ServerContext.GetContext(site);
   UserProfileManager userProfileManager = new UserProfileManager(serverContext);
   UserProfile currentUserUserProfile = userProfileManager.GetUserProfile(System.Web.HttpContext.Current.User.Identity.Name);

   string nameSurname = (string)currentUserUserProfile["preferredname"].Value;
   string email = (string)currentUserUserProfile["workemail"].Value;
   string companyName = (string)currentUserUserProfile["company"].Value;
}
finally
{
   site.RootWeb.Dispose();
   site.Dispose();
}
posted on Friday, January 29, 2010 1:13:28 PM (GMT Standard Time, UTC+00:00)  #    Comments [0] Trackback
# Thursday, January 28, 2010
SPFieldLookupValue category = new SPFieldLookupValue(1, "Books");

and then use it to set field value

item["Category"] = category
posted on Thursday, January 28, 2010 12:11:57 PM (GMT Standard Time, UTC+00:00)  #    Comments [0] Trackback
        static void Main(string[] args)
        {
            SPSite site = null;
            SPWeb web = null;

            try
            {
                site = new SPSite("http://testSite/SubWeb/Pages/");
                web = site.OpenWeb();
                PublishingWeb publishingWeb = PublishingWeb.GetPublishingWeb(web);
                SPContentTypeId contentType = new SPContentTypeId("YourContentTypeId");
                PageLayout[] layouts = publishingWeb.GetAvailablePageLayouts(contentType);
                PageLayout pageLayout = layouts[0];
                string pageName = Guid.NewGuid().ToString() + ".aspx";

                SPUser user = web.EnsureUser("DOMAIN\\USERNAME");
                string createdDate = "2009-11-05T22:35:10Z";
                string modifiedDate = "2009-11-05T22:35:10Z";

                web.AllowUnsafeUpdates = true;
                PublishingPage newPage = publishingWeb.GetPublishingPages().Add(pageName, pageLayout);

                newPage.ListItem["Author"] = user.ID;
                newPage.ListItem["Editor"] = user.ID;
                newPage.ListItem["Created"] = createdDate;
                newPage.ListItem["Modified"] = modifiedDate;
                newPage.ListItem.UpdateOverwriteVersion();

                web.AllowUnsafeUpdates = false;

                Console.WriteLine("OK");
                Console.ReadLine();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
                Console.ReadLine();
            }
            finally
            {
                web.Dispose();
                site.RootWeb.Dispose();
                site.Dispose();
            }
        }
posted on Thursday, January 28, 2010 12:06:33 PM (GMT Standard Time, UTC+00:00)  #    Comments [0] Trackback
        static void Main(string[] args)
        {
            SPSite site = null;
            SPWeb web = null;

            try
            {
                site = new SPSite("http://testsite/subweb/Pages/");
                web = site.OpenWeb();
                PublishingWeb publishingWeb = PublishingWeb.GetPublishingWeb(web);
                SPContentTypeId contentType = new SPContentTypeId("YourContentTypeID");
                PageLayout[] layouts = publishingWeb.GetAvailablePageLayouts(contentType);
                PageLayout pageLayout = layouts[0];
                string pageName = "PageName.aspx";

                PublishingPage newPage = publishingWeb.GetPublishingPages().Add(pageName, pageLayout);
                newPage.Update();
                newPage.ListItem.File.CheckIn("created");
                newPage.ListItem.File.Publish("created");

                Console.WriteLine(newPage.Url);
                Console.WriteLine("OK");
                Console.ReadLine();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
                Console.ReadLine();
            }
            finally
            {
                web.Dispose();
                site.RootWeb.Dispose();
                site.Dispose();
            }
        }
posted on Thursday, January 28, 2010 8:39:37 AM (GMT Standard Time, UTC+00:00)  #    Comments [0] Trackback
# Tuesday, January 12, 2010

1) The first example is a custom field type that you can add to any document library and that returns the main properties of any document by
clicking on it in a fast and user-friendly way. Thanks to the jQuery code embedded in the CAML of the custom field type, the properties are returned via an AJAX query that calls lists.asmx to get the properties. 
This example is the main topic of the video and is rebuilt from scratch.

2). The secund example will be available for download and is overviewed during the video. It's a custom SharePoint calendar where users can type locations in a textbox. All the matching events are highlighted within the calendar directly (they blink) and direct links to the events are shown above the input textbox. 

Again, same principle than for the first example (query to lists.asmx) but this time the jQuery code is isolated in a separate JS file and both the jquery javascript file and the custom one are included OnPreRender of the custom calendar control.

To watch this video, click here.

posted on Tuesday, January 12, 2010 9:09:29 AM (GMT Standard Time, UTC+00:00)  #    Comments [1] Trackback

jQuery is a fast and concise JavaScript Library that simplifies HTML document traversing, event handling, animating, and Ajax interactions for rapid web development (wikipedia article). It was created by John Resig and dual licensed under the MIT License and the GNU General Public License, jQuery is free and open source software.

Marc D. Anderson developed a jQuery library names "jQuery Library for SharePoint Web Services" which abstracts SharePoint's Web Services and makes them easier to use. It also includes functions which use the various Web Service operations to provide more useful (and cool) capabilities. It works entirely client side and requires no server install.

You can download it or you can read blog posts about this project(on Marc D. Anderson's blog)

posted on Tuesday, January 12, 2010 9:04:06 AM (GMT Standard Time, UTC+00:00)  #    Comments [2] Trackback

1. New SharePoint APIs – The new UI framework has more extensibility in the ribbon and natively uses XSLT DataViews in lists vs. previous CAML views. There are new APIs for AJAX and Silverlight applications that make it make it much easier to access SharePoint data with less code and better performance. Improved list access and programmability with REST, ATOM, JSON and LINQ including richer data relationship, validation, joins and projections over SharePoint lists.

2. Application Lifecycle – WSP as the packaging and deployment format for SharePoint solutions. You can save as WSP in SPD and bring that into Visual Studio 2010.

3. Visual Studio 2010 Support – SharePoint 2010 is a first class target for Visual Studio 2010. This includes F5 deployment and debugging as well as designers for various SharePoint project types, web parts, workflow, business connectivity services and integration with the VS Server Explorer. The early feedback on this has been so great, we decided to highlight it in Steve Ballmer's keynote at the SharePoint Conference.

4. Developer Dashboard View – If you have the rights, you can turn on a mode for a SharePoint page which will render at the bottom to show full trace and latency through the SharePoint, .NET and SQL layers. You can use reporting tools described earlier to identify any slow pages in your site and then turn on this view to see a custom web part has bogged down the page by making repeated expensive SharePoint object model calls.

5. Development on Windows 7 – Development on Windows 7 and Vista client machines supported. Although it isn’t a supported configuration for production.


Reference :
http://blogs.msdn.com/sharepoint/archive/2009/10/19/sharepoint-2010.aspx

posted on Tuesday, January 12, 2010 7:57:06 AM (GMT Standard Time, UTC+00:00)  #    Comments [1] Trackback
# Monday, January 11, 2010

Resolution

  • Go to the windows directory and find the TEMP folder. (c:\windows\TEMP) Right click the TEMP folder and select the security tab.
  • Click the add button for adding a new user. Write the name "network service". Give Read/Write rights and click OK.
  • Go to the location c:\windows\system32\Logfiles. Write the name "network service". Give Read/Write rights and click OK.
posted on Monday, January 11, 2010 2:19:53 PM (GMT Standard Time, UTC+00:00)  #    Comments [1] Trackback
  • STS#0 Team Site
  • STS#1 Blank Site
  • STS#2 Document Workspace
  • MPS#0 Basic Meeting Workspace
  • MPS#1 Blank Meeting Workspace
  • MPS#2 Decision Meeting Workspace
  • MPS#3 Social Meeting Workspace
  • MPS#4 Multipage Meeting Workspace
  • WIKI#0 Wiki
  • BLOG#0 Blog

You can use it on your code which creates subwebs programmatically.

SPContext.Current.Web.AllowUnsafeUpdates = true;
SPWebCollection webs = SPContext.Current.Web.Webs;
objWebs.Add("Sample Site", "Sample Site", "This is the Sample Site", 1033,"STS#0", true, false);
SPContext.Current.Web.AllowUnsafeUpdates = false;
posted on Monday, January 11, 2010 1:38:43 PM (GMT Standard Time, UTC+00:00)  #    Comments [1] Trackback
# Wednesday, December 30, 2009

The SharePoint 2010 Beta Developer Training Kit provides developers with deep guidance on how to develop for SharePoint 2010. Through PowerPoint decks, Hands-On Labs, Source Code, and Instructor-Led Videos, the developer kit walks you through an array of important developer topics--including Developer Roadmap, Visual Studio tooling, Workflow, Business Connectivity Services, and much, much more.

You can watch videos at Channel9 and you can download training kit via this link.

posted on Wednesday, December 30, 2009 1:22:23 PM (GMT Standard Time, UTC+00:00)  #    Comments [5] Trackback
# Monday, June 15, 2009
Wrong Way  
SPAttachmentCollection attachments = listitem.Attachments;  
foreach (SPFile file in attachments)
{    
   //Something

 

True  
SPFolder folder = web.Folders["Lists"].SubFolders[list.Title].SubFolders["Attachments"].SubFolders[listitem.ID.ToString()];  

Then you can do:   foreach (SPFile file in folder.Files) {   // Something  }
posted on Monday, June 15, 2009 11:30:33 AM (GMT Daylight Time, UTC+01:00)  #    Comments [9] Trackback
# Saturday, June 06, 2009

SPSite  _site =  new   SPSite ( " http://portal " );
SPWeb web = _site.AllWebs[0];
Microsoft.SharePoint.SPList list = web.SiteUserInfoList;
Microsoft.SharePoint.SPUser user = web.SiteUsers["DOMAIN\\portal.user1"];
Microsoft.SharePoint.SPListItem item = list.Items.GetItemById(user.ID);
item["Picture"] ="http://portal/SiteCollectionImages/portaluser1.jpg";
item.Update();

posted on Saturday, June 06, 2009 11:28:34 AM (GMT Daylight Time, UTC+01:00)  #    Comments [0] Trackback
# Sunday, May 17, 2009
public void  UploadFile(string srcUrl, string destUrl)
{
    if (!File.Exists(srcUrl))
    {
        throw new ArgumentException(String.Format("{0} does not exist", srcUrl), "srcUrl");
    }
 
      

   
SPWeb site = new SPSite(destUrl).OpenWeb();
 
    
    
FileStream fStream = File.OpenRead(srcUrl);
    byte[] contents = new byte[fStream.Length];
    fStream.Read(contents, 0, (int)fStream.Length);
    fStream.Close();
     EnsureParentFolder(site, destUrl);
    site.Files.Add(destUrl, contents);
}
posted on Sunday, May 17, 2009 11:20:18 AM (GMT Daylight Time, UTC+01:00)  #    Comments [0] Trackback
# Saturday, May 16, 2009
SPSite mySite = SPContext.Current.Site;
SPWebCollection allWebs = mySite.AllWebs;
 

foreach (SPWeb web in allWebs)
{
    SPListCollection allLists = web.Lists;
 
    

    
for (int i=0; i<allLists.Count; i++)
    {
        SPList list = allLists[i];
 
        

        
if (list.Title == TextBox1.Text)
        {
            Guid listGuid = list.ID;
            allLists.Delete(listGuid);
        }
    }
}
posted on Saturday, May 16, 2009 11:19:47 AM (GMT Daylight Time, UTC+01:00)  #    Comments [1] Trackback
# Sunday, May 10, 2009
string listTitle = TextBox1.Text.ToString();
string listDescription = TextBox2.Text.ToString();
SPSite mySite = SPContext.Current.Site;
SPWebCollection allWebs = mySite.AllWebs;
 

foreach (SPWeb web in allWebs)
{
    SPListCollection allLists = web.Lists;
    allLists.Add(listTitle,listDescription, SPListTemplateType.GenericList);
}
posted on Sunday, May 10, 2009 11:19:19 AM (GMT Daylight Time, UTC+01:00)  #    Comments [0] Trackback
# Friday, May 08, 2009
SPWeb mySite = SPContext.Current.Web;
SPListItemCollection listItems = mySite.Lists[TextBox1.Text].Items;
int itemCount = listItems.Count;
 

for (int k=0; k<itemCount; k++)
{
    SPListItem item = listItems[k];
 
    

   
if (TextBox2.Text==item["Employee"].ToString())
    {
        listItems.Delete(k);
    }
}
posted on Friday, May 08, 2009 11:18:45 AM (GMT Daylight Time, UTC+01:00)  #    Comments [0] Trackback
# Wednesday, May 06, 2009
SPWeb mySite = SPContext.Current.Web;
SPListItemCollection listItems = mySite.Lists[TextBox1.Text].Items;
 
SPListItem item = listItems.Add(); item["Title"] = TextBox2.Text;
item["Stock"] = Convert.ToInt32(TextBox3.Text);
item["Return Date"] = Convert.ToDateTime(TextBox4.Text);
item["Employee"] = TextBox5.Text;
item.Update();
posted on Wednesday, May 06, 2009 11:18:15 AM (GMT Daylight Time, UTC+01:00)  #    Comments [0] Trackback
# Tuesday, May 05, 2009

SPWeb mySite = SPContext.Current.Web;
SPListCollection lists = mySite.Lists;

string listTitle = TextBox1.Text;
string listDescription = TextBox2.Text;
string listType = ListBox1.SelectedItem.Text;

SPListTemplateType listTemplateType = new SPListTemplateType();

switch(listType)
{
    case "Generic List":
    {
        listTemplateType = SPListTemplateType.GenericList;
        break;
    }

    case "Events":
    {
        listTemplateType = SPListTemplateType.Events;
        break;
    }

    case "Announcements":
    {
        listTemplateType = SPListTemplateType.Announcements;
        break;
    }
}

lists.Add(listTitle, listDescription, listTemplateType);

posted on Tuesday, May 05, 2009 11:17:57 AM (GMT Daylight Time, UTC+01:00)  #    Comments [0] Trackback
# Saturday, May 02, 2009
sitesWebServiceLists.Lists listService = new sitesWebServiceLists.Lists();
listService.Credentials = System.Net.CredentialCache.DefaultCredentials;
listService.Url = "http://MyServer/sites/MySiteCollection/_vti_bin/Lists.asmx";  
System.Xml.XmlNode ndListView = listService.GetListAndView("MyList", "");
string strListID = ndListView.ChildNodes[0].Attributes["Name"].Value;
string strViewID = ndListView.ChildNodes[1].Attributes["Name"].Value;
 
System.Xml.XmlDocument doc = new System.Xml.XmlDocument();
System.Xml.XmlElement batchElement = doc.CreateElement("Batch");

batchElement.SetAttribute("OnError", "Continue");
batchElement.SetAttribute("ListVersion", "1");

batchElement.SetAttribute("ViewName", strViewID);
  batchElement.InnerXml = "<Method ID='1' Cmd='Update'>" +
   "<Field Name='ID'>6</Field>" +
   "<Field Name='Title'>Modified sixth item</Field></Method>" +
   "<Method ID='2' Cmd='Update'><Field Name='ID'>7</Field>" +
   "<Field Name='Title'>Modified seventh item</Field></Method>" +
   "<Method ID='3' Cmd='Delete'><Field Name='ID'>5</Field>" +
   "</Method><Method ID='4' Cmd='New'>" +
   "<Field Name='Title'>Added item</Field></Method>";

try
{
   listService.UpdateListItems(strListID, batchElement);
}
catch (SoapServerException ex)
{
   MessageBox.Show(ex.Message);
}
posted on Saturday, May 02, 2009 11:16:52 AM (GMT Daylight Time, UTC+01:00)  #    Comments [0] Trackback
# Friday, May 01, 2009
Web_Reference.Lists myservice = new Web_Reference.Lists();
myservice.Credentials = System.Net.CredentialCache.DefaultCredentials;
listService.Url = "http://Server_Name/Subsite_Name/_vti_bin/Lists.asmx";
System.Xml.XmlNode node = myservice.GetListCollection();
 

foreach(System.Xml.XmlNode xmlnode in node) 
{
   label1.Text+=xmlnode.Attributes["Title"].Value + "\n";
}
posted on Friday, May 01, 2009 11:16:31 AM (GMT Daylight Time, UTC+01:00)  #    Comments [0] Trackback
# Thursday, April 30, 2009

Web_Reference.UserGroup userGroup = new Web_Reference.UserGroup();
userGroup.Credentials = System.Net.CredentialCache.DefaultCredentials;
userGroup.Url = "http://Server_Name/Subsite_Name/_vti_bin/UserGroup.asmx";
System.Xml.XmlNode usersSite = userGroup.GetUserCollectionFromWeb();
System.Xml.XmlNode userNode = usersSite.FirstChild;
userGroup.AddUserCollectionToGroup("Group_Name",userNode);

posted on Thursday, April 30, 2009 11:15:58 AM (GMT Daylight Time, UTC+01:00)  #    Comments [0] Trackback
# Sunday, April 26, 2009
imagingService.Imaging wsObject = new imagingService.Imaging();
wsObject.Url = "http://<portal_site>/_vti_bin/Imaging.asmx";
wsObject.Credentials = System.Net.CredentialCache.DefaultCredentials;
 
System.IO.FileStream fs = new System.IO.FileStream("C:\\mypicture.jpg", System.IO.FileMode.Open);
byte[] fileBytes = new byte[fs.Length];
fs.Read(fileBytes, 0, (int)fs.Length);
string url = "
http://<portal_site>/DocLibName/ ";
System.Xml.XmlNode result = wsObject.Upload(url, "", fileBytes, "mypicture.jpg", true);
posted on Sunday, April 26, 2009 11:15:28 AM (GMT Daylight Time, UTC+01:00)  #    Comments [0] Trackback
# Saturday, April 25, 2009
comboBox1.Items.Clear();
dws.Webs wsObject = new dws.Webs();
wsObject.Url = "http://<portal_site_adi>/_vti_bin/Webs.asmx";
wsObject.Credentials = System.Net.CredentialCache.DefaultCredentials;
System.Xml.XmlNode node = wsObject.GetWebCollection();
System.Xml.XmlNodeList nodeList = node.ChildNodes;
 

foreach (System.Xml.XmlNode webObj in nodeList)
{
     comboBox1.Items.Add(webObj .Attributes["Title"].Value);
}
 

comboBox1.Text = "Site List is Ready!";
posted on Saturday, April 25, 2009 11:14:49 AM (GMT Daylight Time, UTC+01:00)  #    Comments [0] Trackback
# Sunday, April 19, 2009
        public enum myFarmEnum
        {
            otobus = 0,
            traktor,
            otomobil
        };

        protected myFarmEnum _myEnum; 
          
        [Category("Custom Properties")]
        [DefaultValue(myFarmEnum.hay)]
        [WebPartStorage(Storage.Personal)]
        [FriendlyName("Custom Enum")]
        [Description("Select a value from the dropdown list.")]
        [Browsable(true)]
        public myFarmEnum MyEnum
        {
            get
            {
                return _myEnum;
            }
            set
            {
                _myEnum = value;
            }
        }
posted on Sunday, April 19, 2009 11:12:44 AM (GMT Daylight Time, UTC+01:00)  #    Comments [0] Trackback

        private System.DateTime _myDateTime;
        [Category("Custom Properties")]
        [WebPartStorage(Storage.Personal)]
        [FriendlyNameAttribute("Custom Date Time")]
        [Description("Type a DateTime value.")]
        [Browsable(true)]
        [XmlElement(typeof(System.DateTime))]
        public System.DateTime MyDateTime
        {
            
get
            
{
                return _myDateTime;
            }
            set
            {
                _myDateTime = value;
            }
        }

posted on Sunday, April 19, 2009 11:12:21 AM (GMT Daylight Time, UTC+01:00)  #    Comments [0] Trackback
        private float _myFloat;          
        [Category("Custom Properties")]
        [DefaultValue(c_MyFloatDefault)]
        [WebPartStorage(Storage.Personal)]
        [FriendlyNameAttribute("Custom Float")]
        [Description("Type a floating point value.")]
        [Browsable(true)]
        [XmlElement(ElementName = "MyFloat")]
        public float MyFloat
        {
            get
            {
                return _myFloat;
            }
            set
            {
                _myFloat = value;
            }
        }
posted on Sunday, April 19, 2009 11:11:55 AM (GMT Daylight Time, UTC+01:00)  #    Comments [0] Trackback
        private int _myInt;          
        [Category("Custom Properties")]
        [DefaultValue(c_MyIntDefault)]
        [WebPartStorage(Storage.Personal)]
        [FriendlyNameAttribute("Custom Integer")]
        [Description("Type an integer value.")]
        [Browsable(true)]
        [XmlElement(ElementName = "MyInt")]
        public int MyInt
        {
            get
            {
                return _myInt;
            }
            set
            {
                _myInt = value;
            }
        }
posted on Sunday, April 19, 2009 11:11:29 AM (GMT Daylight Time, UTC+01:00)  #    Comments [0] Trackback

        private bool _myBool;          
       
[Category("Custom Properties")]
        [DefaultValue(c_MyBoolDefault)]
        [WebPartStorage(Storage.Personal)]
        [FriendlyNameAttribute("Custom Boolean")]
        [Description("Select to set value to True.")]
        [Browsable(true)]
        [XmlElement(ElementName = "MyBoolean")]
        public bool MyBool
        {
            get
            {
                return _myBool;
            }
            set
            {
                _myBool = value;
            }
        }

posted on Sunday, April 19, 2009 11:10:56 AM (GMT Daylight Time, UTC+01:00)  #    Comments [0] Trackback
        private string _myString;          
        [Category("Custom Properties")]
        [DefaultValue(c_MyStringDefault)]
        [WebPartStorage(Storage.Personal)]
        [FriendlyNameAttribute("Custom String")]
        [Description("Type a string value.")]
        [Browsable(true)]
        [XmlElement(ElementName = "MyString")]
        public string MyString
        {
            get
            {
                return _myString;
            }
            set
            {
                _myString = value;
            }
        }
posted on Sunday, April 19, 2009 11:10:25 AM (GMT Daylight Time, UTC+01:00)  #    Comments [0] Trackback
# Thursday, April 02, 2009

namespace  DataViewer

{

     public   class   DataView  :  WebPart

     {

         Button  btn;

         GridView  gv;

         protected   override void  CreateChildControls()

        {

            btn =  new  Button();

            btn.Text =  "Data Getir" ;

            btn.Click +=  new EventHandler(btn_DataGetir);

            gv =  new   GridView ();

            this.Controls.Add(btn);

            this.Controls.Add( new   LiteralControl ( "<br>" ));

            this.Controls.Add(gv);

        }

         public   void btn_DataGetir( object  sender,  EventArgs  e)

        {

            DataSet  ds = getData();

            gv.DataSource = ds.Tables[0];

            gv.DataBind();

        }

         public   DataSet getData()

        {

            DataSet  ds =  new DataSet ();

            DataTable  dt =  new   DataTable ();

            dt.Columns.Add( "Alan1" , Type.GetType( "System.String" ));

            dt.Columns.Add( "Alan2" , Type.GetType( "System.String" ));

            dt.Columns.Add( "Alan3" , Type.GetType( "System.String" ));

            DataRow dr;

 

            for  ( int i = 0; i < 10; i++)

            {

                dr = dt.NewRow();

                dr["Alan1"] =  "TestVeriA"  + i;

                dr["Alan2"] =  "TestVeriB"  + i;

                dr["Alan3"] =  "TestVeriC"  + i;

                dt.Rows.Add(dr);

            }

            ds.Tables.Add(dt);

            return  ds;

        }

     }

}

posted on Thursday, April 02, 2009 10:00:30 AM (GMT Daylight Time, UTC+01:00)  #    Comments [0] Trackback
# Wednesday, April 01, 2009

using  System;

using  System.Collections.Generic;

using  System.Text;

using  System.Web.UI;

using  System.Web.UI.WebControls;

using  System.Web.UI.WebControls.WebParts;

namespace  SimpleCalculator

{

     public   class   Calculator :  WebPart

     {

         TextBox tbA;

         TextBox tbB;

         TextBox tbResult;

         Button btnAdd;

         Button btnSub;

 

         protected override   void CreateChildControls()

        {

            base.CreateChildControls();

            EnsurePanelFix();

              UpdatePanel  refreshCalculation =  new   UpdatePanel ();

            ScriptManager scriptHandler =  new   ScriptManager ();

            tbA =  new   TextBox ();

            tbB =  new   TextBox ();

            tbResult =  new   TextBox ();

            btnAdd =  new   Button ();

            btnSub =  new   Button ();

            tbResult.ReadOnly =  true ;

            btnAdd.Text =  "+" ;

            btnSub.Text =  "-" ;

 

        scriptHandler.ID =  "scriptHandler" ;

        refreshCalculation.ID =  "refreshName" ;

        refreshCalculation.UpdateMode = UpdatePanelUpdateMode.Always;

        refreshCalculation.ChildrenAsTriggers =  true ;

        btnAdd.Click +=  new   EventHandler (btnAdd_Click);

        btnSub.Click +=  new   EventHandler (btnSub_Click);

        refreshCalculation.ContentTemplateContainer.Controls.Add(tbA);

        refreshCalculation.ContentTemplateContainer.Controls.Add(newLiteralControl( "<br>" ));

        refreshCalculation.ContentTemplateContainer.Controls.Add(tbB);

        refreshCalculation.ContentTemplateContainer.Controls.Add(newLiteralControl( "<br>" ));

        refreshCalculation.ContentTemplateContainer.Controls.Add(btnAdd);

        refreshCalculation.ContentTemplateContainer.Controls.Add(btnSub);

        refreshCalculation.ContentTemplateContainer.Controls.Add(newLiteralControl( "<br>" ));

        refreshCalculation.ContentTemplateContainer.Controls.Add(tbResult);

        this .Controls.Add(scriptHandler);

        this .Controls.Add(refreshCalculation);

        }

 

         void  btnAdd_Click( object sender,  EventArgs e)

        {

            int  a =  int .Parse(tbA.Text);

              int  b=  int .Parse(tbB.Text);

            int  c = a + b;

            tbResult.Text = c.ToString();

        }

 

         void  btnSub_Click( object sender,  EventArgs e)

        {

            int  a =  int .Parse(tbA.Text);

            int  b =  int .Parse(tbB.Text);

            int  c = a - b;

            tbResult.Text = c.ToString();

        }

         private   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;

                }

              }

              varRestoreToOriginalFormActionCore =

               RestoreToOriginalFormAction;

             RestoreToOriginalFormAction = function()

              {

                if(_spOriginalFormAction != null)

                {

                 RestoreToOriginalFormActionCore();

                 document.forms[0]._initialAction =

                   document.forms[0].action;

                }

              }" ;

                  ScriptManager .RegisterStartupScript( this ,

                   typeof ( Calculator ), "UpdatePanelFixup" ,

                   "_spOriginalFormAction =document.forms[0].action; _spSuppressFormOnSubmitWrapper=true;" ,  true );

            }

        }

     }

}

posted on Wednesday, April 01, 2009 10:00:03 AM (GMT Daylight Time, UTC+01:00)  #    Comments [0] Trackback
# Saturday, March 28, 2009

    class DirectoryActions
    {
        string userName, password, domain = "";
 
        
        
public DirectoryActions(string username, string password, string domain)
        {
            this.userName = username;
            this.password = password;
            this.domain = domain;
        }
          private DirectoryEntry GetDirectoryObject()
        {
            DirectoryEntry oDE;
            oDE = new DirectoryEntry("LDAP://" + domain, userName, password, AuthenticationTypes.Secure);
            return oDE;
        }
 
          

        public  DirectoryEntry GetUser(string mail)
        {
            ArrayList mylist = new ArrayList();
            DirectoryEntry de = GetDirectoryObject();
            DirectorySearcher srch = new DirectorySearcher(de);
            srch.Filter = "(&(objectClass=user)(mail=" + mail + "))";
            srch.SearchScope = SearchScope.Subtree;
            SearchResult results = srch.FindOne();
            DirectoryEntry d = results.GetDirectoryEntry();
            return d;
        }
    }

posted on Saturday, March 28, 2009 9:56:58 AM (GMT Standard Time, UTC+00:00)  #    Comments [1] Trackback
# Wednesday, March 04, 2009

void GetSites(string URLOfWebApplication) 
{
   SPSite SiteCollection = new SPSite(URLOfWebApplication); 
   SPWebCollection Site = SiteCollection.AllWebs;

   foreach (SPWeb in Site)
   {
      SiteListComboBox.Items.Add(x.ToString()); 
   }

   SiteListComboBox.Text = "Please Select a Site";
}

posted on Wednesday, March 04, 2009 9:49:40 AM (GMT Standard Time, UTC+00:00)  #    Comments [0] Trackback
# Tuesday, March 03, 2009

void GetItemsFromDocumentLibrary(string URLOfWebApplicationAndSite, stringDocumentLibrary)
{
   SPSite mysite = new SPSite(URLOfWebApplicationAndSite);

   SPWeb myweb = mysite.OpenWeb();
   SPFolder mylibrary = myweb.Folders[DocumentLibrary];
   SPFileCollection files = mylibrary.Files;

   foreach (SPFile in files) 

   { 
      ItemListBox.Items.Add(x.Name.ToString()); 
   }
}

posted on Tuesday, March 03, 2009 9:49:20 AM (GMT Standard Time, UTC+00:00)  #    Comments [0] Trackback
# Sunday, March 01, 2009
void PostFile(string URLOfWebApplication, string SiteName, string DocLibraryName, stringFilePath, string FileName, string FileExtension) 

   Stream uplFileStream = new FileStream(FilePath, FileMode.Open); 
   byte[] contents = new byte[Convert.ToInt32(uplFileStream.Length)]; 
   uplFileStream.Read(contents, 0, System.Convert.ToInt32(uplFileStream.Length)); 
   uplFileStream.Close(); 
   string docLibPath = URL + "/" + SiteName + "/" + DocLibraryName + "/"; 
  
   SPSite site = new SPSite(docLibPath); 
   SPWeb web = site.OpenWeb(); 
   SPFolder docFolder = web.GetFolder(docLibPath); 
    SPFile docFile;
   docFile = docFolder.Files.Add(FileName + FileExtension, contents);
}
posted on Sunday, March 01, 2009 9:49:01 AM (GMT Standard Time, UTC+00:00)  #    Comments [0] Trackback

SPSite site = new SPSite(" http://litwareportal:28779" ); 
SPWeb web = site.AllWebs[0]; 
SPUser user = web.AllUsers["CONTOSO\\semih"]; 
SPGroup gr = web.Groups["Home Visitors"]; 
gr.AddUser(user);

posted on Sunday, March 01, 2009 9:48:37 AM (GMT Standard Time, UTC+00:00)  #    Comments [0] Trackback
# Sunday, February 15, 2009

SPSite site = new SPSite(" http://litwareportal "); 
SPWeb web = site.AllWebs["PTS"]; 
SPUser user = web.AllUsers["LITWAREINC\\semih"]; 
SPRole rolee = web.Roles["Custom Permission Level"]; 
rolee.AddUser(user); 
Console.WriteLine("UserName : {0}", user.LoginName); 
Console.WriteLine("Site : {0}", site.Url); 
Console.WriteLine("Web : {0}", web.Url); 
Console.WriteLine("Permission Level : {0}", rolee.Name);

posted on Sunday, February 15, 2009 9:48:18 AM (GMT Standard Time, UTC+00:00)  #    Comments [0] Trackback
SPSite site1 = new SPSite(" http://litwareportal" ); 
SPWeb web1 = site1.AllWebs["PTS"]; 
SPDocumentLibrary d = (SPDocumentLibrary)web1.Lists["Document Library"];
SPUser user1 = web1.AllUsers["LITWAREINC\\semih"]; 
d.Permissions.Add(user1, SPRights.AddDelPrivateWebParts SPRights.AddListItemsSPRights.DeleteListItems);
posted on Sunday, February 15, 2009 9:47:53 AM (GMT Standard Time, UTC+00:00)  #    Comments [0] Trackback
# Thursday, February 12, 2009

In Sharepoint development we can easly read data in normal field types. Exp : Single Line of Text, Numeric, Choose, etc. But in a Person or Group field we have some problems. Because this field type stores an xml based data that includes username, domain name, user profile page url, etc. If you want to read only username data in this kind of field you must use different ways to read it.

string fieldValue = item["AssignedTo"].ToString();
SPFieldUserValue assignedTo = new SPFieldUserValue(site.AllWebs[<Your_Site>], fieldValue);
string assignedToUserName = assignedTo.User.LoginName;

posted on Thursday, February 12, 2009 9:31:29 AM (GMT Standard Time, UTC+00:00)  #    Comments [0] Trackback

SharePoint list views don't contain SPListItems or SPListItemCollections, if you want to programmatically retrieve list items from a list in the order specified by a view you've created you have to do it as follows : 

SPListItemCollection items = spWeb.Lists["ListName"].GetItems(spWebInstance.Lists["ListName"].Views ["ViewName"]);  

posted on Thursday, February 12, 2009 9:31:04 AM (GMT Standard Time, UTC+00:00)  #    Comments [0] Trackback
# Wednesday, February 11, 2009

If you want to add user's profile pictures to your existing Sharepoint application, you must add all photos to a picture library and then relate it to users profiles. If you want to do this via code you can use the following. 

 Code written by Mesut Gurbuz (Software Consultant) 

//"s" is the username parameter

SPSite _site = new SPSite(Properties.Settings.Default.SiteUrl);
ServerContext context = ServerContext.GetContext(_site);
UserProfileManager upm = new UserProfileManager(context);
UserProfile user = upm.GetUserProfile("domain\\" + s);
user["PictureURL"].Value = Properties.Settings.Default.SiteUrl + "HR/PublishingImages/" + s + ".jpg";

user.Commit();

posted on Wednesday, February 11, 2009 9:28:54 AM (GMT Standard Time, UTC+00:00)  #    Comments [0] Trackback
# Thursday, February 05, 2009

A user may not be able to reproduce or describe errors while using your application, but if you have logged critical information in your deployed application, the user can export and mail you a copy of the event log.

You can write events to Windows event log in your custom application such as web or windows. If you write Sharepoint spesific application you recieve lots of errors described "Unexpected Error" :)

our application must be registered as an event source before you can write information to the event log. You can register your application as an event source by calling the shared method EventLog.CreateEventSource.

Calling this method adds a registry entry to HKEY_LOCAL_MACHINE\SYSTEM\Services\EventLog, allowing the EventLog service to log information to the log file and display the log in the EventViewer.

In code you must add "System.Diagnostics" namespace and only the following code segment to log errors :

EventLog.WriteEntry(Source, exceptionString, EventType);

posted on Thursday, February 05, 2009 9:19:19 AM (GMT Standard Time, UTC+00:00)  #    Comments [0] Trackback