2010-11-24 1 views
1

Я просмотрел документацию wss 3.0, но ничего не могу найти. Я хотел бы получить локаль для сайта Sharepoint 2007 с помощью веб-сервисов (без доступа к серверу, чтобы он не мог развернуть что-либо на нем), чтобы узнать, в каком часовом поясе настроен сайт. Возможно ли это?Есть ли способ получить локальный сайт сайта Sharepoint с веб-сервисами?

ТНХ

ответ

1

Хорошо, вот что я сделал, чтобы решить эту проблему:

  • сделать запрос к списку для 1 элемента, получая раз набор для локализации сайта
  • сделать запрос для этого элемента , время получения в UTC
  • рассчитать разницу между двумя результатами.

Код:

/// <summary> 
    /// Gets the difference between local time and UTC to calculate offset. 
    /// Makes a query to the list that returns 1 element with times using the locale as set in the site's settings. 
    /// Then makes another query for the same element with UTC times to calculate the difference. 
    /// </summary> 
    /// <param name="list">list to query</param> 
    /// <param name="client">WS object</param> 
    /// <returns>Time offset as TimeSpan object</returns> 
    private TimeSpan getSiteTZOffset(List list, WSLists.Lists client) 
    { 
     //Set up query parameters 
     XmlDocument xmlDoc = new XmlDocument(); 
     XmlNode emptyQuery = xmlDoc.CreateNode(XmlNodeType.Element, "Query", ""); 
     XmlNode queryWithID = xmlDoc.CreateNode(XmlNodeType.Element, "Query", ""); 

     XmlNode ndOptions = xmlDoc.CreateNode(XmlNodeType.Element, "QueryOptions", ""); 
     ndOptions.InnerXml = "<DateInUtc>True</DateInUtc>"; 

     XmlNamespaceManager xnm = new XmlNamespaceManager(xmlDoc.NameTable); 
     xnm.AddNamespace("z", "#RowsetSchema"); 

     // Gets the attribute that serves as modified date 
     MapAttribute modifiedDateAttr = attributes.Single(x => x.Value.DateTimeModifiedField).Value; 
     // Gets the Id attribute 
     MapAttribute idAttr = attributes.Single(x => x.Value.KeyReference).Value; 

     //Get 1 result with site's local time 
     XmlNode resLocalTime = client.GetListItems(list.ListID, list.ViewID, emptyQuery, null, "1", null, null); 
     XmlNodeList itemsLocalTime = resLocalTime.SelectNodes("//z:row", xnm); 

     // 2nd query filters on ID of the item returned by 1st query 
     queryWithID.InnerXml = string.Format("<Where><Eq><FieldRef Name='ID' /><Value Type='Counter'>{0}</Value></Eq></Where>", 
      itemsLocalTime[0].Attributes[idAttr.Name].Value); 

     //get the result with UTC time 
     XmlNode resUtc = client.GetListItems(list.ListID, list.ViewID, queryWithID, null, "1", ndOptions, null); 
     XmlNodeList itemsUtc = resUtc.SelectNodes("//z:row", xnm); 

     //Converts string values to DateTime objects 
     DateTime localTime = DateTime.Parse(itemsLocalTime[0].Attributes[modifiedDateAttr.Name].Value); 
     DateTime utcTime = getUtcTime(itemsUtc[0].Attributes[modifiedDateAttr.Name].Value); 
     // Gets offset 
     TimeSpan offset = localTime - utcTime; 

     return offset; 
    } 
+0

Это ненадежно для часовых поясов с сохранением изменений дневного света. При использовании даты с февраля вы получите другое смещение к UTC, используя дату с июня. Большинство TZ имеют DST. К счастью, смещение UTC к сайту SP TZ может быть получено методом [`GetList`] (http://msdn.microsoft.com/en-us/library/lists.lists.getlist.aspx) метода [` List`] (http://msdn.microsoft.com/en-us/library/lists.aspx). См. Мой ответ здесь. – 2012-11-24 12:39:45

1

часовой пояс веб-сайт SharePoint может быть получен с помощью GetList способа Lists веба-службы. Это кажется странным, чтобы запросить информацию о списке, чтобы получить региональные настройки веб-сайт, но это так :-)

Это отрывок из метода ответа о едином списке:

<List> 
    ... 
    <RegionalSettings> 
    <Language>1033</Language> 
    <Locale>1033</Locale> 
    <AdvanceHijri>0</AdvanceHijri> 
    <CalendarType>1</CalendarType> 
    <Time24>False</Time24> 
    <TimeZone>-60</TimeZone> 
    <SortOrder>2070</SortOrder> 
    <Presence>True</Presence> 
    </RegionalSettings> 
    ... 
</List> 

Времени зона возвращается как смещение к времени UTC в минутах. Если вы добавите его к времени в локальном часовом поясе веб-сайта, вы получите время в часовом поясе UTC. (Если вы хотите получить правильное значение, вам придется учитывать изменения дневного света и применять их в соответствии с сезоном времени.).

// Instantiate the web service. Don't forget to dispose it later. 
// Append the web service suffix (/_vti_bin/Lists.asmx) to the URL 
// of the web site which time zone of you are interested in. 
// If you don't use IWA or the current user has no access to the 
// web site set the service.Credentials instead. 
var service = new Lists(); 
service.Url = "http://myhost/sites/mysite/_vti_bin/Lists.asmx"; 
service.UseDefaultCredentials = true; 
// Get all lists from the web site you want to get the time zone of. 
// Get the XML element at /Lists/List[1]. It can be any accessible list. 
// We will use just the unique list identifier from the atribute ID. 
var lists = service.GetListCollection(); 
var list = lists.ChildNodes.OfType<XmlElement>().FirstOrDefault(); 
if (list == null) 
    throw new ApplicationException("The web has no lists."); 
// Get information about the list which a little about the web too. 
// Get the XML element at /List/RegionalSettings/TimeZone. 
list = (XmlElement) service.GetList(list.GetAttribute("ID")); 
var regionalSettings = list.ChildNodes.OfType<XmlElement>().First(
    item => item.LocalName == "RegionalSettings"); 
var timeZone = regionalSettings.ChildNodes.OfType<XmlElement>().First(
    item => item.LocalName == "TimeZone"); 
// The offset can be added to the time in the web site local time zone 
// to get the UTC time. For example, UTC+1 has the offset -60 minutes. 
var utcOffset = new TimeSpan(0, int.Parse(timeZone.InnerText), 0); 

--- Ферда

+0

Хотя это старый пост, позвольте мне сказать вам, что вы настоящий ГЕНИЙ! В самом деле. Вы заслуживаете награды или чего-то еще. ЭТО ТОЛЬКО ПРАВИЛЬНЫЙ ОТВЕТ НА этот вопрос. Ты великолепен. – MdMazzotti 2014-02-12 15:53:14

 Смежные вопросы

  • Нет связанных вопросов^_^