Popular Posts
Enable SSL connection for Jsoup import org.jsoup.Connection; import org.jsoup.Jsoup; import javax.net.ssl.*; import java.io.IOException; import java.security.KeyManagement... Get files name in batch Windows Batch : get filename using [%%~ni] Linux Shell Script : get filename using [awk, sed] windows sample : rename all *.htm file to ... Translating 2.0 <html> <head>     <title>Translation 2.0</title>     <meta http-equiv="content-type" content="text...
Stats
Showing posts with label SharePoint. Show all posts
Showing posts with label SharePoint. Show all posts
Active site feature
public void Main(string[] args)
{
    var siteCollectionUrl = "http://your_site_url";
    var featureId = "379c069c-c650-451c-8887-aaaf91bf5df8";
 
    using (var ctx = new ClientContext(siteCollectionUrl))
    {
        var web = ctx.Web;
        // activate feature
        ctx.Load(web);
        ctx.Load(web.Features);
        ctx.ExecuteQuery();
        web.Features.Add(new Guid(featureId), false, FeatureDefinitionScope.Site); ;
        ctx.ExecuteQuery();
    }
}
Group operation: create, grant permission and add member using client object model
public void Main(string[] args)
{
    var siteCollectionUrl = "http://your_site_url";
    var member = "domain\\account";

    using (var ctx = new ClientContext(siteCollectionUrl))
    {
        var web = ctx.Web;
        ctx.Load(web, w => w.ServerRelativeUrl);
        ctx.ExecuteQuery();

        // Create a new group named 'Contact'
        var groupInfo = new GroupCreationInformation();
        groupInfo.Title = "Contact";
        groupInfo.Description = string.Format(@"Use this group to grant people full control permissions to the SharePoint site: {0}", groupInfo.Title);
        var group = web.SiteGroups.Add(groupInfo);
        ctx.Load(group);
        ctx.ExecuteQuery();

        // Set group properties
        group.OnlyAllowMembersViewMembership = false;
        group.AllowMembersEditMembership = true;
        group.Update();
        ctx.ExecuteQuery();

        // Grant group permission
        var fullControlPermission = web.RoleDefinitions.GetByName("Full Control");
        var roleBinding = new RoleDefinitionBindingCollection(ctx);
        roleBinding.Add(fullControlPermission);
        web.RoleAssignments.Add(group, roleBinding);
        ctx.ExecuteQuery();

        // Add new member to group
        var u = web.EnsureUser(member);
        ctx.Load(u);
        ctx.ExecuteQuery();
        var userInfo = new UserCreationInformation();
        userInfo.Email = u.Email;
        userInfo.Title = u.Title;
        userInfo.LoginName = u.LoginName;
        group.Users.Add(userInfo);
        ctx.ExecuteQuery();
    }
}
Get file type icon path
/// <summary>
/// An item was added.
/// </summary>
public override void ItemAdded(SPItemEventProperties properties)
{
        var reportItem = properties.ListItem;
        // icon
        var icon = SPUtility.MapToIcon(properties.Web, reportItem["URL Path"].ToString(), "", IconSize.Size16);
        var iconPath = string.Format("/_layouts/15/images/{0}", icon);

        // do something
}
Permission Levels, SPBasePermissions, PermissionMask bit, and default assignments
enum bit Group Enum Name Name in browser Description R C D FC
12 12 List ManageLists Manage Lists Create and delete lists, add or remove columns in a list, and add or remove public views of a list. FC
10 9 List CancelCheckout Override Checkout Discard or check in a document which is checked out to another user. D FC
3 2 List AddListItems Add Items Add items to lists, add documents to document libraries, and add Web discussion comments. C D FC
4 3 List EditListItems Edit Items Edit items in lists, edit documents in document libraries, edit Web discussion comments in documents, and customize Web Part Pages in document libraries. C D FC
5 4 List DeleteListItems Delete Items Delete items from a list, documents from a document library, and Web discussion comments in documents. C D FC
2 1 List ViewListItems View Items View items in lists, documents in document libraries, and view Web discussion comments. R C D FC
6 5 List ApproveItems Approve Items Approve a minor version of a list item or document. D FC
7 6 List OpenItems Open Items View the source of documents with server-side file handlers. R C D FC
8 7 List ViewVersions View Versions View past versions of a list item or document. R C D FC
9 8 List DeleteVersions Delete Versions Delete past versions of a list item or document. C D FC
32 40 List CreateAlerts Create Alerts Create e-mail alerts. R C D FC
13 13 List ViewFormPages View Application Pages View forms, views, and application pages, and enumerate lists. R C D FC
23 26 Site ManagePermissions Manage Permissions Create and change permission levels on the Web site and assign permissions to users and groups. FC
19 22 Site ViewUsageData View Usage Data View reports on Web site usage. FC
21 24 Site ManageSubwebs Create Subsite Create subsites such as team sites, Meeting Workspace sites, and Document Workspace sites.  FC
28 31 Site ManageWeb Manage Web Site Grant the ability to perform all administration tasks for the Web site as well as manage content. Activate, deactivate, or edit properties of Web site scoped Features through the object model or through the user interface (UI). When granted on the root Web site of a site collection, activate, deactivate, or edit properties of site collection scoped Features through the object model. To browse to the Site Collection Features page and activate or deactivate site collection scoped Features through the UI, you must be a site collection administrator. FC
16 19 Site AddAndCustomizePages Add and Customize Pages Add, change, or delete HTML pages or Web Part Pages, and edit the Web site using a Windows SharePoint Services–compatible editor. D FC
17 20 Site ApplyThemeAndBorder Apply Theme and Border Apply a theme or borders to the entire Web site. D FC
18 21 Site ApplyStyleSheets Apply Style Sheets Apply a style sheet (.css file) to the Web site. D FC
22 25 Site CreateGroups Create Groups Create a group of users that can be used anywhere within the site collection. FC
24 27 Site BrowseDirectories Browse Directories Enumerate files and folders in a Web site using Microsoft Office SharePoint Designer 2007 and WebDAV interfaces. C D FC
20 23 Site CreateSSCSite Use Self-Service Site Creation Create a Web site using Self-Service Site Creation.
15 18 Site ViewPages View Pages View pages in a Web site. R C D FC
34 63 Site EnumeratePermissions Enumerate Permissions Enumerate permissions on the Web site, list, folder, document, or list item. FC
25 28 Site BrowseUserInfo Browse User Information View information about users of the Web site. R C D FC
31 39 Site ManageAlerts Manage Alerts Manage alerts for all users of the Web site. FC
30 38 Site UseRemoteAPIs Use Remote Interfaes Use SOAP, WebDAV, or Microsoft Office SharePoint Designer 2007 interfaces to access the Web site. R C D FC
29 37 Site UseClientIntegration Use Client Integration Features Use features that launch client applications; otherwise, users must work on documents locally and upload changes.  R C D FC
14 17 Site Open Open Allow users to open a Web site, list, or folder to access items inside that container. R C D FC
33 41 Site EditMyUserInfo Edit Personal User Information Allows a user to change his or her user information, such as adding a picture. C D FC
11 10 Personal ManagePersonalViews Manage Personal Views Create, change, and delete personal views of lists. C D FC
26 29 Personal AddDelPrivateWebParts Add/Remove Personal Web Parts Add or remove personal Web Parts on a Web Part Page. C D FC
27 30 Personal UpdatePersonalWebParts Update Personal Web Parts Update Web Parts to display personalized information. C D FC
1 0 EmptyMask EmptyMask Has no permissions on the Web site. Not available through the user interface.
35 1 FullMask FullMask Has all permissions on the Web site. Not available through the user interface.

From: http://techtrainingnotes.blogspot.tw/2010/01/sharepoint-permission-levels.html

Get DB Connection that store in Security store
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;
using Microsoft.SharePoint;
using Microsoft.BusinessData.Infrastructure.SecureStore;
using Microsoft.Office.SecureStoreService.Server;
using Microsoft.SharePoint.Administration;
using System.Security;
using Microsoft.SharePoint.Administration.Claims;
using System.Globalization;
using Microsoft.SharePoint.Utilities;
using System.Security.Principal;
using Microsoft.Office.Server.Diagnostics;
using System.Web;

namespace sharepoint.util
{
    public class SecureStoreCredentialLib
    {
        private const string SYSTEMACCOUNT = @"domain\\ishareadmin";

        /// <summary>
        /// Get DB Connection that store in Security store. You should add a Generic field to save your DB Instance.
        /// </summary>
        /// <param name="CredentialName"></param>
        /// <returns></returns>
        public string GetConnectionString(string CredentialName)
        {
            var connection = string.Empty;
            var username = string.Empty;
            var password = string.Empty;
            var dbinstance = string.Empty;

            SecureStoreCredentialCollection credentials = null;
            SPSecurity.RunWithElevatedPrivileges(() =>
            {
                SPContext.Current.Web.AllowUnsafeUpdates = true;
                var adminUser = SPContext.Current.Web.EnsureUser(SYSTEMACCOUNT);
                SPContext.Current.Web.AllowUnsafeUpdates = false;
                using (var site = new SPSite(SPContext.Current.Site.ID, adminUser.UserToken))
                {
                    var provider = new SecureStoreProvider();
                    var context = SPServiceContext.GetContext(site);
                    provider.Context = context;
                    credentials = provider.GetCredentials(CredentialName);
                }
            });

            if (credentials != null)
            {
                foreach (SecureStoreCredential sc in credentials)
                {
                    switch (sc.CredentialType)
                    {
                        case SecureStoreCredentialType.Generic:
                            dbinstance = SecureStoreCredentialLib.ToClrString(sc.Credential);
                            break;
                        case SecureStoreCredentialType.Key:
                            break;
                        case SecureStoreCredentialType.Password:
                            password = SecureStoreCredentialLib.ToClrString(sc.Credential);
                            break;
                        case SecureStoreCredentialType.Pin:
                            break;
                        case SecureStoreCredentialType.UserName:
                            username = SecureStoreCredentialLib.ToClrString(sc.Credential);
                            break;
                        case SecureStoreCredentialType.WindowsPassword:
                            break;
                        case SecureStoreCredentialType.WindowsUserName:
                            break;
                        default:
                            break;
                    }
                }

                connection = string.Format(
                    "Data Source={0};Initial Catalog=iShare2_SiteInfo;User ID={1};Password={2};Persist Security Info=True;",
                    dbinstance,
                    username,
                    password
                );
            }
            else
            {
                throw new Exception("Credentials is null. Cannot get credentials.");
            }

            return connection;
        }

        public SecureStoreCredentialCollection GetCredentials(string targetApplicationID)
        {
            SecureStoreCredentialCollection credentials = null;

            var iss = GetISecureStore();
            var app = iss.GetApplication(targetApplicationID);

            switch (app.Type)
            {
                case TargetApplicationType.Group:
                case TargetApplicationType.Individual:
                    credentials = iss.GetCredentials(targetApplicationID);
                    break;
                case TargetApplicationType.GroupWithTicketing:
                case TargetApplicationType.IndividualWithTicketing:
                    //Didn't test...
                    var ticket = iss.IssueTicket();
                    credentials = iss.RedeemTicket(targetApplicationID, ticket);
                    break;
                case TargetApplicationType.RestrictedGroup:
                case TargetApplicationType.RestrictedIndividual:
                    break;
                default:
                    break;
            }

            return credentials;
        }


        public void AddCredentials(string userName, string userPassword, string DBInstance, string targetApplicationID, string targetApplicationContactEmail)
        {
            CreateTargetApplication(targetApplicationID, targetApplicationContactEmail);

            var iss = GetISecureStore();
            var applicationFields = iss.GetApplicationFields(targetApplicationID);
            var creds = new List<ISecureStoreCredential>(applicationFields.Count);
            var ssClaims = iss.GetApplicationAdministratorClaims(targetApplicationID);

            using (var credentials = new SecureStoreCredentialCollection(creds))
            {
                foreach (var ssClaim in ssClaims)
                {
                    foreach (var taf in applicationFields)
                    {
                        switch (taf.CredentialType)
                        {
                            case SecureStoreCredentialType.Generic:
                                creds.Add(new SecureStoreCredential(MakeSecureString(DBInstance), SecureStoreCredentialType.Generic));
                                break;
                            case SecureStoreCredentialType.Key:
                                break;
                            case SecureStoreCredentialType.Password:
                                creds.Add(new SecureStoreCredential(MakeSecureString(userPassword), SecureStoreCredentialType.Password));
                                break;
                            case SecureStoreCredentialType.Pin:
                                break;
                            case SecureStoreCredentialType.UserName:
                                creds.Add(new SecureStoreCredential(MakeSecureString(userName), SecureStoreCredentialType.UserName));
                                break;
                            case SecureStoreCredentialType.WindowsPassword:
                                break;
                            case SecureStoreCredentialType.WindowsUserName:
                                break;
                            default:
                                break;
                        }
                    }

                    iss.SetCredentials(targetApplicationID, credentials);
                    iss.SetUserCredentials(targetApplicationID, ssClaim, credentials);
                }
            }
        }


        public void CreateTargetApplication(string targetApplicationID, string targetApplicationContactEmail)
        {
            var iss = GetISecureStore();
            var apps = iss.GetApplications();
            var result = apps.Where(a => a.ApplicationId == targetApplicationID);

            if (result.Count() == 0)
            {
                var ta = new TargetApplication(
                    targetApplicationID,
                    targetApplicationID,
                    targetApplicationContactEmail,
                    20,
                    TargetApplicationType.Individual,
                    null
                );
                var taf1 = new TargetApplicationField("UserName", false, SecureStoreCredentialType.UserName);
                var taf2 = new TargetApplicationField("Password", true, SecureStoreCredentialType.Password);
                var taf3 = new TargetApplicationField("DBInstance", false, SecureStoreCredentialType.Generic);
                var oSecureStoreServiceClaimList = new List<SecureStoreServiceClaim>();
                var claim = SPClaimProviderManager.CreateUserClaim(SYSTEMACCOUNT, SPOriginalIssuerType.Windows);
                var adminClaim = new SecureStoreServiceClaim(claim);
                oSecureStoreServiceClaimList.Add(adminClaim);
                var claimcurrent = SPClaimProviderManager.CreateUserClaim(WindowsIdentity.GetCurrent().Name, SPOriginalIssuerType.Windows);
                var ssClaimCurrent = new SecureStoreServiceClaim(claimcurrent);
                oSecureStoreServiceClaimList.Add(ssClaimCurrent);
                var targetClaims = new TargetApplicationClaims(oSecureStoreServiceClaimList, null, null);
                iss.CreateApplication(ta, new List<TargetApplicationField>() { taf1, taf2, taf3 }, targetClaims);
            }
        }

        public void DeleteTargetApplication(string targetApplicationID)
        {
            var iss = GetISecureStore();
            var apps = iss.GetApplications();
            var result = apps.Where(a => a.ApplicationId == targetApplicationID);

            if (result.Count() > 0)
            {
                iss.DeleteApplication(targetApplicationID);
            }
        }

        #region private method
        private static string ToClrString(System.Security.SecureString secureString)
        {
            var ptr = Marshal.SecureStringToBSTR(secureString);
            try
            {
                return Marshal.PtrToStringBSTR(ptr);
            }
            finally
            {
                Marshal.FreeBSTR(ptr);
            }
        }

        private static SecureString MakeSecureString(string value)
        {
            if (value == null)
            {
                return null;
            }

            var secureContent = new SecureString();
            var chArray = value.ToCharArray();

            for (int i = 0; i < chArray.Length; i++)
            {
                secureContent.AppendChar(chArray[i]);
                chArray[i] = '0';
            }
            return secureContent;
        }

        private ISecureStore GetISecureStore()
        {
            var context = SPServiceContext.GetContext(SPServiceApplicationProxyGroup.Default, SPSiteSubscriptionIdentifier.Default);
            var ssp = new SecureStoreServiceProxy();
            var iss = ssp.GetSecureStore(context);
            return iss;
        }

        private static SPSite GetCentralAdminSite()
        {
            var adminWebApp = SPAdministrationWebApplication.Local;
            SPSite adminSite = null;
            if (adminWebApp != null)
            {
                var adminSiteUri = adminWebApp.GetResponseUri(SPUrlZone.Default);
                if (adminSiteUri != null)
                {
                    adminSite = adminWebApp.Sites[adminSiteUri.AbsoluteUri];
                }
            }
            return adminSite;
        }
        #endregion
    }
}
Reference : Code Snippet: Get User Credentials Using the Default Secure Store Provider
Loop execution of workflow

1. Create the first workflow as a trigger. This workflow will start another workflow by update current item as last action. Pause for 5 minutes is to avoid parallel execution.

2. Create the second workflow which do some action and update current item for continue loop. In this case, these two workflow will execute every day and check for status and sending mail.

Multiple line of text limit
With Sharepoint Designer, edit the page of list view. Add xsl template as below to override original template. Source template could be found at http://[servername]/_layouts/xsl/fldtypes.xsl.
<xsl:template name="FieldRef_Note_body" ddwrt:dvt_mode="body" match="FieldRef" mode="Note_body">
  <xsl:param name="thisNode" select="."/>
  <div dir="{@Direction}" class="ms-rtestate-field">
    <xsl:value-of select="concat(substring($thisNode/@*[name()=current()/@Name],0,50), '  ...')" disable-output-escaping="yes"/>
  </div>
</xsl:template>
JSRequest, Get parameters from querystring with javascript in SharePoint

Provides method to parse query string, filename, and pathname from URL

// Initialize first
JSRequest.EnsureSetup();

// Get the current file name
JSRequest.FileName: "qa.aspx"
// Get the current path name
JSRequest.PathName: "/sites/BruceDev/SitePages/qa.aspx"
// Get request query string parameter
JSRequest.QueryString["dy"];
JSRequest
JSRequest = {
    QueryString: null,
    FileName: null,
    PathName: null,
    EnsureSetup: function () {
        if(JSRequest.QueryString != null) return;
        JSRequest.QueryString = new Array();
        var queryString = window.location.search.substring(1);
        var pairs = queryString.split("&");
        for(var i = 0; i < pairs.length; i++) {
            var p = pairs[i].indexOf("=");
            if(p > -1) {
                var key = pairs[i].substring(0, p);
                var value = pairs[i].substring(p + 1);
                JSRequest.QueryString[key] = value;
            }
        }
        var path = JSRequest.PathName = window.location.pathname;
        var p = path.lastIndexOf("/");
        if(p > -1) {
            JSRequest.FileName = path.substring(p + 1);
        } else {
            JSRequest.PageName = path;
        }
    }
};
Fix for SharePoint 2010 scrolling problems for Chrome
Execute on page loaded
function bodyOnLoadWrapperForChrome() {
    //verify we have finished loading init.js
    if (typeof (_spBodyOnLoadWrapper) != 'undefined') {
        //verify we have not already initialized the onload wrapper
        if (typeof (_spBodyOnloadCalled) == 'undefined' || !_spBodyOnloadCalled) {
            //initialize onload functions
            _spBodyOnLoadWrapper();
        }
    }
    else {
        //wait for 10ms and try again if init.js has not been loaded
        setTimeout(bodyOnLoadWrapperForChrome, 100);
    }
}
executeOrDelayUntilScriptLoaded
Executes the specified function if the file containing it is loaded; otherwise, adds it to the pending job queue.
ExecuteOrDelayUntilScriptLoaded(func, depScriptFileName)
or
SP.SOD.executeOrDelayUntilScriptLoaded(func, depScriptFileName)
<script type="text/javascript">
    ExecuteOrDelayUntilScriptLoaded(function() {
        alert('sp.js loaded');
    }, 'sp.js');

    SP.SOD.executeOrDelayUntilScriptLoaded(function() {
        alert('jquery.js loaded');
    }, 'jquery.js');
</script>
Page load event handler on sharepoint
<script type="text/javascript">
    _spBodyOnLoadFunctionNames.push("onPageLoadAction");

    function onPageLoadAction() {
        // code here
    }
</script>
Redirect webpart in sanboxed solution
using System;
using System.ComponentModel;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;

namespace MyWebpart
{
    [ToolboxItemAttribute(false)]
    public class ConsentsApprover : WebPart
    {
        protected override void CreateChildControls()
        {
            Controls.Add(new Literal()
            {
                Text = @"<script type=""text/javascript"">location='your_redirect_url';</script>"
            });
        }
    }
}
Generate thumbnail for list attachment
using System;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using System.Linq;

namespace QuarterlyAward
{
    public partial class Thumbnail : LayoutsPageBase
    {
        /// <summary>
        /// Create thumbnail for list attachment
        /// Query string parameters:
        /// listID: List id
        /// itemID: Item id of list
        /// w: Specified thumbnail width
        /// h: Specified thumbnail height
        /// c: Use cache if cache exist and parameter value is not set
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void Page_Load(object sender, EventArgs e)
        {
            string cacheID = string.Format("{0}#{1}#{2}#{3}",
                Request.QueryString["listID"],
                Request.QueryString["itemID"],
                Request.QueryString["w"],
                Request.QueryString["h"]);
            byte[] thumbnailBinary = null;

            // Cache detection
            if (string.IsNullOrEmpty(Request.QueryString["c"]) && Cache[cacheID] != null)
            {
                thumbnailBinary = Cache[cacheID] as byte[];
                // Output cached thumbnail
                Response.Clear();
                Response.OutputStream.Write(thumbnailBinary, 0, thumbnailBinary.Length);
                Response.ContentType = "image/png";
                Response.End();
                return;
            }

            // Lack of parameter
            if (string.IsNullOrEmpty(Request.QueryString["listID"]) || string.IsNullOrEmpty(Request.QueryString["itemID"]))
            {
                Response.StatusCode = 404;
                return;
            }

            // Validate parameter
            int itemID = -1;
            if (!int.TryParse(Request.QueryString["itemID"], out itemID))
            {
                Response.StatusCode = 404;
                return;
            }

            int width = -1, height = -1;
            int.TryParse(Request.QueryString["w"], out width);
            int.TryParse(Request.QueryString["h"], out height);
            if (width == -1 && height == -1)
            {
                Response.StatusCode = 404;
                return;
            }

            #region Get attachment and generate thumbnail
            using (var web = SPContext.Current.Site.OpenWeb())
            {
                var list = web.Lists[new Guid(Request.QueryString["listID"])];
                var item = list.GetItemById(itemID);

                if (item == null || item.Attachments == null || item.Attachments.Count == 0)
                {
                    Response.StatusCode = 404;
                    return;
                }

                var imageType = new string[] { ".jpg", ".jpeg", ".gif", ".png", ".bmp" };
                // Get attachment folder
                var folder = item.ParentList.RootFolder.SubFolders["Attachments"].SubFolders[item.ID.ToString()];
                // Get image attachment
                var files = folder.Files
                                  .OfType<SPFile>()
                                  .Where(f => imageType.Contains(System.IO.Path.GetExtension(f.ServerRelativeUrl.ToLower())));
                if (!files.Any())
                {
                    Response.StatusCode = 404;
                    return;
                }
                var file = files.First();

                // Open image binary in memory
                var ms = new System.IO.MemoryStream(file.OpenBinary());
                // Load image instance
                var source = System.Drawing.Image.FromStream(ms);
                // Limit width & height
                if (source.Width < width || width < 1) width = source.Width;
                if (source.Height < height || height < 1) height = source.Height;
                var size = adaptProportionalSize(new System.Drawing.Size(width, height), source.Size);

                // Create thumbnail
                var thumbnailImage = source.GetThumbnailImage(size.Width, size.Height, null, IntPtr.Zero);
                // Get thumbnail binary
                ms = new System.IO.MemoryStream();
                thumbnailImage.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
                thumbnailBinary = ms.ToArray();

                // Cache 30 min
                Cache.Add(
                    cacheID,
                    thumbnailBinary,
                    null,
                    System.Web.Caching.Cache.NoAbsoluteExpiration,
                    new TimeSpan(0, 30, 0),
                    System.Web.Caching.CacheItemPriority.High,
                    null);
            }
            #endregion

            // Output thumbnail
            Response.Clear();
            Response.OutputStream.Write(thumbnailBinary, 0, thumbnailBinary.Length);
            Response.ContentType = "image/png";
            Response.End();
        }

        /// <summary>
        /// Caculate appropriate size for thumbnail
        /// </summary>
        /// <param name="szMax"></param>
        /// <param name="szReal"></param>
        /// <returns></returns>
        System.Drawing.Size adaptProportionalSize(System.Drawing.Size szMax, System.Drawing.Size szReal)
        {
            int nWidth;
            int nHeight;
            double sMaxRatio;
            double sRealRatio;

            if (szMax.Width < 1 || szMax.Height < 1 || szReal.Width < 1 || szReal.Height < 1)
                return System.Drawing.Size.Empty;

            sMaxRatio = (double)szMax.Width / (double)szMax.Height;
            sRealRatio = (double)szReal.Width / (double)szReal.Height;

            if (sMaxRatio < sRealRatio)
            {
                nWidth = Math.Min(szMax.Width, szReal.Width);
                nHeight = (int)Math.Round(nWidth / sRealRatio);
            }
            else
            {
                nHeight = Math.Min(szMax.Height, szReal.Height);
                nWidth = (int)Math.Round(nHeight * sRealRatio);
            }

            return new System.Drawing.Size(nWidth, nHeight);
        }
    }
}
Custom webpart properties
AwardView.cs
[ToolboxItemAttribute(false)]
public class AwardView : WebPart
{
    [WebBrowsable(true)]
    [Category("Extended")]
    [WebDescription("Shows when items contains no photo")]
    [WebDisplayName("Substitute Photo")]
    [Personalizable(PersonalizationScope.Shared)]
    public string SubstitutePhoto { get; set; }

    // Visual Studio might automatically update this path when you change the Visual Web Part project item.
    private const string _ascxPath = @"~/_CONTROLTEMPLATES/QuarterlyAward/AwardView/AwardViewUserControl.ascx";

    protected override void CreateChildControls()
    {
        Control control = Page.LoadControl(_ascxPath);
        Controls.Add(control);
    }
}
AwardView.webpart (set default value)
<?xml version="1.0" encoding="utf-8"?>
<webParts>
  <webPart xmlns="http://schemas.microsoft.com/WebPart/v3">
    <metaData>
      <type name="QuarterlyAward.AwardView.AwardView, $SharePoint.Project.AssemblyFullName$" />
      <importErrorMessage>$Resources:core,ImportErrorMessage;</importErrorMessage>
    </metaData>
    <data>
      <properties>
        <property name="Title" type="string">AwardView</property>
        <property name="Description" type="string">My Visual WebPart</property>
        <property name="SubstitutePhoto" type="string">/sites/BruceDev/SiteAssets/Personal.png</property>
      </properties>
    </data>
  </webPart>
</webParts>
Precautions of sharepoint performance issue
  1. Iterating through SPList Items
  2. Requesting too much data from the content database
  3. Memory Leaks with SPSite and SPWeb
  4. Index Columns are not necessarily improving performance
  5. SharePoint is not a relational database for high volume transactional processing
How to avoid the Top 5 SharePoint Performance Mistakes
Sharepoint list field
FieldType Class Type Type Display Name
Attachments Microsoft.SharePoint.SPFieldAttachments Attachments
Boolean Microsoft.SharePoint.SPFieldBoolean Yes/No
Calculated Microsoft.SharePoint.SPFieldCalculated Calculated
Choice Microsoft.SharePoint.SPFieldChoice Choice
Computed Microsoft.SharePoint.SPFieldComputed Computed
ContentTypeId Microsoft.SharePoint.SPField Content Type Id
Counter Microsoft.SharePoint.SPField Counter
Currency Microsoft.SharePoint.SPFieldCurrency Currency
DateTime Microsoft.SharePoint.SPFieldDateTime Date and Time
File Microsoft.SharePoint.SPFieldFile File
Guid Microsoft.SharePoint.SPFieldGuid Guid
Integer Microsoft.SharePoint.SPFieldNumber Integer
Lookup Microsoft.SharePoint.SPFieldLookup Lookup
ModStat Microsoft.SharePoint.SPFieldModStat Moderation Status
Note Microsoft.SharePoint.SPFieldMultiLineText Multiple lines of text
Number Microsoft.SharePoint.SPFieldNumber Number
Text Microsoft.SharePoint.SPFieldText Single line of text
URL Microsoft.SharePoint.SPFieldUrl Hyperlink or Picture
User Microsoft.SharePoint.SPFieldUser Person or Group
UserMulti Microsoft.SharePoint.SPFieldUser Person or Group
Get SPUser from Pserson or Group Column
SPUser GetSPUser(SPField field, object value)
{
 SPFieldUser userField = field as SPFieldUser;
 if (userField == null) return null;
 SPFieldUserValue fieldValue = userField.GetFieldValue(value as string) as SPFieldUserValue;
 if (fieldValue == null) return null;
 SPUser user = fieldValue.User;
 return user;
}
Calculated Field Formulas

Conditional formulas

You can use the following formulas to test the condition of a statement and return a Yes or No value, to test an alternate value such as OK or Not OK, or to return a blank or dash to represent a null value.

Determine whether a number is greater than or less than another number

Use the IF function to perform this comparison.

Column1 Column2 Formula Description (possible result)
15000 9000 =[Column1]>[Column2] Is Column1 greater than Column2? (Yes)
15000 9000 =IF([Column1]<=[Column2], "OK", "Not OK") Is Column1 less than or equal to Column2? (Not OK)
Return a logical value after comparing column contents

For a result that is a logical value (Yes or No), use the AND, OR, and NOT functions.

Column1 Column2 Column3 Formula Description (possible result)
15 9 8 =AND([Column1]>[Column2], [Column1]<[Column3]) Is 15 greater than 9 and less than 8? (No)
15 9 8 =OR([Column1]>[Column2], [Column1]<[Column3]) Is 15 greater than 9 or less than 8? (Yes)
15 9 8 =NOT([Column1]+[Column2]=24) Is 15 plus 9 not equal to 24? (No)

For a result that is another calculation, or any other value other than Yes or No, use the IF, AND, and OR functions.

Column1 Column2 Column3 Formula Description (possible result)
15 9 8 =IF([Column1]=15, "OK", "Not OK") If the value in Column1 equals 15, return "OK". (OK)
15 9 8 =IF(AND([Column1]>[Column2], [Column1]<[Column3]), "OK", "Not OK") If 15 is greater than 9 and less than 8, return "OK". (Not OK)
15 9 8 =IF(OR([Column1]>[Column2], [Column1]<[Column3]), "OK", "Not OK") If 15 is greater than 9 or less than 8, return "OK". (OK)
Display zeroes as blanks or dashes

To display a zero, perform a simple calculation. To display a blank or a dash, use the IF function.

Column1 Column2 Formula Description (possible result)
10 10 =[Column1]-[Column2] Second number subtracted from the first. (0)
15 9 =IF([Column1]-[Column2],[Column1]-[Column2],"-") Returns a dash when the value is zero. (-)
Hide error values in columns

To display a dash, #N/A, or NA in place of an error value, use the ISERROR function.

Column1 Column2 Formula Description (possible result)
10 0 =[Column1]/[Column2] Results in an error (#DIV/0)
10 0 =IF(ISERROR([Column1]/[Column2]),"NA",[Column1]/[Column2]) Returns NA when the value is an error
10 0 =IF(ISERROR([Column1]/[Column2]),"-",[Column1]/[Column2]) Returns a dash when the value is an error

Date and time formulas

You can use the following formulas to perform calculations that are based on dates and times, such as adding a number of days, months, or years to a date, calculating the difference between two dates, and converting time to a decimal value.

Add dates

To add a number of days to a date, use the addition (+) operator.

Column1 Column2 Formula Description (possible result)
6/9/2007 3 =[Column1]+[Column2] Adds 3 days to 6/9/2007 (6/12/2007)
12/10/2008 54 =[Column1]+[Column2] Adds 54 days to 12/10/2008 (2/2/2009)

To add a number of months to a date, use the DATE, YEAR, MONTH, and DAY functions.

Column1 Column2 Formula Description (possible result)
6/9/2007 3 =DATE(YEAR([Column1]),MONTH([Column1])+[Column2],DAY([Column1])) Adds 3 months to 6/9/2007 (9/9/2007)
12/10/2008 25 =DATE(YEAR([Column1]),MONTH([Column1])+[Column2],DAY([Column1])) Adds 25 months to 12/10/2008 (1/10/2011)

To add a number of years to a date, use the DATE, YEAR, MONTH, and DAY functions.

Column1 Column2 Formula Description (possible result)
6/9/2007 3 =DATE(YEAR([Column1])+[Column2],MONTH([Column1]),DAY([Column1])) Adds 3 years to 6/9/2007 (6/9/2010)
12/10/2008 25 =DATE(YEAR([Column1])+[Column2],MONTH([Column1]),DAY([Column1])) Adds 25 years to 12/10/2008 (12/10/2033)

To add a combination of days, months, and years to a date, use the DATE, YEAR, MONTH, and DAY functions.

Column1 Formula Description (possible result)
6/9/2007 =DATE(YEAR([Column1])+3,MONTH([Column1])+1,DAY([Column1])+5) Adds 3 years, 1 month, and 5 days to 6/9/2007 (7/14/2010)
12/10/2008 =DATE(YEAR([Column1])+1,MONTH([Column1])+7,DAY([Column1])+5) Adds 1 year, 7 months, and 5 days to 12/10/2008 (7/15/2010)
Calculate the difference between two dates

Use the DATEDIF function to perform this calculation.

Column1 Column2 Formula Description (possible result)
01-Jan-1995 15-Jun-1999 =DATEDIF([Column1], [Column2],"d") Returns the number of days between the two dates (1626)
01-Jan-1995 15-Jun-1999 =DATEDIF([Column1], [Column2],"ym") Returns the number of months between the dates, ignoring the year part (5)
01-Jan-1995 15-Jun-1999 =DATEDIF([Column1], [Column2],"yd") Returns the number of days between the dates, ignoring the year part (165)
Calculate the difference between two times

To present the result in the standard time format (hours:minutes:seconds), use the subtraction operator (-) and the TEXT function. For this method to work, hours must not exceed 24, and minutes and seconds must not exceed 60.

Column1 Column2 Formula Description (possible result)
06/09/2007 10:35 AM 06/09/2007 3:30 PM =TEXT([Column2]-[Column1],"h") Hours between two times (4)
06/09/2007 10:35 AM 06/09/2007 3:30 PM =TEXT([Column2]-[Column1],"h:mm") Hours and minutes between two times (4:55)
06/09/2007 10:35 AM 06/09/2007 3:30 PM =TEXT([Column2]-[Column1],"h:mm:ss") Hours, minutes, and seconds between two times (4:55:00)

To present the result in a total that is based on one time unit, use the INT function, or HOUR, MINUTE, or SECOND function.

Column1 Column2 Formula Description (possible result)
06/09/2007 10:35 AM 06/10/2007 3:30 PM =INT(([Column2]-[Column1])*24) Total hours between two times (28)
06/09/2007 10:35 AM 06/10/2007 3:30 PM =INT(([Column2]-[Column1])*1440) Total minutes between two times (1735)
06/09/2007 10:35 AM 06/10/2007 3:30 PM =INT(([Column2]-[Column1])*86400) Total seconds between two times (104100)
06/09/2007 10:35 AM 06/10/2007 3:30 PM =HOUR([Column2]-[Column1]) Hours between two times, when the difference does not exceed 24 (4)
06/09/2007 10:35 AM 06/10/2007 3:30 PM =MINUTE([Column2]-[Column1]) Minutes between two times, when the difference does not exceed 60 (55)
06/09/2007 10:35 AM 06/10/2007 3:30 PM =SECOND([Column2]-[Column1]) Seconds between two times, when the difference does not exceed 60 (0)
Convert times

To convert hours from the standard time format to a decimal number, use the INT function.

Column1 Formula Description (possible result)
10:35 AM =([Column1]-INT([Column1]))*24 Number of hours since 12:00 AM (10.583333)
12:15 PM =([Column1]-INT([Column1]))*24 Number of hours since 12:00 AM (12.25)

To convert hours from a decimal number to the standard time format (hours:minutes:seconds), use the division operator and the TEXT function.

Column1 Formula Description (possible result)
23:58 =TEXT(Column1/24, "hh:mm:ss") Hours, minutes, and seconds since 12:00 AM (00:59:55)
2:06 =TEXT(Column1/24, "h:mm") Hours and minutes since 12:00 AM (0:05)
Insert Julian dates

A Julian date refers to a date format that is a combination of the current year and the number of days since the beginning of the year. For example, January 1, 2007, is represented as 2007001 and December 31, 2007, is represented as 2007365. This format is not based on the Julian calendar.

To convert a date to a Julian date, use the TEXT and DATEVALUE functions.

Column1 Formula Description (possible result)
6/23/2007 =TEXT([Column1],"yy")&TEXT(([Column1]-DATEVALUE("1/1/"& TEXT([Column1],"yy"))+1),"000") Date in Julian format, with a two-digit year (07174)
6/23/2007 =TEXT([Column1],"yyyy")&TEXT(([Column1]-DATEVALUE("1/1/"&TEXT([Column1],"yy"))+1),"000") Date in Julian format, with a four-digit year (2007174)

To convert a date to a Julian date that is used in astronomy, use the constant 2415018.50. This formula works only for dates after 3/1/1901, and if you are using the 1900 date system.

Column1 Formula Description (possible result)
6/23/2007 =[Column1]+2415018.50 Date in Julian format, used in astronomy (2454274.50)
Show dates as the day of the week

To convert dates to the text for the day of the week, use the TEXT and WEEKDAY functions.

Column1 Formula Description (possible result)
19-Feb-2007 =TEXT(WEEKDAY([Column1]), "dddd") Calculates the day of the week for the date and returns the full name of the day (Monday)
3-Jan-2008 =TEXT(WEEKDAY([Column1]), "ddd") Calculates the day of the week for the date and returns the abbreviated name of the day (Thu)

Mathematical formulas

You can use the following formulas to perform a variety of mathematical calculations, such as adding, subtracting, multiplying, and dividing numbers; calculating the average or median of numbers; rounding a number; and counting values.

Add numbers

To add numbers in two or more columns in a row, use the addition operator (+) or the SUM function.

Column1 Column2 Column3 Formula Description (possible result)
6 5 4 =[Column1]+[Column2]+[Column3] Adds the values in the first three columns (15)
6 5 4 =SUM([Column1],[Column2],[Column3]) Adds the values in the first three columns (15)
6 5 4 =SUM(IF([Column1]>[Column2], [Column1]-[Column2], 10), [Column3]) If Column1 is greater than Column2, adds the difference and Column3. Else add 10 and Column3 (5)
Subtract numbers

To subtract numbers in two or more columns in a row, use the subtraction operator (-) or the SUM function with negative numbers.

Column1 Column2 Column3 Formula Description (possible result)
15000 9000 -8000 =[Column1]-[Column2] Subtracts 9000 from 15000 (6000)
15000 9000 -8000 =SUM([Column1], [Column2], [Column3]) Adds numbers in the first three columns, including negative values (16000)
Calculate the difference between two numbers as a percentage

Use the subtraction (-) and division (/) operators and the ABS function.

Column1 Column2 Formula Description (possible result)
2342 2500 =([Column2]-[Column1])/ABS([Column1]) Percentage change (6.75% or 0.06746)
Multiply numbers

To multiply numbers in two or more columns in a row, use the multiplication operator (*) or the PRODUCT function.

Column1 Column2 Formula Description (possible result)
5 2 =[Column1]*[Column2] Multiplies the numbers in the first two columns (10)
5 2 =PRODUCT([Column1], [Column2]) Multiplies the numbers in the first two columns (10)
5 2 =PRODUCT([Column1],[Column2],2) Multiplies the numbers in the first two columns and the number 2 (20)
Divide numbers

To divide numbers in two or more columns in a row, use the division operator (/).

Column1 Column2 Formula Description (possible result)
15000 12 =[Column1]/[Column2] Divides 15000 by 12 (1250)
15000 12 =([Column1]+10000)/[Column2] Adds 15000 and 10000, and then divides the total by 12 (2083)
Calculate the average of numbers

The average is also called the mean. To calculate the average of numbers in two or more columns in a row, use the AVERAGE function.

Column1 Column2 Column3 Formula Description (possible result)
6 5 4 =AVERAGE([Column1], [Column2],[Column3]) Average of the numbers in the first three columns (5)
6 5 4 =AVERAGE(IF([Column1]>[Column2], [Column1]-[Column2], 10), [Column3]) If Column1 is greater than Column2, calculate the average of the difference and Column3. Else calculate the average of the value 10 and Column3 (2.5)
Calculate the median of numbers

The median is the value at the center of an ordered range of numbers. Use the MEDIAN function to calculate the median of a group of numbers.

A B C D E F Formula Description (result)
10 7 9 27 0 4 =MEDIAN(A, B, C, D, E, F) Median of numbers in the first 6 columns (8)
Calculate the smallest or largest number in a range

To calculate the smallest or largest number in two or more columns in a row, use the MIN and MAX functions.

Column1 Column2 Column3 Formula Description (possible result)
10 7 9 =MIN([Column1], [Column2], [Column3]) Smallest number (7)
10 7 9 =MAX([Column1], [Column2], [Column3]) Largest number (10)
Count values

To count numeric values, use the COUNT function.

Column1 Column2 Column3 Formula Description (possible result)
Apple 12/12/2007 =COUNT([Column1], [Column2], [Column3]) Counts the number of columns that contain numeric values. Excludes date and time, text, and null values (0)
$12 #DIV/0! 1.01 =COUNT([Column1], [Column2], [Column3]) Counts the number of columns that contain numeric values, but excludes error and logical values (2)
Increase or decrease a number by a percentage

Use the percent (%) operator to perform this calculation.

Column1 Column2 Formula Description (possible result)
23 3% =[Column1]*(1+5%) Increases number in Column1 by 5% (24.15)
23 3% =[Column1]*(1+[Column2]) Increases number in Column1 by the percent value in Column2: 3% (23.69)
23 3% =[Column1]*(1-[Column2]) Decreases number in Column1 by the percent value in Column2: 3% (22.31)
Raise a number to a power

Use the exponentiation operator (^) or the POWER function to perform this calculation.

Column1 Column2 Formula Description (possible result)
5 2 =[Column1]^[Column2] Calculates five squared (25)
5 3 =POWER([Column1], [Column2]) Calculates five cubed (125)
Round a number

To round up a number, use the ROUNDUP, ODD, or EVEN function.

Column1 Formula Description (possible result)
20.3 =ROUNDUP([Column1],0) Rounds 20.3 up to the nearest whole number (21)
-5.9 =ROUNDUP([Column1],0) Rounds -5.9 up to the nearest whole number (-5)
12.5493 =ROUNDUP([Column1],2) Rounds 12.5493 up to the nearest hundredth, two decimal places (12.55)
20.3 =EVEN([Column1]) Rounds 20.3 up to the nearest even number (22)
20.3 =ODD([Column1]) Rounds 20.3 up to the nearest odd number (21)

To round down a number, use the ROUNDDOWN function.

Column1 Formula Description (possible result)
20.3 =ROUNDDOWN([Column1],0) Rounds 20.3 down to the nearest whole number (20)
-5.9 =ROUNDDOWN([Column1],0) Rounds -5.9 down to the nearest whole number (-6)
12.5493 =ROUNDDOWN([Column1],2) Rounds 12.5493 down to the nearest hundredth, two decimal places (12.54)

To round a number to the nearest number or fraction, use the ROUND function.

Column1 Formula Description (possible result)
20.3 =ROUND([Column1],0) Rounds 20.3 down, because the fractional part is less than .5 (20)
5.9 =ROUND([Column1],0) Rounds 5.9 up, because the fractional part is greater than .5 (6)
-5.9 =ROUND([Column1],0) Rounds -5.9 down, because the fractional part is less than -.5 (-6)
1.25 =ROUND([Column1], 1) Rounds the number to the nearest tenth (one decimal place). Because the portion to be rounded is 0.05 or greater, the number is rounded up (result: 1.3)
30.452 =ROUND([Column1], 2) Rounds the number to the nearest hundredth (two decimal places). Because the portion to be rounded, 0.002, is less than 0.005, the number is rounded down (result: 30.45)

To round a number to the significant digit above 0, use the ROUND, ROUNDUP, ROUNDDOWN, INT, and LEN functions.

Column1 Formula Description (possible result)
5492820 =ROUND([Column1],3-LEN(INT([Column1]))) Rounds the number to 3 significant digits (5490000)
22230 =ROUNDDOWN([Column1],3-LEN(INT([Column1]))) Rounds the bottom number down to 3 significant digits (22200)
5492820 =ROUNDUP([Column1], 5-LEN(INT([Column1]))) Rounds the top number up to 5 significant digits (5492900)

Text formulas

You can use the following formulas to manipulate text, such as combining or concatenating the values from multiple columns, comparing the contents of columns, removing characters or spaces, and repeating characters.

Change the case of text

To change the case of text, use the UPPER, LOWER, or PROPER function.

Column1 Formula Description (possible result)
nina Vietzen =UPPER([Column1]) Changes text to uppercase (NINA VIETZEN)
nina Vietzen =LOWER([Column1]) Changes text to lowercase (nina vietzen)
nina Vietzen =PROPER([Column1]) Changes text to title case (Nina Vietzen)
Combine first and last names

To combine first and last names, use the ampersand operator (&) or the CONCATENATE function.

Column1 Column2 Formula Description (possible result)
Carlos Carvallo =[Column1]&[Column2] Combines the two strings (CarlosCarvallo)
Carlos Carvallo =[Column1]&" "&[Column2] Combines the two strings, separated by a space (Carlos Carvallo)
Carlos Carvallo =[Column2]&", "&[Column1] Combines the two strings, separated by a comma and a space (Carvallo, Carlos)
Carlos Carvallo =CONCATENATE([Column2], ",", [Column1]) Combines the two strings, separated by a comma (Carvallo,Carlos)
Combine text and numbers from different columns

To combine text and numbers, use the CONCATENATE function, the ampersand operator (&), or the TEXT function and the ampersand operator.

Column1 Column2 Formula Description (possible result)
Yang 28 =[Column1]&" sold "&[Column2]&" units." Combines contents above into a phrase (Yang sold 28 units.)
Dubois 40% =[Column1]&" sold "&TEXT([Column2],"0%")&" of the total sales." Combines contents above into a phrase (Dubois sold 40% of the total sales.) Note   The TEXT function appends the formatted value of Column2 instead of the underlying value, which is 0.4.
Yang 28 =CONCATENATE([Column1]," sold ",[Column2]," units.") Combines contents above into a phrase (Yang sold 28 units.)
Combine text with a date or time

To combine text with a date or time, use the TEXT function and the ampersand operator (&).

Column1 Column2 Formula Description (possible result)
Billing Date 5-Jun-2007 ="Statement date: "&TEXT([Column2], "d-mmm-yyyy") Combines text with a date (Statement date: 5-Jun-2007)
Billing Date 5-Jun-2007 =[Column1]&" "&TEXT([Column2], "mmm-dd-yyyy") Combines text and date from different columns into one column (Billing Date Jun-05-2007)
Compare column contents

To compare one column to another column or a list of values, use the EXACT and OR functions.

Column1 Column2 Formula Description (possible result)
BD122 BD123 =EXACT([Column1],[Column2]) Compares contents of first two columns (No)
BD122 BD123 =EXACT([Column1], "BD122") Compares contents of Column1 and the string "BD122" (Yes)
Determine whether a column value or a part of it matches specific text

To determine whether a column value or a part of it matches specific text, use the IF, FIND, SEARCH, and ISNUMBER functions.

Column1 Formula Description (possible result)
Vietzen =IF([Column1]="Vietzen", "OK", "Not OK") Determines whether Column1 is Vietzen (OK)
Vietzen =IF(ISNUMBER(FIND("v",[Column1])), "OK", "Not OK") Determines whether Column1 contains the letter v (OK)
BD123 =ISNUMBER(FIND("BD",[Column1])) Determines whether Column1 contains BD (Yes)
Count nonblank columns

To count nonblank columns, use the COUNTA function.

Column1 Column2 Column3 Formula Description (possible result)
Sales 19 =COUNTA([Column1], [Column2]) Counts the number of nonblank columns (2)
Sales 19 =COUNTA([Column1], [Column2], [Column3]) Counts the number of nonblank columns (2)
Remove characters from text

To remove characters from text, use the LEN, LEFT, and RIGHT functions.

Column1 Formula Description (possible result)
Vitamin A =LEFT([Column1],LEN([Column1])-2) Returns 7 (9-2) characters, starting from left (Vitamin)
Vitamin B1 =RIGHT([Column1], LEN([Column1])-8) Returns 2 (10-8) characters, starting from right (B1)
Remove spaces from the beginning and end of a column

To remove spaces from a column, use the TRIM function.

Column1 Formula Description (possible result)
Hello there! =TRIM([Column1]) Removes the spaces from the beginning and end (Hello there!)
Repeat a character in a column

To repeat a character in a column, use the REPT function.

Formula Description (possible result)
=REPT(".",3) Repeats a period 3 times (...)
=REPT("-",10) Repeats a dash 10 times (----------)

reference: Calculated Field Formulas