Thursday, December 8, 2011

REST: Post XML to Update List Item

I need to use vCenter orchestrator to update item in SharePoint list.

Using rest plugin, I post the following XML to SharePoint.

 


   
   http://172.20.34.33/_vti_bin/listdata.svc/Rest(4)
    1
    2011-11-07T17:39:56+08:00
    
      
    
    
      
        0x0100B0118C4AF8B98C408EDC3A87238E73F5
        4
        4
  haha
        Item
        /Lists/rest
      
    

Tuesday, December 6, 2011

HTML in Calculated Column

In a SharePoint list, it looks up a Hyperlink column in another list. After my investigation, Lookup column only supports Text column and Calculated column. 

I decide to use Calculated column and render its content as html. Based on below references link, I add a script file to a content editor. But, it still failed.


After some time, I modify the script file and it works file.

Sunday, December 4, 2011

SPFieldUrl: Open URL in a New Window

When I add a hyperlink column in a list and add an item, I click its hyperlink. Then, it redirects current page to the link. But, I want to open a new window when clicking these links.

In fact, I cannot configure it inside SharePoint. After Googling, I discover it can be done by the following steps:

1. Go to folder "Microsoft Shared\web server extensions\14\TEMPLATE\LAYOUTS\XSL"
2. Open fldtypes.xsl
3. Change line '<a href="{$url}" >' to '<a target="_blank" href="{$url}" >'
3. Save the file and restart IIS

After that, I create a new hyperlink column, it opens a new window when clicking its link.

RenderPattern Element (Field Types)
SharePoint: Creating Custom SharePoint 2010 Field Types
How to: Create a Custom Field Type
Customizing the Rendering of a Custom SPField
What's New: Custom Field Rendering Enhancements

Tuesday, November 22, 2011

C#: Delegate

Here is a simple example of using delegate in C# and it just likes a function pointer in the following code:

  class Demo
    {
        static void Main(string[] args)
        {
            DemoDelegate.process();

            Console.ReadLine();
        }
    }

GridView: dynamic column binding

I try to bind columns to a GridView  dynamically and the code is shown below:

DataTable table = new DataTable();

//add column
table.Columns.Add(new DataColumn("name", typeof(string)));

//add row
DataRow row = table.NewRow();
row["Name"] = "abc";
table.Rows.Add(row);

//bind data to gridView
GridView1.DataSource = table;
GridView1.DataBind();

Saturday, November 19, 2011

ASP.NET: Freeze/Lock Web Page While Loading

When processing a request, web page will be freezed/locked. Hence, users are unable to click any button and just wait.

The following CSS enable Div height 100%:


ASP.NET

C#
protected void submitButton_Click(object sender, EventArgs e)
{
    System.Threading.Thread.Sleep(10000); //loading
}

Last but not least, these code works fine for IE6, Chrome and Firefox.

References:
CSS Div Height 100%
How to Freeze Webpage while it is being processed in .Net 2.0 using AJAX?
Lock/Freeze Web Page using jQuery

Sunday, November 13, 2011

Property Bag

SharePoint applications retrieve configuration settings at run time. Configuration database can be stored in the web.config or configuration database. Property Bag can be stored and retrieved configuration settings at the following levels:
-Farm
-Web Application
-Site Collection
-Site
-List

Reference:
SharePoint Property Bag Settings 2010

Managed code and Unmanaged Code

Managed Code
-It compiles to intermediate Language(IL)
-It runs and is managed by Common Language Runtime (CLR)
-The runtime provides services such as security, memory management and threading

Unmanaged Code
-It compiles directory to machine  code
-It does not run and is not managed by the CLR
-It doesn't get the  services of the runtime

Site Definition and Web Template

Web Template is stored in the Solutions Gallery of the site collection and the solution can also be deployed as a sandboxed solutions to other site collections.


Site definition consists of a combination of files that are placed in the %ProgramFiles%\Common Files\Microsoft Shared\web server extensions\14\TEMPLATE\SiteTemplates. You can adjust the physical storage capacity required by site collection.
(1) WebTemp*.xml
      Identify the site definitions and configurations and provide information about how they appear in the user interface (UI) to users who are creating new websites.
(2) Onet.xml
     Define the navigation areas, specify the list definitions available in the UI, specify document templates and their files, define the base types for lists, and define configurations and modules for site definitions.


Site Definition vs Web Template 
-The user context in which a web template is deployed does not have to have access to the file system of the servers.
-Custom web templates can be modified without affecting existing sites that have been created from the templates.

Master Page and Page Layout

The top-level SharePoint Server site for a site collection hosted on SharePoint Server 2010 has a special document library called the Master Page and Page Layout Gallery. All page layouts and master pages are stored in this document library. The Master Page and Page Layout Gallery supports versioning and workflow, so you can use those features for your master pages and page layouts.

(By default, SharePoint Server 2010 creates a master page gallery for every site; however, you can create only new pages with the page layouts stored in the master page gallery of the top-level site in the site collection).


Master page provide a consistent look and feel for your site. It contains controls that are shared across multiple page layouts, such as navigation, search and custom field controls.


Page Layout contains field controls and Web Parts. All page layouts reference a master page based on the CustomMasterUrl property of the SPWeb class.


Reference:
SharePoint Page Layouts and Master Pages (ECM)

Solution Deployment Security

There are two type of solution introduced in SharePoint 2010:


Farm Solution
In the manifest file, the solution must define that the assembly be deployed to GAC or Bin folder using DeploymentTarget attribute. Farm solution which is hosted in the IIS worker process (W3WP.exe) , run code that affect the whole farm. IIS application pool recycles before SharePoint retracts or deploys the feature.


1. Deployint Assembly to GAC (global assembly cache)
    Assemblies installed in the GAC run with Full trust and it is accessible to full set of object model. You must reset IIS every time you recompile assemblies.


2. Deploying Assembly to Bin folder using CAS
    Assemblies installed in the Bin folder of the application requires you to assign execution permissions. It is only accessible to subset of object model. You can create a custom policy file and SharePoint defines two trust levels : WSS_Minimal and WSS_Medium (local_drive:\Program Files\Common Files\Microsoft Shared\web server extensions\60\config). There are cases that deploying this solution is not suitable:
(1) Workflow
(2) Event receiver
(3) Timer job


Sandboxed Solution
    Sandboxed solution which is hosted in the SharePoint user code solution worker process (SPUCWorkerProcess.exe), run code that can only affect the site collection of the solution. It is not necessary for the SPUCWorkerProcess process to recycle to load the latest version of the solution. There are the most common things that sandboxed solution cannot  do:
(1) Connect to resources that are not located on the local farm
(2) Access a database
(3) Change the threading model
(4) Call unmanaged code
(5) Write to dick
(6) Access resources in a different site collection


References:
Moss 2007 and Code Access Security
Microsoft Windows SharePoint Services and Code Access Security
Differences Between Sandboxed and Farm Solutions
Sandboxed solutions overview (SharePoint Server 2010)
Chapter 4: Sandboxed Solutions
Farm Solutions

Thursday, November 10, 2011

C#: Polymorphism new vs override

new keyword is used to hide an inherited member from a base class
override keyword is used to provide a new implementation of a member inherited from a base method.

class Demo
{
static void Main(string[] args)
{
Animal a = new Cat();
Animal b = new Dog();
Animal c = new Animal();

a.sayHi();
b.sayHi();
c.sayHi();
Console.ReadLine();
}
}

class Animal
{
public Animal()
{
Console.WriteLine("Animal");
}
public virtual void sayHi()
{
Console.WriteLine("Animal sayHi");
}
}

class Cat : Animal
{
public Cat()
{
Console.WriteLine("Cat");
}

public new void sayHi()
{
Console.WriteLine("Cat sayHi");
}
}

class Dog : Animal
{
public Dog()
{
Console.WriteLine("Dog");
}

public override void sayHi()
{
Console.WriteLine("Dog sayHi");
}
}

The result is shown below:

Thursday, November 3, 2011

Could not load file or assembly Microsoft.SqlServer.Smo

In order to use BAM Alerts in Biztalk Server projects, I need to install SQL Notification Services.

I download needed package from the following three components:

1. Microsoft SQL Server native Client
2. Microsoft SQL Server 2005 Management Objects Collection
3. Microsoft SQL Server 2005 Notification Services Client Components

Go to "C:\Windows\assembly", I can find out the relevant dll whose version is '9.0.242.0'.


After the installation of SharePoint Server 2010, the relevant dll is disappeared.Then I cannot configure BAMTool in Biztalk Server 2010.

Hence, I change the order of my installation. 

Tuesday, October 18, 2011

PowerShell: Script to Create a Website

//enable run script in PowerShell
Set-ExecutionPolicy RemoteSigned

//import module
Import-Module WebAdministration

//create a application pool
New-WebAppPool testpool
Set-ItemProperty iis:\AppPools\testpool -name processModel -value @{username="administrator";password="password";identitytype=3}
Set-ItemProperty iis:\AppPools\testpool -name managedRuntimeVersion -value v4.0

//create a web site
New-Item iis:\sites\testSite -physicalpath "C:\Users\WebSite" -bindings @{protocol="http";bindingInformation=":8083:"} -ApplicationPool testPool
$website = get-item iis:\sites\testSite
$website.virtualDirectoryDefaults.userName="administrator"
$website.virtualDirectoryDefaults.password="password"
$website | set-item 

Monday, October 17, 2011

PowerShell: Get-Service -Name "MSSQL$SQLEXPRESS"

You can use "get-service" command to get current status of the service.

But, when I execute the following command in PowerShell:

   Get-Service -Name "MSSQL$SQLEXPRESS"

There is an error found below:

  Get-Service : Cannot find any service with service name 'MSSQL'.
  At line:1 char:12
  + Get-Service <<<< -Name "MSSQL$SQLEXPRESS"

The solution is: using "*" instead of "$"

Tuesday, September 20, 2011

WCF: enable rest operation

I need to call a WCF service through Get, Put and Post operation. And there are some settings needed  in the service contract and web.config.

Methods can be called  through the following URL:

http://ip/sitename/Service1.svc/user/post/{value}

For service contract:
 [ServiceContract]
    public interface IService1
    {
        [OperationContract]
        [WebGet(UriTemplate = "?value={value}")]
        string GetData(int value);
        [OperationContract]
        [WebInvoke(Method = "POST", UriTemplate = "post/{value}")]
        string PostData(String value);
        [OperationContract]
        [WebInvoke(Method = "PUT", UriTemplate = "put/{value}")]
        string PutData(string value);
    }
For web.config:

      
          
              
              
              
          
      
     
        
            
                
            
        
        
        
          
          
        
      
    
    
  

SSH SCP put command workflow: unable to put file

I run the default SCP put command workflow in the orchestrator and the workflow finishes without any error code. But I cannot find the file in the destination.

In the API Explorer, I do some searching. I discover the description of SSHSession which is used to replace SSHCommand.



//original code
var sshCmd = new SSHCommand(ip,username,password) ;
sshCmd.putFile("C:\\orchestrator\\hoho", "//") + "||");
var error = sshCmd.getError() ;
sshCmd.disconnect();


//updated code
var sshSession = new SSHSession(ip,username);
sshSession.connectWithPassword(password);
sshSession.putFile("C:\\orchestrator\\hoho", "hoho");
sshSession.disconnect();

Saturday, July 16, 2011

Linux: loopback address

I run a java application under Linux environment and it throw an exception.

"Server failed to start: java.rmi.RemoteException: Cannot start. localhost.localdomain is a loopback address"

The problem seems related to the host file (\etc\hosts) and its content is shown below:

127.0.0.1 localhost.localdomain localhost
::1 localhost






After the configuration, everything works fine.

Thursday, July 14, 2011

OleDbConnection: insert a parameter into a query

I want to create a OleDbConnection to a excel file and create a parameterized query. An example from msdn is shown below:

string queryString = "SELECT * FROM Table1 WHERE Field1 LIKE ?";
OleDbCommand command = new OleDbCommand(queryString, connection);
command.Parameters.Add("@p1", OleDbType.Char, 3).Value = "a";
OleDbDataReader reader = command.ExecuteReader();

For your reference:
http://msdn.microsoft.com/en-us/library/system.data.oledb.oledbparameter.aspx
http://blogs.msdn.com/b/wriju/archive/2008/01/24/ado-net-oledbcommand-parameterized-query-sequence-rule.aspx

Wednesday, June 29, 2011

JMeter: Distributed Test

I want to set up a distributed testing in my network. Then, I prepare a new vm and configure the settings. You can follow the instruction in the link below:



After the configuration, I run the ApacheJMeter.jar as normal. The next step, I click Run=>Remote Start=>127.0.0.1 and an error message is popped up: 

"Connection refused to host: 127.0.0.1;nested exception is: java.net.ConnectException: Connection refused: connect"


After my investigation, I discover something which can explain above message. If you clcik Run=>Start, the application functions fine. If you click Run=>Remote Start=>127.0.0.1, please run jmeter-server.bat. It is because the application treat the localhost as one of the slaves. 

Everything works fine when I run this bat file.

Friday, June 17, 2011

OpenXml: add reference to System.IO.Packaging

In order to use the API of OpenXML, I need to add a reference to "System.IO.Packaging" to the .Net project.

In a C# file, I cannot reference the .dll directly using "System.IO.Packaging".



Then, I  right click the Reference and then select "Add Reference..." under Solution Explorer 


But I cannot find "System.IO.Packaging" under Tab ".Net"


After my searching, I know that I need to add a reference to "WindowBase" instead of "System.IO.Packaging"


Then, I can reference successfully.



Tuesday, June 14, 2011

Jet 4.0: columns data type in Excel file

Under Jet 4.0, by default, it determine the column data type by first 8 rows.

If you want to the driver determine the data type considering all rows, you can edit the "TypeGuessRows" in Registry Editor.

Go to the Registry Editor by typing "regedit" in cmd, 


Under Registry Editor, go to HKKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Jet\4.0\Engines\Excel



Then, Edit the value "TypeGuessRows" to 0 which means consider all rows to guess data type.


Monday, May 30, 2011

SharePoint foundation: deploy a event handler for custom list

There are severals methods to deploy event handler in SharePoint:
(1) deploy through Visual Studio 2010
(2) deploy solutions through stsadm command

Link an event handler to a specific list
When you create an evnet handler, you cannot find any custom list name in event source.


You select Custom List and press button Finish. After the creation of event handler, you can double click the Elements.xml under EventReceiver1.


Then, you need to change the line from

       <Receivers ListTemplateId="104">

to

      <Receiver ListUrl="List/helloWorld">

 Now, the event handler is linked to the list helloWorld


Deploy the event handler through Visual Studio 2010




There is only one step you need to do: right click the solution and select Deploy. Then, Visual Studio 2010 will deploy and activate the solution automatically.

Deploy the event handler though stsadm

(1) add solution

(2) deploy solution
   
(3) activate the solution


     Go to Site Settings -> Manage site features and press button Activate for the solution


Reference: http://patrickboom.wordpress.com/2010/05/31/using-powershell-to-deploy-sharepoint-solutions-wsp-2/

SharePoint foundation: deploy a workflow in sharepoint

There are several steps needed to deploy workflow solutions manually by stsadm command.

1.  add a solution into SharePoint

 
2. deploy the solution into SharePoint


3. execute the time job


4. Go to Site Settings -> Site Collection Administration -> Site collection features and activate the feature


5. Go to Site Settings -> Site Administration -> Workflows, the status of the feature is active



Tuesday, May 10, 2011

Cannot edit DCOM Config properties

I get an error from my event handler which suggests me to modify  the {000C101C-0000-0000-C000-000000000046} using the Component Services administrative Tool.

1. Administrative Tools ->  Component Services -> {000C101C-0000-0000-C000-000000000046}
2. Right click the {000C101C-0000-0000-C000-000000000046} and then select properties
3. Go to security tab and I cannot edit the "Launch and Activation Permission" and "Access Permissions" ad the choices are grayed out

After another searching, I know that I need to do something in Register Editor

1.  In cmd, type "regedit"
2. Go to HK_LOCAL_MACHINE\SOFTWARE\Classes\AppID\{000C101C-0000-0000-C000-000000000046}
3. Right click it and select permission and then click Adanced
4. Go to Owner tab and update Administrators ad the current Owner


5. Grant the administrators "Full Control"

6. Restart the Component Services

7. You can modify the Permissions now

Monday, May 2, 2011

Event Handler: The object cannot be created from sandboxed code assembly

I create an solution of event handler whose name is "eventHandler-v1.0" and then bind the event handler to a list in SharePoint.

When I start debugging the solution in Visual Studio 2010, an error message is shown as below
"Error creating instance of sandboxed code object. The object cannot be created from sandboxed code assembly."


I suspect the problem comes from the name of my solution which contains '.', so  I try to create a solution whose name without '.' and everything works fine.

Friday, April 29, 2011

Oracle: extract data from Oracle in Window Server 2008 (64 bit)

I need to create an application which is hosted in IIS under 64 bit Window Servers 2008. There are several steps needed to prepare and they are shown as below:

1. download 64 bit Oracle Client and install administration type
     win64_11gR2_client.zip

2. download 32 bit Oracle Client and install administration type
    win32_11gR2_client.zip

3. use Net Configuration Assistant to name a database into tnsname.ora

4. log off the window so that the system can update the environment.

C#: Hosting an WCF application in IIS 7

I need to host an WCF application in IIS 7 under Window Servers 2008 R2. There are several steps needed to follow.

Create an WCF project in Visual Studio 2010



After creating a project WcfService, there are IWCFService.cs, WCFService.svc, WCFService.svc.cs and web.config in the solution.

For IWCFService.cs, you need to declare methods and customer data type.

namespace WcfService
{
     [ServiceContract]
     public interface IWCFService
     {
           [OperationContract]
           People SayHello();
     }
     [DataContract]
     public class People
     {
           [DataMember]
           public String id {get; set;}
           public String name {get; set;}
      }
}

For WCFService.svc.cs, you need to create the method declared in Operation Contract.

namespace WcfService
{
     public class WCFService: IWCFService
     {
           public People SayHello()
           {
                 return new People() {
                          id = "1",
                          name = "name"
                 };
            }
      }
}
For web.config, in order to host in IIS 7, it needs some configurations.


<?xml version="1.0"?> <configuration> <system.serviceModel> <services> <service behaviorConfiguration="CustomerServiceBehavior" name="WcfService.WCFService"> <endpoint address="" binding="wsHttpBinding" contract="WcfService.IWCFService"/> <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/> </service> </services> <behaviors> <serviceBehaviors> <behavior name="CustomerServiceBehavior"> <serviceMetadata httpGetEnabled="true"/> <serviceDebug includeExceptionDetailInFaults="true"/> </behavior> </serviceBehaviors> </behaviors> </system.serviceModel> <system.webServer> <modules runAllManagedModulesForAllRequests="true"/> <directoryBrowse enabled="true"/> </system.webServer> <system.web> <compilation debug="true"/></system.web></configuration>
For WCFService.svc, by default, you need not modify it.

<%@ ServiceHost Language="C#" Debug="true" Service="WcfService.WCFService" CodeBehind="WCFSevice.svc.cs" %>
Debugging Tool
It is quite difficult to do debugging in WCF application. Visual Studio 2010 provides a WCF Testclient interface for developer to invoke menthods.


Configure the file permission for IIS
In order to host the project in IIS, it require to access information inside. You need to select the project folder and then right click "Properties". Under tab "Security", add IIS_IUSERS and assign read permission to it.


Hosting the project in IIS 7
Under IIS, right click folder "Sites" and select "Add Web Site..."


If your application runs under .Net 4.0 version, you need to go to application. Click the application and then click "Advanced Settings..."  to update ".Net Framework Version" to v4.0


Last but not least, you need to restart the web site.

Thursday, April 28, 2011

C#: Read and Query Data from Excel File

The following code will show a simple example which reads and queries data in the file.

       protected static String connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;" +
                                  "Data Source=" + "C:\\sharedsupport.xls;" +
                                  "Extended Properties=Excel 8.0;";         //
        //"Select * from [" + DropDownList1.SelectedValue + "$A5:I" + rowNum + "]"         //
        public Product findValue(Product item, DataTable table, ArrayList fieldList)
        {
            var query = from r in table.AsEnumerable()
                        where r.Field<String>("Product Part Number") == item.name
                        select new{family = r.Field<Object>(fieldList[0].ToString())};
            foreach (var q in query){
                retun new Product() {family = q.family.ToString()};
            }
            return item;
        }         //
        public DataTable getQueryTable(String cmd)
        {
            OleDbConnection conn = new OleDbConnection(connectionString);
            conn.Open();
            OleDbCommand dbCommand = new OleDbCommand(cmd, conn);
            OleDbDataAdapter adapter = new OleDbDataAdapter();
            adapter.SelectCommand = dbCommand;
            DataSet dataSet = new DataSet();
            adapter.Fill(dataSet);
            conn.Close();
            return dataSet.Tables[0];
        }

Wednesday, April 27, 2011

C#: The Microsoft.ACE.OLEDB.14.0 provider is not registered on the local machine

I need to create an application which reads data from a excel file in 64 bit environment and an driver is needed.

Microsoft Access database Engine 2010 Redistributable

After I install the 64bit version, I run the following code to create a connection to an excel file

String connectionString = "Provider=Microsoft.ACE.OLEDB.14.0;" +
                                    "Data Source=" + "C:\\Downloads\\haha.xls;" +
                                    "Extended Properties=Excel 8.0;HDR=YES;";
OleDbConnection conn = new OleDbConnection(connectionString);
conn.Open();
When I runs the above code,  conn.Open() throws an InvalidOperationException was unhandled by user code. The exception shows "The Microsoft.ACE.OLEDB.14.0" provider is not registered on the local machine.


In order to solved this problem, I create a new VM and install the AccessdatabaseEngine.exe in a 64 bit environment. After that, the above code runs fine.

SQL Server: TCP Connection Opening

In order to remote access a SQL Server, I need to open a TCP port for listening.There are several steps are needed to prepared.

(1) Go to "Sql Server Configuration Manager" and expand "SQL Server Network Configuration"

(2) Click the designated instance "SQLEXPRESS"


(3) Right Click "TCP/IP" and then select "Enable"

(4) Right Click "TCP/IP" and then select "Properties"

(5) Select tab "IP Address"

(6) Under "IPALL", enter port "1433" in "TCP Port"


(7) Click button "OK" 

(8) Under "SQL Server Services", right click the designated instance and then select "Restart"