Thursday, September 5, 2013

Creating a custom field type using client-side rendering


1. Right-click the farm solution project and add a new class. Name the class file FavoriteColorFieldType.cs.
2. Copy the following code and paste it in the FavoriteColorFieldType.cs file.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
namespace CustomField
{
    public class FavoriteColorField : SPFieldText
    {
        private const string JSLinkUrl = "~site/_layouts/15/CustomField/CSRFieldType.js";
        public FavoriteColorField(SPFieldCollection fields, string name)
            : base(fields, name) { }
        public FavoriteColorField(SPFieldCollection fields, string typename, string name)
            : base(fields, typename, name) {}
        public override string JSLink
        {
            get
            {
                return JSLinkUrl;
            }
            set
            {
                base.JSLink = value;
            }
        }
    }
}

1.Right-click the farm solution project, and add a SharePoint mapped folder. In the dialog box, select the {SharePointRoot}\Template\XML folder.
2.Right-click the XML folder created in the last step, and add a new XML file. Name the XML file fldtypes_FavoriteColorFieldType.xml.

<?xml version="1.0" encoding="utf-8" ?>
<FieldTypes>
  <FieldType>
    <Field Name="TypeName">FavoriteColorField</Field>
    <Field Name="TypeDisplayName">Favorite color field</Field>
    <Field Name="TypeShortDescription">Favorite color field</Field>
    <Field Name="InternalType">Text</Field>
    <Field Name="SQLType">nvarchar</Field>
    <Field Name="FieldTypeClass">CustomField.FavoriteColorField, $SharePoint.Project.AssemblyFullName$</Field>
    <Field Name="ParentType">Text</Field>
    <Field Name="Sortable">TRUE</Field>
    <Field Name="Filterable">TRUE</Field>
    <Field Name="UserCreatable">TRUE</Field>
    <Field Name="ShowOnListCreate">TRUE</Field>
    <Field Name="ShowOnSurveyCreate">TRUE</Field>
    <Field Name="ShowOnDocumentLibrary">TRUE</Field>
    <Field Name="ShowOnColumnTemplateCreate">TRUE</Field>
  </FieldType>
</FieldTypes>

1.Right-click the farm solution project, and add the SharePoint Layouts mapped folder. A folder created with solutin name
2.Right-click the Layouts->'solution name folder' folder that you created in the last step, and add a new JavaScript file. Name the JavaScript file CSRFieldType.js.

(function () {
    var favoriteColorContext = {};
    favoriteColorContext.Templates = {};
    favoriteColorContext.Templates.Fields = {
        "FavoriteColorField": {
            "View": favoriteColorViewTemplate
        }
    };
    SPClientTemplates.TemplateManager.RegisterTemplateOverrides(favoriteColorContext);
})();
function favoriteColorViewTemplate(ctx) {
    var color = ctx.CurrentItem[ctx.CurrentFieldSchema.Name];
    return "<span style='background-color : " + color + "' >&nbsp;&nbsp;&nbsp;&nbsp;</span>&nbsp;" + color;
}

Now Cteate a Custom List in SharePoint.
And Create a Custom Field using "Custom files type" namely "Favorite color field".
now add few records and in 'FavColFld' give these values "red", "yellow", "green"
http://msdn.microsoft.com/en-us/library/jj220061.aspx
Thank You.

Wednesday, September 4, 2013

Custom Error Logging in C#

1. Cratre a ErrorLogging.txt text file in C:\TestFolder folder
2. if ErrorLogging.txt Exceed 4MB then move this file to C:\TestFolder\BackUpFiles folder and    rename as ErrorLogging_<TimeStamp>.txt.
3. as usally create a new ErrorLogging.txt text file in C:\TestFolder
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ErrorLogging
{
    class ErrorLoggingProgram
    {
        static void Main(string[] args)
        {
            string directory = @"C:\TestFolder";
            try
            {
                if (!Directory.Exists(directory))
                {
                    DirectoryInfo di = Directory.CreateDirectory(directory);
                }
            }
            catch (IOException ioex)
            {
                Console.WriteLine(ioex.Message);
            }
            string errormsg = "first line";
            if (File.Exists(@"C:\TestFolder\ErrorLogging.txt"))
                using (System.IO.StreamWriter file = new System.IO.StreamWriter(@"C:\TestFolder\ErrorLogging.txt", true))
                {
                    file.WriteLine(errormsg);
                    file.Flush();
                    file.Close();
                    FileInfo fi = new FileInfo(@"C:\TestFolder\ErrorLogging.txt");
                    var size = fi.Length;
                    if (File.ReadAllBytes(@"C:\TestFolder\ErrorLogging.txt").Length >= 4 * 1024 * 1024) // (4MB) File to big? Create new
                    {
                        Console.WriteLine("File Size in Bytes: {0} greater than 10kb", size);
                        moveFile();
                    }
                    Console.WriteLine("File Size in Bytes: {0}", size);
                }
            else
                using (System.IO.StreamWriter file = new System.IO.StreamWriter(@"C:\TestFolder\ErrorLogging.txt", true))
                {
                    file.WriteLine(errormsg);
                    Console.WriteLine("Does not Exist" + "\t" + @"C:\TestFolder\ErrorLogging.txt");
                    file.Flush();
                    file.Close();
                }
            Console.ReadKey();
        }
        private static void moveFile()
        {
            string directory = @"C:\TestFolder\BackUpFiles";
            try
            {
                if (!Directory.Exists(directory))
                {
                    DirectoryInfo di = Directory.CreateDirectory(directory);
                }
            }
            catch (IOException ioex)
            {
                Console.WriteLine(ioex.Message);
            }
            string sourceFile = @"C:\TestFolder\ErrorLogging.txt";
            string timeStamp = DateTime.Now.ToString("yyyyMMddHHmmssffff");
            string destinationFile = @"C:\TestFolder\backupfiles\ErrorLogging_" + timeStamp + ".txt";
            System.IO.File.Move(sourceFile, destinationFile);
        }
    }
}

Friday, August 30, 2013

This operation can be performed only on a computer that is joined to a server farm by users who have permissions in SQL Server to read from the configuration database. To connect this server to the server farm, use the SharePoint Products Configuration Wizard, located on the Start menu in Microsoft SharePoint 2010 Products.

This operation can be performed only on a computer that is joined to a server farm by users who have permissions in SQL Server to read from the configuration database. To connect this server to the server farm, use the SharePoint Products Configuration Wizard, located on the Start menu in Microsoft SharePoint 2010 Products.

Go to start -> run -> services.msc -> start "SQL Server (MSSQLSERVER)" service.
now refresh above page. we can see web application will open.

Friday, August 16, 2013

C# (C Sharp) Notes

Delegate:-
-----------
1. The Delegate object can then be passed to code which can call the referenced method, without having to know at compile time which method will be invoked.
Declaration:-
delegate result-type identifier([parameters])
here:-
result-type: The result type, which matches the return type of the function.
identifier: the delegate name.
parameters: The Parameters, that the function takes.
public delegate void SimpleDelegate()
public delegate int ButtonClickHandler(object obj1, object obj2)
Instantiation:-
SimpleDelegate simpleDelegate = new SimpleDelegate(MyFuc);
Invocation:-
simpleDelegate();
Delegate Types:-
1. SingleCast Delegate:- SingleCast Delegate is one that can refer to a single method.
2. MultiCast Delegate:- MultiCast Delegate is can refer to and eventually fire off multiple methods that have the same signature.
1. SingleCast Delegate Example:-
using System;
namespace ExampleDelegate
{
 //Declaration
  public delegate void SimpleDelegate();
   class testDelegate
   {
    public static void MyDelegateFun()
{
Console.WriteLine("This text called form delegate...");
}
public static void Main()
{
//Instantiation
SimpleDelegate simpleDelegate = new SimpleDelegate(MyDelegateFun);
//Invocation
simpleDelegate();
}
   }
}
OutPut:-
This text called form delegate...
2. MultiCast Delegate:-
1. MultiCast Delegates contains list of delegates - called the invocation list - which contains delegates of the same method signature.
2. Whenever the delegate is invoked, it also invokes each delegate in its invocation list.
3. You add and remove delegates from an invocation list using overloaded += and -= operators.
 using System;
public delegate void MultcastTestDelegate();
class Test1
{
 public static void Display1()
 {
  Console.WriteLine("This is the first method");
 }
 public static void Display2()
 {
  Console.WriteLine("This is the second method");
 }
 static void Main()
 {
 //Method 1 to make Multicast
  TestDelegate t1 = new TestDelegate(Display1); //Instantiation t1 delegate
  TestDelegate t2 = new TestDelegate(Display2); //Instantiation t2 delegate
  t1 = t1 + t2; // Make t1 a multicast delegate
  t1(); //Invoke both methods through the delegate //Invocation
  Console.ReadLine();
  //Method 2 to make Multicast
  TestDelegate t1 = new TestDelegate(Display1);
  t1 += new TestDelegate(Display2); // Make t1 a multicast delegate
  t1(); //Invoke both methods through the delegate //Invocation
 }
}
OutPut:-
This is first method
This is the second method
---------------------------------

Wednesday, August 7, 2013

Create Subscription Settings Service Application, App Management Service Application using powershell scripting

http://msdn.microsoft.com/en-us/library/office/apps/fp179923%28v=office.15%29
-->Open PowerShell Command Prompt as administrator.
net start spadminv4
net start sptimerv4

//my domain name is "TestDomain"
Set-SPAppDomain  "TestDomainapps.net" [domain name + apps + .com/.net]
Set-SPAppSiteSubscriptionName -Name "app" -Confirm:$false

Get-SPServiceInstance | where{$_.GetType().Name -eq "AppManagementServiceInstance" -or $_.GetType().Name -eq "SPSubscriptionSettingsServiceInstance"} | Start-SPServiceInstance

Create Managed Account:-
$account= New-SPManagedAccount [this step is optional if already managed a/c have.]

Get Managed Account:-
$account = Get-SPManagedAccount "TestDomain\username" (domain\username)

Create Subscription Settings Service Application:-
$appPoolSubSvc = New-SPServiceApplicationPool -Name SettingsServiceAppPool -Account $account
$appSubSvc = New-SPSubscriptionSettingsServiceApplication –ApplicationPool $appPoolSubSvc –Name SubscriptionSettingsServiceApplication –DatabaseName SubscriptionSettingsServiceApplicationDB
$proxySubSvc = New-SPSubscriptionSettingsServiceApplicationProxy –ServiceApplication $appSubSvc

Create App Management Service Application :-
$appPoolAppSvc = New-SPServiceApplicationPool -Name AppServiceAppPool -Account $account
$appAppSvc = New-SPAppManagementServiceApplication -ApplicationPool $appPoolAppSvc -Name AppManagementServiceApplication -DatabaseName AppManagementServiceApplicationDB
$proxyAppSvc = New-SPAppManagementServiceApplicationProxy -ServiceApplication $appAppSvc
----------------------------------------------------------------------------------------------------------

Tuesday, August 6, 2013

Create your first content app for Excel by using "Napa" Office 365 Development Tools

MyAppPage.html:-
------------------
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <title>PageTitle</title>
    <link href="../../Content/Office.css" rel="stylesheet" type="text/css" />
    <link href="../App.css" rel="stylesheet" type="text/css" />
    <script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.7.1.min.js" type="text/javascript"></script>
    <script src="https://appsforoffice.microsoft.com/lib/1.0/hosted/office.js" type="text/javascript"></script>
    <script src="../App.js" type="text/javascript"></script>
    <script src="MyAppPage.js" type="text/javascript"></script>
</head>
<body>
    <div style="padding: 15px; overflow: auto; border: .2em solid #000;">
        <table>
            <tr>
                <td>
                    <button id="get-text" style="width: 100px;">Get symbol</button>
                </td>
                <td>
                    <button id="bind-text" style="width: 100px;">Bind to cell</button>
                </td>
            </tr>
            <tr>
                <td>
                    <input id="input" style="width: 100px;" />
                </td>
                <td>
                    <button id="add-text" style="width: 100px;">Add symbol</button>
                </td>
            </tr>
        </table>
        <h1>
            <div id="stock-name"></div>
        </h1>
        <table border="true">
            <tr>
                <td>
                    <table>
                        <tr>
                            <td>Prev close:</td>
                            <td id="prev-close"></td>
                        </tr>
                        <tr>
                            <td>Open:</td>
                            <td id="open"></td>
                        </tr>
                        <tr>
                            <td>Bid:</td>
                            <td id="bid"></td>
                        </tr>
                        <tr>
                            <td>Ask:</td>
                            <td id="ask"></td>
                        </tr>
                        <tr>
                            <td>1y Target Est::</td>
                            <td id="target-est"></td>
                        </tr>
                        <tr>
                            <td>Days range:</td>
                            <td id="days-range"></td>
                        </tr>
                    </table>
                </td>
                <td>
                    <table>
                        <tr>
                            <td>Volume:</td>
                            <td id="volume"></td>
                        </tr>
                        <tr>
                            <td>Avg daily volume:</td>
                            <td id="avg-volume"></td>
                        </tr>
                        <tr>
                            <td>Market capitalization:</td>
                            <td id="market-cap"></td>
                        </tr>
                        <tr>
                            <td>PE Ratio:</td>
                            <td id="pe-ratio"></td>
                        </tr>
                        <tr>
                            <td>Earnings p share:</td>
                            <td id="earnings"></td>
                        </tr>
                        <tr>
                            <td>Dividend yield:</td>
                            <td id="yield"></td>
                        </tr>
                    </table>
                </td>
            </tr>
        </table>
    </div>
</body>
</html>
MyAppPage.js:-
-----------------
/// <reference path="../App.js" />
(function () {
    "use strict";
    // The initialize function must be run each time a new page is loaded
    Office.initialize = function (reason) {
        $(document).ready(function () {
            $('#get-text').click(getTextFromDocument);
            $('#add-text').click(addTextToDocument);
            $('#bind-text').click(addBindingFromSelection);
            Office.context.document.addHandlerAsync
            (Office.EventType.DocumentSelectionChanged, updateApp);
        });
    }
})();
function getTextFromDocument() {
    Office.context.document.getSelectedDataAsync(Office.CoercionType.Text,
        {
            valueFormat: "unformatted", filterType: "all"
        },
        function (asyncResult) {
            showStockData(asyncResult.value);
        });
}
function showStockData(symbol) {
    // Yahoo YQL - http://developer.yahoo.com/yql/
    var yql = 'select * from yahoo.finance.quotes where symbol in (\'' + symbol + '\')';
    var queryURL = 'https://query.yahooapis.com/v1/public/yql?q=' + yql + '&format=json&env=http%3A%2F%2Fdatatables.org%2Falltables.env&callback=?';
    $.getJSON(queryURL, function (results) {
        if (results.query.count > 0) {
            var quotes = results.query.results.quote;
            $('#stock-name').text(quotes.Name);
            $('#prev-close').text(quotes.PreviousClose);
            $('#open').text(quotes.Open);
            $('#bid').text(quotes.Bid);
            $('#ask').text(quotes.Ask);
            $('#target-est').text(quotes.OneyrTargetPrice);
            $('#days-range').text(quotes.DaysRange);
            $('#volume').text(quotes.Volume);
            $('#avg-volume').text(quotes.AverageDailyVolume);
            $('#market-cap').text(quotes.MarketCapitalization);
            $('#pe-ratio').text(quotes.PERatio);
            $('#earnings').text(quotes.EarningsShare);
            $('#yield').text(quotes.DividendYield);
        }
    });
}
function addTextToDocument() {
    var e = document.getElementById("input");
    var text = e.value;
    Office.context.document.setSelectedDataAsync(text,
        function (asyncResult) { });
}
function updateApp() {
    getTextFromDocument();
}
function addBindingFromSelection() {
    Office.context.document.bindings.addFromSelectionAsync(Office.BindingType.Text, { id: 'MyBinding' },
        function (asyncResult) {
            Office.select("bindings#MyBinding").addHandlerAsync
               (Office.EventType.BindingDataChanged, onBindingSelectionChanged);
        }
    );
}
function onBindingSelectionChanged(eventArgs) {
    Office.select("bindings#MyBinding").getDataAsync
        (function (asyncResult) {
            if (asyncResult.value !== "") {
                showStockData(asyncResult.value);
            }
        });
}
 Click on 'Run' Button. then below excel will open in other window.
Thank You.

Saturday, July 27, 2013

Install Language Pack in SharePoint




Build CAML Query Dynamically based on Passing Parameters to the Query in SharePoint.

string camlQuery = CreateCAMLQuery(parameters); 
private static string CreateCAMLQuery(string[] parameters)
        {
            StringBuilder sb = new StringBuilder(); 
            if (parameters.Length == 0)
            {
                AppendEQ(sb, "all", "all");
            }
            for (int i = 0; i < parameters.Length; i += 2)
            {
                AppendEQ(sb, parameters[i], parameters[i + 1]);
                if (i > 0)
                {
                    sb.Insert(0, "<And>");
                    sb.Append("</And>");
                }
            }
            sb.Insert(0, "<Where>");
            sb.Append("</Where>"); 
            return sb.ToString();
        }

        private static void AppendEQ(StringBuilder sb, string column, string value)
        {
            sb.Append("<Eq>");
            if (column == "state")
            {
                sb.Append("<FieldRef Name='state'/>");
                sb.AppendFormat("<Value Type='Lookup'>{0}</Value>", value);
            }
            if (column == "City")
            {
                sb.Append("<FieldRef Name='City'/>");
                sb.AppendFormat("<Value Type='Lookup'>{0}</Value>", value);
            }
            if (column == "VehicleMake")
            {
                sb.Append("<FieldRef Name='VehicleMake'/>");
                sb.AppendFormat("<Value Type='Choice'>{0}</Value>", value);
            }
            if (column == "GarageType")
            {
                sb.Append("<FieldRef Name='GarageType'/>");
                sb.AppendFormat("<Value Type='Choice'>{0}</Value>", value);
            }
            sb.Append("</Eq>");
        }

Featured Post

Automating Azure DevOps Task Tracking: A Complete PowerShell Solution

Automating Azure DevOps Task Tracking: A Complete PowerShell Solution param ( [ Parameter ( Mandatory = $false )] [ Alias ( 'Fr...

Popular posts