понедельник, 17 октября 2011 г.

Google Chrome Java Script Consol and jquery in Sharepoint 2010

Hello!
How to debug you java script in console google Chrome? All good, but, where you use jquery and function $(),
you have one small problems. Sharepoint has his function $().
Open C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\TEMPLATE\LAYOUTS\1033   file - CmsSiteManager.js
and replace $ on Microsoft$. It's all.
Good day!

воскресенье, 11 сентября 2011 г.

Sort list of Views with sql method


this powershell script sort list of views without they deleting.


$SortedListUser = New-Object 'System.Collections.Generic.List[string]'
$MyPath = Read-Host "Path To File"
$MyFile = Get-Content $MyPath
foreach ($i in $MyFile) {
if($i -ne "")
{
   $SortedListUser.Add($i)
}
}
$SortedListDesc = New-Object 'System.Collections.Generic.List[string]'
for( $i = $SortedListUser.Count; $i -ge 0; $i-=1 )
{ $SortedListDesc.Add($SortedListUser[$i]) }
$Connection = New-Object System.Data.SQLClient.SQLConnection
$Connection.ConnectionString =
"Data Source=server;Initial Catalog=db ;Integrated Security=True"
$Connection.Open()
$TeamSitePrompt = Read-Host "What is the Team Site URL (i.e. http://test.com/teamsite)"
$ListNamePrompt = Read-Host "What is the List Name you want to sort"
$Web = Get-SPWeb $TeamSitePrompt
$List = $Web.Lists[$ListNamePrompt]
$Views = $List.Views
#Create a Sorted List to store the Views you want to Sort
$SortedList = New-Object 'System.Collections.Generic.List[string]'  
foreach ($CurrentItemUser in $SortedListUser)
{
foreach ($CurrentViewItem in $Views)
{

if($CurrentItemUser -eq $CurrentViewItem.Title)
{
  Write-Host $CurrentViewItem.Id
  $uslovie = $CurrentViewItem.Id
  $Command = New-Object System.Data.SQLClient.SQLCommand
  $Command.Connection = $Connection
  $Command.CommandText = "UPDATE WSS_Content.dbo.AllWebParts SET tp_CreationTime = GETDATE() Where tp_ListId ='"+$List.Id+"' AND tp_ID ='"+$CurrentViewItem.Id+"'"
  #$Command.CommandText
$Command.ExecuteNonQuery()
}
}
}
$Connection.Close()


Create txt  file, sorting name of views :
view1
view2
view3

Run script!

Add items to dropdown in a Infopath with sql data


First add a field, check "Repeating" checkbox and select this field in the drop down control from "Look up values in the form's data source".
Then using the following code, add the data.



 private string getConnectionString(SPWebApplication myWebApplication,string typeBD)
        {
            string ConnectionString = string.Empty;
            if (myWebApplication.Properties != null && myWebApplication.Properties.Count > 0 && myWebApplication.Properties.ContainsKey(typeBD))
            {
                ConnectionString = GetString(myWebApplication.Properties[typeBD]);
            }
            return ConnectionString;
        }
        private string GetString(object obj)
        {
            string str = "";
            if (obj != null)
                str = obj.ToString();
            return str;
        }

        public void FormEvents_Loading(object sender, LoadingEventArgs e)
        {
             string connection = "";
             using (SPSite site = new SPSite(this.ServerInfo.SharePointSiteUrl.ToString()))
             {
                 connection = getConnectionString(site.WebApplication, "Akcent");
                 string query = "";
                 query = @"SELECT
                                 [id]
                                ,[guid]
                                ,[code]
                                ,[caption]
                                ,[type_id]
                            FROM [Budget].[SACG].[v_ref_cfo_src]";
                 int field_sql = 3;//поле отображения
                 SetDataToDropDown(connection, query, "ValuesField", field_sql);
}
}

This method get the field with data and set you values!

private void SetDataToDropDown(string connection,string queryString,string fieldName,int field_sql)
        {
            DataSet dsLoc = GetDataFromSql(connection,queryString);
            XPathNavigator DOMMain = DataSources[""].CreateNavigator();
            XPathNavigator Loc = DOMMain.SelectSingleNode("/my:myFields/my:"+fieldName, this.NamespaceManager);
            Loc.SetValue("");
            XPathNavigator templateNode = Loc.Clone();
            foreach (DataRow dr in dsLoc.Tables[0].Rows)
            {
                XPathNavigator newNode = templateNode.Clone();
                string value = dr[field_sql].ToString();
                newNode.SetValue(value);
                Loc.InsertAfter(newNode);
            }
            Loc.DeleteSelf();
        }
        private DataSet GetDataFromSql(string connection_string, string queryString)
        {
            DataSet dsLoc = new DataSet();
            SPSecurity.RunWithElevatedPrivileges(delegate()
           {
               using (SqlConnection connection = new SqlConnection(connection_string))
               {
                   connection.Open();
                   SqlCommand command = new SqlCommand(
                       queryString, connection);
                   SqlDataAdapter sqlData = new SqlDataAdapter(command);
                   sqlData.Fill(dsLoc);
                   connection.Close();
               }
           });
            return dsLoc;
        }

It's all!

InfoPath 2010 and new SPSite() error


Hello, if you work with infoPath and try create an new SPSite object you have an error with "/".
This means that, you infoPath form dont have need permissions in security level.
Do next step: Go to "File"

click "Advanced form options":
Set "Full trast".
Now, you are can create an new SPSite!

четверг, 8 сентября 2011 г.

Call WCF service (on Sharepoint 2010) from MSSQL2008 x64

Hello, I call wcf service (on sharepoint 2010) from MSSQL 2008 x64.
First open Visual studio, and create empty sharepoint project and add wcf project.
example


using Microsoft.SharePoint.Client.Services;
using System.ServiceModel.Activation;
using Microsoft.SharePoint;
using System;
using System.Text;

namespace SharePointWCF
{
    [BasicHttpBindingServiceMetadataExchangeEndpoint]
    [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Required)]
    public class WCFSql : IWCFSql
    {
        // To test this service, use the Visual Studio WCF Test client
        // set the endpoint to http://sp1/_vti_bin/SharePointWCF/WCFSql.svc/mex
        public string UpdateStatus(string url,string testSTR)
        {
            SPSecurity.RunWithElevatedPrivileges(delegate() {
            using (SPWeb web = new SPSite(url).OpenWeb())
            {
                SPList list = web.Lists["HelloSql"];
                SPListItem item = list.AddItem();
                item["Title"] = testSTR;
                item.Update();
            }
            });
            return "true";
        }
    }
}


Example sql Trigger:

using System;
using System.Data;
using System.Data.SqlClient;
using Microsoft.SqlServer.Server;
using System.Web;
using SqlServerProject1.SQLService;
using System.ServiceModel;
public partial class Triggers
{

    // Enter existing table or view for the target and uncomment the attribute line
    public static void Trigger1()
    {
        System.ServiceModel.EndpointAddress ep = new System.ServiceModel.EndpointAddress(new Uri("http://sp1/_vti_bin/SharePointWCF/WCFSql.svc"));
        BasicHttpBinding binding = new BasicHttpBinding();
        binding.Security.Mode = BasicHttpSecurityMode.TransportCredentialOnly;
        binding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Ntlm;
        //Create an instance of the service proxye
        SqlServerProject1.SQLService.WCFSqlClient SqlService = new SqlServerProject1.SQLService.WCFSqlClient(binding, ep);
        SqlService.ChannelFactory.Credentials.Windows.ClientCredential = new System.Net.NetworkCredential("login", "pass", "domain");
        SqlService.ClientCredentials.Windows.ClientCredential = new System.Net.NetworkCredential("login", "pass", "domen");
        SqlService.ClientCredentials.UserName.UserName = @"domain\login";
        SqlService.ClientCredentials.UserName.Password = @"pass";
        // Replace with your own code
        SqlContext.Pipe.Send("Trigger FIRED");
        SqlTriggerContext triggContext = SqlContext.TriggerContext;
        SqlConnection conn = new SqlConnection("context connection =true");
        conn.Open();
        SqlCommand sqlComm = conn.CreateCommand();
        SqlPipe sqlP = SqlContext.Pipe;
        SqlDataReader dr;
        sqlP.Send("ddddd");
        sqlComm.CommandText = "SELECT [SP_ID],[Status] from inserted";
        dr = sqlComm.ExecuteReader();
        while (dr.Read())
            SqlService.UpdateStatus("http://sp1/",dr[0].ToString());
        
    }
}

Next go to MSSQL2008.

Steps.
1. Go to the management studio of SQL Server, first makes sure we are CLR enabled. 
user master
go
sp_configure 'clr enabled', 1
go
reconfigure
go


2. Set the database trushworthy
alter database [database name]
set trustworthy on;
go


3. Create assemblies. When I created relate assemblies, I got numerous errors. I' going to explain how I made them worked. 

problem 1)
Msg 33009, Level 16, State 2, Procedure usp_xxxxx, Line 0
The database owner SID recorded in the master database differs from the database owner SID recorded in database ‘YourDatabase’. You should correct this situation by resetting the owner of database ‘YourDatabase’ using the ALTER AUTHORIZATION statement.


=> I executed the below command. 
EXEC dbo.sp_changedbowner @loginame = N'sa', @map = false

Sum up

all created assemblies and their paths are the following.
1) System.Runtime.Serialization
'C:\Windows\Microsoft.NET\Framework\v3.0\Windows Communication Foundation\System.Runtime.Serialization.dll'

2) SMDiagnostics
'c:\Windows\Microsoft.net\Framework\v3.0\Windows Communication Foundation\SMdiagnostics.dll'


3) System.Web
'C:\Windows\Microsoft.NET\Framework64\v2.0.50727\System.Web.dll'


4) System.Messaging
'C:\Windows\Microsoft.NET\Framework64\v2.0.50727\System.Messaging.dll'


5) System.IdentityModel
'C:\Windows\winsxs\msil_system.identitymodel_b77a5c561934e089_6.1.7601.17514_none_f1b6cabd00b1e098\System.IdentityModel.dll'


6) System.IdentityModel.Selectors
'C:\Program Files\Reference Assemblies\Microsoft\Framework\v3.0\System.IdentityModel.Selectors.dll'      


7) Microsoft.Transactions.Bridge
'C:\Windows\Microsoft.NET\Framework\v3.0\Windows Communication Foundation\Microsoft.Transactions.Bridge.dll'      


8) System.ServiceModel
'C:\Program Files\Reference Assemblies\Microsoft\Framework\v3.0\System.ServiceModel.dll'


9) System.Drawing
'C:\Windows\Microsoft.NET\Framework64\v2.0.50727\System.Drawing.dll'

Test you trigger!




среда, 24 августа 2011 г.

Sort views in "List Views"

Group by more 2 fields in List sharepoint 2010

Delete Label "New" for New ListItem

Windows SharePoint Services 3.0 Web site

To stop the !New tag from appearing next to new entries on a Windows SharePoint Services 3.0 Web site, use the Stsadm.exe tool to change the "Days to Show New Icon" property to zero.

To do this, follow these steps:
  1. Click Start, point to All Programs, point to Accessories, and then click Command Prompt.
  2. Type the following commands, and then press ENTER after each command:
    cd /d %programfiles%\Common Files\Microsoft Shared\Web Server Extensions\12\BIN
    stsadm.exe -o setproperty -pn days-to-show-new-icon -pv 0 -url [Your Virtual Server's URL] 

    Windows SharePoint Services Web site

    To stop the !New tag from appearing next to new entries on a Windows SharePoint Services Web site, use the Stsadm.exe tool to change the "Days to Show New Icon" property to zero.

    To do this, follow these steps:
    1. Click Start, point to All Programs, point to Accessories, and then click Command Prompt.
    2. Type the following commands, and then press ENTER after each command:
      cd /d %programfiles%\Common Files\Microsoft Shared\Web Server Extensions\60\BIN
      stsadm.exe -o setproperty -pn days-to-show-new-icon -pv 0 -url [Your Virtual Server's URL]

SharePoint Team Services Web site

To stop the !New tag from appearing next to new entries on a SharePoint Team Services Web site, use the Owsadm.exe tool to change the "New Item Display Cutoff" property to zero.

To do this, follow these steps:
  1. Click Start, point to All Programs, point to Accessories, and then click Command Prompt.
  2. Type the following commands, and then press ENTER after each command:
    cd /d %programfiles%\Common Files\Microsoft Shared\Web Server Extensions\50\BIN
    owsadm.exe -o setproperty -pn NewItemDisplayCutoff -pv 0 -p [Your Virtual Server's Port]

понедельник, 18 июля 2011 г.

Sharepoint WCF and java script

Сегодня поговорим о возможности запросов к пользовательским wcf из java script кода.
Как создавать пользовательский  wcf я не буду рассматривать, это очень просто. Рассмотрим мой js класс для работы с wcf.
var MakeClass = function(){
    return function( args ){
        if( this instanceof arguments.callee ){
            if( typeof this.__construct == "function" ) this.__construct.apply( this, args );
        }else return new arguments.callee( arguments );
    };
}
var NewClass = function( variables, constructor, functions ){
    var retn = MakeClass();
    for( var key in variables ){
        retn.prototype[key] = variables[key];
    }
    for( var key in functions ){
        retn.prototype[key] = functions[key];
    }
    retn.prototype.__construct = constructor;
    return retn;
}
var GetCurrantUser = NewClass({
 "UserLogin":"",
 "UserName":"",
 "web":null,
 "currentUser":null,
 "context":null,
 "propertyName":"Title",
 "url":"",
 "params":null,
 "method":""
 },
 function(url,params,method)
 {
    this.method = method;
    this.params = params;
    this.url = 'http://'+document.domain+url;
    this.connect();
 },
 {
 "connect": function()
 {
                        try
                            {
                            this.context = new SP.ClientContext.get_current();
                            this.web = this.context.get_web();
                            this.currentUser = this.web.get_currentUser();
                            this.currentUser.retrieve();
                            this.context.load(this.web);
                            this.context.executeQueryAsync(Function.createDelegate(this, this.onSuccessMethod), Function.createDelegate(this, this.onFailureMethod));
                            }
                            catch(e)
                            {
                            var self = this;
                            setTimeout(function() {self.connect();}, 5000);
                            }
 },
 "onSuccessMethod":function(sender, args)
 {
 var userObject = this.web.get_currentUser();
 this.Set_userData(userObject.get_title(),userObject.get_loginName());
    //alert('User name:' + userObject.get_title() + '\n Login Name:' + userObject.get_loginName());
 },
 "onFailureMethod":function(sender, args)
 {
 //alert('request failed ' + args.get_message() + '\n' + args.get_stackTrace());
 alert('Error');
 },
 "Set_userData":function(name,login)
 {
    this.UserName = name;
    this.UserLogin = login;
    this.GetUserPropertyByAccountName();
 },
 "get_hostname_from_url":function(url) {
    return url.match(/:\/\/(.[^\/]+)/)[1];
},
 "GetUserPropertyByAccountName": function() {
 // VariablesW
 var xmlHttpReq = null;
 // Mozilla/Safari
 if (window.XMLHttpRequest) {
  xmlHttpReq = new XMLHttpRequest();
 }
 //IE
 else if (window.ActiveXObject) {
  xmlHttpReq = new ActiveXObject("Microsoft.XMLHTTP");
 }
 if (xmlHttpReq) {
     xmlHttpReq.open('POST', this.url, false); //если мы ставим тут true то это значит асинхронность запроса, и нужно писать метод для него, он у нас был =) но там был неверный хмл
  //Set the Headers
  xmlHttpReq.setRequestHeader('Content-Type', 'text/xml');
  xmlHttpReq.setRequestHeader('SOAPAction', 'http://tempuri.org/I'+this.url.split("/")[this.url.split("/").length-1].match(/.*(?=[.])/)+'/'+this.method);
  //get the XML Request string
    var xml_params="";
      for(var key in this.params ){
      xml_params+='<'+key+'>'+this.params[key]+'</'+key+'>';
    }
  xmlHttpReq.send('<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/">'
    + '<s:Body>'
    + '<'+this.method+' xmlns="http://tempuri.org/">'
    + xml_params
    + '</'+this.method+'>'
    + ' </s:Body>'
    + '</s:Envelope>');
if (xmlHttpReq.readyState == 4) {
    if (xmlHttpReq.status == 200) {
    var re = new RegExp("(?:(<"+this.method+"Result>))(.*(?=(<\/"+this.method+"Result>)))", "g");
    alert(xmlHttpReq.responseText.match(re));
    alert(xmlHttpReq.responseText);
    }
    else {
     alert(xmlHttpReq);
    }
   }
 }
 else {
  alert('unable to create XMLHttpRequest object');
 }
}
})
var user = GetCurrantUser('/_vti_bin/WCF/WCFjs.svc',{"str":"str"},"HelloWorld");
Для работы с wcf вам просто нужно в конструктор передать путь к нему ('/_vti_bin/WCF/WCFjs.svc'), название и значение параметров ({"str":"str"}) и им метода ("HelloWorld").
Результатом будет вывод на экран ответа от сервера, дальнейший разбор xml зависит от ваших задач. Спасибо.

вторник, 5 июля 2011 г.

Sharepoint 2010 and UserProfileManager from console app

Добрый день!
Когда вы работаете с консольного приложения и получаете ошибку (Object reference not set to an instance of an object) при таком коде:
UserProfileManager profileManager = new UserProfileManager(contect);

Нужно сделать следующее:
  1. Open the SharePoint 2010 Central Administration page, and then click Manage Service Applications.
  2. Select the row for the User Profile Service application. Instead of clicking the name, select the row to highlight it.
  3. On the Service Applications tab, click Permissions.
  4. In the Connection Permissions for User Profile Service Application dialog box, add the user or group that needs permission to run impersonation applications. After you click Add, and the user name shows in the list of claims, select the added user in the list and then select the Full Control check box. Otherwise, the user is not added when you click OK. Full Control is the only option.
  5. To ensure that the user or group is added, reopen the Connection Permissions for User Profile Service Application dialog box and confirm that the new user or group displays in the list of claims. 
Ссылка на  оригинал статьи:  
 http://ctp.social.technet.microsoft.com/Forums/en-NZ/sharepoint2010programming/thread/09ca1621-1c26-4208-ab62-7bf52df14e23

Экспорт SPList in Excel

Поговорим о экспoрте листа в Excel, и сохранения его в библиотеке документов.
Очень часто возникает необходимость экспортировать не весь список в excel а только некую его часть. Я покажу пример того, как быстро и удобно построить такой экспорт. Использовать мы будем решение которое базируется на создании простого xml:
XmlDocument _report;
            StringBuilder file_content = new StringBuilder();
            file_content.Append(@"<?xml version='1.0'?>
                <?mso-application progid='Excel.Sheet'?>
                <Workbook xmlns='urn:schemas-microsoft-com:office:spreadsheet'
                 xmlns:o='urn:schemas-microsoft-com:office:office'
                 xmlns:x='urn:schemas-microsoft-com:office:excel'
                 xmlns:ss='urn:schemas-microsoft-com:office:spreadsheet'
                 xmlns:html='http://www.w3.org/TR/REC-html40'>
                 <DocumentProperties xmlns='urn:schemas-microsoft-com:office:office'>
                  <Author>PIB</Author>
                  <LastAuthor>PIB</LastAuthor>
                  <LastPrinted>2009-09-15T12:46:54Z</LastPrinted>
                  <Created>2004-05-05T13:41:40Z</Created>
                  <LastSaved>2010-01-18T12:59:49Z</LastSaved>
                  <Company>PIB</Company>
                  <Version>1.00</Version>
                 </DocumentProperties>
                 <OfficeDocumentSettings xmlns='urn:schemas-microsoft-com:office:office'>
                  <AllowPNG/>
                 </OfficeDocumentSettings>
                 <ExcelWorkbook xmlns='urn:schemas-microsoft-com:office:excel'>
                  <SupBook>
                   <Path>Sheet2</Path>
                   <SheetName>Sheet2</SheetName>
                  </SupBook>
                  <WindowHeight>6450</WindowHeight>
                  <WindowWidth>9720</WindowWidth>
                  <WindowTopX>-15</WindowTopX>
                  <WindowTopY>-15</WindowTopY>
                  <TabRatio>831</TabRatio>
                  <PrecisionAsDisplayed/>
                  <DoNotSaveLinkValues/>
                  <ProtectStructure>False</ProtectStructure>
                  <ProtectWindows>False</ProtectWindows>
                 </ExcelWorkbook>
                 <Styles>
                  <Style ss:ID='Default' ss:Name='Normal'>
                   <Alignment ss:Vertical='Bottom'/>
                   <Borders/>
                   <Font ss:FontName='Arial Cyr' x:CharSet='204'/>
                   <Interior/>
                   <NumberFormat ss:Format='_(* #,##0_);_(* \(#,##0.00\);_(* ??_);_(@_)'/>
                   <Protection/>
                  </Style>
                  <Style ss:ID='s62'>
                  <Alignment ss:Vertical='Bottom' ss:WrapText='1'/>
                  <NumberFormat ss:Format='@'/>
                  </Style>
                 </Styles>
                <Worksheet ss:Name='Рабочий лист");
 Дальше объявляем поля:
file_content.Append(@"'>
                                 <Names>
                                   <NamedRange ss:Name='spp10test_akhz_bp_vw_day_real_plan_all'
                                    ss:RefersTo='=Sheet2!R1C1:R31465C8'/>
                                  </Names>
                              <Table ss:ExpandedColumnCount='14'>
                               <Column ss:Width='20'/>
                               <Column ss:Width='80'/>
                               <Column ss:Width='150'/>
                               <Column ss:Width='250'/>
                               <Column ss:Width='100'/>
                               <Column ss:Width='50'/>
                               <Column ss:Width='152'/>
                               <Column ss:Width='100'/>
                               <Column ss:Width='122'/>
                               <Column ss:Width='122'/>
                               <Column ss:Width='180'/>
                               <Column ss:Width='100'/>
                               <Column ss:Width='102'/>
                               <Column ss:Width='140'/>
                               <Row>");
Вносим название колонок из массива:
public static string[] Workshops = new string[] {
            "№ п/п",
            "Дата и время",
            "Тема жалобы",
            "Описание жалобы",
            "Регион",
            "Город",
            "Ф.И.О. Клиента",
            "Телефон клиента",
            "Зарегистрировал",
            "Исполнитель",
            "Результат решения",
            "Дата, время обратной связи",
            "Примечания",
            "Статус обращения" 
        };
 Добавляем поля:
foreach(string name in Workshops)
            {
                file_content.Append(@"<Cell><Data ss:Type='String'>" +name + @"</Data></Cell>");
            }
             file_content.Append(@"</Row>");Дальше я написал фильтер по дате для выбору данных из input
 start_date = Microsoft.SharePoint.Utilities.SPUtility.CreateISO8601DateTimeFromSystemDateTime(DateTime.ParseExact(Hidden_start_date.Value.ToString(), "dd.MM.yyyy", CultureInfo.InvariantCulture));
                end_date = Microsoft.SharePoint.Utilities.SPUtility.CreateISO8601DateTimeFromSystemDateTime(DateTime.ParseExact(Hidden_end_date.Value.ToString(), "dd.MM.yyyy", CultureInfo.InvariantCulture));
         
и сам запрос к листу:
SPQuery query = new SPQuery();
            query.Query = "<Where><And><Geq><FieldRef Name='CallbackDate' /><Value  Type='DateTime'>" + start_date + "</Value></Geq><Leq><FieldRef Name='CallbackDate' /><Value Type='DateTime'>" + end_date + "</Value></Leq></And></Where>";
            SPListItemCollection items = data_List.GetItems(query);
Теперь заполняем ячейки данными:
foreach (SPListItem item in items)
            {
                file_content.Append(@"<Row><Cell><Data ss:Type='String'>");
                file_content.Append(Get_String_From_Obj(item[Workshops[0]]));
                file_content.Append(@"</Data></Cell><Cell><Data ss:Type='String'>");
                file_content.Append(Get_String_From_Obj(item[Workshops[1]]));
                file_content.Append(@"</Data></Cell><Cell><Data ss:Type='String'>");
                file_content.Append(Get_String_From_Obj(item[Workshops[2]]));
                file_content.Append(@"</Data></Cell><Cell ss:StyleID='s62'><Data ss:Type='String'>");
                file_content.Append(Get_String_From_Obj(item[Workshops[3]]));
                file_content.Append(@"</Data></Cell><Cell><Data ss:Type='String'>");
                file_content.Append(Get_String_From_Obj(item[Workshops[4]]));
                file_content.Append(@"</Data></Cell><Cell><Data ss:Type='String'>");
                file_content.Append(Get_String_From_Obj(item[Workshops[5]]));
                file_content.Append(@"</Data></Cell><Cell><Data ss:Type='String' >");
                file_content.Append(Get_String_From_Obj(item[Workshops[6]]));
                file_content.Append(@"</Data></Cell><Cell><Data ss:Type='String'>");
                file_content.Append(Get_String_From_Obj(item[Workshops[7]]));
                file_content.Append(@"</Data></Cell><Cell><Data ss:Type='String'>");
                file_content.Append(getUser(new SPFieldUserValue(web, Get_String_From_Obj(item["Author"]))));
                file_content.Append(@"</Data></Cell><Cell><Data ss:Type='String'>");
                file_content.Append(getUser(new SPFieldUserValue(web,Get_String_From_Obj(item[Workshops[9]]))));
                file_content.Append(@"</Data></Cell><Cell ss:StyleID='s62'><Data ss:Type='String'>");
                file_content.Append(Get_String_From_Obj(item[Workshops[10]]));
                file_content.Append(@"</Data></Cell><Cell><Data ss:Type='String'>");
                file_content.Append(Get_String_From_Obj(item[Workshops[11]]));
                file_content.Append(@"</Data></Cell><Cell ss:StyleID='s62'><Data ss:Type='String'>");
                file_content.Append(Get_String_From_Obj(item[Workshops[12]]));
                file_content.Append(@"</Data></Cell><Cell><Data ss:Type='String'>");
                file_content.Append(Get_String_From_Obj(item[Workshops[13]]));
                file_content.Append(@"</Data></Cell></Row>");
            }
<Cell ss:StyleID='s62'> это стиль для текстового поля с переносом по буквам в ячейке.
методы которые тут задействованы:

private string Get_String_From_Obj(object obj)
        {
            string str = "";
            if (obj != null)
            {
                str = obj.ToString();
            }
            return str;
        }
        public string getUser(SPFieldUserValue field_user)
        {
            if (field_user != null)
            {
                return Get_String_From_Obj(field_user.LookupValue);
            }
            return "";
        }
Дальше добавим в нашу xml следующие:
file_content.Append(@"</Table>
                            <WorksheetOptions xmlns='urn:schemas-microsoft-com:office:excel'>
                            <PageSetup>
                            <Header x:Margin='0.3'/>
                            <Footer x:Margin='0.3'/>
                            <PageMargins x:Bottom='0.75' x:Left='0.7' x:Right='0.7' x:Top='0.75'/>
                            </PageSetup>
                            <Visible>SheetHidden</Visible>
                            <Print>
                            <ValidPrinterInfo/>
                            <HorizontalResolution>600</HorizontalResolution>
                            <VerticalResolution>600</VerticalResolution>
                            </Print>
                            <Selected/>
                            <FilterOn/>
                            <Panes>
                            <Pane>
                            <Number>3</Number>
                            <ActiveRow>25583</ActiveRow>
                            <ActiveCol>3</ActiveCol>
                            </Pane>
                            </Panes>
                            <ProtectObjects>False</ProtectObjects>
                            <ProtectScenarios>False</ProtectScenarios>
                            </WorksheetOptions>
                            </Worksheet>
                            </Workbook>");
И теперь сохраним его в библиотеку:
 MemoryStream stream = new MemoryStream();
            _report = new XmlDocument();
            _report.LoadXml(file_content.ToString());
            _report.Save(stream);
            SPUser user = web.CurrentUser;
            SPFile file = web.Files.Add(web.Url + "/" + sourceListObj.RootFolder.ToString() + "/" + String.Format("{0}_отчет_{1}.xls", user.Name, date.ToString("dddd, dd MMMM yyyy h mm tt")), stream.GetBuffer(), true);
            file.Update();
 Вот и все!

Edit ListItem in popup window from Silverlight or Js in Sharepoint 2010

Добрый день!
Сегодня поговорим о том, как редактировать элементы списка из Silverlight приложения.
 Нас интересует именно встроенный редактор текста в Sharepoint который позволяет создавать ссылки, загружать картинки, рисовать таблицы и прочие красивые вещи. Но нам ведь не хотелось бы давать доступ на страницу списка для обычных пользователей, поэтому я вам расскажу как сделать это просто и красиво.

Для начала выясним что такое popup окно в sharepoint 2010, это красивое всплывающее окно построенное на js. Пример вы можете увидеть когда открываете редактирование элемента списка или просмотр элемента.
string js =
                    var options = {
url: '_layouts/listform.aspx?PageType=6&ListId='IdList'&ID='IdListItem',
                    title: 'Редактирование элемента',
                    allowMaximize: true,
                    showClose: true,
                    width: 625,
                    height: 525,
                    showMaximized: true,
                    dialogReturnValueCallback: silentCallback};
                    function open() {SP.UI.ModalDialog.showModalDialog(options);}
                   function silentCallback(dialogResult, returnValue) {alert('I am here');}
                    function refreshCallback(dialogResult, returnValue) {
                    SP.UI.Notify.addNotification('Operation Successful!');                             SP.UI.ModalDialog.RefreshPage(SP.UI.DialogResult.OK);
                    }
              HtmlWindow htmlWindow = HtmlPage.Window;
                htmlWindow.Eval(js);
 И нужно просто вызвать функцию  open();
Для выполнения функции по возврату назад я использую  silentCallback(), в которую можно передать параметр и с которой можно вызвать метод Silverlight приложения(как это делать я писал в блоге).
Вот так просто и красиво вы получите Sharepoint редактор текста на своей странице.
И не нужно использовать свои решения и создавать красивые редакторы на которые  могут уйти недели времени.








понедельник, 4 июля 2011 г.

Как работать с javascript из silverlight приложения? Или void Silverlight from js!

Доброе время суток!
Сегодня я расскажу как работать с языком java script из приложения написаного на Silverlight, а так же как осуществить обратную связь, как из java script вызвать метод приложения silverlight или получить доступ к свойству silverlight программы.
Приступим!
Технология Silverlight позволяет очень просто работать с js скриптами, а также регистрировать функции js прям из программы Silverlight! Для доступа к DOM модели используется класс  HtmlPage. Пример вывода "HelloWorld" из программы Silverlight:
HtmlWindow htmlWindow = HtmlPage.Window;
htmlWindow.Eval("alert(\"HelloWorld!\");");
Что бы зарегистрировать свою функцию js из программы Silverlight:
string js = "function Hello()"+
               "{ alert(\"HelloWorld!\");}";
             var script = HtmlPage.Document.CreateElement("script");
            script.SetAttribute("type", "text/javascript");
            script.SetProperty("text", js);
            HtmlPage.Document.Body.AppendChild(script);

И теперь вы его можете вызвать через 
HtmlWindow htmlWindow = HtmlPage.Window;
htmlWindow.Eval("Hello();");

Теперь я расскажу как работать с методами Silverlight приложения из js.
Для этого Вам нужно зарегистрировать в вашем Silverlight приложении объект самого приложения:
 HtmlPage.RegisterScriptableObject("Page", this);
Теперь что бы обратится к этому объекту из js функции нужно найти на странице html контейнер с объектом Silverlight:
function Get_Silverlight()
{
   var silverlightObj_id;
  var reg = new RegExp("(SilverlightObjectTag)");                 
 var objects = document.getElementsByTagName("object");
                    for(i=0;i<objects.length;i++)
                   {                    if(objects[i].getAttribute("id")!=null)
                    {     var match=objects[i].getAttribute("id").match(re);
                    if(match!=null && match.length !=null && match.length > 0)
                   {      silverlightObj_id = objects[i].getAttribute("id");     }}}  return silverlightObj_id;}
Пример кода как можно найти объект Silverlight на странице Sharepoint если вы воспользовались вебпартом для вставки Silverlight. Используя jquery этот код станет в разы проще :)

Теперь что бы вызвать метод в Silverlight приложении нужно указать самому Silverlight приложению что этот метод доступен из вне программы:
[ScriptableMember()]
      public void HelloFromJs(string helloMessage)
      {
HtmlWindow htmlWindow = HtmlPage.Window;
htmlWindow.Eval("alert('"+helloMessage+"');");
       }
И что бы вызвать из js этот метод надо следующее:
function HelloToSilverlight()
                    {
                    var id = Get_Silverlight();//ее мы создали ранее
                   var control = document.getElementById(id);
                   control.content.Page.HelloFromJs("I am js"); //Page мы регистрировали как объект в //Silverlight приложении
                    }
Что бы получить доступ к переменной Silverlight приложении нужно ее обьявить в приложении
 [ScriptableMemberAttribute]
        public string SomeProperty { get; set; }

И доступ к ней будет осуществляться через control.content.Page.SomeProperty
Этот инструмент помогает сделать прочную связь между js и Silverlight а так же обойти ошибку компилятора при передачи кода html в js функцию в Silverlight приложении.
Спасибо!