{ // 获取包含Hugging Face文本的span元素 const spans = link.querySelectorAll('span.whitespace-nowrap, span.hidden.whitespace-nowrap'); spans.forEach(span => { if (span.textContent && span.textContent.trim().match(/Hugging\s*Face/i)) { span.textContent = 'AI快站'; } }); }); // 替换logo图片的alt属性 document.querySelectorAll('img[alt*="Hugging"], img[alt*="Face"]').forEach(img => { if (img.alt.match(/Hugging\s*Face/i)) { img.alt = 'AI快站 logo'; } }); } // 替换导航栏中的链接 function replaceNavigationLinks() { // 已替换标记,防止重复运行 if (window._navLinksReplaced) { return; } // 已经替换过的链接集合,防止重复替换 const replacedLinks = new Set(); // 只在导航栏区域查找和替换链接 const headerArea = document.querySelector('header') || document.querySelector('nav'); if (!headerArea) { return; } // 在导航区域内查找链接 const navLinks = headerArea.querySelectorAll('a'); navLinks.forEach(link => { // 如果已经替换过,跳过 if (replacedLinks.has(link)) return; const linkText = link.textContent.trim(); const linkHref = link.getAttribute('href') || ''; // 替换Spaces链接 - 仅替换一次 if ( (linkHref.includes('/spaces') || linkHref === '/spaces' || linkText === 'Spaces' || linkText.match(/^s*Spacess*$/i)) && linkText !== 'PDF TO Markdown' && linkText !== 'PDF TO Markdown' ) { link.textContent = 'PDF TO Markdown'; link.href = 'https://fast360.xyz'; link.setAttribute('target', '_blank'); link.setAttribute('rel', 'noopener noreferrer'); replacedLinks.add(link); } // 删除Posts链接 else if ( (linkHref.includes('/posts') || linkHref === '/posts' || linkText === 'Posts' || linkText.match(/^s*Postss*$/i)) ) { if (link.parentNode) { link.parentNode.removeChild(link); } replacedLinks.add(link); } // 替换Docs链接 - 仅替换一次 else if ( (linkHref.includes('/docs') || linkHref === '/docs' || linkText === 'Docs' || linkText.match(/^s*Docss*$/i)) && linkText !== 'Voice Cloning' ) { link.textContent = 'Voice Cloning'; link.href = 'https://vibevoice.info/'; replacedLinks.add(link); } // 删除Enterprise链接 else if ( (linkHref.includes('/enterprise') || linkHref === '/enterprise' || linkText === 'Enterprise' || linkText.match(/^s*Enterprises*$/i)) ) { if (link.parentNode) { link.parentNode.removeChild(link); } replacedLinks.add(link); } }); // 查找可能嵌套的Spaces和Posts文本 const textNodes = []; function findTextNodes(element) { if (element.nodeType === Node.TEXT_NODE) { const text = element.textContent.trim(); if (text === 'Spaces' || text === 'Posts' || text === 'Enterprise') { textNodes.push(element); } } else { for (const child of element.childNodes) { findTextNodes(child); } } } // 只在导航区域内查找文本节点 findTextNodes(headerArea); // 替换找到的文本节点 textNodes.forEach(node => { const text = node.textContent.trim(); if (text === 'Spaces') { node.textContent = node.textContent.replace(/Spaces/g, 'PDF TO Markdown'); } else if (text === 'Posts') { // 删除Posts文本节点 if (node.parentNode) { node.parentNode.removeChild(node); } } else if (text === 'Enterprise') { // 删除Enterprise文本节点 if (node.parentNode) { node.parentNode.removeChild(node); } } }); // 标记已替换完成 window._navLinksReplaced = true; } // 替换代码区域中的域名 function replaceCodeDomains() { // 特别处理span.hljs-string和span.njs-string元素 document.querySelectorAll('span.hljs-string, span.njs-string, span[class*="hljs-string"], span[class*="njs-string"]').forEach(span => { if (span.textContent && span.textContent.includes('huggingface.co')) { span.textContent = span.textContent.replace(/huggingface.co/g, 'aifasthub.com'); } }); // 替换hljs-string类的span中的域名(移除多余的转义符号) document.querySelectorAll('span.hljs-string, span[class*="hljs-string"]').forEach(span => { if (span.textContent && span.textContent.includes('huggingface.co')) { span.textContent = span.textContent.replace(/huggingface.co/g, 'aifasthub.com'); } }); // 替换pre和code标签中包含git clone命令的域名 document.querySelectorAll('pre, code').forEach(element => { if (element.textContent && element.textContent.includes('git clone')) { const text = element.innerHTML; if (text.includes('huggingface.co')) { element.innerHTML = text.replace(/huggingface.co/g, 'aifasthub.com'); } } }); // 处理特定的命令行示例 document.querySelectorAll('pre, code').forEach(element => { const text = element.innerHTML; if (text.includes('huggingface.co')) { // 针对git clone命令的专门处理 if (text.includes('git clone') || text.includes('GIT_LFS_SKIP_SMUDGE=1')) { element.innerHTML = text.replace(/huggingface.co/g, 'aifasthub.com'); } } }); // 特别处理模型下载页面上的代码片段 document.querySelectorAll('.flex.border-t, .svelte_hydrator, .inline-block').forEach(container => { const content = container.innerHTML; if (content && content.includes('huggingface.co')) { container.innerHTML = content.replace(/huggingface.co/g, 'aifasthub.com'); } }); // 特别处理模型仓库克隆对话框中的代码片段 try { // 查找包含"Clone this model repository"标题的对话框 const cloneDialog = document.querySelector('.svelte_hydration_boundary, [data-target="MainHeader"]'); if (cloneDialog) { // 查找对话框中所有的代码片段和命令示例 const codeElements = cloneDialog.querySelectorAll('pre, code, span'); codeElements.forEach(element => { if (element.textContent && element.textContent.includes('huggingface.co')) { if (element.innerHTML.includes('huggingface.co')) { element.innerHTML = element.innerHTML.replace(/huggingface.co/g, 'aifasthub.com'); } else { element.textContent = element.textContent.replace(/huggingface.co/g, 'aifasthub.com'); } } }); } // 更精确地定位克隆命令中的域名 document.querySelectorAll('[data-target]').forEach(container => { const codeBlocks = container.querySelectorAll('pre, code, span.hljs-string'); codeBlocks.forEach(block => { if (block.textContent && block.textContent.includes('huggingface.co')) { if (block.innerHTML.includes('huggingface.co')) { block.innerHTML = block.innerHTML.replace(/huggingface.co/g, 'aifasthub.com'); } else { block.textContent = block.textContent.replace(/huggingface.co/g, 'aifasthub.com'); } } }); }); } catch (e) { // 错误处理但不打印日志 } } // 当DOM加载完成后执行替换 if (document.readyState === 'loading') { document.addEventListener('DOMContentLoaded', () => { replaceHeaderBranding(); replaceNavigationLinks(); replaceCodeDomains(); // 只在必要时执行替换 - 3秒后再次检查 setTimeout(() => { if (!window._navLinksReplaced) { console.log('[Client] 3秒后重新检查导航链接'); replaceNavigationLinks(); } }, 3000); }); } else { replaceHeaderBranding(); replaceNavigationLinks(); replaceCodeDomains(); // 只在必要时执行替换 - 3秒后再次检查 setTimeout(() => { if (!window._navLinksReplaced) { console.log('[Client] 3秒后重新检查导航链接'); replaceNavigationLinks(); } }, 3000); } // 增加一个MutationObserver来处理可能的动态元素加载 const observer = new MutationObserver(mutations => { // 检查是否导航区域有变化 const hasNavChanges = mutations.some(mutation => { // 检查是否存在header或nav元素变化 return Array.from(mutation.addedNodes).some(node => { if (node.nodeType === Node.ELEMENT_NODE) { // 检查是否是导航元素或其子元素 if (node.tagName === 'HEADER' || node.tagName === 'NAV' || node.querySelector('header, nav')) { return true; } // 检查是否在导航元素内部 let parent = node.parentElement; while (parent) { if (parent.tagName === 'HEADER' || parent.tagName === 'NAV') { return true; } parent = parent.parentElement; } } return false; }); }); // 只在导航区域有变化时执行替换 if (hasNavChanges) { // 重置替换状态,允许再次替换 window._navLinksReplaced = false; replaceHeaderBranding(); replaceNavigationLinks(); } }); // 开始观察document.body的变化,包括子节点 if (document.body) { observer.observe(document.body, { childList: true, subtree: true }); } else { document.addEventListener('DOMContentLoaded', () => { observer.observe(document.body, { childList: true, subtree: true }); }); } })(); \", message);\n else\n content.Append (\"\");\n\n var enc = Encoding.UTF8;\n var entity = enc.GetBytes (content.ToString ());\n res.ContentEncoding = enc;\n res.ContentLength64 = entity.LongLength;\n\n res.Close (entity, true);\n }\n catch {\n Close (true);\n }\n }\n }\n\n #endregion\n }\n}\n"},"gt":{"kind":"string","value":""}}},{"rowIdx":96203,"cells":{"context":{"kind":"string","value":"using Interviewer.Common;\nusing InterviewerHubApp.Common;\nusing InterviewerHubApp.Services;\nusing System;\nusing System.Collections.Generic;\nusing System.Collections.ObjectModel;\nusing System.IO;\nusing System.Linq;\nusing System.Net.Http;\nusing System.Runtime.Serialization.Json;\nusing System.Text;\nusing System.Threading.Tasks;\nusing System.Windows.Input;\nusing Windows.Storage;\nusing Windows.UI.Xaml;\n\nnamespace WpfInterviewer\n{\n public class MainViewModel : BaseModel\n\t{\n\t\tprivate class RunTestCommand : ICommand\n\t\t{\n\t\t\tpublic event EventHandler CanExecuteChanged;\n\n\t\t\tpublic bool CanExecute(object parameter)\n\t\t\t{\n\t\t\t\treturn !MainViewModel.ViewModel.IsRunning;\n\t\t\t}\n\n\t\t\tpublic void Execute(object parameter)\n\t\t\t{\n\t\t\t\tMainViewModel.ViewModel.RunQuestions(int.Parse(parameter.ToString()));\n\t\t\t}\n\t\t}\n\n\t\tprivate class RunQuestionCommand : ICommand\n\t\t{\n\t\t\tprivate readonly int _rating;\n\n\t\t\tpublic event EventHandler CanExecuteChanged;\n\n\t\t\tpublic RunQuestionCommand(int rating)\n\t\t\t{\n\t\t\t\t_rating = rating;\n\t\t\t}\n\n\t\t\tpublic bool CanExecute(object parameter)\n\t\t\t{\n\t\t\t\treturn MainViewModel.ViewModel.SelectedQuestion != null;\n\t\t\t}\n\n\t\t\tpublic void Execute(object parameter)\n\t\t\t{\n\t\t\t\tMainViewModel.ViewModel.QuestionAnswered(_rating, parameter as Question);\n\t\t\t}\n\t\t}\n\n private class RunShowAddQuestionsCommand : ICommand\n {\n public event EventHandler CanExecuteChanged;\n\n public RunShowAddQuestionsCommand()\n {\n }\n\n public bool CanExecute(object parameter)\n {\n return null != MainViewModel.ViewModel.SelectedArea;\n }\n\n public void Execute(object parameter)\n {\n //new AddQuestions().ShowDialog();\n }\n }\n\n\t\tprivate static MainViewModel _viewModel;\n\n\t\tprivate configuration _selectedConfiguration;\n\t\tprivate Profile _selectedProfile;\n\t\tprivate Platform _selectedPlatform;\n\t\tprivate KnowledgeArea _selectedKnowledgeArea;\n\t\tprivate Area _selectedArea;\n\t\tprivate Question _selectedQuestion;\n\n\t\tprivate int _maxQuestionsCount = 10;\n\t\tprivate int _questionsCount = 5;\n\t\tprivate bool _isLoaded = false;\n\t\tprivate bool _isRunning = false;\n\n\t\tprivate int _passedCount = 0;\n\t\tprivate int _failedCount = 0;\n\t\tprivate int _undefinedCount = 0;\n private int _totalQuestions = 0;\n\n\t\tprivate string _interviewedPerson;\n private string _apiBaseUrl = \"http://localhost:52485/api/\";\n\n public string ServicesUrl\n {\n get { return _apiBaseUrl; }\n set\n {\n if (!string.IsNullOrWhiteSpace(value))\n {\n Uri uri = null;\n if (Uri.TryCreate(value, UriKind.Absolute, out uri))\n {\n _apiBaseUrl = value;\n OnPropertyChanged();\n SetServicesSetting(value);\n }\n }\n }\n }\n\n private void SetServicesSetting(string url)\n {\n var settings = ApplicationData.Current.RoamingSettings;\n if (null == settings.Values[\"Services.Url\"])\n {\n settings.Values.Add(\"Services.Url\", url);\n }\n else\n {\n settings.Values[\"Services.Url\"] = url;\n }\n }\n\n public MainViewModel()\n {\n var settings = ApplicationData.Current.RoamingSettings;\n if(null == settings.Values[\"Services.Url\"])\n {\n settings.Values.Add(\"Services.Url\", _apiBaseUrl);\n }\n _apiBaseUrl = (string)settings.Values[\"Services.Url\"];\n }\n\n public static MainViewModel ViewModel\n\t\t{\n\t\t\tget\n\t\t\t{\n\t\t\t if (null == _viewModel)\n\t\t\t {\n\t\t\t _viewModel = new MainViewModel(); \n }\n return _viewModel;\n\t\t\t}\n\t\t}\n\n public override bool IsValid()\n {\n return SelectedConfiguration != null && SelectedConfiguration.IsValid();\n }\n\n public async Task LoadConfiguration()\n {\n if (!_isLoaded)\n {\n using (var client = ApiServiceFactory.CreateService(_apiBaseUrl))\n {\n SelectedConfiguration = await client.GetConfiguration();\n }\n\n RunQuestionsCommand.Execute(1);\n\n _isLoaded = true;\n }\n\n return SelectedConfiguration;\n }\n\n public async void SavePendingChanges()\n {\n if (SelectedConfiguration == null) return;\n\n var result = 0;\n foreach(var p in this.Platforms)\n {\n if(p.IsDirty && p.IsValid())\n {\n if(p.Id == 0)\n {\n result = await InsertPlatform(p);\n p.Id = result;\n }\n else\n {\n result = await UpdatePlatform(p);\n\n }\n p.IsDirty = result == 0;\n }\n\n foreach (var ka in p.KnowledgeArea)\n {\n if(ka.IsDirty && ka.IsValid())\n {\n if(ka.Id == 0)\n {\n result = await InsertKnowledgeArea(ka);\n ka.Id = result;\n }\n else\n {\n result = await UpdateKnowledgeArea(ka);\n }\n ka.IsDirty = result == 0;\n }\n\n foreach(var a in ka.Area)\n {\n if(a.IsDirty && a.IsValid())\n {\n if(a.Id == 0)\n {\n result = await InsertArea(a);\n a.Id = result;\n }\n else\n {\n result = await UpdateArea(a);\n }\n a.IsDirty = result == 0;\n }\n\n foreach (var q in a.Question)\n {\n if(q.IsDirty && q.IsValid())\n {\n if(q.Id == 0)\n {\n result = await InsertQuestion(q);\n q.Id = result;\n }\n else\n {\n result = await UpdateQuestion(q);\n }\n q.IsDirty = result == 0;\n }\n }\n }\n }\n }\n }\n \n public async Task InsertPlatform(Platform item)\n {\n using (var client = ApiServiceFactory.CreateService(_apiBaseUrl))\n {\n return await client.AddItem(item);\n }\n }\n\n public async Task UpdatePlatform(Platform item)\n {\n using (var client = ApiServiceFactory.CreateService(_apiBaseUrl))\n {\n return await client.UpdateItem(item);\n }\n }\n\n public async Task DeletePlatform(Platform item)\n {\n using (var client = ApiServiceFactory.CreateService(_apiBaseUrl))\n {\n return await client.AddItem(item);\n }\n }\n\n public async Task InsertKnowledgeArea(KnowledgeArea item)\n {\n using (var client = ApiServiceFactory.CreateService(_apiBaseUrl))\n {\n return await client.AddItem(item);\n }\n }\n\n public async Task UpdateKnowledgeArea(KnowledgeArea item)\n {\n using (var client = ApiServiceFactory.CreateService(_apiBaseUrl))\n {\n return await client.UpdateItem(item);\n }\n }\n\n public async Task DeleteKnowledgeArea(KnowledgeArea item)\n {\n using (var client = ApiServiceFactory.CreateService(_apiBaseUrl))\n {\n return await client.AddItem(item);\n }\n }\n\n public async Task InsertArea(Area item)\n {\n using (var client = ApiServiceFactory.CreateService(_apiBaseUrl))\n {\n return await client.AddItem(item);\n }\n }\n\n public async Task UpdateArea(Area item)\n {\n using (var client = ApiServiceFactory.CreateService(_apiBaseUrl))\n {\n return await client.UpdateItem(item);\n }\n }\n\n public async Task DeleteArea(Area item)\n {\n using (var client = ApiServiceFactory.CreateService(_apiBaseUrl))\n {\n return await client.AddItem(item);\n }\n }\n\n public async Task InsertQuestion(Question item)\n {\n using (var client = ApiServiceFactory.CreateService(_apiBaseUrl))\n {\n return await client.AddItem(item);\n }\n }\n\n public async Task UpdateQuestion(Question item)\n {\n using (var client = ApiServiceFactory.CreateService(_apiBaseUrl))\n {\n return await client.UpdateItem(item);\n }\n }\n\n public async Task DeleteQuestion(Question item)\n {\n using (var client = ApiServiceFactory.CreateService(_apiBaseUrl))\n {\n return await client.AddItem(item);\n }\n }\n\n public configuration SelectedConfiguration\n\t\t{\n\t\t\tget\n\t\t\t{\n\t\t\t\treturn _selectedConfiguration;\n\t\t\t}\n\t\t\tset\n\t\t\t{\n\t\t\t\t_selectedConfiguration = value;\n\n\t\t\t\tOnPropertyChanged(\"SelectedConfiguration\");\n\t\t\t\tOnPropertyChanged(\"Platforms\");\n\t\t\t\tOnPropertyChanged(\"Profiles\");\n\t\t\t\tOnPropertyChanged(\"QuestionsCountRange\");\n\t\t\t}\n\t\t}\n\n\t\tpublic IEnumerable Profiles\n\t\t{\n\t\t\tget\n\t\t\t{\n var profiles = SelectedConfiguration.Profile.Any()\n ? SelectedConfiguration.Profile\n : from p in SelectedConfiguration.Platform\n from prof in p.Profile\n from req in prof.Requirement\n where req.PlatformId == p.Id\n select prof;\n SelectedProfile = profiles.FirstOrDefault();\n\t\t\t\treturn profiles.Distinct();\n\t\t\t}\n\t\t}\n\n\t\tpublic Profile SelectedProfile\n\t\t{\n\t\t\tget\n\t\t\t{\n\t\t\t\treturn _selectedProfile;\n\t\t\t}\n\t\t\tset\n\t\t\t{\n\t\t\t\t_selectedProfile = value;\n\t\t\t\tOnPropertyChanged(\"SelectedProfile\");\n\t\t\t}\n\t\t}\n\n\t\tpublic IEnumerable Platforms\n\t\t{\n\t\t\tget\n\t\t\t{\n SelectedPlatform = SelectedConfiguration.Platform.FirstOrDefault();\n\t\t\t\treturn SelectedConfiguration.Platform;\n\t\t\t}\n\t\t}\n\n\t\tpublic Platform SelectedPlatform\n\t\t{\n\t\t\tget\n\t\t\t{\n\t\t\t\treturn _selectedPlatform;\n\t\t\t}\n\t\t\tset\n\t\t\t{\n\t\t\t\t_selectedPlatform = value;\n\t\t\t\tOnPropertyChanged(\"SelectedPlatform\");\n\t\t\t if (value == null) return;\n\n\t\t\t\tSelectedKnowledgeArea = value.KnowledgeArea.FirstOrDefault();\n\t\t\t}\n\t\t}\n\n\t\tpublic KnowledgeArea SelectedKnowledgeArea\n\t\t{\n\t\t\tget\n\t\t\t{\n\t\t\t\treturn _selectedKnowledgeArea;\n\t\t\t}\n\t\t\tset\n\t\t\t{\n\t\t\t\t_selectedKnowledgeArea = value;\n\t\t\t\tOnPropertyChanged(\"SelectedKnowledgeArea\");\n\t\t\t if (value == null) return;\n\n\t\t\t\tSelectedArea = value.Area.FirstOrDefault();\n\t\t\t}\n\t\t}\n\n\t\tpublic Area SelectedArea\n\t\t{\n\t\t\tget\n\t\t\t{\n\t\t\t\treturn _selectedArea;\n\t\t\t}\n\t\t\tset\n\t\t\t{\n\t\t\t\t_selectedArea = value;\n\t\t\t\tOnPropertyChanged(\"SelectedArea\");\n if (value == null) return;\n \n SelectedQuestion = value.Question.FirstOrDefault();\n\t\t\t}\n\t\t}\n\n\t\tpublic Question SelectedQuestion\n\t\t{\n\t\t\tget\n\t\t\t{\n\t\t\t\treturn _selectedQuestion;\n\t\t\t}\n\t\t\tset\n\t\t\t{\n\t\t\t\t_selectedQuestion = value;\n\t\t\t\tOnPropertyChanged(\"SelectedQuestion\");\n\t\t\t}\n\t\t}\n\n\t\tpublic int QuestionsCount\n\t\t{\n\t\t\tget\n\t\t\t{\n\t\t\t\treturn _questionsCount;\n\t\t\t}\n\t\t\tset\n\t\t\t{\n\t\t\t\t_questionsCount = value;\n\t\t\t\tOnPropertyChanged(\"QuestionsCount\");\n\t\t\t}\n\t\t}\n\n\t\tpublic IEnumerable QuestionsCountRange\n\t\t{\n\t\t\tget\n\t\t\t{\n\t\t\t\tvar list = new List();\n\t\t\t\tfor (var i = 1; i <= _maxQuestionsCount; i++)\n\t\t\t\t{\n\t\t\t\t\tlist.Add(i);\n\t\t\t\t}\n\t\t\t\treturn list;\n\t\t\t}\n\t\t}\n\n\t\tpublic bool IsRunning\n\t\t{\n\t\t\tget\n\t\t\t{\n\t\t\t\treturn _isRunning;\n\t\t\t}\n\t\t\tset\n\t\t\t{\n\t\t\t\t_isRunning = value;\n\t\t\t\tOnPropertyChanged(\"IsRunning\");\n\t\t\t}\n\t\t}\n\n private ICommand _runQuestionsCommand;\n public ICommand RunQuestionsCommand\n\t\t{\n\t\t\tget\n\t\t\t{\n\t\t\t\treturn _runQuestionsCommand ?? (_runQuestionsCommand = new MainViewModel.RunTestCommand());\n\t\t\t}\n\t\t}\n\n private ICommand _questionUpCommand;\n public ICommand QuestionUpCommand\n\t\t{\n\t\t\tget\n\t\t\t{\n\t\t\t\treturn _questionUpCommand ?? (_questionUpCommand = new MainViewModel.RunQuestionCommand(1));\n\t\t\t}\n\t\t}\n\n private ICommand _questionDownCommand;\n public ICommand QuestionDownCommand\n\t\t{\n\t\t\tget\n\t\t\t{\n return _questionDownCommand ?? (_questionDownCommand = new MainViewModel.RunQuestionCommand(0));\n\t\t\t}\n\t\t}\n\n private ICommand _questionUndefCommand;\n public ICommand QuestionUndefCommand\n\t\t{\n\t\t\tget\n\t\t\t{\n return _questionUndefCommand ?? (_questionUndefCommand = new MainViewModel.RunQuestionCommand(-1));\n\t\t\t}\n\t\t}\n\n private ICommand _showAddQuestionsCommand;\n public ICommand ShowAddQuestionsCommand\n {\n get\n {\n return _showAddQuestionsCommand ?? (_showAddQuestionsCommand = new MainViewModel.RunShowAddQuestionsCommand());\n }\n }\n\n private RelayCommand _addKnowdlegeArea;\n public RelayCommand AddKnowledgeArea\n {\n get\n {\n return _addKnowdlegeArea ?? (_addKnowdlegeArea = new RelayCommand(\n () => {\n MainViewModel.ViewModel.SelectedPlatform.KnowledgeArea\n .Add(new KnowledgeArea {\n PlatformId = MainViewModel.ViewModel.SelectedPlatform.Id,\n Id = 0,\n Name = \"Undefined\",\n Area = new ObservableCollection(),\n IsDirty = true \n });\n },\n () => MainViewModel.ViewModel.SelectedPlatform != null\n ));\n }\n }\n\n private RelayCommand _addArea;\n public RelayCommand AddArea\n {\n get\n {\n return _addArea ?? (_addArea = new RelayCommand(\n () => {\n MainViewModel.ViewModel.SelectedKnowledgeArea.Area\n .Add(new Area\n {\n KnowledgeAreaId = MainViewModel.ViewModel.SelectedKnowledgeArea.Id,\n Id = 0,\n Name = \"Undefined\",\n Question = new ObservableCollection(),\n IsDirty = true\n });\n },\n () => MainViewModel.ViewModel.SelectedKnowledgeArea != null\n ));\n }\n }\n\n private RelayCommand _addQuestion;\n public RelayCommand AddQuestion\n {\n get\n {\n return _addQuestion ?? (_addQuestion = new RelayCommand(\n () => {\n MainViewModel.ViewModel.SelectedArea.Question\n .Add(new Question\n {\n AreaId = MainViewModel.ViewModel.SelectedArea.Id,\n Id = 0,\n Name = \"Undefined\",\n Value = \"Undefined\",\n Level = 1,\n Weight = 1,\n IsDirty = true\n });\n },\n () => MainViewModel.ViewModel.SelectedArea != null\n ));\n }\n }\n\n private bool _isEditingPlatformProps = false;\n public bool IsEditingPlatformProps {\n get { return _isEditingPlatformProps; }\n set\n {\n _isEditingPlatformProps = value;\n OnPropertyChanged();\n OnPropertyChanged(\"PlatformEditVisibility\");\n }\n }\n public Visibility PlatformEditVisibility\n {\n get { return _isEditingPlatformProps ? Visibility.Visible : Visibility.Collapsed; }\n }\n\n private RelayCommand _editingPlatformProps;\n public RelayCommand EditingPlatformProps\n {\n get\n {\n return _editingPlatformProps ?? (_editingPlatformProps = new RelayCommand(\n () => {\n MainViewModel.ViewModel.IsEditingPlatformProps = !MainViewModel.ViewModel.IsEditingPlatformProps;\n },\n () => MainViewModel.ViewModel.SelectedPlatform != null\n ));\n }\n }\n\n private bool _isEditingKnowledgeAreaProps = false;\n public bool IsEditingKnowledgeAreaProps\n {\n get { return _isEditingKnowledgeAreaProps; }\n set\n {\n _isEditingKnowledgeAreaProps = value;\n OnPropertyChanged();\n OnPropertyChanged(\"KnowledgeAreaEditVisibility\");\n }\n }\n public Visibility KnowledgeAreaEditVisibility\n {\n get { return _isEditingKnowledgeAreaProps ? Visibility.Visible : Visibility.Collapsed; }\n }\n\n private RelayCommand _editingKnowledgeAreaProps;\n public RelayCommand EditingKnowledgeAreaProps\n {\n get\n {\n return _editingKnowledgeAreaProps ?? (_editingKnowledgeAreaProps = new RelayCommand(\n () => {\n MainViewModel.ViewModel.IsEditingKnowledgeAreaProps= !MainViewModel.ViewModel.IsEditingKnowledgeAreaProps;\n },\n () => MainViewModel.ViewModel.SelectedKnowledgeArea != null\n ));\n }\n }\n\n private bool _isEditingAreaProps = false;\n public bool IsEditingAreaProps\n {\n get { return _isEditingAreaProps; }\n set\n {\n _isEditingAreaProps = value;\n OnPropertyChanged();\n OnPropertyChanged(\"AreaEditVisibility\");\n }\n }\n public Visibility AreaEditVisibility\n {\n get { return _isEditingAreaProps ? Visibility.Visible : Visibility.Collapsed; }\n }\n\n private RelayCommand _editingAreaProps;\n public RelayCommand EditingAreaProps\n {\n get\n {\n return _editingAreaProps ?? (_editingAreaProps = new RelayCommand(\n () => {\n MainViewModel.ViewModel.IsEditingAreaProps = !MainViewModel.ViewModel.IsEditingAreaProps;\n },\n () => MainViewModel.ViewModel.SelectedArea != null\n ));\n }\n }\n\n private bool _isEditingQuestionProps = false;\n public bool IsEditingQuestionProps\n {\n get { return _isEditingQuestionProps; }\n set\n {\n _isEditingQuestionProps = value;\n OnPropertyChanged();\n OnPropertyChanged(\"QuestionEditVisibility\");\n }\n }\n public Visibility QuestionEditVisibility\n {\n get { return _isEditingQuestionProps ? Visibility.Visible : Visibility.Collapsed; }\n }\n\n private RelayCommand _editingQuestionProps;\n public RelayCommand EditingQuestionProps\n {\n get\n {\n return _editingQuestionProps ?? (_editingQuestionProps = new RelayCommand(\n () => {\n MainViewModel.ViewModel.IsEditingQuestionProps = !MainViewModel.ViewModel.IsEditingQuestionProps;\n },\n () => MainViewModel.ViewModel.SelectedQuestion != null\n ));\n }\n }\n\n public int PassedCount\n\t\t{\n\t\t\tget\n\t\t\t{\n\t\t\t\treturn _passedCount;\n\t\t\t}\n\t\t\tset\n\t\t\t{\n\t\t\t\t_passedCount = value;\n\t\t\t\tOnPropertyChanged(\"PassedCount\");\n OnPropertyChanged(\"AppliedQuestions\");\n }\n\t\t}\n\n\t\tpublic int FailedCount\n\t\t{\n\t\t\tget\n\t\t\t{\n\t\t\t\treturn _failedCount;\n\t\t\t}\n\t\t\tset\n\t\t\t{\n\t\t\t\t_failedCount = value;\n\t\t\t\tOnPropertyChanged(\"FailedCount\");\n OnPropertyChanged(\"AppliedQuestions\");\n }\n\t\t}\n\n\t\tpublic int UndefinedCount\n\t\t{\n\t\t\tget\n\t\t\t{\n\t\t\t\treturn _undefinedCount;\n\t\t\t}\n\t\t\tset\n\t\t\t{\n\t\t\t\t_undefinedCount = value;\n\t\t\t\tOnPropertyChanged(\"UndefinedCount\");\n OnPropertyChanged(\"AppliedQuestions\");\n }\n\t\t}\n\n public int TotalQuestions\n {\n get\n {\n return _totalQuestions;\n }\n set\n {\n _totalQuestions = value;\n PassedCount = 0;\n FailedCount = 0;\n UndefinedCount = 0;\n OnPropertyChanged(\"TotalQuestions\");\n OnPropertyChanged(\"AppliedQuestions\");\n }\n }\n\n public int AppliedQuestions\n {\n get\n {\n return Math.Min(TotalQuestions, PassedCount + FailedCount + UndefinedCount + 1);\n }\n }\n\n public string InterviewedPerson\n\t\t{\n\t\t\tget\n\t\t\t{\n\t\t\t\treturn _interviewedPerson;\n\t\t\t}\n\t\t\tset\n\t\t\t{\n\t\t\t\t_interviewedPerson = value;\n\t\t\t\tOnPropertyChanged(\"InterviewedPerson\");\n\t\t\t}\n\t\t}\t\t\n\n\t\tprivate void QuestionAnswered(int rating, Question question)\n\t\t{\n SelectedQuestion = question;\n SelectedQuestion.AlreadyAnswered = true;\n SelectedQuestion.rating = rating;\n\t\t\tswitch (rating)\n\t\t\t{\n\t\t\tcase -1:\n\t\t\t\tUndefinedCount++;\n\t\t\t\tbreak;\n\t\t\tcase 0:\n\t\t\t\tFailedCount++;\n\t\t\t\tbreak;\n\t\t\tcase 1:\n\t\t\t\tPassedCount++;\n\t\t\t\tbreak;\n\t\t\t}\n\n SelectedQuestion = GetNextQuestion();\n\t\t}\n\n\t\tprivate void RunQuestions(int mode)\n\t\t{\n\t\t\tIsRunning = true;\n\t\t\ttry\n\t\t\t{\n\t\t\t\tif (mode == 1) //get random questions\n\t\t\t\t{\n\t\t\t\t\tToogleAnsweredFlag(true);\n\n\t\t\t\t var questions = from p in Platforms\n\t\t\t\t from ka in p.KnowledgeArea\n\t\t\t\t from a in ka.Area\n\t\t\t\t select a.Question;\n\n\t\t\t\t foreach (var q in questions.Where(x => x.Count() > 0))\n\t\t\t\t {\n\t\t\t\t var randomIndexes = GetRandomIndexes(q.Count());\n\t\t\t\t foreach (var i in randomIndexes)\n\t\t\t\t {\n\t\t\t\t q.ElementAt(i).AlreadyAnswered = false;\n\t\t\t\t }\n\t\t\t\t }\n\n TotalQuestions = GetPendingQuestions();\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tToogleAnsweredFlag(false);\n\t\t\t\t}\n\t\t\t\tOnPropertyChanged(\"Platforms\");\n\n if(mode == 1)\n {\n //var window = new AskQuestions();\n //window.ShowDialog();\n }\n\t\t\t}\n\t\t\tfinally\n\t\t\t{\n\t\t\t\tIsRunning = false;\n\t\t\t}\n\t\t}\n\n\t private IEnumerable GetRandomIndexes(int itemsCount)\n\t {\n var rand = new Random(100);\n\t var list = new List();\n\t if (itemsCount <= QuestionsCount)\n\t {\n for(var i=0;i= 2M)\n\t {\n\t while (list.Count < Math.Min(QuestionsCount, itemsCount))\n\t {\n\t var randIndex = rand.Next(0, itemsCount - 1);\n\t if (!list.Contains(randIndex))\n\t list.Add(randIndex);\n\t }\n\t }\n\t else\n\t {\n\t var dismissList = new List();\n\t for (var i = 0; i < itemsCount - QuestionsCount; i++)\n\t {\n var randIndex = rand.Next(0, itemsCount - 1);\n if (!dismissList.Contains(randIndex))\n dismissList.Add(randIndex);\n\t }\n\n for (var i = 0; i < itemsCount; i++)\n if(!dismissList.Contains(i))\n list.Add(i);\n\t }\n\t }\n\n\t return list.ToArray();\n\t }\n\n\t\tprivate void ToogleAnsweredFlag(bool answered)\n\t\t{\n\t\t\tforeach (var q2 in from p in Platforms\n\t\t\t from ka in p.KnowledgeArea\n\t\t\t from a in ka.Area\n\t\t\t from q in a.Question\n\t\t\tselect q)\n\t\t\t{\n\t\t\t\tq2.AlreadyAnswered = answered;\n\t\t\t}\n\t\t}\n\n private int GetPendingQuestions()\n {\n var pendingQuestions = 0;\n foreach (var q2 in from p in Platforms\n from ka in p.KnowledgeArea\n from a in ka.Area\n from q in a.Question\n select q)\n {\n pendingQuestions += q2.AlreadyAnswered ? 0 : 1;\n }\n\n return pendingQuestions;\n }\n\n private Question GetNextQuestion()\n {\n foreach(var p in Platforms)\n {\n foreach(var ka in p.KnowledgeArea)\n {\n foreach(var a in ka.Area)\n {\n foreach(var q in a.Question)\n {\n if (!q.AlreadyAnswered)\n {\n if (p != SelectedPlatform)\n SelectedPlatform = p;\n\n if (ka != SelectedKnowledgeArea)\n SelectedKnowledgeArea = ka;\n\n if (a != SelectedArea)\n SelectedArea = a;\n\n return q;\n }\n }\n }\n }\n }\n\n return null;\n }\n }\n}\n"},"gt":{"kind":"string","value":""}}},{"rowIdx":96204,"cells":{"context":{"kind":"string","value":"using System.Linq;\nusing System.Threading.Tasks;\nusing OmniSharp.Models;\nusing OmniSharp.Roslyn.CSharp.Services.Navigation;\nusing OmniSharp.Tests;\nusing Xunit;\n\nnamespace OmniSharp.Roslyn.CSharp.Tests\n{\n public class FindSymbolsFacts\n {\n [Fact]\n public async Task Can_find_symbols()\n {\n var source = @\"\n namespace Some.Long.Namespace\n {\n public class Foo\n {\n private string _field = 0;\n private string AutoProperty { get; }\n private string Property\n {\n get { return _field; }\n set { _field = value; }\n }\n private string Method() {}\n private string Method(string param) {}\n\n private class Nested\n {\n private string NestedMethod() {}\n }\n }\n }\";\n\n var usages = await FindSymbols(source);\n var symbols = usages.QuickFixes.Select(q => q.Text);\n\n var expected = new[] {\n \"Foo\",\n \"_field\",\n \"AutoProperty\",\n \"Property\",\n \"Method()\",\n \"Method(string param)\",\n \"Nested\",\n \"NestedMethod()\"\n };\n Assert.Equal(expected, symbols);\n }\n\n [Fact]\n public async Task Does_not_return_event_keyword()\n {\n var source = @\"\n public static class Game\n {\n public static event GameEvent GameResumed;\n }\";\n\n var usages = await FindSymbols(source);\n var symbols = usages.QuickFixes.Select(q => q.Text);\n\n var expected = new[] {\n \"Game\",\n \"GameResumed\"\n };\n Assert.Equal(expected, symbols);\n }\n\n [Fact]\n public async Task Can_find_symbols_kinds()\n {\n var source = @\"\n namespace Some.Long.Namespace\n {\n public class Foo\n {\n private string _field = 0;\n private string AutoProperty { get; }\n private string Property\n {\n get { return _field; }\n set { _field = value; }\n }\n private string Method() {}\n private string Method(string param) {}\n\n private class Nested\n {\n private string NestedMethod() {}\n }\n }\n }\";\n\n var usages = await FindSymbols(source);\n var symbols = usages.QuickFixes.Cast().Select(q => q.Kind);\n\n var expected = new[] {\n \"Class\",\n \"Field\",\n \"Property\",\n \"Property\",\n \"Method\",\n \"Method\",\n \"Class\",\n \"Method\"\n };\n Assert.Equal(expected, symbols);\n }\n\n [Fact]\n public async Task Returns_interface_kind()\n {\n var source = @\"public interface Foo {}\";\n\n var usages = await FindSymbols(source);\n var symbols = usages.QuickFixes.Cast().Select(q => q.Kind);\n Assert.Equal(\"Interface\", symbols.First());\n }\n\n [Fact]\n public async Task Returns_enum_kind()\n {\n var source = @\"public enum Foo {}\";\n\n var usages = await FindSymbols(source);\n var symbols = usages.QuickFixes.Cast().Select(q => q.Kind);\n Assert.Equal(\"Enum\", symbols.First());\n }\n\n [Fact]\n public async Task Returns_struct_kind()\n {\n var source = @\"public struct Foo {}\";\n\n var usages = await FindSymbols(source);\n var symbols = usages.QuickFixes.Cast().Select(q => q.Kind);\n Assert.Equal(\"Struct\", symbols.First());\n }\n\n [Fact]\n public async Task Returns_delegate_kind()\n {\n var source = @\"public delegate void Foo();\";\n\n var usages = await FindSymbols(source);\n var symbols = usages.QuickFixes.Cast().Select(q => q.Kind);\n Assert.Equal(\"Delegate\", symbols.First());\n }\n\n [Fact]\n public async Task Can_find_symbols_using_filter()\n {\n var source = @\"\n namespace Some.Long.Namespace\n {\n public class Foo\n {\n private string _field = 0;\n private string AutoProperty { get; }\n private string Property\n {\n get { return _field; }\n set { _field = value; }\n }\n private void Method() {}\n private string Method(string param) {}\n\n private class Nested\n {\n private string NestedMethod() {}\n }\n }\n }\";\n\n var usages = await FindSymbolsWithFilter(source, \"meth\");\n var symbols = usages.QuickFixes.Select(q => q.Text);\n\n var expected = new[] {\n \"Method()\",\n \"Method(string param)\"\n };\n Assert.Equal(expected, symbols);\n }\n\n private async Task FindSymbols(string source)\n {\n var workspace = await TestHelpers.CreateSimpleWorkspace(source);\n var controller = new FindSymbolsService(workspace);\n RequestHandler requestHandler = controller;\n return await requestHandler.Handle(null);\n }\n\n private async Task FindSymbolsWithFilter(string source, string filter)\n {\n var workspace = await TestHelpers.CreateSimpleWorkspace(source);\n var controller = new FindSymbolsService(workspace);\n RequestHandler requestHandler = controller;\n var request = new FindSymbolsRequest { Filter = filter };\n return await controller.Handle(request);\n }\n }\n}\n"},"gt":{"kind":"string","value":""}}},{"rowIdx":96205,"cells":{"context":{"kind":"string","value":"using System;\nusing System.Collections.Generic;\nusing System.Globalization;\nusing System.Linq;\nusing Prism.Properties;\n\nnamespace Prism.Modularity\n{\n /// \n /// Component responsible for coordinating the modules' type loading and module initialization process.\n /// \n public partial class ModuleManager : IModuleManager, IDisposable\n {\n private readonly IModuleInitializer moduleInitializer;\n private IEnumerable typeLoaders;\n private HashSet subscribedToModuleTypeLoaders = new HashSet();\n\n /// \n /// Initializes an instance of the class.\n /// \n /// Service used for initialization of modules.\n /// Catalog that enumerates the modules to be loaded and initialized.\n public ModuleManager(IModuleInitializer moduleInitializer, IModuleCatalog moduleCatalog)\n {\n this.moduleInitializer = moduleInitializer ?? throw new ArgumentNullException(nameof(moduleInitializer));\n ModuleCatalog = moduleCatalog ?? throw new ArgumentNullException(nameof(moduleCatalog));\n }\n\n /// \n /// The module catalog specified in the constructor.\n /// \n protected IModuleCatalog ModuleCatalog { get; }\n\n /// \n /// Gets all the classes that are in the .\n /// \n public IEnumerable Modules => ModuleCatalog.Modules;\n\n /// \n /// Raised repeatedly to provide progress as modules are loaded in the background.\n /// \n public event EventHandler ModuleDownloadProgressChanged;\n\n private void RaiseModuleDownloadProgressChanged(ModuleDownloadProgressChangedEventArgs e)\n {\n ModuleDownloadProgressChanged?.Invoke(this, e);\n }\n\n /// \n /// Raised when a module is loaded or fails to load.\n /// \n public event EventHandler LoadModuleCompleted;\n\n private void RaiseLoadModuleCompleted(IModuleInfo moduleInfo, Exception error)\n {\n this.RaiseLoadModuleCompleted(new LoadModuleCompletedEventArgs(moduleInfo, error));\n }\n\n private void RaiseLoadModuleCompleted(LoadModuleCompletedEventArgs e)\n {\n this.LoadModuleCompleted?.Invoke(this, e);\n }\n\n /// \n /// Initializes the modules marked as on the .\n /// \n public void Run()\n {\n this.ModuleCatalog.Initialize();\n\n this.LoadModulesWhenAvailable();\n }\n\n\n /// \n /// Loads and initializes the module on the with the name .\n /// \n /// Name of the module requested for initialization.\n public void LoadModule(string moduleName)\n {\n var module = this.ModuleCatalog.Modules.Where(m => m.ModuleName == moduleName);\n if (module == null || module.Count() != 1)\n {\n throw new ModuleNotFoundException(moduleName, string.Format(CultureInfo.CurrentCulture, Resources.ModuleNotFound, moduleName));\n }\n\n var modulesToLoad = this.ModuleCatalog.CompleteListWithDependencies(module);\n\n this.LoadModuleTypes(modulesToLoad);\n }\n\n /// \n /// Checks if the module needs to be retrieved before it's initialized.\n /// \n /// Module that is being checked if needs retrieval.\n /// \n protected virtual bool ModuleNeedsRetrieval(IModuleInfo moduleInfo)\n {\n if (moduleInfo == null)\n throw new ArgumentNullException(nameof(moduleInfo));\n\n if (moduleInfo.State == ModuleState.NotStarted)\n {\n // If we can instantiate the type, that means the module's assembly is already loaded into\n // the AppDomain and we don't need to retrieve it.\n bool isAvailable = Type.GetType(moduleInfo.ModuleType) != null;\n if (isAvailable)\n {\n moduleInfo.State = ModuleState.ReadyForInitialization;\n }\n\n return !isAvailable;\n }\n\n return false;\n }\n\n private void LoadModulesWhenAvailable()\n {\n var whenAvailableModules = this.ModuleCatalog.Modules.Where(m => m.InitializationMode == InitializationMode.WhenAvailable);\n var modulesToLoadTypes = this.ModuleCatalog.CompleteListWithDependencies(whenAvailableModules);\n if (modulesToLoadTypes != null)\n {\n this.LoadModuleTypes(modulesToLoadTypes);\n }\n }\n\n private void LoadModuleTypes(IEnumerable moduleInfos)\n {\n if (moduleInfos == null)\n {\n return;\n }\n\n foreach (var moduleInfo in moduleInfos)\n {\n if (moduleInfo.State == ModuleState.NotStarted)\n {\n if (this.ModuleNeedsRetrieval(moduleInfo))\n {\n this.BeginRetrievingModule(moduleInfo);\n }\n else\n {\n moduleInfo.State = ModuleState.ReadyForInitialization;\n }\n }\n }\n\n this.LoadModulesThatAreReadyForLoad();\n }\n\n /// \n /// Loads the modules that are not initialized and have their dependencies loaded.\n /// \n protected virtual void LoadModulesThatAreReadyForLoad()\n {\n bool keepLoading = true;\n while (keepLoading)\n {\n keepLoading = false;\n var availableModules = this.ModuleCatalog.Modules.Where(m => m.State == ModuleState.ReadyForInitialization);\n\n foreach (var moduleInfo in availableModules)\n {\n if ((moduleInfo.State != ModuleState.Initialized) && (this.AreDependenciesLoaded(moduleInfo)))\n {\n moduleInfo.State = ModuleState.Initializing;\n this.InitializeModule(moduleInfo);\n keepLoading = true;\n break;\n }\n }\n }\n }\n\n private void BeginRetrievingModule(IModuleInfo moduleInfo)\n {\n var moduleInfoToLoadType = moduleInfo;\n IModuleTypeLoader moduleTypeLoader = this.GetTypeLoaderForModule(moduleInfoToLoadType);\n moduleInfoToLoadType.State = ModuleState.LoadingTypes;\n\n // Delegate += works differently between SL and WPF.\n // We only want to subscribe to each instance once.\n if (!this.subscribedToModuleTypeLoaders.Contains(moduleTypeLoader))\n {\n moduleTypeLoader.ModuleDownloadProgressChanged += this.IModuleTypeLoader_ModuleDownloadProgressChanged;\n moduleTypeLoader.LoadModuleCompleted += this.IModuleTypeLoader_LoadModuleCompleted;\n this.subscribedToModuleTypeLoaders.Add(moduleTypeLoader);\n }\n\n moduleTypeLoader.LoadModuleType(moduleInfo);\n }\n\n private void IModuleTypeLoader_ModuleDownloadProgressChanged(object sender, ModuleDownloadProgressChangedEventArgs e)\n {\n this.RaiseModuleDownloadProgressChanged(e);\n }\n\n private void IModuleTypeLoader_LoadModuleCompleted(object sender, LoadModuleCompletedEventArgs e)\n {\n if (e.Error == null)\n {\n if ((e.ModuleInfo.State != ModuleState.Initializing) && (e.ModuleInfo.State != ModuleState.Initialized))\n {\n e.ModuleInfo.State = ModuleState.ReadyForInitialization;\n }\n\n // This callback may call back on the UI thread, but we are not guaranteeing it.\n // If you were to add a custom retriever that retrieved in the background, you\n // would need to consider dispatching to the UI thread.\n this.LoadModulesThatAreReadyForLoad();\n }\n else\n {\n this.RaiseLoadModuleCompleted(e);\n\n // If the error is not handled then I log it and raise an exception.\n if (!e.IsErrorHandled)\n {\n this.HandleModuleTypeLoadingError(e.ModuleInfo, e.Error);\n }\n }\n }\n\n /// \n /// Handles any exception occurred in the module typeloading process,\n /// and throws a .\n /// This method can be overridden to provide a different behavior.\n /// \n /// The module metadata where the error happened.\n /// The exception thrown that is the cause of the current error.\n /// \n [System.Diagnostics.CodeAnalysis.SuppressMessage(\"Microsoft.Design\", \"CA1062:Validate arguments of public methods\", MessageId = \"1\")]\n protected virtual void HandleModuleTypeLoadingError(IModuleInfo moduleInfo, Exception exception)\n {\n if (moduleInfo == null)\n throw new ArgumentNullException(nameof(moduleInfo));\n\n\n if (!(exception is ModuleTypeLoadingException moduleTypeLoadingException))\n {\n moduleTypeLoadingException = new ModuleTypeLoadingException(moduleInfo.ModuleName, exception.Message, exception);\n }\n\n throw moduleTypeLoadingException;\n }\n\n private bool AreDependenciesLoaded(IModuleInfo moduleInfo)\n {\n var requiredModules = this.ModuleCatalog.GetDependentModules(moduleInfo);\n if (requiredModules == null)\n {\n return true;\n }\n\n int notReadyRequiredModuleCount =\n requiredModules.Count(requiredModule => requiredModule.State != ModuleState.Initialized);\n\n return notReadyRequiredModuleCount == 0;\n }\n\n private IModuleTypeLoader GetTypeLoaderForModule(IModuleInfo moduleInfo)\n {\n foreach (IModuleTypeLoader typeLoader in this.ModuleTypeLoaders)\n {\n if (typeLoader.CanLoadModuleType(moduleInfo))\n {\n return typeLoader;\n }\n }\n\n throw new ModuleTypeLoaderNotFoundException(moduleInfo.ModuleName, string.Format(CultureInfo.CurrentCulture, Resources.NoRetrieverCanRetrieveModule, moduleInfo.ModuleName), null);\n }\n\n private void InitializeModule(IModuleInfo moduleInfo)\n {\n if (moduleInfo.State == ModuleState.Initializing)\n {\n this.moduleInitializer.Initialize(moduleInfo);\n moduleInfo.State = ModuleState.Initialized;\n this.RaiseLoadModuleCompleted(moduleInfo, null);\n }\n }\n\n #region Implementation of IDisposable\n\n /// \n /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.\n /// \n /// Calls .\n /// 2\n public void Dispose()\n {\n this.Dispose(true);\n GC.SuppressFinalize(this);\n }\n\n /// \n /// Disposes the associated s.\n /// \n /// When , it is being called from the Dispose method.\n protected virtual void Dispose(bool disposing)\n {\n foreach (IModuleTypeLoader typeLoader in this.ModuleTypeLoaders)\n {\n if (typeLoader is IDisposable disposableTypeLoader)\n {\n disposableTypeLoader.Dispose();\n }\n }\n }\n\n #endregion\n }\n}\n"},"gt":{"kind":"string","value":""}}},{"rowIdx":96206,"cells":{"context":{"kind":"string","value":"// ***********************************************************************\n// Copyright (c) 2014 Charlie Poole\n//\n// Permission is hereby granted, free of charge, to any person obtaining\n// a copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to\n// permit persons to whom the Software is furnished to do so, subject to\n// the following conditions:\n//\n// The above copyright notice and this permission notice shall be\n// included in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\n// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\n// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n// ***********************************************************************\n\nusing System;\nusing System.Collections.Generic;\nusing System.Globalization;\nusing System.Diagnostics;\nusing System.IO;\nusing System.Threading;\nusing NUnit.Framework.Constraints;\nusing NUnit.Framework.Interfaces;\nusing NUnit.Framework.Internal.Execution;\n\n#if !SILVERLIGHT && !NETCF && !PORTABLE\nusing System.Runtime.Remoting.Messaging;\nusing System.Security.Principal;\nusing NUnit.Framework.Compatibility;\n#endif\n\nnamespace NUnit.Framework.Internal\n{\n /// \n /// Helper class used to save and restore certain static or\n /// singleton settings in the environment that affect tests\n /// or which might be changed by the user tests.\n ///\n /// An internal class is used to hold settings and a stack\n /// of these objects is pushed and popped as Save and Restore\n /// are called.\n /// \n public class TestExecutionContext\n#if !SILVERLIGHT && !NETCF && !PORTABLE\n : LongLivedMarshalByRefObject, ILogicalThreadAffinative\n#endif\n {\n // NOTE: Be very careful when modifying this class. It uses\n // conditional compilation extensively and you must give\n // thought to whether any new features will be supported\n // on each platform. In particular, instance fields,\n // properties, initialization and restoration must all\n // use the same conditions for each feature.\n\n #region Instance Fields\n\n /// \n /// Link to a prior saved context\n /// \n private TestExecutionContext _priorContext;\n\n /// \n /// Indicates that a stop has been requested\n /// \n private TestExecutionStatus _executionStatus;\n\n /// \n /// The event listener currently receiving notifications\n /// \n private ITestListener _listener = TestListener.NULL;\n\n /// \n /// The number of assertions for the current test\n /// \n private int _assertCount;\n\n private Randomizer _randomGenerator;\n\n private IWorkItemDispatcher _dispatcher;\n\n /// \n /// The current culture\n /// \n private CultureInfo _currentCulture;\n\n /// \n /// The current UI culture\n /// \n private CultureInfo _currentUICulture;\n\n /// \n /// The current test result\n /// \n private TestResult _currentResult;\n\n#if !NETCF && !SILVERLIGHT && !PORTABLE\n /// \n /// The current Principal.\n /// \n private IPrincipal _currentPrincipal;\n#endif\n\n #endregion\n\n #region Constructors\n\n /// \n /// Initializes a new instance of the class.\n /// \n public TestExecutionContext()\n {\n _priorContext = null;\n TestCaseTimeout = 0;\n UpstreamActions = new List();\n\n _currentCulture = CultureInfo.CurrentCulture;\n _currentUICulture = CultureInfo.CurrentUICulture;\n\n#if !NETCF && !SILVERLIGHT && !PORTABLE\n _currentPrincipal = Thread.CurrentPrincipal;\n#endif\n\n CurrentValueFormatter = (val) => MsgUtils.DefaultValueFormatter(val);\n IsSingleThreaded = false;\n }\n\n /// \n /// Initializes a new instance of the class.\n /// \n /// An existing instance of TestExecutionContext.\n public TestExecutionContext(TestExecutionContext other)\n {\n _priorContext = other;\n\n CurrentTest = other.CurrentTest;\n CurrentResult = other.CurrentResult;\n TestObject = other.TestObject;\n WorkDirectory = other.WorkDirectory;\n _listener = other._listener;\n StopOnError = other.StopOnError;\n TestCaseTimeout = other.TestCaseTimeout;\n UpstreamActions = new List(other.UpstreamActions);\n\n _currentCulture = other.CurrentCulture;\n _currentUICulture = other.CurrentUICulture;\n\n#if !NETCF && !SILVERLIGHT && !PORTABLE\n _currentPrincipal = other.CurrentPrincipal;\n#endif\n\n CurrentValueFormatter = other.CurrentValueFormatter;\n\n Dispatcher = other.Dispatcher;\n ParallelScope = other.ParallelScope;\n IsSingleThreaded = other.IsSingleThreaded;\n }\n\n #endregion\n\n #region Static Singleton Instance\n\n /// \n /// The current context, head of the list of saved contexts.\n /// \n#if SILVERLIGHT || PORTABLE\n [ThreadStatic]\n private static TestExecutionContext current;\n#elif NETCF\n private static LocalDataStoreSlot slotContext = Thread.AllocateDataSlot();\n#else\n private static readonly string CONTEXT_KEY = \"NUnit.Framework.TestContext\";\n#endif\n\n /// \n /// Gets the current context.\n /// \n /// The current context.\n public static TestExecutionContext CurrentContext\n {\n get\n {\n // If a user creates a thread then the current context\n // will be null. This also happens when the compiler\n // automatically creates threads for async methods.\n // We create a new context, which is automatically\n // populated with _values taken from the current thread.\n#if SILVERLIGHT || PORTABLE\n if (current == null)\n current = new TestExecutionContext();\n\n return current;\n#elif NETCF\n var current = (TestExecutionContext)Thread.GetData(slotContext);\n if (current == null)\n {\n current = new TestExecutionContext();\n Thread.SetData(slotContext, current);\n }\n\n return current;\n#else\n var context = GetTestExecutionContext();\n if (context == null) // This can happen on Mono\n {\n context = new TestExecutionContext();\n CallContext.SetData(CONTEXT_KEY, context);\n }\n\n return context;\n#endif\n }\n\n private set\n {\n#if SILVERLIGHT || PORTABLE\n current = value;\n#elif NETCF\n Thread.SetData(slotContext, value);\n#else\n if (value == null)\n CallContext.FreeNamedDataSlot(CONTEXT_KEY);\n else\n CallContext.SetData(CONTEXT_KEY, value);\n#endif\n }\n }\n\n#if !SILVERLIGHT && !NETCF && !PORTABLE\n /// \n /// Get the current context or return null if none is found.\n /// \n public static TestExecutionContext GetTestExecutionContext()\n {\n return CallContext.GetData(CONTEXT_KEY) as TestExecutionContext;\n }\n#endif\n\n /// \n /// Clear the current context. This is provided to\n /// prevent \"leakage\" of the CallContext containing\n /// the current context back to any runners.\n /// \n public static void ClearCurrentContext()\n {\n CurrentContext = null;\n }\n\n #endregion\n\n #region Properties\n\n /// \n /// Gets or sets the current test\n /// \n public Test CurrentTest { get; set; }\n\n /// \n /// The time the current test started execution\n /// \n public DateTime StartTime { get; set; }\n\n /// \n /// The time the current test started in Ticks\n /// \n public long StartTicks { get; set; }\n\n /// \n /// Gets or sets the current test result\n /// \n public TestResult CurrentResult\n {\n get { return _currentResult; }\n set\n {\n _currentResult = value;\n if (value != null)\n OutWriter = value.OutWriter;\n }\n }\n\n /// \n /// Gets a TextWriter that will send output to the current test result.\n /// \n public TextWriter OutWriter { get; private set; }\n\n /// \n /// The current test object - that is the user fixture\n /// object on which tests are being executed.\n /// \n public object TestObject { get; set; }\n\n /// \n /// Get or set the working directory\n /// \n public string WorkDirectory { get; set; }\n\n /// \n /// Get or set indicator that run should stop on the first error\n /// \n public bool StopOnError { get; set; }\n\n /// \n /// Gets an enum indicating whether a stop has been requested.\n /// \n public TestExecutionStatus ExecutionStatus\n {\n get\n {\n // ExecutionStatus may have been set to StopRequested or AbortRequested\n // in a prior context. If so, reflect the same setting in this context.\n if (_executionStatus == TestExecutionStatus.Running && _priorContext != null)\n _executionStatus = _priorContext.ExecutionStatus;\n\n return _executionStatus;\n }\n set\n {\n _executionStatus = value;\n\n // Push the same setting up to all prior contexts\n if (_priorContext != null)\n _priorContext.ExecutionStatus = value;\n }\n }\n\n /// \n /// The current test event listener\n /// \n internal ITestListener Listener\n {\n get { return _listener; }\n set { _listener = value; }\n }\n\n /// \n /// The current WorkItemDispatcher\n /// \n internal IWorkItemDispatcher Dispatcher\n {\n get\n {\n if (_dispatcher == null)\n _dispatcher = new SimpleWorkItemDispatcher();\n\n return _dispatcher;\n }\n set { _dispatcher = value; }\n }\n\n /// \n /// The ParallelScope to be used by tests running in this context.\n /// For builds with out the parallel feature, it has no effect.\n /// \n public ParallelScope ParallelScope { get; set; }\n\n /// \n /// The unique name of the worker that spawned the context.\n /// For builds with out the parallel feature, it is null.\n /// \n public string WorkerId {get; internal set;}\n\n /// \n /// Gets the RandomGenerator specific to this Test\n /// \n public Randomizer RandomGenerator\n {\n get\n {\n if (_randomGenerator == null)\n _randomGenerator = new Randomizer(CurrentTest.Seed);\n return _randomGenerator;\n }\n }\n\n /// \n /// Gets the assert count.\n /// \n /// The assert count.\n internal int AssertCount\n {\n get { return _assertCount; }\n }\n\n /// \n /// Gets or sets the test case timeout value\n /// \n public int TestCaseTimeout { get; set; }\n\n /// \n /// Gets a list of ITestActions set by upstream tests\n /// \n public List UpstreamActions { get; private set; }\n\n // TODO: Put in checks on all of these settings\n // with side effects so we only change them\n // if the value is different\n\n /// \n /// Saves or restores the CurrentCulture\n /// \n public CultureInfo CurrentCulture\n {\n get { return _currentCulture; }\n set\n {\n _currentCulture = value;\n#if !NETCF && !PORTABLE\n Thread.CurrentThread.CurrentCulture = _currentCulture;\n#endif\n }\n }\n\n /// \n /// Saves or restores the CurrentUICulture\n /// \n public CultureInfo CurrentUICulture\n {\n get { return _currentUICulture; }\n set\n {\n _currentUICulture = value;\n#if !NETCF && !PORTABLE\n Thread.CurrentThread.CurrentUICulture = _currentUICulture;\n#endif\n }\n }\n\n#if !NETCF && !SILVERLIGHT && !PORTABLE\n /// \n /// Gets or sets the current for the Thread.\n /// \n public IPrincipal CurrentPrincipal\n {\n get { return _currentPrincipal; }\n set\n {\n _currentPrincipal = value;\n Thread.CurrentPrincipal = _currentPrincipal;\n }\n }\n#endif\n\n /// \n /// The current head of the ValueFormatter chain, copied from MsgUtils.ValueFormatter\n /// \n public ValueFormatter CurrentValueFormatter { get; private set; }\n\n /// \n /// If true, all tests must run on the same thread. No new thread may be spawned.\n /// \n public bool IsSingleThreaded { get; set; }\n\n #endregion\n\n #region Instance Methods\n\n /// \n /// Record any changes in the environment made by\n /// the test code in the execution context so it\n /// will be passed on to lower level tests.\n /// \n public void UpdateContextFromEnvironment()\n {\n _currentCulture = CultureInfo.CurrentCulture;\n _currentUICulture = CultureInfo.CurrentUICulture;\n\n#if !NETCF && !SILVERLIGHT && !PORTABLE\n _currentPrincipal = Thread.CurrentPrincipal;\n#endif\n }\n\n /// \n /// Set up the execution environment to match a context.\n /// Note that we may be running on the same thread where the\n /// context was initially created or on a different thread.\n /// \n public void EstablishExecutionEnvironment()\n {\n#if !NETCF && !PORTABLE\n Thread.CurrentThread.CurrentCulture = _currentCulture;\n Thread.CurrentThread.CurrentUICulture = _currentUICulture;\n#endif\n\n#if !NETCF && !SILVERLIGHT && !PORTABLE\n Thread.CurrentPrincipal = _currentPrincipal;\n#endif\n\n CurrentContext = this;\n }\n\n /// \n /// Increments the assert count by one.\n /// \n public void IncrementAssertCount()\n {\n Interlocked.Increment(ref _assertCount);\n }\n\n /// \n /// Increments the assert count by a specified amount.\n /// \n public void IncrementAssertCount(int count)\n {\n // TODO: Temporary implementation\n while (count-- > 0)\n Interlocked.Increment(ref _assertCount);\n }\n\n /// \n /// Adds a new ValueFormatterFactory to the chain of formatters\n /// \n /// The new factory\n public void AddFormatter(ValueFormatterFactory formatterFactory)\n {\n CurrentValueFormatter = formatterFactory(CurrentValueFormatter);\n }\n\n #endregion\n\n #region InitializeLifetimeService\n\n#if !SILVERLIGHT && !NETCF && !PORTABLE\n /// \n /// Obtain lifetime service object\n /// \n /// \n public override object InitializeLifetimeService()\n {\n return null;\n }\n#endif\n\n #endregion\n }\n}\n"},"gt":{"kind":"string","value":""}}},{"rowIdx":96207,"cells":{"context":{"kind":"string","value":"/*\n * Exchange Web Services Managed API\n *\n * Copyright (c) Microsoft Corporation\n * All rights reserved.\n *\n * MIT License\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy of this\n * software and associated documentation files (the \"Software\"), to deal in the Software\n * without restriction, including without limitation the rights to use, copy, modify, merge,\n * publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons\n * to whom the Software is furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all copies or\n * substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,\n * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR\n * PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE\n * FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n * DEALINGS IN THE SOFTWARE.\n */\n\nnamespace Microsoft.Exchange.WebServices.Data\n{\n using System;\n using System.Collections;\n using System.Collections.Generic;\n using System.Diagnostics;\n using System.Globalization;\n using System.IO;\n using System.Linq;\n using System.Net;\n using System.Reflection;\n using System.Text;\n using System.Text.RegularExpressions;\n using System.Threading;\n using System.Xml;\n\n /// \n /// EWS utilities\n /// \n internal static class EwsUtilities\n {\n #region Private members\n\n /// \n /// Map from XML element names to ServiceObject type and constructors. \n /// \n private static LazyMember serviceObjectInfo = new LazyMember(\n delegate()\n {\n return new ServiceObjectInfo();\n });\n\n /// \n /// Version of API binary.\n /// \n private static LazyMember buildVersion = new LazyMember(\n delegate()\n {\n try\n {\n FileVersionInfo fileInfo = FileVersionInfo.GetVersionInfo(Assembly.GetExecutingAssembly().Location);\n return fileInfo.FileVersion;\n }\n catch\n {\n // OM:2026839 When run in an environment with partial trust, fetching the build version blows up.\n // Just return a hardcoded value on failure.\n return \"0.0\";\n }\n });\n\n /// \n /// Dictionary of enum type to ExchangeVersion maps. \n /// \n private static LazyMember>> enumVersionDictionaries = new LazyMember>>(\n () => new Dictionary>()\n {\n { typeof(WellKnownFolderName), BuildEnumDict(typeof(WellKnownFolderName)) },\n { typeof(ItemTraversal), BuildEnumDict(typeof(ItemTraversal)) },\n { typeof(ConversationQueryTraversal), BuildEnumDict(typeof(ConversationQueryTraversal)) },\n { typeof(FileAsMapping), BuildEnumDict(typeof(FileAsMapping)) },\n { typeof(EventType), BuildEnumDict(typeof(EventType)) },\n { typeof(MeetingRequestsDeliveryScope), BuildEnumDict(typeof(MeetingRequestsDeliveryScope)) },\n { typeof(ViewFilter), BuildEnumDict(typeof(ViewFilter)) },\n });\n\n /// \n /// Dictionary of enum type to schema-name-to-enum-value maps.\n /// \n private static LazyMember>> schemaToEnumDictionaries = new LazyMember>>(\n () => new Dictionary>\n {\n { typeof(EventType), BuildSchemaToEnumDict(typeof(EventType)) },\n { typeof(MailboxType), BuildSchemaToEnumDict(typeof(MailboxType)) },\n { typeof(FileAsMapping), BuildSchemaToEnumDict(typeof(FileAsMapping)) },\n { typeof(RuleProperty), BuildSchemaToEnumDict(typeof(RuleProperty)) },\n { typeof(WellKnownFolderName), BuildSchemaToEnumDict(typeof(WellKnownFolderName)) },\n });\n\n /// \n /// Dictionary of enum type to enum-value-to-schema-name maps.\n /// \n private static LazyMember>> enumToSchemaDictionaries = new LazyMember>>(\n () => new Dictionary>\n {\n { typeof(EventType), BuildEnumToSchemaDict(typeof(EventType)) },\n { typeof(MailboxType), BuildEnumToSchemaDict(typeof(MailboxType)) },\n { typeof(FileAsMapping), BuildEnumToSchemaDict(typeof(FileAsMapping)) },\n { typeof(RuleProperty), BuildEnumToSchemaDict(typeof(RuleProperty)) },\n { typeof(WellKnownFolderName), BuildEnumToSchemaDict(typeof(WellKnownFolderName)) },\n });\n\n /// \n /// Dictionary to map from special CLR type names to their \"short\" names.\n /// \n private static LazyMember> typeNameToShortNameMap = new LazyMember>(\n () => new Dictionary\n {\n { \"Boolean\", \"bool\" },\n { \"Int16\", \"short\" },\n { \"Int32\", \"int\" },\n { \"String\", \"string\" }\n });\n #endregion\n\n #region Constants\n\n internal const string XSFalse = \"false\";\n internal const string XSTrue = \"true\";\n\n internal const string EwsTypesNamespacePrefix = \"t\";\n internal const string EwsMessagesNamespacePrefix = \"m\";\n internal const string EwsErrorsNamespacePrefix = \"e\";\n internal const string EwsSoapNamespacePrefix = \"soap\";\n internal const string EwsXmlSchemaInstanceNamespacePrefix = \"xsi\";\n internal const string PassportSoapFaultNamespacePrefix = \"psf\";\n internal const string WSTrustFebruary2005NamespacePrefix = \"wst\";\n internal const string WSAddressingNamespacePrefix = \"wsa\";\n internal const string AutodiscoverSoapNamespacePrefix = \"a\";\n internal const string WSSecurityUtilityNamespacePrefix = \"wsu\";\n internal const string WSSecuritySecExtNamespacePrefix = \"wsse\";\n\n internal const string EwsTypesNamespace = \"http://schemas.microsoft.com/exchange/services/2006/types\";\n internal const string EwsMessagesNamespace = \"http://schemas.microsoft.com/exchange/services/2006/messages\";\n internal const string EwsErrorsNamespace = \"http://schemas.microsoft.com/exchange/services/2006/errors\";\n internal const string EwsSoapNamespace = \"http://schemas.xmlsoap.org/soap/envelope/\";\n internal const string EwsSoap12Namespace = \"http://www.w3.org/2003/05/soap-envelope\";\n internal const string EwsXmlSchemaInstanceNamespace = \"http://www.w3.org/2001/XMLSchema-instance\";\n internal const string PassportSoapFaultNamespace = \"http://schemas.microsoft.com/Passport/SoapServices/SOAPFault\";\n internal const string WSTrustFebruary2005Namespace = \"http://schemas.xmlsoap.org/ws/2005/02/trust\";\n internal const string WSAddressingNamespace = \"http://www.w3.org/2005/08/addressing\"; // \"http://schemas.xmlsoap.org/ws/2004/08/addressing\";\n internal const string AutodiscoverSoapNamespace = \"http://schemas.microsoft.com/exchange/2010/Autodiscover\";\n internal const string WSSecurityUtilityNamespace = \"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd\";\n internal const string WSSecuritySecExtNamespace = \"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd\";\n\n /// \n /// Regular expression for legal domain names.\n /// \n internal const string DomainRegex = \"^[-a-zA-Z0-9_.]+$\";\n #endregion\n\n /// \n /// Asserts that the specified condition if true.\n /// \n /// Assertion.\n /// The caller.\n /// The message to use if assertion fails.\n internal static void Assert(\n bool condition,\n string caller,\n string message)\n {\n Debug.Assert(\n condition,\n string.Format(\"[{0}] {1}\", caller, message));\n }\n\n /// \n /// Gets the namespace prefix from an XmlNamespace enum value.\n /// \n /// The XML namespace.\n /// Namespace prefix string.\n internal static string GetNamespacePrefix(XmlNamespace xmlNamespace)\n {\n switch (xmlNamespace)\n {\n case XmlNamespace.Types:\n return EwsTypesNamespacePrefix;\n case XmlNamespace.Messages:\n return EwsMessagesNamespacePrefix;\n case XmlNamespace.Errors:\n return EwsErrorsNamespacePrefix;\n case XmlNamespace.Soap:\n case XmlNamespace.Soap12:\n return EwsSoapNamespacePrefix;\n case XmlNamespace.XmlSchemaInstance:\n return EwsXmlSchemaInstanceNamespacePrefix;\n case XmlNamespace.PassportSoapFault:\n return PassportSoapFaultNamespacePrefix;\n case XmlNamespace.WSTrustFebruary2005:\n return WSTrustFebruary2005NamespacePrefix;\n case XmlNamespace.WSAddressing:\n return WSAddressingNamespacePrefix;\n case XmlNamespace.Autodiscover:\n return AutodiscoverSoapNamespacePrefix;\n default:\n return string.Empty;\n }\n }\n\n /// \n /// Gets the namespace URI from an XmlNamespace enum value.\n /// \n /// The XML namespace.\n /// Uri as string\n internal static string GetNamespaceUri(XmlNamespace xmlNamespace)\n {\n switch (xmlNamespace)\n {\n case XmlNamespace.Types:\n return EwsTypesNamespace;\n case XmlNamespace.Messages:\n return EwsMessagesNamespace;\n case XmlNamespace.Errors:\n return EwsErrorsNamespace;\n case XmlNamespace.Soap:\n return EwsSoapNamespace;\n case XmlNamespace.Soap12:\n return EwsSoap12Namespace;\n case XmlNamespace.XmlSchemaInstance:\n return EwsXmlSchemaInstanceNamespace;\n case XmlNamespace.PassportSoapFault:\n return PassportSoapFaultNamespace;\n case XmlNamespace.WSTrustFebruary2005:\n return WSTrustFebruary2005Namespace;\n case XmlNamespace.WSAddressing:\n return WSAddressingNamespace;\n case XmlNamespace.Autodiscover:\n return AutodiscoverSoapNamespace;\n default:\n return string.Empty;\n }\n }\n\n /// \n /// Gets the XmlNamespace enum value from a namespace Uri.\n /// \n /// XML namespace Uri.\n /// XmlNamespace enum value.\n internal static XmlNamespace GetNamespaceFromUri(string namespaceUri)\n {\n switch (namespaceUri)\n {\n case EwsErrorsNamespace:\n return XmlNamespace.Errors;\n case EwsTypesNamespace:\n return XmlNamespace.Types;\n case EwsMessagesNamespace:\n return XmlNamespace.Messages;\n case EwsSoapNamespace:\n return XmlNamespace.Soap;\n case EwsSoap12Namespace:\n return XmlNamespace.Soap12;\n case EwsXmlSchemaInstanceNamespace:\n return XmlNamespace.XmlSchemaInstance;\n case PassportSoapFaultNamespace:\n return XmlNamespace.PassportSoapFault;\n case WSTrustFebruary2005Namespace:\n return XmlNamespace.WSTrustFebruary2005;\n case WSAddressingNamespace:\n return XmlNamespace.WSAddressing;\n default:\n return XmlNamespace.NotSpecified;\n }\n }\n\n /// \n /// Creates EWS object based on XML element name.\n /// \n /// The type of the service object.\n /// The service.\n /// Name of the XML element.\n /// Service object.\n internal static TServiceObject CreateEwsObjectFromXmlElementName(ExchangeService service, string xmlElementName)\n where TServiceObject : ServiceObject\n {\n Type itemClass;\n\n if (EwsUtilities.serviceObjectInfo.Member.XmlElementNameToServiceObjectClassMap.TryGetValue(xmlElementName, out itemClass))\n {\n CreateServiceObjectWithServiceParam creationDelegate;\n\n if (EwsUtilities.serviceObjectInfo.Member.ServiceObjectConstructorsWithServiceParam.TryGetValue(itemClass, out creationDelegate))\n {\n return (TServiceObject)creationDelegate(service);\n }\n else\n {\n throw new ArgumentException(Strings.NoAppropriateConstructorForItemClass);\n }\n }\n else\n {\n return default(TServiceObject);\n }\n }\n\n /// \n /// Creates Item from Item class.\n /// \n /// The item attachment.\n /// The item class.\n /// If true, item attachment is new.\n /// New Item.\n internal static Item CreateItemFromItemClass(\n ItemAttachment itemAttachment,\n Type itemClass,\n bool isNew)\n {\n CreateServiceObjectWithAttachmentParam creationDelegate;\n\n if (EwsUtilities.serviceObjectInfo.Member.ServiceObjectConstructorsWithAttachmentParam.TryGetValue(itemClass, out creationDelegate))\n {\n return (Item)creationDelegate(itemAttachment, isNew);\n }\n else\n {\n throw new ArgumentException(Strings.NoAppropriateConstructorForItemClass);\n }\n }\n\n /// \n /// Creates Item based on XML element name.\n /// \n /// The item attachment.\n /// Name of the XML element.\n /// New Item.\n internal static Item CreateItemFromXmlElementName(ItemAttachment itemAttachment, string xmlElementName)\n {\n Type itemClass;\n\n if (EwsUtilities.serviceObjectInfo.Member.XmlElementNameToServiceObjectClassMap.TryGetValue(xmlElementName, out itemClass))\n {\n return CreateItemFromItemClass(itemAttachment, itemClass, false);\n }\n else\n {\n return null;\n }\n }\n\n /// \n /// Gets the expected item type based on the local name.\n /// \n /// \n /// \n internal static Type GetItemTypeFromXmlElementName(string xmlElementName)\n {\n Type itemClass = null;\n EwsUtilities.serviceObjectInfo.Member.XmlElementNameToServiceObjectClassMap.TryGetValue(xmlElementName, out itemClass);\n return itemClass;\n }\n\n /// \n /// Finds the first item of type TItem (not a descendant type) in the specified collection.\n /// \n /// The type of the item to find.\n /// The collection.\n /// A TItem instance or null if no instance of TItem could be found.\n internal static TItem FindFirstItemOfType(IEnumerable items)\n where TItem : Item\n {\n Type itemType = typeof(TItem);\n\n foreach (Item item in items)\n {\n // We're looking for an exact class match here.\n if (item.GetType() == itemType)\n {\n return (TItem)item;\n }\n }\n\n return null;\n }\n\n #region Tracing routines\n\n /// \n /// Write trace start element.\n /// \n /// The writer to write the start element to.\n /// The trace tag.\n /// If true, include build version attribute.\n [System.Diagnostics.CodeAnalysis.SuppressMessage(\"Exchange.Usage\", \"EX0009:DoNotUseDateTimeNowOrFromFileTime\", Justification = \"Client API\")]\n private static void WriteTraceStartElement(\n XmlWriter writer,\n string traceTag,\n bool includeVersion)\n {\n writer.WriteStartElement(\"Trace\");\n writer.WriteAttributeString(\"Tag\", traceTag);\n writer.WriteAttributeString(\"Tid\", Thread.CurrentThread.ManagedThreadId.ToString());\n writer.WriteAttributeString(\"Time\", DateTime.UtcNow.ToString(\"u\", DateTimeFormatInfo.InvariantInfo));\n\n if (includeVersion)\n {\n writer.WriteAttributeString(\"Version\", EwsUtilities.BuildVersion);\n }\n }\n\n /// \n /// Format log message.\n /// \n /// Kind of the entry.\n /// The log entry.\n /// XML log entry as a string.\n internal static string FormatLogMessage(string entryKind, string logEntry)\n {\n StringBuilder sb = new StringBuilder();\n using (StringWriter writer = new StringWriter(sb))\n {\n using (XmlTextWriter xmlWriter = new XmlTextWriter(writer))\n {\n xmlWriter.Formatting = Formatting.Indented;\n\n EwsUtilities.WriteTraceStartElement(xmlWriter, entryKind, false);\n\n xmlWriter.WriteWhitespace(Environment.NewLine);\n xmlWriter.WriteValue(logEntry);\n xmlWriter.WriteWhitespace(Environment.NewLine);\n\n xmlWriter.WriteEndElement(); // Trace\n xmlWriter.WriteWhitespace(Environment.NewLine);\n }\n }\n return sb.ToString();\n }\n\n /// \n /// Format the HTTP headers.\n /// \n /// StringBuilder.\n /// The HTTP headers.\n private static void FormatHttpHeaders(StringBuilder sb, WebHeaderCollection headers)\n {\n foreach (string key in headers.Keys)\n {\n sb.Append(\n string.Format(\n \"{0}: {1}\\n\",\n key,\n headers[key]));\n }\n }\n\n /// \n /// Format request HTTP headers.\n /// \n /// The HTTP request.\n internal static string FormatHttpRequestHeaders(IEwsHttpWebRequest request)\n {\n StringBuilder sb = new StringBuilder();\n sb.Append(string.Format(\"{0} {1} HTTP/1.1\\n\", request.Method, request.RequestUri.AbsolutePath));\n EwsUtilities.FormatHttpHeaders(sb, request.Headers);\n sb.Append(\"\\n\");\n\n return sb.ToString();\n }\n\n /// \n /// Format response HTTP headers.\n /// \n /// The HTTP response.\n internal static string FormatHttpResponseHeaders(IEwsHttpWebResponse response)\n {\n StringBuilder sb = new StringBuilder();\n sb.Append(\n string.Format(\n \"HTTP/{0} {1} {2}\\n\",\n response.ProtocolVersion,\n (int)response.StatusCode,\n response.StatusDescription));\n\n sb.Append(EwsUtilities.FormatHttpHeaders(response.Headers));\n sb.Append(\"\\n\");\n return sb.ToString();\n }\n\n /// \n /// Format request HTTP headers.\n /// \n /// The HTTP request.\n internal static string FormatHttpRequestHeaders(HttpWebRequest request)\n {\n StringBuilder sb = new StringBuilder();\n sb.Append(\n string.Format(\n \"{0} {1} HTTP/{2}\\n\",\n request.Method.ToUpperInvariant(),\n request.RequestUri.AbsolutePath,\n request.ProtocolVersion));\n\n sb.Append(EwsUtilities.FormatHttpHeaders(request.Headers));\n sb.Append(\"\\n\");\n return sb.ToString();\n }\n\n /// \n /// Formats HTTP headers.\n /// \n /// The headers.\n /// Headers as a string\n private static string FormatHttpHeaders(WebHeaderCollection headers)\n {\n StringBuilder sb = new StringBuilder();\n foreach (string key in headers.Keys)\n {\n sb.Append(\n string.Format(\n \"{0}: {1}\\n\",\n key,\n headers[key]));\n }\n return sb.ToString();\n }\n\n /// \n /// Format XML content in a MemoryStream for message.\n /// \n /// Kind of the entry.\n /// The memory stream.\n /// XML log entry as a string.\n internal static string FormatLogMessageWithXmlContent(string entryKind, MemoryStream memoryStream)\n {\n StringBuilder sb = new StringBuilder();\n XmlReaderSettings settings = new XmlReaderSettings();\n settings.ConformanceLevel = ConformanceLevel.Fragment;\n settings.IgnoreComments = true;\n settings.IgnoreWhitespace = true;\n settings.CloseInput = false;\n\n // Remember the current location in the MemoryStream.\n long lastPosition = memoryStream.Position;\n\n // Rewind the position since we want to format the entire contents.\n memoryStream.Position = 0;\n\n try\n {\n using (XmlReader reader = XmlReader.Create(memoryStream, settings))\n {\n using (StringWriter writer = new StringWriter(sb))\n {\n using (XmlTextWriter xmlWriter = new XmlTextWriter(writer))\n {\n xmlWriter.Formatting = Formatting.Indented;\n\n EwsUtilities.WriteTraceStartElement(xmlWriter, entryKind, true);\n\n while (!reader.EOF)\n {\n xmlWriter.WriteNode(reader, true);\n }\n\n xmlWriter.WriteEndElement(); // Trace\n xmlWriter.WriteWhitespace(Environment.NewLine);\n }\n }\n }\n }\n catch (XmlException)\n {\n // We tried to format the content as \"pretty\" XML. Apparently the content is\n // not well-formed XML or isn't XML at all. Fallback and treat it as plain text.\n sb.Length = 0;\n memoryStream.Position = 0;\n sb.Append(Encoding.UTF8.GetString(memoryStream.GetBuffer(), 0, (int)memoryStream.Length));\n }\n\n // Restore Position in the stream.\n memoryStream.Position = lastPosition;\n\n return sb.ToString();\n }\n\n #endregion\n\n #region Stream routines\n\n /// \n /// Copies source stream to target.\n /// \n /// The source.\n /// The target.\n internal static void CopyStream(Stream source, Stream target)\n {\n // See if this is a MemoryStream -- we can use WriteTo.\n MemoryStream memContentStream = source as MemoryStream;\n if (memContentStream != null)\n {\n memContentStream.WriteTo(target);\n }\n else\n {\n // Otherwise, copy data through a buffer\n byte[] buffer = new byte[4096];\n int bufferSize = buffer.Length;\n int bytesRead = source.Read(buffer, 0, bufferSize);\n while (bytesRead > 0)\n {\n target.Write(buffer, 0, bytesRead);\n bytesRead = source.Read(buffer, 0, bufferSize);\n }\n }\n }\n\n #endregion\n\n /// \n /// Gets the build version.\n /// \n /// The build version.\n internal static string BuildVersion\n {\n get { return EwsUtilities.buildVersion.Member; }\n }\n\n #region Conversion routines\n\n /// \n /// Convert bool to XML Schema bool.\n /// \n /// Bool value.\n /// String representing bool value in XML Schema.\n internal static string BoolToXSBool(bool value)\n {\n return value ? EwsUtilities.XSTrue : EwsUtilities.XSFalse;\n }\n\n /// \n /// Parses an enum value list.\n /// \n /// Type of value.\n /// The list.\n /// The value.\n /// The separators.\n internal static void ParseEnumValueList(\n IList list,\n string value,\n params char[] separators)\n where T : struct\n {\n EwsUtilities.Assert(\n typeof(T).IsEnum,\n \"EwsUtilities.ParseEnumValueList\",\n \"T is not an enum type.\");\n\n string[] enumValues = value.Split(separators);\n\n foreach (string enumValue in enumValues)\n {\n list.Add((T)Enum.Parse(typeof(T), enumValue, false));\n }\n }\n\n /// \n /// Converts an enum to a string, using the mapping dictionaries if appropriate.\n /// \n /// The enum value to be serialized\n /// String representation of enum to be used in the protocol\n internal static string SerializeEnum(Enum value)\n {\n Dictionary enumToStringDict;\n string strValue;\n if (enumToSchemaDictionaries.Member.TryGetValue(value.GetType(), out enumToStringDict) &&\n enumToStringDict.TryGetValue(value, out strValue))\n {\n return strValue;\n }\n else\n {\n return value.ToString();\n }\n }\n\n /// \n /// Parses specified value based on type.\n /// \n /// Type of value.\n /// The value.\n /// Value of type T.\n internal static T Parse(string value)\n {\n if (typeof(T).IsEnum)\n {\n Dictionary stringToEnumDict;\n Enum enumValue;\n if (schemaToEnumDictionaries.Member.TryGetValue(typeof(T), out stringToEnumDict) &&\n stringToEnumDict.TryGetValue(value, out enumValue))\n {\n // This double-casting is ugly, but necessary. By this point, we know that T is an Enum\n // (same as returned by the dictionary), but the compiler can't prove it. Thus, the \n // up-cast before we can down-cast.\n return (T)((object)enumValue);\n }\n else\n {\n return (T)Enum.Parse(typeof(T), value, false);\n }\n }\n else\n {\n return (T)Convert.ChangeType(value, typeof(T), CultureInfo.InvariantCulture);\n }\n }\n\n /// \n /// Tries to parses the specified value to the specified type.\n /// \n /// The type into which to cast the provided value.\n /// The value to parse.\n /// The value cast to the specified type, if TryParse succeeds. Otherwise, the value of result is indeterminate.\n /// True if value could be parsed; otherwise, false.\n internal static bool TryParse(string value, out T result)\n {\n try\n {\n result = EwsUtilities.Parse(value);\n\n return true;\n }\n //// Catch all exceptions here, we're not interested in the reason why TryParse failed.\n catch (Exception)\n {\n result = default(T);\n\n return false;\n }\n }\n\n /// \n /// Converts the specified date and time from one time zone to another.\n /// \n /// The date time to convert.\n /// The source time zone.\n /// The destination time zone.\n /// A DateTime that holds the converted\n internal static DateTime ConvertTime(\n DateTime dateTime,\n TimeZoneInfo sourceTimeZone,\n TimeZoneInfo destinationTimeZone)\n {\n try\n {\n return TimeZoneInfo.ConvertTime(\n dateTime,\n sourceTimeZone,\n destinationTimeZone);\n }\n catch (ArgumentException e)\n {\n throw new TimeZoneConversionException(\n string.Format(\n Strings.CannotConvertBetweenTimeZones,\n EwsUtilities.DateTimeToXSDateTime(dateTime),\n sourceTimeZone.DisplayName,\n destinationTimeZone.DisplayName),\n e);\n }\n }\n\n /// \n /// Reads the string as date time, assuming it is unbiased (e.g. 2009/01/01T08:00)\n /// and scoped to service's time zone.\n /// \n /// The date string.\n /// The service.\n /// The string's value as a DateTime object.\n internal static DateTime ParseAsUnbiasedDatetimescopedToServicetimeZone(string dateString, ExchangeService service)\n {\n // Convert the element's value to a DateTime with no adjustment.\n DateTime tempDate = DateTime.Parse(dateString, CultureInfo.InvariantCulture);\n\n // Set the kind according to the service's time zone\n if (service.TimeZone == TimeZoneInfo.Utc)\n {\n return new DateTime(tempDate.Ticks, DateTimeKind.Utc);\n }\n else if (EwsUtilities.IsLocalTimeZone(service.TimeZone))\n {\n return new DateTime(tempDate.Ticks, DateTimeKind.Local);\n }\n else\n {\n return new DateTime(tempDate.Ticks, DateTimeKind.Unspecified);\n }\n }\n\n /// \n /// Determines whether the specified time zone is the same as the system's local time zone.\n /// \n /// The time zone to check.\n /// \n /// true if the specified time zone is the same as the system's local time zone; otherwise, false.\n /// \n internal static bool IsLocalTimeZone(TimeZoneInfo timeZone)\n {\n return (TimeZoneInfo.Local == timeZone) || (TimeZoneInfo.Local.Id == timeZone.Id && TimeZoneInfo.Local.HasSameRules(timeZone));\n }\n\n /// \n /// Convert DateTime to XML Schema date.\n /// \n /// The date to be converted.\n /// String representation of DateTime.\n internal static string DateTimeToXSDate(DateTime date)\n {\n // Depending on the current culture, DateTime formatter will \n // translate dates from one culture to another (e.g. Gregorian to Lunar). The server\n // however, considers all dates to be in Gregorian, so using the InvariantCulture will\n // ensure this.\n string format;\n\n switch (date.Kind)\n {\n case DateTimeKind.Utc:\n format = \"yyyy-MM-ddZ\";\n break;\n case DateTimeKind.Unspecified:\n format = \"yyyy-MM-dd\";\n break;\n default: // DateTimeKind.Local is remaining\n format = \"yyyy-MM-ddzzz\";\n break;\n }\n\n return date.ToString(format, CultureInfo.InvariantCulture);\n }\n\n /// \n /// Dates the DateTime into an XML schema date time.\n /// \n /// The date time.\n /// String representation of DateTime.\n internal static string DateTimeToXSDateTime(DateTime dateTime)\n {\n string format = \"yyyy-MM-ddTHH:mm:ss.fff\";\n\n switch (dateTime.Kind)\n {\n case DateTimeKind.Utc:\n format += \"Z\";\n break;\n case DateTimeKind.Local:\n format += \"zzz\";\n break;\n default:\n break;\n }\n\n // Depending on the current culture, DateTime formatter will replace ':' with \n // the DateTimeFormatInfo.TimeSeparator property which may not be ':'. Force the proper string\n // to be used by using the InvariantCulture.\n return dateTime.ToString(format, CultureInfo.InvariantCulture);\n }\n\n /// \n /// Convert EWS DayOfTheWeek enum to System.DayOfWeek.\n /// \n /// The day of the week.\n /// System.DayOfWeek value.\n internal static DayOfWeek EwsToSystemDayOfWeek(DayOfTheWeek dayOfTheWeek)\n {\n if (dayOfTheWeek == DayOfTheWeek.Day ||\n dayOfTheWeek == DayOfTheWeek.Weekday ||\n dayOfTheWeek == DayOfTheWeek.WeekendDay)\n {\n throw new ArgumentException(\n string.Format(\"Cannot convert {0} to System.DayOfWeek enum value\", dayOfTheWeek),\n \"dayOfTheWeek\");\n }\n else\n {\n return (DayOfWeek)dayOfTheWeek;\n }\n }\n\n /// \n /// Convert System.DayOfWeek type to EWS DayOfTheWeek.\n /// \n /// The dayOfWeek.\n /// EWS DayOfWeek value\n internal static DayOfTheWeek SystemToEwsDayOfTheWeek(DayOfWeek dayOfWeek)\n {\n return (DayOfTheWeek)dayOfWeek;\n }\n\n /// \n /// Takes a System.TimeSpan structure and converts it into an \n /// xs:duration string as defined by the W3 Consortiums Recommendation\n /// \"XML Schema Part 2: Datatypes Second Edition\", \n /// http://www.w3.org/TR/xmlschema-2/#duration\n /// \n /// TimeSpan structure to convert\n /// xs:duration formatted string\n internal static string TimeSpanToXSDuration(TimeSpan timeSpan)\n {\n // Optional '-' offset\n string offsetStr = (timeSpan.TotalSeconds < 0) ? \"-\" : string.Empty;\n\n // The TimeSpan structure does not have a Year or Month \n // property, therefore we wouldn't be able to return an xs:duration\n // string from a TimeSpan that included the nY or nM components.\n return String.Format(\n \"{0}P{1}DT{2}H{3}M{4}S\",\n offsetStr,\n Math.Abs(timeSpan.Days),\n Math.Abs(timeSpan.Hours),\n Math.Abs(timeSpan.Minutes),\n Math.Abs(timeSpan.Seconds) + \".\" + Math.Abs(timeSpan.Milliseconds));\n }\n\n /// \n /// Takes an xs:duration string as defined by the W3 Consortiums\n /// Recommendation \"XML Schema Part 2: Datatypes Second Edition\", \n /// http://www.w3.org/TR/xmlschema-2/#duration, and converts it\n /// into a System.TimeSpan structure\n /// \n /// \n /// This method uses the following approximations:\n /// 1 year = 365 days\n /// 1 month = 30 days\n /// Additionally, it only allows for four decimal points of\n /// seconds precision.\n /// \n /// xs:duration string to convert\n /// System.TimeSpan structure\n internal static TimeSpan XSDurationToTimeSpan(string xsDuration)\n {\n Regex timeSpanParser = new Regex(\n \"(?-)?\" +\n \"P\" +\n \"((?[0-9]+)Y)?\" +\n \"((?[0-9]+)M)?\" +\n \"((?[0-9]+)D)?\" +\n \"(T\" +\n \"((?[0-9]+)H)?\" +\n \"((?[0-9]+)M)?\" +\n \"((?[0-9]+)(\\\\.(?[0-9]+))?S)?)?\");\n\n Match m = timeSpanParser.Match(xsDuration);\n if (!m.Success)\n {\n throw new ArgumentException(Strings.XsDurationCouldNotBeParsed);\n }\n string token = m.Result(\"${pos}\");\n bool negative = false;\n if (!String.IsNullOrEmpty(token))\n {\n negative = true;\n }\n\n // Year\n token = m.Result(\"${year}\");\n int year = 0;\n if (!String.IsNullOrEmpty(token))\n {\n year = Int32.Parse(token);\n }\n\n // Month\n token = m.Result(\"${month}\");\n int month = 0;\n if (!String.IsNullOrEmpty(token))\n {\n month = Int32.Parse(token);\n }\n\n // Day\n token = m.Result(\"${day}\");\n int day = 0;\n if (!String.IsNullOrEmpty(token))\n {\n day = Int32.Parse(token);\n }\n\n // Hour\n token = m.Result(\"${hour}\");\n int hour = 0;\n if (!String.IsNullOrEmpty(token))\n {\n hour = Int32.Parse(token);\n }\n\n // Minute\n token = m.Result(\"${minute}\");\n int minute = 0;\n if (!String.IsNullOrEmpty(token))\n {\n minute = Int32.Parse(token);\n }\n\n // Seconds\n token = m.Result(\"${seconds}\");\n int seconds = 0;\n if (!String.IsNullOrEmpty(token))\n {\n seconds = Int32.Parse(token);\n }\n\n int milliseconds = 0;\n token = m.Result(\"${precision}\");\n\n // Only allowed 4 digits of precision\n if (token.Length > 4)\n {\n token = token.Substring(0, 4);\n }\n\n if (!String.IsNullOrEmpty(token))\n {\n milliseconds = Int32.Parse(token);\n }\n\n // Apply conversions of year and months to days.\n // Year = 365 days\n // Month = 30 days\n day = day + (year * 365) + (month * 30);\n TimeSpan retval = new TimeSpan(day, hour, minute, seconds, milliseconds);\n\n if (negative)\n {\n retval = -retval;\n }\n\n return retval;\n }\n\n /// \n /// Converts the specified time span to its XSD representation.\n /// \n /// The time span.\n /// The XSD representation of the specified time span.\n public static string TimeSpanToXSTime(TimeSpan timeSpan)\n {\n return string.Format(\n \"{0:00}:{1:00}:{2:00}\",\n timeSpan.Hours,\n timeSpan.Minutes,\n timeSpan.Seconds);\n }\n\n #endregion\n\n #region Type Name utilities\n /// \n /// Gets the printable name of a CLR type.\n /// \n /// The type.\n /// Printable name.\n public static string GetPrintableTypeName(Type type)\n {\n if (type.IsGenericType)\n {\n // Convert generic type to printable form (e.g. List)\n string genericPrefix = type.Name.Substring(0, type.Name.IndexOf('`'));\n StringBuilder nameBuilder = new StringBuilder(genericPrefix);\n\n // Note: building array of generic parameters is done recursively. Each parameter could be any type.\n string[] genericArgs = type.GetGenericArguments().ToList().ConvertAll(t => GetPrintableTypeName(t)).ToArray();\n\n nameBuilder.Append(\"<\");\n nameBuilder.Append(string.Join(\",\", genericArgs));\n nameBuilder.Append(\">\");\n return nameBuilder.ToString();\n }\n else if (type.IsArray)\n {\n // Convert array type to printable form.\n string arrayPrefix = type.Name.Substring(0, type.Name.IndexOf('['));\n StringBuilder nameBuilder = new StringBuilder(EwsUtilities.GetSimplifiedTypeName(arrayPrefix));\n for (int rank = 0; rank < type.GetArrayRank(); rank++)\n {\n nameBuilder.Append(\"[]\");\n }\n return nameBuilder.ToString();\n }\n else\n {\n return EwsUtilities.GetSimplifiedTypeName(type.Name);\n }\n }\n\n /// \n /// Gets the printable name of a simple CLR type.\n /// \n /// The type name.\n /// Printable name.\n private static string GetSimplifiedTypeName(string typeName)\n {\n // If type has a shortname (e.g. int for Int32) map to the short name.\n string name;\n return typeNameToShortNameMap.Member.TryGetValue(typeName, out name) ? name : typeName;\n }\n\n #endregion\n\n #region EmailAddress parsing\n\n /// \n /// Gets the domain name from an email address.\n /// \n /// The email address.\n /// Domain name.\n internal static string DomainFromEmailAddress(string emailAddress)\n {\n string[] emailAddressParts = emailAddress.Split('@');\n\n if (emailAddressParts.Length != 2 || string.IsNullOrEmpty(emailAddressParts[1]))\n {\n throw new FormatException(Strings.InvalidEmailAddress);\n }\n\n return emailAddressParts[1];\n }\n\n #endregion\n\n #region Method parameters validation routines\n\n /// \n /// Validates parameter (and allows null value).\n /// \n /// The param.\n /// Name of the param.\n internal static void ValidateParamAllowNull(object param, string paramName)\n {\n ISelfValidate selfValidate = param as ISelfValidate;\n\n if (selfValidate != null)\n {\n try\n {\n selfValidate.Validate();\n }\n catch (ServiceValidationException e)\n {\n throw new ArgumentException(\n Strings.ValidationFailed,\n paramName,\n e);\n }\n }\n\n ServiceObject ewsObject = param as ServiceObject;\n\n if (ewsObject != null)\n {\n if (ewsObject.IsNew)\n {\n throw new ArgumentException(Strings.ObjectDoesNotHaveId, paramName);\n }\n }\n }\n\n /// \n /// Validates parameter (null value not allowed).\n /// \n /// The param.\n /// Name of the param.\n internal static void ValidateParam(object param, string paramName)\n {\n bool isValid;\n\n string strParam = param as string;\n if (strParam != null)\n {\n isValid = !string.IsNullOrEmpty(strParam);\n }\n else\n {\n isValid = param != null;\n }\n\n if (!isValid)\n {\n throw new ArgumentNullException(paramName);\n }\n\n ValidateParamAllowNull(param, paramName);\n }\n\n /// \n /// Validates parameter collection.\n /// \n /// The collection.\n /// Name of the param.\n internal static void ValidateParamCollection(IEnumerable collection, string paramName)\n {\n ValidateParam(collection, paramName);\n\n int count = 0;\n\n foreach (object obj in collection)\n {\n try\n {\n ValidateParam(obj, string.Format(\"collection[{0}]\", count));\n }\n catch (ArgumentException e)\n {\n throw new ArgumentException(\n string.Format(\"The element at position {0} is invalid\", count),\n paramName,\n e);\n }\n\n count++;\n }\n\n if (count == 0)\n {\n throw new ArgumentException(Strings.CollectionIsEmpty, paramName);\n }\n }\n\n /// \n /// Validates string parameter to be non-empty string (null value allowed).\n /// \n /// The string parameter.\n /// Name of the parameter.\n internal static void ValidateNonBlankStringParamAllowNull(string param, string paramName)\n {\n if (param != null)\n {\n // Non-empty string has at least one character which is *not* a whitespace character\n if (param.Length == param.CountMatchingChars((c) => Char.IsWhiteSpace(c)))\n {\n throw new ArgumentException(Strings.ArgumentIsBlankString, paramName);\n }\n }\n }\n\n /// \n /// Validates string parameter to be non-empty string (null value not allowed).\n /// \n /// The string parameter.\n /// Name of the parameter.\n internal static void ValidateNonBlankStringParam(string param, string paramName)\n {\n if (param == null)\n {\n throw new ArgumentNullException(paramName);\n }\n\n ValidateNonBlankStringParamAllowNull(param, paramName);\n }\n\n /// \n /// Validates the enum value against the request version.\n /// \n /// The enum value.\n /// The request version.\n /// Raised if this enum value requires a later version of Exchange.\n internal static void ValidateEnumVersionValue(Enum enumValue, ExchangeVersion requestVersion)\n {\n Type enumType = enumValue.GetType();\n Dictionary enumVersionDict = enumVersionDictionaries.Member[enumType];\n ExchangeVersion enumVersion = enumVersionDict[enumValue];\n if (requestVersion < enumVersion)\n {\n throw new ServiceVersionException(\n string.Format(\n Strings.EnumValueIncompatibleWithRequestVersion,\n enumValue.ToString(),\n enumType.Name,\n enumVersion));\n }\n }\n\n /// \n /// Validates service object version against the request version.\n /// \n /// The service object.\n /// The request version.\n /// Raised if this service object type requires a later version of Exchange.\n internal static void ValidateServiceObjectVersion(ServiceObject serviceObject, ExchangeVersion requestVersion)\n {\n ExchangeVersion minimumRequiredServerVersion = serviceObject.GetMinimumRequiredServerVersion();\n\n if (requestVersion < minimumRequiredServerVersion)\n {\n throw new ServiceVersionException(\n string.Format(\n Strings.ObjectTypeIncompatibleWithRequestVersion,\n serviceObject.GetType().Name,\n minimumRequiredServerVersion));\n }\n }\n\n /// \n /// Validates property version against the request version.\n /// \n /// The Exchange service.\n /// The minimum server version that supports the property.\n /// Name of the property.\n internal static void ValidatePropertyVersion(\n ExchangeService service,\n ExchangeVersion minimumServerVersion,\n string propertyName)\n {\n if (service.RequestedServerVersion < minimumServerVersion)\n {\n throw new ServiceVersionException(\n string.Format(\n Strings.PropertyIncompatibleWithRequestVersion,\n propertyName,\n minimumServerVersion));\n }\n }\n\n /// \n /// Validates method version against the request version.\n /// \n /// The Exchange service.\n /// The minimum server version that supports the method.\n /// Name of the method.\n internal static void ValidateMethodVersion(\n ExchangeService service,\n ExchangeVersion minimumServerVersion,\n string methodName)\n {\n if (service.RequestedServerVersion < minimumServerVersion)\n {\n throw new ServiceVersionException(\n string.Format(\n Strings.MethodIncompatibleWithRequestVersion,\n methodName,\n minimumServerVersion));\n }\n }\n\n /// \n /// Validates class version against the request version.\n /// \n /// The Exchange service.\n /// The minimum server version that supports the method.\n /// Name of the class.\n internal static void ValidateClassVersion(\n ExchangeService service,\n ExchangeVersion minimumServerVersion,\n string className)\n {\n if (service.RequestedServerVersion < minimumServerVersion)\n {\n throw new ServiceVersionException(\n string.Format(\n Strings.ClassIncompatibleWithRequestVersion,\n className,\n minimumServerVersion));\n }\n }\n\n /// \n /// Validates domain name (null value allowed)\n /// \n /// Domain name.\n /// Parameter name.\n internal static void ValidateDomainNameAllowNull(string domainName, string paramName)\n {\n if (domainName != null)\n {\n Regex regex = new Regex(DomainRegex);\n\n if (!regex.IsMatch(domainName))\n {\n throw new ArgumentException(string.Format(Strings.InvalidDomainName, domainName), paramName);\n }\n }\n }\n\n /// \n /// Gets version for enum member.\n /// \n /// Type of the enum.\n /// The enum name.\n /// Exchange version in which the enum value was first defined.\n private static ExchangeVersion GetEnumVersion(Type enumType, string enumName)\n {\n MemberInfo[] memberInfo = enumType.GetMember(enumName);\n EwsUtilities.Assert(\n (memberInfo != null) && (memberInfo.Length > 0),\n \"EwsUtilities.GetEnumVersion\",\n \"Enum member \" + enumName + \" not found in \" + enumType);\n\n object[] attrs = memberInfo[0].GetCustomAttributes(typeof(RequiredServerVersionAttribute), false);\n if (attrs != null && attrs.Length > 0)\n {\n return ((RequiredServerVersionAttribute)attrs[0]).Version;\n }\n else\n {\n return ExchangeVersion.Exchange2007_SP1;\n }\n }\n\n /// \n /// Builds the enum to version mapping dictionary.\n /// \n /// Type of the enum.\n /// Dictionary of enum values to versions.\n private static Dictionary BuildEnumDict(Type enumType)\n {\n Dictionary dict = new Dictionary();\n string[] names = Enum.GetNames(enumType);\n foreach (string name in names)\n {\n Enum value = (Enum)Enum.Parse(enumType, name, false);\n ExchangeVersion version = GetEnumVersion(enumType, name);\n dict.Add(value, version);\n }\n return dict;\n }\n\n /// \n /// Gets the schema name for enum member.\n /// \n /// Type of the enum.\n /// The enum name.\n /// The name for the enum used in the protocol, or null if it is the same as the enum's ToString().\n private static string GetEnumSchemaName(Type enumType, string enumName)\n {\n MemberInfo[] memberInfo = enumType.GetMember(enumName);\n EwsUtilities.Assert(\n (memberInfo != null) && (memberInfo.Length > 0),\n \"EwsUtilities.GetEnumSchemaName\",\n \"Enum member \" + enumName + \" not found in \" + enumType);\n\n object[] attrs = memberInfo[0].GetCustomAttributes(typeof(EwsEnumAttribute), false);\n if (attrs != null && attrs.Length > 0)\n {\n return ((EwsEnumAttribute)attrs[0]).SchemaName;\n }\n else\n {\n return null;\n }\n }\n\n /// \n /// Builds the schema to enum mapping dictionary.\n /// \n /// Type of the enum.\n /// The mapping from enum to schema name\n private static Dictionary BuildSchemaToEnumDict(Type enumType)\n {\n Dictionary dict = new Dictionary();\n string[] names = Enum.GetNames(enumType);\n foreach (string name in names)\n {\n Enum value = (Enum)Enum.Parse(enumType, name, false);\n string schemaName = EwsUtilities.GetEnumSchemaName(enumType, name);\n\n if (!String.IsNullOrEmpty(schemaName))\n {\n dict.Add(schemaName, value);\n }\n }\n return dict;\n }\n\n /// \n /// Builds the enum to schema mapping dictionary.\n /// \n /// Type of the enum.\n /// The mapping from enum to schema name\n private static Dictionary BuildEnumToSchemaDict(Type enumType)\n {\n Dictionary dict = new Dictionary();\n string[] names = Enum.GetNames(enumType);\n foreach (string name in names)\n {\n Enum value = (Enum)Enum.Parse(enumType, name, false);\n string schemaName = EwsUtilities.GetEnumSchemaName(enumType, name);\n\n if (!String.IsNullOrEmpty(schemaName))\n {\n dict.Add(value, schemaName);\n }\n }\n return dict;\n }\n #endregion\n\n #region IEnumerable utility methods\n\n /// \n /// Gets the enumerated object count.\n /// \n /// The objects.\n /// Count of objects in IEnumerable.\n internal static int GetEnumeratedObjectCount(IEnumerable objects)\n {\n int count = 0;\n\n foreach (object obj in objects)\n {\n count++;\n }\n\n return count;\n }\n\n /// \n /// Gets enumerated object at index.\n /// \n /// The objects.\n /// The index.\n /// Object at index.\n internal static object GetEnumeratedObjectAt(IEnumerable objects, int index)\n {\n int count = 0;\n\n foreach (object obj in objects)\n {\n if (count == index)\n {\n return obj;\n }\n\n count++;\n }\n\n throw new ArgumentOutOfRangeException(\"index\", Strings.IEnumerableDoesNotContainThatManyObject);\n }\n\n #endregion\n\n #region Extension methods\n /// \n /// Count characters in string that match a condition.\n /// \n /// The string.\n /// Predicate to evaluate for each character in the string.\n /// Count of characters that match condition expressed by predicate.\n internal static int CountMatchingChars(this string str, Predicate charPredicate)\n {\n int count = 0;\n foreach (char ch in str)\n {\n if (charPredicate(ch))\n {\n count++;\n }\n }\n\n return count;\n }\n\n /// \n /// Determines whether every element in the collection matches the conditions defined by the specified predicate.\n /// \n /// Entry type.\n /// The collection.\n /// Predicate that defines the conditions to check against the elements.\n /// True if every element in the collection matches the conditions defined by the specified predicate; otherwise, false.\n internal static bool TrueForAll(this IEnumerable collection, Predicate predicate)\n {\n foreach (T entry in collection)\n {\n if (!predicate(entry))\n {\n return false;\n }\n }\n\n return true;\n }\n\n /// \n /// Call an action for each member of a collection.\n /// \n /// The collection.\n /// The action to apply.\n /// Collection element type.\n internal static void ForEach(this IEnumerable collection, Action action)\n {\n foreach (T entry in collection)\n {\n action(entry);\n }\n }\n #endregion\n }\n}\n"},"gt":{"kind":"string","value":""}}},{"rowIdx":96208,"cells":{"context":{"kind":"string","value":"//------------------------------------------------------------------------------\n// \n// Copyright (c) Microsoft Corporation. All rights reserved.\n// \n// [....]\n// [....]\n//------------------------------------------------------------------------------\n\nnamespace System.Data.SqlClient {\n using System;\n using System.Data.Common;\n using System.Data.ProviderBase;\n using System.Data.Sql;\n using System.Data.SqlTypes;\n using System.Diagnostics;\n using System.Globalization;\n using System.Runtime.CompilerServices;\n using System.Runtime.InteropServices;\n using System.Security;\n using System.Security.Permissions;\n using System.Text;\n using System.Threading;\n using System.Runtime.Versioning;\n\n internal sealed class TdsParserStaticMethods {\n\n private TdsParserStaticMethods() { /* prevent utility class from being insantiated*/ }\n //\n // Static methods\n //\n\n // SxS: this method accesses registry to resolve the alias.\n [ResourceExposure(ResourceScope.None)]\n [ResourceConsumption(ResourceScope.Machine, ResourceScope.Machine)]\n static internal void AliasRegistryLookup(ref string host, ref string protocol) {\n if (!ADP.IsEmpty(host)) {\n const String folder = \"SOFTWARE\\\\Microsoft\\\\MSSQLServer\\\\Client\\\\ConnectTo\";\n // Put a try...catch... around this so we don't abort ANY connection if we can't read the registry.\n string aliasLookup = (string) ADP.LocalMachineRegistryValue(folder, host);\n if (!ADP.IsEmpty(aliasLookup)) {\n /* Result will be in the form of: \"DBNMPNTW,\\\\blained1\\pipe\\sql\\query\". or\n Result will be in the form of: \"DBNETLIB, via:\\\\blained1\\pipe\\sql\\query\".\n\n supported formats:\n tcp\t- DBMSSOCN,[server|server\\instance][,port]\n np - DBNMPNTW,[\\\\server\\pipe\\sql\\query | \\\\server\\pipe\\MSSQL$instance\\sql\\query]\n where \\sql\\query is the pipename and can be replaced with any other pipe name\n via - [DBMSGNET,server,port | DBNETLIB, via:server, port]\n sm - DBMSLPCN,server\n\n unsupported formats:\n rpc - DBMSRPCN,server,[parameters] where parameters could be \"username,password\"\n bv - DBMSVINN,service@group@organization\n appletalk - DBMSADSN,objectname@zone\n spx - DBMSSPXN,[service | address,port,network]\n */\n // We must parse into the two component pieces, then map the first protocol piece to the\n // appropriate value.\n int index = aliasLookup.IndexOf(',');\n\n // If we found the key, but there was no \",\" in the string, it is a bad Alias so return.\n if (-1 != index) {\n string parsedProtocol = aliasLookup.Substring(0, index).ToLower(CultureInfo.InvariantCulture);\n\n // If index+1 >= length, Alias consisted of \"FOO,\" which is a bad alias so return.\n if (index+1 < aliasLookup.Length) {\n string parsedAliasName = aliasLookup.Substring(index+1);\n\n // Fix bug 298286\n if (\"dbnetlib\" == parsedProtocol) {\n index = parsedAliasName.IndexOf(':');\n if (-1 != index && index + 1 < parsedAliasName.Length) {\n parsedProtocol = parsedAliasName.Substring (0, index);\n if (SqlConnectionString.ValidProtocal (parsedProtocol)) {\n protocol = parsedProtocol;\n host = parsedAliasName.Substring(index + 1);\n }\n }\n }\n else {\n protocol = (string)SqlConnectionString.NetlibMapping()[parsedProtocol];\n if (null != protocol) {\n host = parsedAliasName;\n }\n }\n }\n }\n }\n }\n }\n\n // Encrypt password to be sent to SQL Server\n // Note: The same logic is used in SNIPacketSetData (SniManagedWrapper) to encrypt passwords stored in SecureString\n // If this logic changed, SNIPacketSetData needs to be changed as well\n static internal Byte[] EncryptPassword(string password) {\n Byte[] bEnc = new Byte[password.Length << 1];\n int s;\n byte bLo;\n byte bHi;\n\n for (int i = 0; i < password.Length; i ++) {\n s = (int) password[i];\n bLo = (byte) (s & 0xff);\n bHi = (byte) ((s >> 8) & 0xff);\n bEnc[i<<1] = (Byte) ( (((bLo & 0x0f) << 4) | (bLo >> 4)) ^ 0xa5 );\n bEnc[(i<<1)+1] = (Byte) ( (((bHi & 0x0f) << 4) | (bHi >> 4)) ^ 0xa5);\n }\n return bEnc;\n }\n\n [ResourceExposure(ResourceScope.None)] // SxS: we use this method for TDS login only\n [ResourceConsumption(ResourceScope.Process, ResourceScope.Process)]\n static internal int GetCurrentProcessIdForTdsLoginOnly() {\n return SafeNativeMethods.GetCurrentProcessId();\n }\n\n\n [SecurityPermission(SecurityAction.Assert, Flags = SecurityPermissionFlag.UnmanagedCode)]\n [ResourceExposure(ResourceScope.None)] // SxS: we use this method for TDS login only\n [ResourceConsumption(ResourceScope.Process, ResourceScope.Process)]\n static internal Int32 GetCurrentThreadIdForTdsLoginOnly() {\n#pragma warning disable 618\n return AppDomain.GetCurrentThreadId(); // don't need this to be support fibres;\n#pragma warning restore 618\n }\n\n\n [ResourceExposure(ResourceScope.None)] // SxS: we use MAC address for TDS login only\n [ResourceConsumption(ResourceScope.Machine, ResourceScope.Machine)]\n static internal byte[] GetNetworkPhysicalAddressForTdsLoginOnly() {\n // NIC address is stored in NetworkAddress key. However, if NetworkAddressLocal key\n // has a value that is not zero, then we cannot use the NetworkAddress key and must\n // instead generate a random one. I do not fully understand why, this is simply what\n // the native providers do. As for generation, I use a random number generator, which\n // means that different processes on the same machine will have different NIC address\n // values on the server. It is not ideal, but native does not have the same value for\n // different processes either.\n\n const string key = \"NetworkAddress\";\n const string localKey = \"NetworkAddressLocal\";\n const string folder = \"SOFTWARE\\\\Description\\\\Microsoft\\\\Rpc\\\\UuidTemporaryData\";\n\n int result = 0;\n byte[] nicAddress = null;\n\n object temp = ADP.LocalMachineRegistryValue(folder, localKey);\n if (temp is int) {\n result = (int) temp;\n }\n\n if (result <= 0) {\n temp = ADP.LocalMachineRegistryValue(folder, key);\n if (temp is byte[]) {\n nicAddress = (byte[]) temp;\n }\n }\n\n if (null == nicAddress) {\n nicAddress = new byte[TdsEnums.MAX_NIC_SIZE];\n Random random = new Random();\n random.NextBytes(nicAddress);\n }\n\n return nicAddress;\n }\n // translates remaining time in stateObj (from user specified timeout) to timout value for SNI\n static internal Int32 GetTimeoutMilliseconds(long timeoutTime) {\n // User provided timeout t | timeout value for SNI | meaning\n // ------------------------+-----------------------+------------------------------\n // t == long.MaxValue | -1 | infinite timeout (no timeout)\n // t>0 && tint.MaxValue | int.MaxValue | must not exceed int.MaxValue\n\n if (Int64.MaxValue == timeoutTime) {\n return -1; // infinite timeout\n }\n\n long msecRemaining = ADP.TimerRemainingMilliseconds(timeoutTime);\n\n if (msecRemaining < 0) {\n return 0;\n }\n if (msecRemaining > (long)Int32.MaxValue) {\n return Int32.MaxValue;\n }\n return (Int32)msecRemaining;\n }\n\n static internal long GetTimeoutSeconds(int timeout) {\n return GetTimeout((long)timeout * 1000L);\n }\n\n static internal long GetTimeout(long timeoutMilliseconds) {\n long result;\n if (timeoutMilliseconds <= 0) {\n result = Int64.MaxValue; // no timeout...\n }\n else {\n try\n {\n result = checked(ADP.TimerCurrent() + ADP.TimerFromMilliseconds(timeoutMilliseconds));\n }\n catch (OverflowException)\n {\n // In case of overflow, set to 'infinite' timeout\n result = Int64.MaxValue;\n }\n }\n return result;\n }\n\n static internal bool TimeoutHasExpired(long timeoutTime) {\n bool result = false;\n\n if (0 != timeoutTime && Int64.MaxValue != timeoutTime) {\n result = ADP.TimerHasExpired(timeoutTime);\n }\n return result;\n }\n\n static internal int NullAwareStringLength(string str) {\n if (str == null) {\n return 0;\n }\n else {\n return str.Length;\n }\n }\n\n static internal int GetRemainingTimeout(int timeout, long start) {\n if (timeout <= 0) {\n return timeout;\n }\n long remaining = ADP.TimerRemainingSeconds(start + ADP.TimerFromSeconds(timeout));\n if (remaining <= 0) {\n return 1;\n }\n else {\n return checked((int)remaining);\n }\n }\n\n }\n}\n"},"gt":{"kind":"string","value":""}}},{"rowIdx":96209,"cells":{"context":{"kind":"string","value":"using System;\nusing System.Xml.Linq;\n\nnamespace WixSharp\n{\n /// \n /// Defines service installer for the file being installed. It encapsulates functionality provided\n /// by ServiceInstall and ServiceConfig WiX elements.\n /// \n /// The following sample demonstrates how to install service:\n /// \n /// File service;\n /// var project =\n /// new Project(\"My Product\",\n /// new Dir(@\"%ProgramFiles%\\My Company\\My Product\",\n /// service = new File(@\"..\\SimpleService\\MyApp.exe\")));\n ///\n /// service.ServiceInstaller = new ServiceInstaller\n /// {\n /// Name = \"WixSharp.TestSvc\",\n /// StartOn = SvcEvent.Install,\n /// StopOn = SvcEvent.InstallUninstall_Wait,\n /// RemoveOn = SvcEvent.Uninstall_Wait,\n /// };\n /// ...\n ///\n /// Compiler.BuildMsi(project);\n /// \n /// \n public class ServiceInstaller : WixEntity, IGenericEntity\n {\n private SvcEvent startOn;\n private SvcEvent stopOn;\n private SvcEvent removeOn;\n\n /// \n /// Initializes a new instance of the class.\n /// \n public ServiceInstaller()\n {\n }\n\n /// \n /// Initializes a new instance of the class with properties/fields initialized with specified parameters.\n /// \n /// The name.\n public ServiceInstaller(string name)\n {\n Name = name;\n }\n\n /// \n /// Primary key used to identify this particular entry.\n /// \n [Xml]\n public new string Id { get { return base.Id; } set { base.Id = value; } }\n\n /// \n /// This is the localizable name of the environment variable\n /// \n [Xml]\n public new string Name\n {\n get\n {\n return base.Name;\n }\n set\n {\n base.Name = value;\n if (DisplayName == null)\n {\n DisplayName = value;\n }\n\n if (Description == null)\n {\n Description = value;\n }\n }\n }\n\n // public PermissionExt Permission;\n\n /// \n /// The display name of the service as it is listed in the Control Panel.\n /// If not specified the name of the service will be used instead.\n /// \n [Xml]\n public string DisplayName;\n\n /// \n /// The description of the service as it is listed in the Control Panel.\n /// \n [Xml]\n public string Description;\n\n /// \n /// The type of the service (e.g. kernel/system driver, process). The default value is SvcType.ownProcess.\n /// \n [Xml]\n public SvcType Type = SvcType.ownProcess;\n\n /// \n /// Defines the way service starts. The default value is SvcStartType.auto.\n /// \n [Xml]\n public SvcStartType Start = SvcStartType.auto;\n\n /// \n /// The error control associated with the service startup. The default value is SvcErrorControl.normal.\n /// \n [Xml]\n public SvcErrorControl ErrorControl = SvcErrorControl.normal;\n\n /// \n /// Associates 'start service' action with the specific service installation event.\n /// The default value is SvcEvent.Install. Meaning \"start the service when it is installed\".\n /// \n /// Set this member to null if you don't want to start the service at any stage of the installation.\n /// \n /// \n public SvcEvent StartOn\n {\n get\n {\n return startOn;\n }\n set\n {\n if (value != null)\n {\n value.Id = \"Start\" + Id;\n value.Name = Name;\n value.Start = value.Type;\n }\n\n startOn = value;\n }\n }\n\n /// \n /// Associates 'stop service' action with the specific service installation event.\n /// The default value is SvcEvent.InstallUninstall_Wait. Meaning \"stop the\n /// service when it is being installed and uninstalled and wait for the action completion\".\n /// \n /// Set this member to null if you don't want to stop the service at any stage of the installation.\n /// \n /// \n public SvcEvent StopOn\n {\n get\n {\n return stopOn;\n }\n set\n {\n if (value != null)\n {\n value.Id = \"Stop\" + Id;\n value.Name = Name;\n value.Stop = value.Type;\n }\n\n stopOn = value;\n }\n }\n\n /// \n /// Associates 'remove service' action with the specific service installation event.\n /// The default value is SvcEvent.Uninstall. Meaning \"remove the service when it is uninstalled\".\n /// \n /// Set this member to null if you don't want to remove the service at any stage of the installation.\n /// \n /// \n public SvcEvent RemoveOn\n {\n get\n {\n return removeOn;\n }\n set\n {\n if (value != null)\n {\n value.Id = \"Remove\" + Id;\n value.Name = Name;\n value.Remove = value.Type;\n }\n\n removeOn = value;\n }\n }\n\n /// \n /// Semicolon separated list of the names of the external service the service being installed depends on.\n /// It supposed to be names (not the display names) of a previously installed services.\n /// For example: DependsOn = \"Dnscache;Dhcp\"\n /// \n public ServiceDependency[] DependsOn;\n\n private ServiceConfig Config;\n\n private ServiceConfigUtil ConfigUtil;\n\n /// \n /// Fully qualified names must be used even for local accounts,\n /// e.g.: \".\\LOCAL_ACCOUNT\". Valid only when ServiceType is ownProcess.\n /// \n [Xml]\n public string Account;\n\n /// \n /// Contains any command line arguments or properties required to run the service.\n /// \n [Xml]\n public string Arguments;\n\n /// \n /// Determines whether the existing service description will be ignored. If 'yes', the service description will be null,\n /// even if the Description attribute is set.\n /// \n [Xml]\n public bool? EraseDescription;\n\n /// \n /// Whether or not the service interacts with the desktop.\n /// \n [Xml]\n public bool? Interactive;\n\n /// \n /// The load ordering group that this service should be a part of.\n /// \n [Xml]\n public string LoadOrderGroup;\n\n /// \n /// The password for the account. Valid only when the account has a password.\n /// \n [Xml]\n public string Password;\n\n /// \n /// The PermissionEx element associated with the emitted ServiceInstall element.\n /// \n public PermissionEx PermissionEx;\n\n /// \n /// The overall install should fail if this service fails to install.\n /// \n [Xml]\n public bool? Vital;\n\n #region ServiceConfig attributes\n\n /// \n /// Specifies whether an auto-start service should delay its start until after all other auto-start services.\n /// This property only affects auto-start services. If this property is not initialized the setting is not configured.\n /// \n public bool? DelayedAutoStart;\n\n //public object FailureActionsWhen { get; set; } //note implementing util:serviceconfig instead\n\n /// \t ConfigUtil?.Process(newContext);\n /// Specifies time in milliseconds that the Service Control Manager (SCM) waits after notifying\n /// the service of a system shutdown. If this attribute is not present the default value, 3 minutes, is used.\n /// \n public int? PreShutdownDelay;\n\n /// \n /// Specifies the service SID to apply to the service\n /// \n public ServiceSid ServiceSid;\n\n /// \n /// Specifies whether to configure the service when the parent Component is installed, reinstalled, or uninstalled\n /// \n /// \n /// Defaults to ConfigureServiceTrigger.Install.\n /// Strictly applies to the configuration of properties: DelayedAutoStart, PreShutdownDelay, ServiceSid.\n /// \n public ConfigureServiceTrigger ConfigureServiceTrigger = ConfigureServiceTrigger.Install;\n\n #endregion ServiceConfig attributes\n\n #region Util:ServiceConfig attributes\n\n /// \n /// Action to take on the first failure of the service\n /// \n public FailureActionType FirstFailureActionType = FailureActionType.none;\n\n /// \n /// If any of the three *ActionType attributes is \"runCommand\",\n /// this specifies the command to run when doing so.\n /// \n public string ProgramCommandLine;\n\n /// \n /// If any of the three *ActionType attributes is \"reboot\",\n /// this specifies the message to broadcast to server users before doing so.\n /// \n public string RebootMessage;\n\n /// \n /// Number of days after which to reset the failure count to zero if there are no failures.\n /// \n public int? ResetPeriodInDays;\n\n /// \n /// If any of the three *ActionType attributes is \"restart\",\n /// this specifies the number of seconds to wait before doing so.\n /// \n public int? RestartServiceDelayInSeconds;\n\n /// \n /// Action to take on the second failure of the service.\n /// \n public FailureActionType SecondFailureActionType = FailureActionType.none;\n\n /// \n /// Action to take on the third failure of the service.\n /// \n public FailureActionType ThirdFailureActionType = FailureActionType.none;\n\n #endregion Util:ServiceConfig attributes\n\n /// \n /// The URL reservations associated with the service\n /// \n public IGenericEntity[] UrlReservations = new IGenericEntity[0];\n\n private bool RequiresConfig()\n {\n return DelayedAutoStart != null ||\n PreShutdownDelay != null ||\n ServiceSid != null;\n // note ConfigureServiceTrigger value is irrelevant as it will be used only if the\n // fields above are not empty;\n }\n\n private bool RequiresConfigUtil()\n {\n return FirstFailureActionType != FailureActionType.none ||\n SecondFailureActionType != FailureActionType.none ||\n ThirdFailureActionType != FailureActionType.none ||\n !string.IsNullOrEmpty(ProgramCommandLine) ||\n !string.IsNullOrEmpty(RebootMessage) ||\n ResetPeriodInDays != null ||\n RestartServiceDelayInSeconds != null;\n }\n\n /// \n /// Adds itself as an XML content into the WiX source being generated from the .\n /// See 'Wix#/samples/Extensions' sample for the details on how to implement this interface correctly.\n /// \n /// The context.\n public void Process(ProcessingContext context)\n {\n if (RequiresConfig())\n {\n Config = new ServiceConfig\n {\n DelayedAutoStart = DelayedAutoStart,\n PreShutdownDelay = PreShutdownDelay,\n ServiceSid = ServiceSid,\n ConfigureServiceTrigger = ConfigureServiceTrigger,\n };\n }\n\n if (RequiresConfigUtil())\n {\n ConfigUtil = new ServiceConfigUtil\n {\n FirstFailureActionType = FirstFailureActionType,\n SecondFailureActionType = SecondFailureActionType,\n ThirdFailureActionType = ThirdFailureActionType,\n ProgramCommandLine = ProgramCommandLine,\n RebootMessage = RebootMessage,\n ResetPeriodInDays = ResetPeriodInDays,\n RestartServiceDelayInSeconds = RestartServiceDelayInSeconds,\n };\n }\n\n XElement ServiceInstaller = this.ToXElement(\"ServiceInstall\");\n if (PermissionEx != null)\n {\n ServiceInstaller.AddElement(this.PermissionEx.ToXElement(WixExtension.Util, \"PermissionEx\"));\n }\n\n context.XParent.Add(ServiceInstaller);\n\n var newContext = new ProcessingContext\n {\n Project = context.Project,\n Parent = context.Project,\n XParent = ServiceInstaller,\n FeatureComponents = context.FeatureComponents,\n };\n\n if (DependsOn != null)\n {\n foreach (ServiceDependency dependency in DependsOn)\n {\n dependency.Process(newContext);\n }\n }\n\n Config?.Process(newContext);\n\n if (UrlReservations != null)\n {\n foreach (IGenericEntity urlReservation in UrlReservations)\n {\n urlReservation.Process(newContext);\n }\n }\n\n ConfigUtil?.Process(newContext);\n\n StopOn?.Process(context);\n StartOn?.Process(context);\n RemoveOn?.Process(context);\n }\n }\n}\n"},"gt":{"kind":"string","value":""}}},{"rowIdx":96210,"cells":{"context":{"kind":"string","value":"/*\n * Copyright (c) 2015 Mehrzad Chehraz (mehrzady@gmail.com)\n * Released under the MIT License\n * http://chehraz.ir/mit_license\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n */\nnamespace Atf.Core.Text {\n using System;\n using System.Collections.Generic;\n using System.Globalization;\n using System.Text;\n\n internal class DateTimeFormatter {\n #region Specifier info\n public enum ValueType {\n None = 0,\n Numeral,\n Items,\n Static,\n StaticItems,\n StringLiteral,\n }\n public enum SpecifierType {\n s,\n ss,\n m,\n mm,\n h,\n hh,\n H,\n HH,\n t,\n tt,\n d,\n dd,\n ddd,\n dddd,\n M,\n MM,\n MMM,\n MMMM,\n y,\n yy,\n yyy,\n yyyy,\n g,\n DateSeparator,\n TimeSeparator,\n StringLiteral,\n }\n public struct SpecifierInfo {\n public SpecifierInfo(SpecifierType type, ValueType valueType, string symbol,\n int max, bool matchesExtraSymbols)\n : this() {\n MatchesExtraSymbols = matchesExtraSymbols;\n MaxLength = max;\n Symbol = symbol;\n Type = type;\n ValueType = valueType;\n }\n public bool MatchesExtraSymbols {\n get;\n set;\n }\n public int MaxLength {\n get;\n set;\n }\n public string Symbol {\n get;\n set;\n }\n public SpecifierType Type {\n get;\n set;\n }\n public ValueType ValueType {\n get;\n set;\n }\n public static SpecifierInfo CreateStringLiteralSpecifier(string text) {\n return new SpecifierInfo(SpecifierType.StringLiteral, ValueType.StringLiteral, text, -1, false);\n\n }\n public override string ToString() {\n if (this.Symbol != null) {\n return this.Symbol.ToString();\n }\n return base.ToString();\n }\n }\n #endregion\n\n #region Fields\n private static readonly char escapeCharacter = '\\\\';\n private static Dictionary> specSymbolCache;\n private static readonly SpecifierInfo s_s = new SpecifierInfo(SpecifierType.s, ValueType.Numeral, \"s\", 2, false);\n private static readonly SpecifierInfo s_ss = new SpecifierInfo(SpecifierType.ss, ValueType.Numeral, \"ss\", 2, true);\n private static readonly SpecifierInfo s_m = new SpecifierInfo(SpecifierType.m, ValueType.Numeral, \"m\", 2, false);\n private static readonly SpecifierInfo s_mm = new SpecifierInfo(SpecifierType.mm, ValueType.Numeral, \"mm\", 2, true);\n private static readonly SpecifierInfo s_h = new SpecifierInfo(SpecifierType.h, ValueType.Numeral, \"h\", 2, false);\n private static readonly SpecifierInfo s_hh = new SpecifierInfo(SpecifierType.hh, ValueType.Numeral, \"hh\", 2, true);\n private static readonly SpecifierInfo s_H = new SpecifierInfo(SpecifierType.H, ValueType.Numeral, \"H\", 2, false);\n private static readonly SpecifierInfo s_HH = new SpecifierInfo(SpecifierType.HH, ValueType.Numeral, \"HH\", 2, true);\n private static readonly SpecifierInfo s_t = new SpecifierInfo(SpecifierType.t, ValueType.Items, \"t\", 1, false);\n private static readonly SpecifierInfo s_tt = new SpecifierInfo(SpecifierType.tt, ValueType.Items, \"tt\", 2, true);\n\n private static readonly SpecifierInfo s_d = new SpecifierInfo(SpecifierType.d, ValueType.Numeral, \"d\", 2, false);\n private static readonly SpecifierInfo s_dd = new SpecifierInfo(SpecifierType.dd, ValueType.Numeral, \"dd\", 2, false);\n private static readonly SpecifierInfo s_ddd = new SpecifierInfo(SpecifierType.ddd, ValueType.StaticItems, \"ddd\", 0, false);\n private static readonly SpecifierInfo s_dddd = new SpecifierInfo(SpecifierType.dddd, ValueType.StaticItems, \"dddd\", 0, true);\n private static readonly SpecifierInfo s_M = new SpecifierInfo(SpecifierType.M, ValueType.Numeral, \"M\", 2, false);\n private static readonly SpecifierInfo s_MM = new SpecifierInfo(SpecifierType.MM, ValueType.Numeral, \"MM\", 2, false);\n private static readonly SpecifierInfo s_MMM = new SpecifierInfo(SpecifierType.MMM, ValueType.Items, \"MMM\", 0, false);\n private static readonly SpecifierInfo s_MMMM = new SpecifierInfo(SpecifierType.MMMM, ValueType.Items, \"MMMM\", 0, true);\n private static readonly SpecifierInfo s_y = new SpecifierInfo(SpecifierType.y, ValueType.Numeral, \"y\", 2, false);\n private static readonly SpecifierInfo s_yy = new SpecifierInfo(SpecifierType.yy, ValueType.Numeral, \"yy\", 2, false);\n private static readonly SpecifierInfo s_yyy = new SpecifierInfo(SpecifierType.yyy, ValueType.Numeral, \"yyy\", 4, false);\n private static readonly SpecifierInfo s_yyyy = new SpecifierInfo(SpecifierType.yyyy, ValueType.Numeral, \"yyyy\", 4, true);\n private static readonly SpecifierInfo s_g = new SpecifierInfo(SpecifierType.g, ValueType.Static, \"g\", -1, true);\n\n private static readonly SpecifierInfo s_DateSeparator = new SpecifierInfo(SpecifierType.DateSeparator, ValueType.Static,\n \"/\", -1, false);\n private static readonly SpecifierInfo s_TimeSeparator = new SpecifierInfo(SpecifierType.TimeSeparator, ValueType.Static,\n \":\", -1, false);\n private static readonly SpecifierInfo[] Specifiers = new SpecifierInfo[] { \n s_s,\n s_ss,\n s_m,\n s_mm,\n s_h,\n s_hh,\n s_H,\n s_HH,\n s_t,\n s_tt,\n s_d,\n s_dd,\n s_ddd,\n s_dddd,\n s_M,\n s_MM,\n s_MMM,\n s_MMMM,\n s_y,\n s_yy,\n s_yyy,\n s_yyyy,\n s_g,\n s_DateSeparator,\n s_TimeSeparator,\n };\n public event EventHandler ValueChanged;\n private DateTimeFormatInfo dateTimeFormat;\n private bool am = true;\n private int? day;\n private int? hour;\n private int? minute;\n private int? month;\n private int? second;\n private int? year;\n private DateTime? value;\n\n\n #endregion\n\n #region Constructor\n public DateTimeFormatter(DateTimeFormatInfo dateTimeFormat) {\n if (dateTimeFormat == null) {\n throw new ArgumentNullException(\"dateTimeFormat\");\n }\n this.dateTimeFormat = dateTimeFormat;\n }\n public DateTimeFormatter(DateTimeFormatInfo dateTimeFormat, DateTime? value) {\n if (dateTimeFormat == null) {\n throw new ArgumentNullException(\"dateTimeFormat\");\n }\n this.dateTimeFormat = dateTimeFormat;\n this.Value = value;\n }\n #endregion\n\n #region Properties\n public DateTime? Time {\n get {\n if (this.hour.HasValue && this.minute.HasValue && this.second.HasValue) {\n DateTime minDateTime = this.Calendar.MinSupportedDateTime;\n\n return new DateTime(minDateTime.Year, minDateTime.Month, minDateTime.Day,\n this.hour.Value, this.minute.Value, this.second.Value);\n }\n return null;\n }\n }\n public DateTime? Value {\n get {\n return this.value;\n }\n set {\n if (this.value != value) {\n this.value = value;\n this.SetDateTimeComponents();\n }\n }\n }\n #endregion\n\n #region Methods \n public void ClearComponentValue(SpecifierInfo specifier) {\n switch (specifier.Type) {\n case SpecifierType.s:\n case SpecifierType.ss:\n if (this.second != null) {\n this.second = null;\n this.UpdateDateTimeComponets();\n }\n break;\n case SpecifierType.m:\n case SpecifierType.mm:\n if (this.minute != null) {\n this.minute = null;\n this.UpdateDateTimeComponets();\n }\n break;\n case SpecifierType.h:\n case SpecifierType.hh:\n if (this.hour != null) {\n this.hour = null;\n this.UpdateDateTimeComponets();\n }\n break;\n case SpecifierType.d:\n case SpecifierType.dd:\n if (this.day != null) {\n this.day = null;\n this.UpdateDateTimeComponets();\n }\n break;\n case SpecifierType.M:\n case SpecifierType.MM:\n if (this.month != null) {\n this.month = null;\n this.UpdateDateTimeComponets();\n }\n break;\n case SpecifierType.y:\n case SpecifierType.yy:\n case SpecifierType.yyy:\n case SpecifierType.yyyy:\n if (this.year != null) {\n this.year = null;\n this.UpdateDateTimeComponets();\n }\n break;\n }\n }\n public void ClearInvalids() {\n if (this.year == null || this.month == null || this.day == null) {\n this.year = this.month = this.day = null;\n }\n }\n public bool DecreaseComponentValue(SpecifierInfo specifier) {\n switch (specifier.Type) {\n case SpecifierType.s:\n case SpecifierType.ss:\n if (this.second.HasValue && this.second.Value > 0) {\n this.second--;\n }\n else {\n this.second = 59;\n }\n return true;\n case SpecifierType.m:\n case SpecifierType.mm:\n if (this.minute.HasValue && this.minute.Value > 0) {\n this.minute--;\n }\n else {\n this.minute = 59;\n }\n return true;\n case SpecifierType.h:\n case SpecifierType.hh:\n case SpecifierType.H:\n case SpecifierType.HH:\n if (this.hour.HasValue && this.hour.Value > 0) {\n this.hour--;\n }\n else {\n this.hour = 23;\n }\n this.am = hour < 12;\n return true;\n case SpecifierType.d:\n case SpecifierType.dd:\n if (this.day.HasValue && this.day.Value > 1) {\n this.day--;\n }\n else {\n if (this.year.HasValue && this.month.HasValue) {\n int daysInMonth = this.Calendar.GetDaysInMonth(this.year.Value, this.month.Value);\n this.day = daysInMonth;\n return true;\n }\n this.day = 31; /********/\n }\n return true;\n\n case SpecifierType.M:\n case SpecifierType.MM:\n case SpecifierType.MMM:\n case SpecifierType.MMMM:\n if (this.month.HasValue && this.month.Value > 1) {\n this.month--;\n }\n else {\n if (this.year.HasValue) {\n int monthsInYear = this.Calendar.GetMonthsInYear(this.year.Value);\n this.month = monthsInYear;\n return true;\n }\n this.month = 12; /**********/\n }\n return true;\n\n case SpecifierType.y:\n case SpecifierType.yy:\n case SpecifierType.yyy:\n case SpecifierType.yyyy:\n int minYear = this.Calendar.GetYear(this.Calendar.MinSupportedDateTime);\n if (this.year.HasValue && this.year.Value > minYear) {\n this.year--;\n }\n else {\n this.year = this.Calendar.GetYear(DateTime.Now);\n }\n return true;\n case SpecifierType.t:\n case SpecifierType.tt:\n if (this.hour.HasValue) {\n if (this.hour < 12) {\n this.hour += 12;\n this.am = false;\n }\n else {\n this.hour -= 12;\n this.am = true;\n }\n return true;\n }\n return false;\n\n }\n return false;\n }\n public bool EditComponentValue(SpecifierInfo specifier, int componentValue, bool commit, int length) {\n switch (specifier.Type) {\n case SpecifierType.s:\n case SpecifierType.ss:\n if (componentValue < 0) {\n return false;\n }\n if (componentValue < 60) {\n if (commit) {\n this.second = componentValue;\n this.UpdateDateTimeComponets();\n }\n return true;\n }\n return false;\n\n case SpecifierType.m:\n case SpecifierType.mm:\n if (componentValue < 0) {\n return false;\n }\n if (componentValue < 60) {\n if (commit) {\n this.minute = componentValue;\n this.UpdateDateTimeComponets();\n }\n return true;\n }\n return false;\n case SpecifierType.h:\n case SpecifierType.hh:\n if (componentValue < 0) {\n return false;\n }\n if (!commit) {\n if (componentValue < 24) {\n return true;\n }\n return false;\n }\n if (componentValue == 0) {\n this.hour = 0;\n }\n else if (componentValue < 12) {\n this.hour = this.am ? componentValue : componentValue + 12;\n }\n else if (componentValue < 24) {\n this.hour = componentValue;\n }\n else {\n return false;\n }\n this.UpdateDateTimeComponets();\n return true;\n case SpecifierType.H:\n case SpecifierType.HH:\n if (componentValue < 0) {\n return false;\n }\n if (componentValue < 24) {\n if (commit) {\n this.hour = componentValue;\n this.UpdateDateTimeComponets();\n }\n return true;\n }\n return false;\n case SpecifierType.d:\n case SpecifierType.dd:\n if (componentValue <= 0) {\n return false;\n }\n if (this.year.HasValue && this.month.HasValue) {\n int daysInMonth = this.Calendar.GetDaysInMonth(this.year.Value, this.month.Value);\n if (componentValue > daysInMonth) {\n return false;\n }\n }\n if (commit) {\n this.day = componentValue;\n this.UpdateDateTimeComponets();\n }\n return true;\n case SpecifierType.M:\n case SpecifierType.MM:\n if (componentValue <= 0) {\n return false;\n }\n if (this.year.HasValue) {\n int monthsInYear = this.Calendar.GetMonthsInYear(this.year.Value);\n if (componentValue > monthsInYear) {\n return false;\n }\n }\n if (commit) {\n this.month = componentValue;\n this.UpdateDateTimeComponets();\n }\n return true;\n case SpecifierType.y:\n case SpecifierType.yy:\n if (componentValue <= 0) {\n return false;\n }\n if (componentValue <= 99) {\n if (commit) {\n this.year = this.Calendar.ToFourDigitYear(componentValue);\n this.UpdateDateTimeComponets();\n }\n return true;\n }\n return false;\n case SpecifierType.yyy:\n case SpecifierType.yyyy:\n if (componentValue <= 0) {\n return false;\n }\n if (length <= 2 && componentValue <= 99) {\n if (commit) {\n this.year = this.Calendar.ToFourDigitYear(componentValue);\n this.UpdateDateTimeComponets();\n }\n return true;\n }\n else {\n int maxYear = this.Calendar.GetYear(this.Calendar.MaxSupportedDateTime);\n int minYear = this.Calendar.GetYear(this.Calendar.MinSupportedDateTime);\n if (componentValue >= minYear && componentValue <= maxYear) {\n if (commit) {\n this.year = componentValue;\n this.UpdateDateTimeComponets();\n }\n return true;\n }\n else if (componentValue > maxYear) {\n if (commit) {\n this.UpdateDateTimeComponets();\n return true;\n }\n return false;\n }\n else if (componentValue < minYear) {\n if (commit) {\n this.UpdateDateTimeComponets();\n }\n return true;\n }\n }\n return false;\n\n }\n return false;\n }\n public static string Format(string format, DateTimeFormatInfo dateTimeFormat,\n Calendar calendar, DateTime? value) {\n SpecifierInfo[] specifiers = GetSpecifiers(format);\n DateTimeFormatter formatter = new DateTimeFormatter(dateTimeFormat, value);\n StringBuilder sb = new StringBuilder();\n foreach (var specifier in specifiers) {\n sb.Append(formatter.GetDisplayText(specifier));\n }\n return sb.ToString();\n }\n public string GetDisplayText(SpecifierInfo specifier) {\n if (specifier.ValueType == ValueType.StringLiteral) {\n return specifier.Symbol;\n }\n string displayText = null;\n switch (specifier.Type) {\n case SpecifierType.s:\n if (this.second.HasValue) {\n displayText = this.second.Value.ToString();\n }\n break;\n case SpecifierType.ss:\n if (this.second.HasValue) {\n displayText = this.second.Value.ToString(\"00\");\n }\n break;\n case SpecifierType.m:\n if (this.minute.HasValue) {\n displayText = this.minute.Value.ToString();\n }\n break;\n case SpecifierType.mm:\n if (this.minute.HasValue) {\n displayText = this.minute.Value.ToString(\"00\");\n }\n break;\n case SpecifierType.h:\n if (this.hour.HasValue) {\n int hour = this.hour.Value;\n if (hour > 12) {\n hour -= 12;\n }\n displayText = hour.ToString();\n }\n break;\n case SpecifierType.hh:\n if (this.hour.HasValue) {\n int hour = this.hour.Value;\n if (hour > 12) {\n hour -= 12;\n }\n displayText = hour.ToString(\"00\");\n }\n break;\n case SpecifierType.H:\n if (this.hour.HasValue) {\n displayText = this.hour.ToString();\n }\n break;\n case SpecifierType.HH:\n if (this.hour.HasValue) {\n displayText = this.hour.Value.ToString(\"00\");\n }\n break;\n case SpecifierType.t:\n if (this.hour.HasValue) {\n int hour = this.hour.Value;\n string designator;\n if (hour < 12) {\n designator = this.DateTimeFormat.AMDesignator;\n }\n else {\n designator = this.DateTimeFormat.PMDesignator;\n }\n if (!string.IsNullOrEmpty(designator)) {\n displayText = designator.Substring(0, 1);\n }\n else {\n displayText = string.Empty;\n }\n }\n break;\n case SpecifierType.tt:\n if (this.hour.HasValue) {\n int hour = this.hour.Value;\n if (hour < 12) {\n displayText = this.DateTimeFormat.AMDesignator;\n }\n else {\n displayText = this.DateTimeFormat.PMDesignator;\n }\n }\n break;\n case SpecifierType.d:\n if (this.day.HasValue) {\n displayText = this.day.ToString();\n }\n break;\n case SpecifierType.dd:\n if (this.day.HasValue) {\n displayText = this.day.Value.ToString(\"00\");\n }\n break;\n case SpecifierType.ddd:\n if (this.value.HasValue) {\n var dayOfWeek = this.Calendar.GetDayOfWeek(this.value.Value);\n displayText = this.DateTimeFormat.GetAbbreviatedDayName(dayOfWeek);\n }\n break;\n case SpecifierType.dddd:\n if (this.value.HasValue) {\n var dayOfWeek = this.Calendar.GetDayOfWeek(this.value.Value);\n displayText = this.DateTimeFormat.GetDayName(dayOfWeek);\n }\n break;\n case SpecifierType.M:\n if (this.month.HasValue) {\n displayText = this.month.ToString();\n }\n break;\n case SpecifierType.MM:\n if (this.month.HasValue) {\n displayText = this.month.Value.ToString(\"00\");\n }\n break;\n case SpecifierType.MMM:\n if (this.month.HasValue) {\n displayText = this.DateTimeFormat.GetAbbreviatedMonthName(this.month.Value);\n }\n break;\n case SpecifierType.MMMM:\n if (this.month.HasValue) {\n displayText = this.DateTimeFormat.GetMonthName(this.month.Value);\n }\n break;\n case SpecifierType.y:\n if (this.year.HasValue) {\n displayText = (this.year.Value % 100).ToString();\n }\n break;\n case SpecifierType.yy:\n if (this.year.HasValue) {\n displayText = (this.year.Value % 100).ToString(\"00\");\n }\n break;\n case SpecifierType.yyy:\n if (this.year.HasValue) {\n displayText = this.year.Value.ToString(\"000\");\n }\n break;\n case SpecifierType.yyyy:\n if (this.year.HasValue) {\n displayText = this.year.Value.ToString(\"0000\");\n }\n break;\n case SpecifierType.g:\n case SpecifierType.DateSeparator:\n case SpecifierType.TimeSeparator:\n return GetStaticDisplayText(specifier, this.DateTimeFormat, this.Calendar, this.Value);\n default:\n throw new ArgumentOutOfRangeException(\"specifier.Type\");\n }\n return displayText;\n }\n public static string GetStaticDisplayText(SpecifierInfo specifier, DateTimeFormatInfo dateTimeFormat,\n Calendar calendar, DateTime? value) {\n if (specifier.ValueType != ValueType.Static) {\n throw new ArgumentException(\"specifier\");\n }\n switch (specifier.Type) {\n case SpecifierType.g:\n if (value.HasValue) {\n int era = calendar.GetEra(value.Value);\n return dateTimeFormat.GetEraName(era);\n }\n return string.Empty;\n case SpecifierType.DateSeparator:\n return dateTimeFormat.DateSeparator;\n case SpecifierType.TimeSeparator:\n return dateTimeFormat.TimeSeparator;\n default:\n throw new ArgumentOutOfRangeException(\"specifier.Type\");\n }\n }\n public string[] GetItems(SpecifierType specifierType) {\n return GetItems(specifierType, this.DateTimeFormat);\n }\n public static string[] GetItems(SpecifierType specifierType, DateTimeFormatInfo dateTimeFormat) {\n switch (specifierType) {\n case SpecifierType.ddd:\n return dateTimeFormat.AbbreviatedDayNames;\n case SpecifierType.dddd:\n return dateTimeFormat.DayNames;\n case SpecifierType.MMM:\n return dateTimeFormat.AbbreviatedMonthNames;\n case SpecifierType.MMMM:\n return dateTimeFormat.MonthNames;\n case SpecifierType.t:\n string amDesignator = dateTimeFormat.AMDesignator;\n string pmDesignator = dateTimeFormat.PMDesignator;\n string[] items = new string[] {\n !string.IsNullOrEmpty(amDesignator) ? amDesignator.Substring(0, 1) : string.Empty,\n !string.IsNullOrEmpty(pmDesignator) ? pmDesignator.Substring(0, 1) : string.Empty,\n\n };\n return items;\n case SpecifierType.tt:\n return new string[] {\n dateTimeFormat.AMDesignator,\n dateTimeFormat.PMDesignator,\n };\n default:\n throw new ArgumentOutOfRangeException(\"specifierType\");\n }\n }\n public static SpecifierInfo[] GetSpecifiers(string format) {\n if (format == null) {\n throw new ArgumentNullException(\"format\");\n }\n StringBuilder stringLiteral = new StringBuilder();\n var matchedSpecifiers = new List();\n int length = format.Length;\n for (int index = 0; index < length; ) {\n char symbol = format[index];\n if (symbol.Equals(escapeCharacter)) {\n if (index < length - 1) {\n index++; // Move to the next character\n stringLiteral.Append(format[index]);\n index++;\n }\n continue;\n }\n var specsOfSymbol = GetSpecsOfSymbol(symbol);\n int lastMatchedRepeatCount = 1;\n SpecifierInfo matchedSpecifier = new SpecifierInfo();\n bool specifierFound = false;\n int repeatCount = 0;\n if (specsOfSymbol != null) {\n do {\n repeatCount++;\n foreach (var specifier in specsOfSymbol) {\n int specSymbolCount = specifier.Symbol.Length;\n if (specSymbolCount == repeatCount || (specSymbolCount < repeatCount &&\n specifier.MatchesExtraSymbols)) {\n matchedSpecifier = specifier;\n lastMatchedRepeatCount = repeatCount;\n specifierFound = true;\n\n }\n }\n\n } while ((index + repeatCount) < length && format[index + repeatCount].Equals(symbol));\n }\n else {\n repeatCount = 1;\n }\n if (specifierFound) {\n if (stringLiteral.Length > 0) {\n var slSpecifier = SpecifierInfo.CreateStringLiteralSpecifier(stringLiteral.ToString());\n matchedSpecifiers.Add(slSpecifier);\n stringLiteral = new StringBuilder();\n }\n matchedSpecifiers.Add(matchedSpecifier);\n }\n else {\n stringLiteral.Append(new string(symbol, repeatCount));\n }\n index += lastMatchedRepeatCount;\n }\n if (stringLiteral.Length > 0) {\n var slSpecifier = SpecifierInfo.CreateStringLiteralSpecifier(stringLiteral.ToString());\n matchedSpecifiers.Add(slSpecifier);\n }\n return matchedSpecifiers.ToArray();\n }\n public bool IncreaseComponentValue(SpecifierInfo specifier) {\n switch (specifier.Type) {\n case SpecifierType.s:\n case SpecifierType.ss:\n if (this.second.HasValue && this.second.Value < 59) {\n this.second++;\n }\n else {\n this.second = 1;\n }\n return true;\n case SpecifierType.m:\n case SpecifierType.mm:\n if (this.minute.HasValue && this.minute.Value < 59) {\n this.minute++;\n }\n else {\n this.minute = 1;\n }\n return true;\n case SpecifierType.h:\n case SpecifierType.hh:\n case SpecifierType.H:\n case SpecifierType.HH:\n if (this.hour.HasValue && this.hour.Value < 23) {\n this.hour++;\n }\n else {\n this.hour = 0;\n\n }\n this.am = hour < 12;\n return true;\n case SpecifierType.d:\n case SpecifierType.dd:\n if (this.day.HasValue) {\n if (this.year.HasValue && this.month.HasValue) {\n int daysInMonth = this.Calendar.GetDaysInMonth(this.year.Value, this.month.Value);\n if (this.day.Value < daysInMonth) {\n this.day++;\n return true;\n }\n }\n }\n this.day = 1;\n return true;\n\n case SpecifierType.M:\n case SpecifierType.MM:\n case SpecifierType.MMM:\n case SpecifierType.MMMM:\n if (this.month.HasValue) {\n if (this.year.HasValue) {\n int monthsInYear = this.Calendar.GetMonthsInYear(this.year.Value);\n if (this.month.Value < monthsInYear) {\n this.month++;\n return true;\n }\n }\n else {\n if (this.month.Value < 12) { /**********/\n this.month++;\n return true;\n }\n }\n }\n this.month = 1;\n return true;\n\n case SpecifierType.y:\n case SpecifierType.yy:\n case SpecifierType.yyy:\n case SpecifierType.yyyy:\n if (this.year.HasValue) {\n int maxYear = this.Calendar.GetYear(this.Calendar.MaxSupportedDateTime);\n if (this.year.Value < maxYear) {\n this.year++;\n return true;\n }\n else {\n return false;\n }\n }\n this.year = this.Calendar.GetYear(DateTime.Now);\n return true;\n case SpecifierType.t:\n case SpecifierType.tt:\n if (this.hour.HasValue) {\n if (this.hour < 12) {\n this.hour += 12;\n this.am = false;\n }\n else {\n this.hour -= 12;\n this.am = true;\n }\n return true;\n }\n return false;\n }\n return false;\n }\n protected static IList GetSpecsOfSymbol(char symbol) {\n IList specifiers;\n if (specSymbolCache == null) {\n specSymbolCache = new Dictionary>();\n }\n else {\n if (specSymbolCache.TryGetValue(symbol, out specifiers)) {\n return specifiers;\n }\n }\n specifiers = new List();\n foreach (var specifier in Specifiers) {\n if (specifier.ValueType != ValueType.StringLiteral &&\n specifier.Symbol[0].Equals(symbol)) {\n specifiers.Add(specifier);\n }\n }\n if (specifiers.Count > 0) {\n specSymbolCache.Add(symbol, specifiers);\n return specifiers;\n }\n return null;\n }\n private void SetDateTimeComponents() {\n if (this.value.HasValue) {\n DateTime _value = this.value.Value;\n Calendar calendar = this.Calendar;\n this.day = calendar.GetDayOfMonth(_value);\n this.hour = calendar.GetHour(_value);\n this.minute = calendar.GetMinute(_value);\n this.month = calendar.GetMonth(_value);\n this.second = calendar.GetSecond(_value);\n this.year = calendar.GetYear(_value);\n this.am = this.hour < 12;\n }\n else {\n this.day =\n this.hour =\n this.minute =\n this.month =\n this.second =\n this.year = null;\n this.am = true;\n }\n }\n private static bool ShouldCommit(int? dateTimeValue, int? value) {\n if (dateTimeValue.HasValue) {\n return !value.HasValue || !dateTimeValue.Value.Equals(value.Value);\n }\n return value.HasValue;\n }\n public bool ShouldCommit(SpecifierInfo specifier) {\n if (specifier.ValueType == ValueType.StringLiteral) {\n return false;\n }\n int? dateTimeValue = null;\n switch (specifier.Type) {\n case SpecifierType.s:\n return ShouldCommit(this.value.HasValue ? (int?)this.value.Value.Second : null, this.second);\n case SpecifierType.m:\n case SpecifierType.mm:\n return ShouldCommit(this.value.HasValue ? (int?)this.value.Value.Minute : null, this.minute); \n case SpecifierType.h:\n case SpecifierType.hh: \n case SpecifierType.H: \n case SpecifierType.HH:\n case SpecifierType.t: // Correct??\n case SpecifierType.tt: // Correct??\n return ShouldCommit(this.value.HasValue ? (int?)this.value.Value.Hour : null, this.hour); \n case SpecifierType.d:\n case SpecifierType.dd:\n case SpecifierType.ddd: // Correct??\n case SpecifierType.dddd: // Correct??\n if (this.value.HasValue) {\n dateTimeValue = this.Calendar.GetDayOfMonth(this.value.Value);\n }\n return ShouldCommit(dateTimeValue, this.day); \n case SpecifierType.M:\n case SpecifierType.MM:\n case SpecifierType.MMM:\n case SpecifierType.MMMM:\n if (this.value.HasValue) {\n dateTimeValue = this.Calendar.GetMonth(this.value.Value);\n }\n return ShouldCommit(dateTimeValue, this.month); \n case SpecifierType.y: \n case SpecifierType.yy:\n case SpecifierType.yyy:\n case SpecifierType.yyyy:\n if (this.value.HasValue) {\n dateTimeValue = this.Calendar.GetYear(this.value.Value);\n }\n return ShouldCommit(dateTimeValue, this.year);\n case SpecifierType.g:\n case SpecifierType.DateSeparator:\n case SpecifierType.TimeSeparator:\n return false;\n default:\n throw new ArgumentOutOfRangeException(\"specifier.Type\");\n }\n }\n private void UpdateDateTimeComponets() {\n int hour = this.hour.HasValue ? this.hour.Value : 0;\n int minute = this.minute.HasValue ? this.minute.Value : 0;\n int second = this.second.HasValue ? this.second.Value : 0;\n DateTime? newValue = null;\n if (this.year.HasValue) {\n int year = this.year.Value;\n int maxYear = this.Calendar.GetYear(this.Calendar.MaxSupportedDateTime);\n int minYear = this.Calendar.GetYear(this.Calendar.MinSupportedDateTime);\n if (year > maxYear) {\n this.year = year = maxYear;\n }\n else if (year < minYear) {\n this.year = year = minYear;\n }\n if (this.month.HasValue) {\n int month = this.month.Value;\n int monthsInYear = this.Calendar.GetMonthsInYear(this.year.Value);\n if (monthsInYear < month) {\n this.month = month = monthsInYear;\n }\n if (this.day.HasValue) {\n int day = this.day.Value;\n int daysInMonth = this.Calendar.GetDaysInMonth(this.year.Value, this.month.Value);\n if (daysInMonth < day) {\n this.day = day = daysInMonth;\n }\n DateTimeKind kind = DateTimeKind.Unspecified;\n if (this.value.HasValue) {\n kind = this.value.Value.Kind;\n }\n newValue = new DateTime(year, month, day, hour, minute, second, 0, this.Calendar, kind);\n }\n }\n }\n this.am = this.hour < 12;\n if (!newValue.HasValue) {\n // If one of the time componets are set, set null ones to zero\n // So 11:null:null becomes 11:00:00 and so one\n if (this.hour.HasValue || this.minute.HasValue || this.second.HasValue) {\n this.hour = hour;\n this.minute = minute;\n this.second = second;\n }\n }\n if (newValue != this.value) {\n this.value = newValue;\n if (this.ValueChanged != null) {\n this.ValueChanged(this, EventArgs.Empty);\n }\n }\n }\n #endregion\n\n #region Properties\n protected Calendar Calendar {\n get {\n return this.dateTimeFormat.Calendar; ;\n }\n }\n public DateTimeFormatInfo DateTimeFormat {\n get {\n return this.dateTimeFormat;\n }\n }\n #endregion\n }\n}\n"},"gt":{"kind":"string","value":""}}},{"rowIdx":96211,"cells":{"context":{"kind":"string","value":"// Copyright (c) Microsoft. All rights reserved.\n// Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nusing System;\nusing System.Collections.Generic;\nusing Xunit;\n\nnamespace System.Linq.Tests.LegacyTests\n{\n public class SingleTests\n {\n public class Single003\n {\n private static int Single001()\n {\n var q = from x in new[] { 999.9m }\n select x;\n\n var rst1 = q.Single();\n var rst2 = q.Single();\n\n return ((rst1 == rst2) ? 0 : 1);\n }\n\n private static int Single002()\n {\n var q = from x in new[] { \"!@#$%^\" }\n where !String.IsNullOrEmpty(x)\n select x;\n\n var rst1 = q.Single();\n var rst2 = q.Single();\n\n return ((rst1 == rst2) ? 0 : 1);\n }\n\n private static int Single0003()\n {\n var q = from x in new[] { 0 }\n select x;\n\n var rst1 = q.Single();\n var rst2 = q.Single();\n\n return ((rst1 == rst2) ? 0 : 1);\n }\n\n public static int Main()\n {\n int ret = RunTest(Single001) + RunTest(Single002) + RunTest(Single0003);\n if (0 != ret)\n Console.Write(s_errorMessage);\n\n return ret;\n }\n\n private static string s_errorMessage = String.Empty;\n private delegate int D();\n\n private static int RunTest(D m)\n {\n int n = m();\n if (0 != n)\n s_errorMessage += m.ToString() + \" - FAILED!\\r\\n\";\n return n;\n }\n\n [Fact]\n public void Test()\n {\n Assert.Equal(0, Main());\n }\n }\n\n public class Single1a\n {\n // source is of type IList, source is empty\n public static int Test1a()\n {\n int[] source = { };\n\n IList list = source as IList;\n\n if (list == null) return 1;\n\n try\n {\n var actual = source.Single();\n return 1;\n }\n catch (InvalidOperationException)\n {\n return 0;\n }\n }\n\n\n public static int Main()\n {\n return Test1a();\n }\n\n [Fact]\n public void Test()\n {\n Assert.Equal(0, Main());\n }\n }\n\n public class Single1b\n {\n // source is of type IList, source has only one element\n public static int Test1b()\n {\n int[] source = { 4 };\n int expected = 4;\n\n IList list = source as IList;\n\n if (list == null) return 1;\n\n var actual = source.Single();\n\n return ((expected == actual) ? 0 : 1);\n }\n\n\n public static int Main()\n {\n return Test1b();\n }\n\n [Fact]\n public void Test()\n {\n Assert.Equal(0, Main());\n }\n }\n\n public class Single1c\n {\n // source is of type IList, source has > 1 element\n public static int Test1c()\n {\n int[] source = { 4, 4, 4, 4, 4 };\n\n IList list = source as IList;\n\n if (list == null) return 1;\n\n try\n {\n var actual = source.Single();\n return 1;\n }\n catch (InvalidOperationException)\n {\n return 0;\n }\n }\n\n\n public static int Main()\n {\n return Test1c();\n }\n\n [Fact]\n public void Test()\n {\n Assert.Equal(0, Main());\n }\n }\n\n public class Single1d\n {\n // source is NOT of type IList, source is empty\n public static int Test1d()\n {\n IEnumerable source = Functions.NumRange(0, 0);\n\n IList list = source as IList;\n\n if (list != null) return 1;\n\n try\n {\n var actual = source.Single();\n return 1;\n }\n catch (InvalidOperationException)\n {\n return 0;\n }\n }\n\n\n public static int Main()\n {\n return Test1d();\n }\n\n [Fact]\n public void Test()\n {\n Assert.Equal(0, Main());\n }\n }\n\n public class Single1e\n {\n // source is NOT of type IList, source has only one element\n public static int Test1e()\n {\n IEnumerable source = Functions.NumRange(-5, 1);\n int expected = -5;\n\n IList list = source as IList;\n\n if (list != null) return 1;\n\n var actual = source.Single();\n\n return ((expected == actual) ? 0 : 1);\n }\n\n\n public static int Main()\n {\n return Test1e();\n }\n\n [Fact]\n public void Test()\n {\n Assert.Equal(0, Main());\n }\n }\n\n public class Single1f\n {\n // source is NOT of type IList, source has > 1 element\n public static int Test1f()\n {\n IEnumerable source = Functions.NumRange(3, 5);\n\n IList list = source as IList;\n\n if (list != null) return 1;\n\n try\n {\n var actual = source.Single();\n return 1;\n }\n catch (InvalidOperationException)\n {\n return 0;\n }\n }\n\n\n public static int Main()\n {\n return Test1f();\n }\n\n [Fact]\n public void Test()\n {\n Assert.Equal(0, Main());\n }\n }\n\n public class Single2a\n {\n // source is empty\n public static int Test2a()\n {\n int[] source = { };\n Func predicate = Functions.IsEven;\n\n try\n {\n var actual = source.Single(predicate);\n return 1;\n }\n catch (InvalidOperationException)\n {\n return 0;\n }\n }\n\n\n public static int Main()\n {\n return Test2a();\n }\n\n [Fact]\n public void Test()\n {\n Assert.Equal(0, Main());\n }\n }\n\n public class Single2b\n {\n // source has 1 element and predicate is true\n public static int Test2b()\n {\n int[] source = { 4 };\n Func predicate = Functions.IsEven;\n int expected = 4;\n\n var actual = source.Single(predicate);\n\n return ((expected == actual) ? 0 : 1);\n }\n\n\n public static int Main()\n {\n return Test2b();\n }\n\n [Fact]\n public void Test()\n {\n Assert.Equal(0, Main());\n }\n }\n\n public class Single2c\n {\n // source has 1 element and predicate is false\n public static int Test2c()\n {\n int[] source = { 3 };\n Func predicate = Functions.IsEven;\n\n try\n {\n var actual = source.Single(predicate);\n return 1;\n }\n catch (InvalidOperationException)\n {\n return 0;\n }\n }\n\n\n public static int Main()\n {\n return Test2c();\n }\n\n [Fact]\n public void Test()\n {\n Assert.Equal(0, Main());\n }\n }\n\n public class Single2d\n {\n // source has > 1 element and predicate is false for all\n public static int Test2d()\n {\n int[] source = { 3, 1, 7, 9, 13, 19 };\n Func predicate = Functions.IsEven;\n\n try\n {\n var actual = source.Single(predicate);\n return 1;\n }\n catch (InvalidOperationException)\n {\n return 0;\n }\n }\n\n\n public static int Main()\n {\n return Test2d();\n }\n\n [Fact]\n public void Test()\n {\n Assert.Equal(0, Main());\n }\n }\n\n public class Single2e\n {\n // source has > 1 element and predicate is true only for last element\n public static int Test2e()\n {\n int[] source = { 3, 1, 7, 9, 13, 19, 20 };\n Func predicate = Functions.IsEven;\n int expected = 20;\n\n var actual = source.Single(predicate);\n\n return ((expected == actual) ? 0 : 1);\n }\n\n\n public static int Main()\n {\n return Test2e();\n }\n\n [Fact]\n public void Test()\n {\n Assert.Equal(0, Main());\n }\n }\n\n public class Single2f\n {\n // source has > 1 element and predicate is true for 1st and last element\n public static int Test2f()\n {\n int[] source = { 2, 3, 1, 7, 9, 13, 19, 10 };\n Func predicate = Functions.IsEven;\n\n try\n {\n var actual = source.Single(predicate);\n return 1;\n }\n catch (InvalidOperationException)\n {\n return 0;\n }\n }\n\n\n public static int Main()\n {\n return Test2f();\n }\n\n [Fact]\n public void Test()\n {\n Assert.Equal(0, Main());\n }\n }\n }\n}\n"},"gt":{"kind":"string","value":""}}},{"rowIdx":96212,"cells":{"context":{"kind":"string","value":"using System;\nusing System.Globalization;\nusing System.Linq;\nusing System.Net;\nusing System.Threading.Tasks;\nusing Microsoft.Extensions.Logging;\nusing Orleans;\nusing Orleans.AzureUtils;\nusing Orleans.Runtime;\nusing Orleans.Runtime.Configuration;\nusing Orleans.TestingHost.Utils;\nusing TestExtensions;\nusing UnitTests.MembershipTests;\nusing Xunit;\nusing Xunit.Abstractions;\n\nnamespace Tester.AzureUtils\n{\n /// \n /// Tests for operation of Orleans SiloInstanceManager using AzureStore - Requires access to external Azure storage\n /// \n [TestCategory(\"Azure\"), TestCategory(\"Storage\")]\n public class SiloInstanceTableManagerTests : IClassFixture, IDisposable\n {\n public class Fixture : IDisposable\n {\n public ILoggerFactory LoggerFactory { get; set; } =\n TestingUtils.CreateDefaultLoggerFactory(\"SiloInstanceTableManagerTests.log\");\n\n public void Dispose()\n {\n this.LoggerFactory.Dispose();\n }\n }\n\n private string deploymentId;\n private int generation;\n private SiloAddress siloAddress;\n private SiloInstanceTableEntry myEntry;\n private OrleansSiloInstanceManager manager;\n private readonly ITestOutputHelper output;\n\n public SiloInstanceTableManagerTests(ITestOutputHelper output, Fixture fixture)\n {\n TestUtils.CheckForAzureStorage();\n this.output = output;\n deploymentId = \"test-\" + Guid.NewGuid();\n generation = SiloAddress.AllocateNewGeneration();\n siloAddress = SiloAddressUtils.NewLocalSiloAddress(generation);\n\n output.WriteLine(\"DeploymentId={0} Generation={1}\", deploymentId, generation);\n\n output.WriteLine(\"Initializing SiloInstanceManager\");\n manager = OrleansSiloInstanceManager.GetManager(deploymentId, TestDefaultConfiguration.DataConnectionString, fixture.LoggerFactory)\n .WaitForResultWithThrow(SiloInstanceTableTestConstants.Timeout);\n }\n\n // Use TestCleanup to run code after each test has run\n public void Dispose()\n {\n if(manager != null && SiloInstanceTableTestConstants.DeleteEntriesAfterTest)\n {\n TimeSpan timeout = SiloInstanceTableTestConstants.Timeout;\n\n output.WriteLine(\"TestCleanup Timeout={0}\", timeout);\n\n manager.DeleteTableEntries(deploymentId).WaitWithThrow(timeout);\n\n output.WriteLine(\"TestCleanup - Finished\");\n manager = null;\n }\n }\n\n [SkippableFact, TestCategory(\"Functional\")]\n public void SiloInstanceTable_Op_RegisterSiloInstance()\n {\n RegisterSiloInstance();\n }\n\n [SkippableFact, TestCategory(\"Functional\")]\n public void SiloInstanceTable_Op_ActivateSiloInstance()\n {\n RegisterSiloInstance();\n\n manager.ActivateSiloInstance(myEntry);\n }\n\n [SkippableFact, TestCategory(\"Functional\")]\n public void SiloInstanceTable_Op_UnregisterSiloInstance()\n {\n RegisterSiloInstance();\n\n manager.UnregisterSiloInstance(myEntry);\n }\n\n [SkippableFact, TestCategory(\"Functional\")]\n public async Task SiloInstanceTable_Op_CreateSiloEntryConditionally()\n {\n bool didInsert = await manager.TryCreateTableVersionEntryAsync()\n .WithTimeout(AzureTableDefaultPolicies.TableOperationTimeout);\n\n Assert.True(didInsert, \"Did insert\");\n }\n\n [SkippableFact, TestCategory(\"Functional\")]\n public async Task SiloInstanceTable_Register_CheckData()\n {\n const string testName = \"SiloInstanceTable_Register_CheckData\";\n output.WriteLine(\"Start {0}\", testName);\n\n RegisterSiloInstance();\n\n var data = await FindSiloEntry(siloAddress);\n SiloInstanceTableEntry siloEntry = data.Item1;\n string eTag = data.Item2;\n\n Assert.NotNull(eTag); // ETag should not be null\n Assert.NotNull(siloEntry); // SiloInstanceTableEntry should not be null\n\n Assert.Equal(SiloInstanceTableTestConstants.INSTANCE_STATUS_CREATED, siloEntry.Status);\n\n CheckSiloInstanceTableEntry(myEntry, siloEntry);\n output.WriteLine(\"End {0}\", testName);\n }\n\n [SkippableFact, TestCategory(\"Functional\")]\n public async Task SiloInstanceTable_Activate_CheckData()\n {\n RegisterSiloInstance();\n\n manager.ActivateSiloInstance(myEntry);\n\n var data = await FindSiloEntry(siloAddress);\n Assert.NotNull(data); // Data returned should not be null\n\n SiloInstanceTableEntry siloEntry = data.Item1;\n string eTag = data.Item2;\n\n Assert.NotNull(eTag); // ETag should not be null\n Assert.NotNull(siloEntry); // SiloInstanceTableEntry should not be null\n\n Assert.Equal(SiloInstanceTableTestConstants.INSTANCE_STATUS_ACTIVE, siloEntry.Status);\n\n CheckSiloInstanceTableEntry(myEntry, siloEntry);\n }\n\n [SkippableFact, TestCategory(\"Functional\")]\n public async Task SiloInstanceTable_Unregister_CheckData()\n {\n RegisterSiloInstance();\n\n manager.UnregisterSiloInstance(myEntry);\n\n var data = await FindSiloEntry(siloAddress);\n SiloInstanceTableEntry siloEntry = data.Item1;\n string eTag = data.Item2;\n\n Assert.NotNull(eTag); // ETag should not be null\n Assert.NotNull(siloEntry); // SiloInstanceTableEntry should not be null\n\n Assert.Equal(SiloInstanceTableTestConstants.INSTANCE_STATUS_DEAD, siloEntry.Status);\n\n CheckSiloInstanceTableEntry(myEntry, siloEntry);\n }\n\n [SkippableFact, TestCategory(\"Functional\")]\n public void SiloInstanceTable_FindAllGatewayProxyEndpoints()\n {\n RegisterSiloInstance();\n\n var gateways = manager.FindAllGatewayProxyEndpoints().GetResult();\n Assert.Equal(0, gateways.Count); // \"Number of gateways before Silo.Activate\"\n\n manager.ActivateSiloInstance(myEntry);\n\n gateways = manager.FindAllGatewayProxyEndpoints().GetResult();\n Assert.Equal(1, gateways.Count); // \"Number of gateways after Silo.Activate\"\n\n Uri myGateway = gateways.First();\n Assert.Equal(myEntry.Address, myGateway.Host.ToString()); // \"Gateway address\"\n Assert.Equal(myEntry.ProxyPort, myGateway.Port.ToString(CultureInfo.InvariantCulture)); // \"Gateway port\"\n }\n\n [SkippableFact, TestCategory(\"Functional\")]\n public void SiloAddress_ToFrom_RowKey()\n {\n string ipAddress = \"1.2.3.4\";\n int port = 5555;\n int generation = 6666;\n\n IPAddress address = IPAddress.Parse(ipAddress);\n IPEndPoint endpoint = new IPEndPoint(address, port);\n SiloAddress siloAddress = SiloAddress.New(endpoint, generation);\n\n string MembershipRowKey = SiloInstanceTableEntry.ConstructRowKey(siloAddress);\n\n output.WriteLine(\"SiloAddress = {0} Row Key string = {1}\", siloAddress, MembershipRowKey);\n\n SiloAddress fromRowKey = SiloInstanceTableEntry.UnpackRowKey(MembershipRowKey);\n\n output.WriteLine(\"SiloAddress result = {0} From Row Key string = {1}\", fromRowKey, MembershipRowKey);\n\n Assert.Equal(siloAddress, fromRowKey);\n Assert.Equal(SiloInstanceTableEntry.ConstructRowKey(siloAddress), SiloInstanceTableEntry.ConstructRowKey(fromRowKey));\n }\n\n private void RegisterSiloInstance()\n {\n string partitionKey = deploymentId;\n string rowKey = SiloInstanceTableEntry.ConstructRowKey(siloAddress);\n\n IPEndPoint myEndpoint = siloAddress.Endpoint;\n\n myEntry = new SiloInstanceTableEntry\n {\n PartitionKey = partitionKey,\n RowKey = rowKey,\n\n DeploymentId = deploymentId,\n Address = myEndpoint.Address.ToString(),\n Port = myEndpoint.Port.ToString(CultureInfo.InvariantCulture),\n Generation = generation.ToString(CultureInfo.InvariantCulture),\n\n HostName = myEndpoint.Address.ToString(),\n ProxyPort = \"30000\",\n\n RoleName = \"MyRole\",\n SiloName = \"MyInstance\",\n UpdateZone = \"0\",\n FaultZone = \"0\",\n StartTime = LogFormatter.PrintDate(DateTime.UtcNow),\n };\n\n output.WriteLine(\"MyEntry={0}\", myEntry);\n\n manager.RegisterSiloInstance(myEntry);\n }\n\n private async Task> FindSiloEntry(SiloAddress siloAddr)\n {\n string partitionKey = deploymentId;\n string rowKey = SiloInstanceTableEntry.ConstructRowKey(siloAddr);\n\n output.WriteLine(\"FindSiloEntry for SiloAddress={0} PartitionKey={1} RowKey={2}\", siloAddr, partitionKey, rowKey);\n\n Tuple data = await manager.ReadSingleTableEntryAsync(partitionKey, rowKey);\n\n output.WriteLine(\"FindSiloEntry returning Data={0}\", data);\n return data;\n }\n\n private void CheckSiloInstanceTableEntry(SiloInstanceTableEntry referenceEntry, SiloInstanceTableEntry entry)\n {\n Assert.Equal(referenceEntry.DeploymentId, entry.DeploymentId);\n Assert.Equal(referenceEntry.Address, entry.Address);\n Assert.Equal(referenceEntry.Port, entry.Port);\n Assert.Equal(referenceEntry.Generation, entry.Generation);\n Assert.Equal(referenceEntry.HostName, entry.HostName);\n //Assert.Equal(referenceEntry.Status, entry.Status);\n Assert.Equal(referenceEntry.ProxyPort, entry.ProxyPort);\n Assert.Equal(referenceEntry.RoleName, entry.RoleName);\n Assert.Equal(referenceEntry.SiloName, entry.SiloName);\n Assert.Equal(referenceEntry.UpdateZone, entry.UpdateZone);\n Assert.Equal(referenceEntry.FaultZone, entry.FaultZone);\n Assert.Equal(referenceEntry.StartTime, entry.StartTime);\n Assert.Equal(referenceEntry.IAmAliveTime, entry.IAmAliveTime);\n Assert.Equal(referenceEntry.MembershipVersion, entry.MembershipVersion);\n\n Assert.Equal(referenceEntry.SuspectingTimes, entry.SuspectingTimes);\n Assert.Equal(referenceEntry.SuspectingSilos, entry.SuspectingSilos);\n }\n }\n}\n"},"gt":{"kind":"string","value":""}}},{"rowIdx":96213,"cells":{"context":{"kind":"string","value":"using Saga.Shared.Definitions;\nusing System;\nusing System.Collections.Generic;\nusing System.Diagnostics;\nusing System.Net.Sockets;\nusing System.Threading;\n\nnamespace Saga.Tasks\n{\n public static class LifespanAI\n {\n #region Private Members\n\n /// \n /// List of LifespanThreads where monster objects can be assigned to.\n /// \n private static List LifespanThreads = new List();\n\n /// \n /// A zero based index of the next thread where to register with\n /// \n /// \n /// This is a volatile field containing the next threadstate where\n /// to register the AI to. Tbe next threadstate will should indicate\n /// that the AI is registered on several lists. Reducing the\n /// error amount.\n /// \n private static volatile int NextThreadState = 0;\n\n /// \n /// Number representing the number of activated monsters.\n /// \n private static volatile int NumberSubscribedMobs = 0;\n\n #endregion Private Members\n\n #region Public Members\n\n /// \n /// Subscribes a AI controler for it's lifespan updates.\n /// \n /// \n /// The primairy target for this is to make them moveable.\n /// \n /// Target who to subscribe\n public static void Subscribe(IArtificialIntelligence e)\n {\n if (!e.Lifespan.IsRegistered)\n {\n int ThreadA = NextThreadState;\n int ThreadB = ThreadA + 1;\n LifespanThreads[ThreadA].Register(e);\n e.Lifespan.LifespanThread = ThreadB;\n NextThreadState = ++NextThreadState % LifespanThreads.Count;\n NumberSubscribedMobs++;\n }\n }\n\n /// \n /// Unsubscribes a AI controler for it's lifespan updates.\n /// \n /// \n public static void Unsubscribe(IArtificialIntelligence e)\n {\n if (e.Lifespan.IsRegistered)\n {\n NextThreadState = (e.Lifespan.LifespanThread - 1);\n LifespanThreads[(e.Lifespan.LifespanThread - 1)].Unregister(e);\n e.Lifespan.LifespanThread = 0;\n NumberSubscribedMobs--;\n }\n }\n\n /// \n /// Checks if the AI controler is subscribed.\n /// \n /// AI controler to check\n /// True if the controller is subscribed\n public static bool IsSubscribed(IArtificialIntelligence e)\n {\n return e.Lifespan.IsRegistered;\n }\n\n #endregion Public Members\n\n #region Constructor / Deconstructor\n\n /// \n /// Initializes all the threadstates.\n /// \n /// \n /// It creates 4 thread states by default.\n /// \n static LifespanAI()\n {\n LifespanThreads.Add(new ThreadState());\n LifespanThreads.Add(new ThreadState());\n LifespanThreads.Add(new ThreadState());\n LifespanThreads.Add(new ThreadState());\n }\n\n internal static void Stop()\n {\n //remove all lifespan threads\n for (int i = 0; i < LifespanThreads.Count; i++)\n LifespanThreads[i].Stop();\n LifespanThreads.Clear();\n }\n\n #endregion Constructor / Deconstructor\n\n #region Nested Classes/Structures\n\n private sealed class ThreadState\n {\n private Thread d;\n\n public ThreadState()\n {\n d = new Thread(new ThreadStart(Process));\n d.Start();\n }\n\n ~ThreadState()\n {\n Stop();\n d = null;\n }\n\n internal void Stop()\n {\n try\n {\n if (d != null && d.IsAlive)\n {\n GC.SuppressFinalize(d);\n d.Abort();\n }\n }\n finally\n {\n if (d != null)\n GC.ReRegisterForFinalize(d);\n }\n }\n\n /// \n /// List of activated AI\n /// \n internal List ActivatedAI = new List(25);\n\n /// \n /// Indication if the AI is processing.\n /// \n private volatile bool IsWritting = false;\n\n /// \n /// Registers a AI object\n /// \n /// \n internal void Register(IArtificialIntelligence c)\n {\n try\n {\n IsWritting = true;\n //Add a random delay to make mobs appear they move pure random\n int rand = Saga.Managers.WorldTasks._random.Next(0, 1000);\n c.Lifespan.lasttick = Environment.TickCount + rand;\n ActivatedAI.Add(c);\n }\n finally\n {\n IsWritting = false;\n }\n }\n\n /// \n /// Unregisters a AI object\n /// \n /// \n internal void Unregister(IArtificialIntelligence c)\n {\n try\n {\n IsWritting = true;\n c.Lifespan.lasttick = Environment.TickCount;\n ActivatedAI.Remove(c);\n }\n finally\n {\n IsWritting = false;\n }\n }\n\n /// \n /// Processes all threads\n /// \n internal void Process()\n {\n while (!Environment.HasShutdownStarted)\n {\n try\n {\n for (int i = 0; i < ActivatedAI.Count; i++)\n {\n try\n {\n if (IsWritting == false)\n ActivatedAI[i].Process();\n }\n catch (SocketException)\n {\n //DO NOT PROCESS THIS\n }\n catch (ThreadAbortException e)\n {\n throw e;\n }\n catch (Exception e)\n {\n Trace.WriteLine(e);\n }\n }\n\n Thread.Sleep(1);\n }\n catch (ThreadAbortException)\n {\n break;\n }\n }\n }\n }\n\n /// \n /// Supplies as interaction base for IArtificialIntelligence objects.\n /// \n public sealed class Lifespan\n {\n /// \n /// Index to which ThreadState object the map\n /// was assigned to\n /// \n internal int LifespanThread = 0;\n\n /// \n /// Tick when it was last updated.\n /// \n public int lasttick;\n\n /// \n /// Checks if the Lifespan object was registered\n /// \n public bool IsRegistered\n {\n get\n {\n return LifespanThread > 0;\n }\n }\n\n /// \n /// Subscribes the Lifespan Object\n /// \n public void Subscribe(IArtificialIntelligence ai)\n {\n LifespanAI.Subscribe(ai);\n }\n\n /// \n /// Ubsubscribes the Lifespan Object\n /// \n public void Unsubscribe(IArtificialIntelligence ai)\n {\n LifespanAI.Unsubscribe(ai);\n }\n }\n\n #endregion Nested Classes/Structures\n }\n}\n"},"gt":{"kind":"string","value":""}}},{"rowIdx":96214,"cells":{"context":{"kind":"string","value":"using System;\nusing System.Windows.Forms;\nusing System.Drawing;\nusing System.Runtime.InteropServices;\nusing System.ComponentModel;\n\nnamespace xDockPanel\n{\n [ToolboxItem(false)]\n public partial class DockWindow : Panel, INestedPanesContainer, ISplitterDragSource\n {\n private DockPanel m_dockPanel;\n private DockState m_dockState;\n private SplitterControl m_splitter;\n private NestedPaneCollection m_nestedPanes;\n\n internal DockWindow(DockPanel dockPanel, DockState dockState)\n {\n m_nestedPanes = new NestedPaneCollection(this);\n m_dockPanel = dockPanel;\n m_dockState = dockState;\n Visible = false;\n\n SuspendLayout();\n\n if (DockState == DockState.Left || DockState == DockState.Right ||\n DockState == DockState.Top || DockState == DockState.Bottom)\n {\n m_splitter = new SplitterControl();\n Controls.Add(m_splitter);\n }\n\n if (DockState == DockState.Left)\n {\n Dock = DockStyle.Left;\n m_splitter.Dock = DockStyle.Right;\n }\n else if (DockState == DockState.Right)\n {\n Dock = DockStyle.Right;\n m_splitter.Dock = DockStyle.Left;\n }\n else if (DockState == DockState.Top)\n {\n Dock = DockStyle.Top;\n m_splitter.Dock = DockStyle.Bottom;\n }\n else if (DockState == DockState.Bottom)\n {\n Dock = DockStyle.Bottom;\n m_splitter.Dock = DockStyle.Top;\n }\n else if (DockState == DockState.Document)\n {\n Dock = DockStyle.Fill;\n }\n\n ResumeLayout();\n }\n\n public VisibleNestedPaneCollection VisibleNestedPanes\n {\n get { return NestedPanes.VisibleNestedPanes; }\n }\n\n public NestedPaneCollection NestedPanes\n {\n get { return m_nestedPanes; }\n }\n\n public DockPanel DockPanel\n {\n get { return m_dockPanel; }\n }\n\n public DockState DockState\n {\n get { return m_dockState; }\n }\n\n public bool IsFloat\n {\n get { return DockState == DockState.Float; }\n }\n\n internal DockPane DefaultPane\n {\n get { return VisibleNestedPanes.Count == 0 ? null : VisibleNestedPanes[0]; }\n }\n\n public virtual Rectangle DisplayingRectangle\n {\n get\n {\n Rectangle rect = ClientRectangle;\n // if DockWindow is document, exclude the border\n if (DockState == DockState.Document)\n {\n rect.X += 1;\n rect.Y += 1;\n rect.Width -= 2;\n rect.Height -= 2;\n }\n // exclude the splitter\n else if (DockState == DockState.Left)\n rect.Width -= Measures.SplitterSize;\n else if (DockState == DockState.Right)\n {\n rect.X += Measures.SplitterSize;\n rect.Width -= Measures.SplitterSize;\n }\n else if (DockState == DockState.Top)\n rect.Height -= Measures.SplitterSize;\n else if (DockState == DockState.Bottom)\n {\n rect.Y += Measures.SplitterSize;\n rect.Height -= Measures.SplitterSize;\n }\n\n return rect;\n }\n }\n\n protected override void OnPaint(PaintEventArgs e)\n {\n // if DockWindow is document, draw the border\n if (DockState == DockState.Document)\n e.Graphics.DrawRectangle(SystemPens.ControlDark, ClientRectangle.X, ClientRectangle.Y, ClientRectangle.Width - 1, ClientRectangle.Height - 1);\n\n base.OnPaint(e);\n }\n\n protected override void OnLayout(LayoutEventArgs levent)\n {\n VisibleNestedPanes.Refresh();\n if (VisibleNestedPanes.Count == 0)\n {\n if (Visible)\n Visible = false;\n }\n else if (!Visible)\n {\n Visible = true;\n VisibleNestedPanes.Refresh();\n }\n\n base.OnLayout (levent);\n }\n\n #region ISplitterDragSource Members\n\n void ISplitterDragSource.BeginDrag(Rectangle rectSplitter)\n {\n }\n\n void ISplitterDragSource.EndDrag()\n {\n }\n\n bool ISplitterDragSource.IsVertical\n {\n get { return (DockState == DockState.Left || DockState == DockState.Right); }\n }\n\n Rectangle ISplitterDragSource.DragLimitBounds\n {\n get\n {\n Rectangle rectLimit = DockPanel.DockArea;\n Point location;\n if ((Control.ModifierKeys & Keys.Shift) == 0)\n location = Location;\n else\n location = DockPanel.DockArea.Location;\n\n if (((ISplitterDragSource)this).IsVertical)\n {\n rectLimit.X += MeasurePane.MinSize;\n rectLimit.Width -= 2 * MeasurePane.MinSize;\n rectLimit.Y = location.Y;\n if ((Control.ModifierKeys & Keys.Shift) == 0)\n rectLimit.Height = Height;\n }\n else\n {\n rectLimit.Y += MeasurePane.MinSize;\n rectLimit.Height -= 2 * MeasurePane.MinSize;\n rectLimit.X = location.X;\n if ((Control.ModifierKeys & Keys.Shift) == 0)\n rectLimit.Width = Width;\n }\n\n return DockPanel.RectangleToScreen(rectLimit);\n }\n }\n\n void ISplitterDragSource.MoveSplitter(int offset)\n {\n if ((Control.ModifierKeys & Keys.Shift) != 0)\n SendToBack();\n\n Rectangle rectDockArea = DockPanel.DockArea;\n if (DockState == DockState.Left && rectDockArea.Width > 0)\n {\n if (DockPanel.DockLeftPortion > 1)\n DockPanel.DockLeftPortion = Width + offset;\n else\n DockPanel.DockLeftPortion += ((double)offset) / (double)rectDockArea.Width;\n }\n else if (DockState == DockState.Right && rectDockArea.Width > 0)\n {\n if (DockPanel.DockRightPortion > 1)\n DockPanel.DockRightPortion = Width - offset;\n else\n DockPanel.DockRightPortion -= ((double)offset) / (double)rectDockArea.Width;\n }\n else if (DockState == DockState.Bottom && rectDockArea.Height > 0)\n {\n if (DockPanel.DockBottomPortion > 1)\n DockPanel.DockBottomPortion = Height - offset;\n else\n DockPanel.DockBottomPortion -= ((double)offset) / (double)rectDockArea.Height;\n }\n else if (DockState == DockState.Top && rectDockArea.Height > 0)\n {\n if (DockPanel.DockTopPortion > 1)\n DockPanel.DockTopPortion = Height + offset;\n else\n DockPanel.DockTopPortion += ((double)offset) / (double)rectDockArea.Height;\n }\n }\n\n #region IDragSource Members\n\n Control IDragSource.DragControl\n {\n get { return this; }\n }\n\n #endregion\n #endregion\n }\n}\n"},"gt":{"kind":"string","value":""}}},{"rowIdx":96215,"cells":{"context":{"kind":"string","value":"// Copyright (c) Microsoft Corporation. All rights reserved.\n// Licensed under the MIT License. See License.txt in the project root for\n// license information.\n// \n// Code generated by Microsoft (R) AutoRest Code Generator.\n// Changes may cause incorrect behavior and will be lost if the code is\n// regenerated.\n\nnamespace Fixtures.AcceptanceTestsReport\n{\n using Microsoft.Rest;\n using Models;\n\n /// \n /// Test Infrastructure for AutoRest\n /// \n public partial class AutoRestReportService : Microsoft.Rest.ServiceClient, IAutoRestReportService\n {\n /// \n /// The base URI of the service.\n /// \n public System.Uri BaseUri { get; set; }\n\n /// \n /// Gets or sets json serialization settings.\n /// \n public Newtonsoft.Json.JsonSerializerSettings SerializationSettings { get; private set; }\n\n /// \n /// Gets or sets json deserialization settings.\n /// \n public Newtonsoft.Json.JsonSerializerSettings DeserializationSettings { get; private set; }\n\n /// \n /// Initializes a new instance of the AutoRestReportService class.\n /// \n /// \n /// Optional. The delegating handlers to add to the http client pipeline.\n /// \n public AutoRestReportService(params System.Net.Http.DelegatingHandler[] handlers) : base(handlers)\n {\n this.Initialize();\n }\n\n /// \n /// Initializes a new instance of the AutoRestReportService class.\n /// \n /// \n /// Optional. The http client handler used to handle http transport.\n /// \n /// \n /// Optional. The delegating handlers to add to the http client pipeline.\n /// \n public AutoRestReportService(System.Net.Http.HttpClientHandler rootHandler, params System.Net.Http.DelegatingHandler[] handlers) : base(rootHandler, handlers)\n {\n this.Initialize();\n }\n\n /// \n /// Initializes a new instance of the AutoRestReportService class.\n /// \n /// \n /// Optional. The base URI of the service.\n /// \n /// \n /// Optional. The delegating handlers to add to the http client pipeline.\n /// \n /// \n /// Thrown when a required parameter is null\n /// \n public AutoRestReportService(System.Uri baseUri, params System.Net.Http.DelegatingHandler[] handlers) : this(handlers)\n {\n if (baseUri == null)\n {\n throw new System.ArgumentNullException(\"baseUri\");\n }\n this.BaseUri = baseUri;\n }\n\n /// \n /// Initializes a new instance of the AutoRestReportService class.\n /// \n /// \n /// Optional. The base URI of the service.\n /// \n /// \n /// Optional. The http client handler used to handle http transport.\n /// \n /// \n /// Optional. The delegating handlers to add to the http client pipeline.\n /// \n /// \n /// Thrown when a required parameter is null\n /// \n public AutoRestReportService(System.Uri baseUri, System.Net.Http.HttpClientHandler rootHandler, params System.Net.Http.DelegatingHandler[] handlers) : this(rootHandler, handlers)\n {\n if (baseUri == null)\n {\n throw new System.ArgumentNullException(\"baseUri\");\n }\n this.BaseUri = baseUri;\n }\n\n /// \n /// An optional partial-method to perform custom initialization.\n /// \n partial void CustomInitialize();\n /// \n /// Initializes client properties.\n /// \n private void Initialize()\n {\n this.BaseUri = new System.Uri(\"http://localhost\");\n SerializationSettings = new Newtonsoft.Json.JsonSerializerSettings\n {\n Formatting = Newtonsoft.Json.Formatting.Indented,\n DateFormatHandling = Newtonsoft.Json.DateFormatHandling.IsoDateFormat,\n DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Utc,\n NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore,\n ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Serialize,\n ContractResolver = new Microsoft.Rest.Serialization.ReadOnlyJsonContractResolver(),\n Converters = new System.Collections.Generic.List\n {\n new Microsoft.Rest.Serialization.Iso8601TimeSpanConverter()\n }\n };\n DeserializationSettings = new Newtonsoft.Json.JsonSerializerSettings\n {\n DateFormatHandling = Newtonsoft.Json.DateFormatHandling.IsoDateFormat,\n DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Utc,\n NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore,\n ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Serialize,\n ContractResolver = new Microsoft.Rest.Serialization.ReadOnlyJsonContractResolver(),\n Converters = new System.Collections.Generic.List\n {\n new Microsoft.Rest.Serialization.Iso8601TimeSpanConverter()\n }\n };\n CustomInitialize();\n } \n /// \n /// Get test coverage report\n /// \n /// \n /// Headers that will be added to request.\n /// \n /// \n /// The cancellation token.\n /// \n /// \n /// Thrown when the operation returned an invalid status code\n /// \n /// \n /// Thrown when unable to deserialize the response\n /// \n /// \n /// A response object containing the response body and response headers.\n /// \n public async System.Threading.Tasks.Task>> GetReportWithHttpMessagesAsync(System.Collections.Generic.Dictionary> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))\n {\n // Tracing\n bool _shouldTrace = Microsoft.Rest.ServiceClientTracing.IsEnabled;\n string _invocationId = null;\n if (_shouldTrace)\n {\n _invocationId = Microsoft.Rest.ServiceClientTracing.NextInvocationId.ToString();\n System.Collections.Generic.Dictionary tracingParameters = new System.Collections.Generic.Dictionary();\n tracingParameters.Add(\"cancellationToken\", cancellationToken);\n Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, \"GetReport\", tracingParameters);\n }\n // Construct URL\n var _baseUrl = this.BaseUri.AbsoluteUri;\n var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith(\"/\") ? \"\" : \"/\")), \"report\").ToString();\n // Create HTTP transport objects\n System.Net.Http.HttpRequestMessage _httpRequest = new System.Net.Http.HttpRequestMessage();\n System.Net.Http.HttpResponseMessage _httpResponse = null;\n _httpRequest.Method = new System.Net.Http.HttpMethod(\"GET\");\n _httpRequest.RequestUri = new System.Uri(_url);\n // Set Headers\n if (customHeaders != null)\n {\n foreach(var _header in customHeaders)\n {\n if (_httpRequest.Headers.Contains(_header.Key))\n {\n _httpRequest.Headers.Remove(_header.Key);\n }\n _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);\n }\n }\n\n // Serialize Request\n string _requestContent = null;\n // Send Request\n if (_shouldTrace)\n {\n Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest);\n }\n cancellationToken.ThrowIfCancellationRequested();\n _httpResponse = await this.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);\n if (_shouldTrace)\n {\n Microsoft.Rest.ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);\n }\n System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode;\n cancellationToken.ThrowIfCancellationRequested();\n string _responseContent = null;\n if ((int)_statusCode != 200)\n {\n var ex = new ErrorException(string.Format(\"Operation returned an invalid status code '{0}'\", _statusCode));\n try\n {\n _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);\n Error _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject(_responseContent, this.DeserializationSettings);\n if (_errorBody != null)\n {\n ex.Body = _errorBody;\n }\n }\n catch (Newtonsoft.Json.JsonException)\n {\n // Ignore the exception\n }\n ex.Request = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent);\n ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent);\n if (_shouldTrace)\n {\n Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex);\n }\n _httpRequest.Dispose();\n if (_httpResponse != null)\n {\n _httpResponse.Dispose();\n }\n throw ex;\n }\n // Create Result\n var _result = new Microsoft.Rest.HttpOperationResponse>();\n _result.Request = _httpRequest;\n _result.Response = _httpResponse;\n // Deserialize Response\n if ((int)_statusCode == 200)\n {\n _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);\n try\n {\n _result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject>(_responseContent, this.DeserializationSettings);\n }\n catch (Newtonsoft.Json.JsonException ex)\n {\n _httpRequest.Dispose();\n if (_httpResponse != null)\n {\n _httpResponse.Dispose();\n }\n throw new Microsoft.Rest.SerializationException(\"Unable to deserialize the response.\", _responseContent, ex);\n }\n }\n if (_shouldTrace)\n {\n Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result);\n }\n return _result;\n }\n\n }\n}\n"},"gt":{"kind":"string","value":""}}},{"rowIdx":96216,"cells":{"context":{"kind":"string","value":"using System;\n\nnamespace KeyGeneratingCaches.Api.Verification\n{\n /// \n /// A test helper that can be used to verify that an implementation of IKeyGeneratingCache conforms to the public API\n /// \n public class ApiTester\n {\n private readonly IKeyGeneratingCache _testSubject;\n\n\n /// \n /// Initializes a new instance of the class.\n /// \n /// The implementation of IKeyGeneratingCache that is to be tested\n public ApiTester (IKeyGeneratingCache testSubject)\n {\n _testSubject = testSubject;\n }\n\n\n\n public bool PassesAllApiTests(string testCaseName)\n {\n testCaseName = testCaseName ?? \"Passes All Api Tests\";\n\n var test1 = AValidCacheKeyIsReturnedOnAdd ();\n var test2 = TheCacheMissHandlerIsExecutedForANonExistentKey ();\n var test3 = AValidCacheKeyIsReturnedFromGetForANonExistentKey ();\n var test4 = AValidCacheKeyIsReturnedFromGetForAGenuineKey ();\n var test5 = ANewCacheKeyIsReturnedForACacheMiss ();\n var test6 = RemoveDoesNotThrowAnyExceptions ();\n var test7 = TheExpectedDataIsReturnedFromGetForANonExistentKey ();\n var test8 = TheExpectedDataIsReturnedFromGetForAGenuineKey ();\n var test9 = NullKeySuppliedToGetDoesNotResultInExceptions ();\n var test10 = EmptyKeySuppliedToGetDoesNotResultInExceptions ();\n\n\n Console.WriteLine ();\n Console.WriteLine (String.Format(\"Running all IKeyGeneratingCache Api Tests for test case '{0}'...\", testCaseName));\n\n Console.WriteLine (FormatForOutput(\"A valid cache key is returned on `Add`\", test1));\n Console.WriteLine (FormatForOutput(\"The cache miss handler is executed for a non-existent key\", test2));\n Console.WriteLine (FormatForOutput(\"A valid cache key is returned from `Get` for a non-existent key\", test3));\n Console.WriteLine (FormatForOutput(\"A valid cache key is returned from `Get` for a genuine key\", test4));\n Console.WriteLine (FormatForOutput(\"A new cache key is returned for a cache miss\", test5));\n Console.WriteLine (FormatForOutput(\"`Remove` does not throw any exceptions\", test6));\n Console.WriteLine (FormatForOutput(\"The expected data is returned from `Get` for a non-existent key\", test7));\n Console.WriteLine (FormatForOutput(\"The expected data is returned from `Get` for a genuine key\", test8));\n Console.WriteLine (FormatForOutput(\"Null key supplied to `Get` does not result in exceptions\", test9));\n Console.WriteLine (FormatForOutput(\"Empty key supplied to `Get` does not result in exceptions\", test10));\n\n Console.WriteLine (\"...test run complete\");\n Console.WriteLine ();\n\n\n return test1\n && test2\n && test3\n && test4\n && test5\n && test6\n && test7\n && test8\n && test9\n && test10;\n }\n\n public bool AValidCacheKeyIsReturnedOnAdd()\n {\n try\n {\n var resultOfAdd = _testSubject.Add (new System.FileStyleUriParser ());\n return !String.IsNullOrWhiteSpace (resultOfAdd);\n }\n catch(Exception)\n {\n return false;\n }\n }\n\n public bool TheCacheMissHandlerIsExecutedForANonExistentKey()\n {\n var nonExistentKey = Guid.NewGuid ().ToString ();\n var result = false;\n Func cacheMissHandler = () =>\n {\n result = true;\n return new FileStyleUriParser ();\n };\n _testSubject.Get (nonExistentKey, cacheMissHandler);\n return result;\n }\n\n public bool AValidCacheKeyIsReturnedFromGetForANonExistentKey()\n {\n var nonExistentKey = Guid.NewGuid ().ToString ();\n Func cacheMissHandler = () =>\n {\n return new FileStyleUriParser ();\n };\n var cacheMissResult = _testSubject.Get (nonExistentKey, cacheMissHandler);\n return cacheMissResult != null && !String.IsNullOrWhiteSpace (cacheMissResult.Key);\n }\n\n public bool AValidCacheKeyIsReturnedFromGetForAGenuineKey()\n {\n var dataToCache = new FileStyleUriParser ();\n Func cacheMissHandler = () =>\n {\n return new FileStyleUriParser ();\n };\n\n var genuineKey = _testSubject.Add (dataToCache);\n var cachedData = _testSubject.Get (genuineKey, cacheMissHandler);\n\n return cachedData != null && !String.IsNullOrWhiteSpace (cachedData.Key);\n }\n\n public bool ANewCacheKeyIsReturnedForACacheMiss()\n {\n var nonExistentKey = Guid.NewGuid ().ToString ();\n Func cacheMissHandler = () =>\n {\n return new FileStyleUriParser ();\n };\n var cacheMissResult = _testSubject.Get (nonExistentKey, cacheMissHandler);\n return cacheMissResult != null && !nonExistentKey.Equals (cacheMissResult.Key);\n }\n\n public bool RemoveDoesNotThrowAnyExceptions()\n {\n var madeUpKeyForRemoval = Guid.NewGuid ().ToString ();\n try\n {\n _testSubject.Remove(madeUpKeyForRemoval);\n return true;\n }\n catch(Exception)\n {\n return false;\n }\n }\n\n public bool TheExpectedDataIsReturnedFromGetForANonExistentKey()\n {\n var nonExistentKey = Guid.NewGuid ().ToString ();\n var expectedData = new FileStyleUriParser ();\n Func cacheMissHandler = () =>\n {\n return expectedData;\n };\n var getResult = _testSubject.Get (nonExistentKey, cacheMissHandler);\n return getResult.Data.Equals(expectedData);\n }\n\n public bool TheExpectedDataIsReturnedFromGetForAGenuineKey()\n {\n var expectedData = new FileStyleUriParser ();\n Func cacheMissHandler = () =>\n {\n return expectedData;\n };\n var genuineKey = _testSubject.Add (expectedData);\n var getResult = _testSubject.Get (genuineKey, cacheMissHandler);\n return getResult.Data.Equals(expectedData);\n }\n\n public bool NullKeySuppliedToGetDoesNotResultInExceptions()\n {\n string nullKey = null;\n Func cacheMissHandler = () =>\n {\n return new FileStyleUriParser ();\n };\n\n try\n {\n _testSubject.Get (nullKey, cacheMissHandler);\n return true;\n }\n catch (Exception)\n {\n return false;\n }\n }\n\n public bool EmptyKeySuppliedToGetDoesNotResultInExceptions()\n {\n var emptyKey = String.Empty;\n Func cacheMissHandler = () =>\n {\n return new FileStyleUriParser ();\n };\n\n try\n {\n _testSubject.Get (emptyKey, cacheMissHandler);\n return true;\n }\n catch (Exception)\n {\n return false;\n }\n }\n\n\n\n private string FormatForOutput(string testDescription, bool testPassed)\n {\n var resultString = testPassed.ToString ();\n var indentation = \"\\t\";\n if (!testPassed)\n {\n resultString = testPassed.ToString ().ToUpperInvariant () + \"\\t!!!!\";\n indentation = \"!!!!\\t\";\n }\n return indentation + testDescription + \": \" + resultString;\n }\n }\n}\n"},"gt":{"kind":"string","value":""}}},{"rowIdx":96217,"cells":{"context":{"kind":"string","value":"using System;\nusing System.Linq;\nusing System.Collections.Generic;\nusing UnityEngine;\nusing KSP.Localization;\n\n\n\nnamespace KERBALISM\n{\n\n\tpublic class HardDrive : PartModule, IScienceDataContainer, ISpecifics, IModuleInfo, IPartMassModifier, IPartCostModifier\n\t{\n\t\t[KSPField] public double dataCapacity = -1; // base drive capacity, in Mb. -1 = unlimited\n\t\t[KSPField] public int sampleCapacity = -1; // base drive capacity, in slots. -1 = unlimited\n\t\t[KSPField] public string title = \"Kerbodyne ZeroBit\"; // drive name to be displayed in file manager\n\t\t[KSPField] public string experiment_id = string.Empty; // if set, restricts write access to the experiment on the same part, with the given experiment_id.\n\n\t\t[KSPField] public int maxDataCapacityFactor = 4; // how much additional data capacity to allow in editor\n\t\t[KSPField] public int maxSampleCapacityFactor = 4; // how much additional data capacity to allow in editor\n\n\t\t[KSPField] public float dataCapacityCost = 400; // added part cost per data capacity\n\t\t[KSPField] public float dataCapacityMass = 0.005f; // added part mass per data capacity\n\t\t[KSPField] public float sampleCapacityCost = 300; // added part cost per sample capacity\n\t\t[KSPField] public float sampleCapacityMass = 0.008f; // added part mass per sample capacity\n\n\t\t[KSPField(isPersistant = true)] public uint hdId = 0;\n\t\t[KSPField(isPersistant = true)] public double effectiveDataCapacity = -1.0; // effective drive capacity, in Mb. -1 = unlimited\n\t\t[KSPField(isPersistant = true)] public int effectiveSampleCapacity = -1; // effective drive capacity, in slots. -1 = unlimited\n\n\t\t[KSPField(isPersistant = false, guiName = \"#KERBALISM_HardDrive_DataCapacity\", guiActive = false, guiActiveEditor = false, groupName = \"Science\", groupDisplayName = \"#KERBALISM_Group_Science\"), UI_ChooseOption(scene = UI_Scene.Editor)]//Data Capacity--Science\n\t\tpublic string dataCapacityUI = \"0\";\n\t\t[KSPField(isPersistant = false, guiName = \"#KERBALISM_HardDrive_SampleCapacity\", guiActive = false, guiActiveEditor = false, groupName = \"Science\", groupDisplayName = \"#KERBALISM_Group_Science\"), UI_ChooseOption(scene = UI_Scene.Editor)]//Sample Capacity--Science\n\t\tpublic string sampleCapacityUI = \"0\";\n\t\t[KSPField(guiActive = true, guiName = \"#KERBALISM_HardDrive_Capacity\", guiActiveEditor = true, groupName = \"Science\", groupDisplayName = \"#KERBALISM_Group_Science\")]//Capacity--Science\n\t\tpublic string Capacity;\n\n\t\tprivate Drive drive;\n\t\tprivate double totalSampleMass;\n\n\t\tList> dataCapacities = null;\n\t\tList> sampleCapacities = null;\n\n\t\tpublic override void OnStart(StartState state)\n\t\t{\n\t\t\t// don't break tutorial scenarios\n\t\t\tif (Lib.DisableScenario(this)) return;\n\n\t\t\tif (Lib.IsEditor())\n\t\t\t{\n\t\t\t\tif (effectiveDataCapacity == -1.0)\n\t\t\t\t\teffectiveDataCapacity = dataCapacity;\n\n\t\t\t\tif (dataCapacity > 0.0 && maxDataCapacityFactor > 0)\n\t\t\t\t{\n\t\t\t\t\tFields[\"dataCapacityUI\"].guiActiveEditor = true;\n\t\t\t\t\tvar o =(UI_ChooseOption)Fields[\"dataCapacityUI\"].uiControlEditor;\n\n\t\t\t\t\tdataCapacities = GetDataCapacitySizes();\n\t\t\t\t\tint currentCapacityIndex = dataCapacities.FindIndex(p => p.Value == effectiveDataCapacity);\n\t\t\t\t\tif (currentCapacityIndex >= 0)\n\t\t\t\t\t{\n\t\t\t\t\t\tdataCapacityUI = dataCapacities[currentCapacityIndex].Key;\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\teffectiveDataCapacity = dataCapacities[0].Value;\n\t\t\t\t\t\tdataCapacityUI = dataCapacities[0].Key;\n\t\t\t\t\t}\n\n\t\t\t\t\tstring[] dataOptions = new string[dataCapacities.Count];\n\t\t\t\t\tfor(int i = 0; i < dataCapacities.Count; i++)\n\t\t\t\t\t\tdataOptions[i] = Lib.HumanReadableDataSize(dataCapacities[i].Value);\n\t\t\t\t\to.options = dataOptions;\n\t\t\t\t}\n\n\t\t\t\tif (effectiveSampleCapacity == -1)\n\t\t\t\t\teffectiveSampleCapacity = sampleCapacity;\n\n\t\t\t\tif (sampleCapacity > 0 && maxSampleCapacityFactor > 0)\n\t\t\t\t{\n\t\t\t\t\tFields[\"sampleCapacityUI\"].guiActiveEditor = true;\n\t\t\t\t\tvar o = (UI_ChooseOption)Fields[\"sampleCapacityUI\"].uiControlEditor;\n\n\t\t\t\t\tsampleCapacities = GetSampleCapacitySizes();\n\t\t\t\t\tint currentCapacityIndex = sampleCapacities.FindIndex(p => p.Value == effectiveSampleCapacity);\n\t\t\t\t\tif (currentCapacityIndex >= 0)\n\t\t\t\t\t{\n\t\t\t\t\t\tsampleCapacityUI = sampleCapacities[currentCapacityIndex].Key;\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\teffectiveSampleCapacity = sampleCapacities[0].Value;\n\t\t\t\t\t\tsampleCapacityUI = sampleCapacities[0].Key;\n\t\t\t\t\t}\n\n\t\t\t\t\tstring[] sampleOptions = new string[sampleCapacities.Count];\n\t\t\t\t\tfor (int i = 0; i < sampleCapacities.Count; i++)\n\t\t\t\t\t\tsampleOptions[i] = Lib.HumanReadableSampleSize(sampleCapacities[i].Value);\n\t\t\t\t\to.options = sampleOptions;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (Lib.IsFlight() && hdId == 0) hdId = part.flightID;\n\n\t\t\tif (drive == null)\n\t\t\t{\n\t\t\t\tif (!Lib.IsFlight())\n\t\t\t\t{\n\t\t\t\t\tdrive = new Drive(title, effectiveDataCapacity, effectiveSampleCapacity, !string.IsNullOrEmpty(experiment_id));\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tPartData pd = vessel.KerbalismData().GetPartData(part.flightID);\n\t\t\t\t\tif (pd.Drive == null)\n\t\t\t\t\t{\n\t\t\t\t\t\tdrive = new Drive(part.partInfo.title, effectiveDataCapacity, effectiveSampleCapacity, !string.IsNullOrEmpty(experiment_id));\n\t\t\t\t\t\tpd.Drive = drive;\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\tdrive = pd.Drive;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tUpdateCapacity();\n\t\t}\n\n\t\tprotected List> GetDataCapacitySizes()\n\t\t{\n\t\t\tList> result = new List>();\n\t\t\tfor(var i = 1; i <= maxDataCapacityFactor; i++)\n\t\t\t\tresult.Add(new KeyValuePair(Lib.HumanReadableDataSize(dataCapacity * i), dataCapacity * i));\n\t\t\treturn result;\n\t\t}\n\n\t\tprotected List> GetSampleCapacitySizes()\n\t\t{\n\t\t\tList> result = new List>();\n\t\t\tfor (var i = 1; i <= maxSampleCapacityFactor; i++)\n\t\t\t\tresult.Add(new KeyValuePair(Lib.HumanReadableSampleSize(sampleCapacity * i), sampleCapacity * i));\n\t\t\treturn result;\n\t\t}\n\n\t\tpublic void FixedUpdate()\n\t\t{\n\t\t\tUpdateCapacity();\n\t\t}\n\n\t\tpublic void Update()\n\t\t{\n\t\t\tif (drive == null)\n\t\t\t\treturn;\n\n\t\t\tif (Lib.IsEditor())\n\t\t\t{\n\t\t\t\tbool update = false;\n\t\t\t\tif(dataCapacities != null)\n\t\t\t\t{\n\t\t\t\t\tforeach (var c in dataCapacities)\n\t\t\t\t\t\tif (c.Key == dataCapacityUI)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tupdate |= effectiveDataCapacity != c.Value;\n\t\t\t\t\t\t\teffectiveDataCapacity = c.Value;\n\t\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif (sampleCapacities != null)\n\t\t\t\t{\n\t\t\t\t\tforeach (var c in sampleCapacities)\n\t\t\t\t\t\tif (c.Key == sampleCapacityUI)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tupdate |= effectiveSampleCapacity != c.Value;\n\t\t\t\t\t\t\teffectiveSampleCapacity = c.Value;\n\t\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tdrive.dataCapacity = effectiveDataCapacity;\n\t\t\t\tdrive.sampleCapacity = effectiveSampleCapacity;\n\n\t\t\t\tFields[\"sampleCapacityUI\"].guiActiveEditor = sampleCapacity > 0 && !IsPrivate();\n\t\t\t\tFields[\"dataCapacityUI\"].guiActiveEditor = dataCapacity > 0 && !IsPrivate();\n\n\t\t\t\tif (update)\n\t\t\t\t{\n\t\t\t\t\tGameEvents.onEditorShipModified.Fire(EditorLogic.fetch.ship);\n\t\t\t\t\tUpdateCapacity();\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (Lib.IsFlight())\n\t\t\t{\n\t\t\t\t// show DATA UI button, with size info\n\t\t\t\tEvents[\"ToggleUI\"].guiName = Lib.StatusToggle(Local.HardDrive_Data, drive.Empty() ? Local.HardDrive_Dataempty : drive.Size());//\"Data\"\"empty\"\n\t\t\t\tEvents[\"ToggleUI\"].active = !IsPrivate();\n\n\t\t\t\t// show TakeData eva action button, if there is something to take\n\t\t\t\tEvents[\"TakeData\"].active = !drive.Empty();\n\n\t\t\t\t// show StoreData eva action button, if active vessel is an eva kerbal and there is something to store from it\n\t\t\t\tVessel v = FlightGlobals.ActiveVessel;\n\t\t\t\tEvents[\"StoreData\"].active = !IsPrivate() && v != null && v.isEVA && !EVA.IsDead(v);\n\n\t\t\t\t// hide TransferLocation button\n\t\t\t\tvar transferVisible = !IsPrivate();\n\t\t\t\tif(transferVisible)\n\t\t\t\t{\n\t\t\t\t\ttransferVisible = Drive.GetDrives(vessel, true).Count > 1;\n\t\t\t\t}\n\t\t\t\tEvents[\"TransferData\"].active = transferVisible;\n\t\t\t\tEvents[\"TransferData\"].guiActive = transferVisible;\n\t\t\t}\n\t\t}\n\n\t\tpublic bool IsPrivate()\n\t\t{\n\t\t\treturn drive.is_private;\n\t\t}\n\n\t\tprivate void UpdateCapacity()\n\t\t{\n\t\t\tif (drive == null)\n\t\t\t\treturn;\n\t\t\t\n\t\t\tdouble mass = 0;\n\t\t\tforeach (var sample in drive.samples.Values) mass += sample.mass;\n\t\t\ttotalSampleMass = mass;\n\n\t\t\tif (effectiveDataCapacity < 0 || effectiveSampleCapacity < 0 || IsPrivate())\n\t\t\t{\n\t\t\t\tFields[\"Capacity\"].guiActive = false;\n\t\t\t\tFields[\"Capacity\"].guiActiveEditor = false;\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tdouble availableDataCapacity = effectiveDataCapacity;\n\t\t\tint availableSlots = effectiveSampleCapacity;\n\n\t\t\tif (Lib.IsFlight())\n\t\t\t{\n\t\t\t\tavailableDataCapacity = drive.FileCapacityAvailable();\n\t\t\t\tavailableSlots = Lib.SampleSizeToSlots(drive.SampleCapacityAvailable());\n\t\t\t}\n\n\t\t\tCapacity = string.Empty;\n\t\t\tif(availableDataCapacity > double.Epsilon)\n\t\t\t\tCapacity = Lib.HumanReadableDataSize(availableDataCapacity);\n\t\t\tif(availableSlots > 0)\n\t\t\t{\n\t\t\t\tif (Capacity.Length > 0) Capacity += \" \";\n\t\t\t\tCapacity += Lib.HumanReadableSampleSize(availableSlots);\n\t\t\t}\n\n\t\t\tif(Lib.IsFlight() && totalSampleMass > double.Epsilon)\n\t\t\t{\n\t\t\t\tCapacity += \" \" + Lib.HumanReadableMass(totalSampleMass);\n\t\t\t}\n\t\t}\n\n\t\tpublic Drive GetDrive()\n\t\t{\n\t\t\treturn drive;\n\t\t}\n\n\t\t[KSPEvent(guiActive = true, guiName = \"_\", active = true, groupName = \"Science\", groupDisplayName = \"#KERBALISM_Group_Science\")]//Science\n\t\tpublic void ToggleUI()\n\t\t{\n\t\t\tUI.Open((Panel p) => p.Fileman(vessel));\n\t\t}\n\n\t\t[KSPEvent(guiName = \"#KERBALISM_HardDrive_TransferData\", active = false, groupName = \"Science\", groupDisplayName = \"#KERBALISM_Group_Science\")]//Science\n\t\tpublic void TransferData()\n\t\t{\n\t\t\tvar hardDrives = vessel.FindPartModulesImplementing();\n\t\t\tforeach(var hardDrive in hardDrives)\n\t\t\t{\n\t\t\t\tif (hardDrive == this) continue;\n\t\t\t\thardDrive.drive.Move(drive, PreferencesScience.Instance.sampleTransfer || Lib.CrewCount(vessel) > 0);\n\t\t\t}\n\t\t}\n\n\t\t[KSPEvent(guiActive = false, guiActiveUnfocused = true, guiActiveUncommand = true, guiName = \"#KERBALISM_HardDrive_TakeData\", active = true, groupName = \"Science\", groupDisplayName = \"#KERBALISM_Group_Science\")]//Science\n\t\tpublic void TakeData()\n\t\t{\n\t\t\t// disable for dead eva kerbals\n\t\t\tVessel v = FlightGlobals.ActiveVessel;\n\t\t\tif (v == null || EVA.IsDead(v)) return;\n\n\t\t\t// transfer data\n\t\t\tif(!Drive.Transfer(drive, v, PreferencesScience.Instance.sampleTransfer || Lib.CrewCount(v) > 0))\n\t\t\t{\n\t\t\t\tMessage.Post\n\t\t\t\t(\n\t\t\t\t\tLib.Color(Lib.BuildString(Local.HardDrive_WARNING_title), Lib.Kolor.Red, true),//\"WARNING: not evering copied\"\n\t\t\t\t\tLib.BuildString(Local.HardDrive_WARNING)//\"Storage is at capacity\"\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\n\t\t[KSPEvent(guiActive = false, guiActiveUnfocused = true, guiActiveUncommand = true, guiName = \"#KERBALISM_HardDrive_TransferData\", active = true, groupName = \"Science\", groupDisplayName = \"#KERBALISM_Group_Science\")]//Science\n\t\tpublic void StoreData()\n\t\t{\n\t\t\t// disable for dead eva kerbals\n\t\t\tVessel v = FlightGlobals.ActiveVessel;\n\t\t\tif (v == null || EVA.IsDead(v)) return;\n\n\t\t\t// transfer data\n\t\t\tif(!Drive.Transfer(v, drive, PreferencesScience.Instance.sampleTransfer || Lib.CrewCount(v) > 0))\n\t\t\t{\n\t\t\t\tMessage.Post\n\t\t\t\t(\n\t\t\t\t\tLib.Color(Lib.BuildString(Local.HardDrive_WARNING_title), Lib.Kolor.Red, true),//\"WARNING: not evering copied\"\n\t\t\t\t\tLib.BuildString(Local.HardDrive_WARNING)//\"Storage is at capacity\"\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\n\n\t\t// part tooltip\n\t\tpublic override string GetInfo()\n\t\t{\n\t\t\treturn Specs().Info();\n\t\t}\n\n\t\t// science container implementation\n\t\tpublic ScienceData[] GetData()\n\t\t{\n\t\t\t// generate and return stock science data\n\t\t\tList data = new List();\n\n\t\t\t// this might be called before we had the chance to execute our OnStart() method\n\t\t\t// (looking at you, RasterPropMonitor)\n\t\t\tif(drive != null)\n\t\t\t{\n\t\t\t\tforeach (File file in drive.files.Values)\n\t\t\t\t\tdata.Add(file.ConvertToStockData());\n\n\t\t\t\tforeach (Sample sample in drive.samples.Values)\n\t\t\t\t\tdata.Add(sample.ConvertToStockData());\n\t\t\t}\n\n\t\t\treturn data.ToArray();\n\t\t}\n\n\t\t// TODO do something about limited capacity...\n\t\t// EVAs returning should get a warning if needed\n\t\t// TODO : this should not be used for EVA boarding, too much information is lost in the conversion\n\t\tpublic void ReturnData(ScienceData data)\n\t\t{\n\t\t\tSubjectData subjectData = ScienceDB.GetSubjectDataFromStockId(data.subjectID);\n\t\t\tif (subjectData == null)\n\t\t\t\treturn;\n\n\t\t\tif (data.baseTransmitValue > Science.maxXmitDataScalarForSample || data.transmitBonus > Science.maxXmitDataScalarForSample)\n\t\t\t{\n\t\t\t\tdrive.Record_file(subjectData, data.dataAmount);\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tdrive.Record_sample(subjectData, data.dataAmount, subjectData.ExpInfo.MassPerMB * data.dataAmount);\n\t\t\t}\n\t\t}\n\n\t\tpublic void DumpData(ScienceData data)\n\t\t{\n\t\t\tSubjectData subjectData = ScienceDB.GetSubjectDataFromStockId(data.subjectID);\n\t\t\t// remove the data\n\t\t\tif (data.baseTransmitValue > float.Epsilon || data.transmitBonus > float.Epsilon)\n\t\t\t{\n\t\t\t\tdrive.Delete_file(subjectData, data.dataAmount);\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tdrive.Delete_sample(subjectData, data.dataAmount);\n\t\t\t}\n\t\t}\n\n\t\tpublic void ReviewData()\n\t\t{\n\t\t\tUI.Open((p) => p.Fileman(vessel));\n\t\t}\n\n\t\tpublic void ReviewDataItem(ScienceData data)\n\t\t{\n\t\t\tReviewData();\n\t\t}\n\n\t\tpublic int GetScienceCount()\n\t\t{\n\t\t\t// We are forced to return zero, or else EVA kerbals re-entering a pod\n\t\t\t// will complain about being unable to store the data (but they shouldn't)\n\t\t\treturn 0;\n\n\t\t\t/*Drive drive = DB.Vessel(vessel).drive;\n\n\t\t\t// if not the preferred drive\n\t\t\tif (drive.location != part.flightID) return 0;\n\n\t\t\t// return number of entries\n\t\t\treturn drive.files.Count + drive.samples.Count;*/\n\t\t}\n\n\t\tpublic bool IsRerunnable()\n\t\t{\n\t\t\t// don't care\n\t\t\treturn false;\n\t\t}\n\n\t\t//public override string GetModuleDisplayName() { return \"Hard Drive\"; }\n\n\t\t// specifics support\n\t\tpublic Specifics Specs()\n\t\t{\n\t\t\tSpecifics specs = new Specifics();\n\t\t\tspecs.Add(Local.HardDrive_info1, dataCapacity >= 0 ? Lib.HumanReadableDataSize(dataCapacity) : Local.HardDrive_Capacityunlimited);//\"File capacity\"\"unlimited\"\n\t\t\tspecs.Add(Local.HardDrive_info2, sampleCapacity >= 0 ? Lib.HumanReadableSampleSize(sampleCapacity) : Local.HardDrive_Capacityunlimited);//\"Sample capacity\"\"unlimited\"\n\t\t\treturn specs;\n\t\t}\n\n\t\t// module info support\n\t\tpublic string GetModuleTitle() { return \"Hard Drive\"; }\n\t\tpublic override string GetModuleDisplayName() { return Local.HardDrive; }//\"Hard Drive\"\n\t\tpublic string GetPrimaryField() { return string.Empty; }\n\t\tpublic Callback GetDrawModulePanelCallback() { return null; }\n\n\t\t// module mass support\n\t\tpublic float GetModuleMass(float defaultMass, ModifierStagingSituation sit) {\n\t\t\tdouble result = totalSampleMass;\n\n\t\t\tif (effectiveSampleCapacity > sampleCapacity && sampleCapacity > 0)\n\t\t\t{\n\t\t\t\tvar sampleMultiplier = (effectiveSampleCapacity / sampleCapacity) - 1;\n\t\t\t\tresult += sampleMultiplier * sampleCapacityMass;\n\t\t\t}\n\n\t\t\tif (effectiveDataCapacity > dataCapacity && dataCapacity > 0)\n\t\t\t{\n\t\t\t\tvar dataMultiplier = (effectiveDataCapacity / dataCapacity) - 1.0;\n\t\t\t\tresult += dataMultiplier * dataCapacityMass;\n\t\t\t}\n\n\t\t\tif(Double.IsNaN(result))\n\t\t\t{\n\t\t\t\tLib.Log(\"Drive mass is NaN: esc \" + effectiveSampleCapacity + \" scm \" + sampleCapacityMass + \" dedcm \" + effectiveDataCapacity + \" dcm \" + dataCapacityMass + \" tsm \" + totalSampleMass);\n\t\t\t\treturn 0;\n\t\t\t}\n\n\t\t\treturn (float)result;\n\t\t}\n\t\tpublic ModifierChangeWhen GetModuleMassChangeWhen() { return ModifierChangeWhen.CONSTANTLY; }\n\n\t\t// module cost support\n\t\tpublic float GetModuleCost(float defaultCost, ModifierStagingSituation sit)\n\t\t{\n\t\t\tdouble result = 0;\n\n\t\t\tif(effectiveSampleCapacity > sampleCapacity && sampleCapacity > 0)\n\t\t\t{\n\t\t\t\tvar sampleMultiplier = (effectiveSampleCapacity / sampleCapacity) - 1;\n\t\t\t\tresult += sampleMultiplier * sampleCapacityCost;\n\t\t\t}\n\n\t\t\tif (effectiveDataCapacity > dataCapacity && dataCapacity > 0)\n\t\t\t{\n\t\t\t\tvar dataMultiplier = (effectiveDataCapacity / dataCapacity) - 1.0;\n\t\t\t\tresult += dataMultiplier * dataCapacityCost;\n\t\t\t}\n\n\t\t\treturn (float)result;\n\t\t}\n\t\tpublic ModifierChangeWhen GetModuleCostChangeWhen() { return ModifierChangeWhen.CONSTANTLY; }\n\t}\n\n\n} // KERBALISM\n\n\n"},"gt":{"kind":"string","value":""}}},{"rowIdx":96218,"cells":{"context":{"kind":"string","value":"/*\n * Copyright (c) Contributors, http://opensimulator.org/\n * See CONTRIBUTORS.TXT for a full list of copyright holders.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n * * Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and/or other materials provided with the distribution.\n * * Neither the name of the OpenSimulator Project nor the\n * names of its contributors may be used to endorse or promote products\n * derived from this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY\n * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY\n * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */\n\nusing Mono.Addins;\nusing Nini.Config;\nusing OpenMetaverse;\nusing OpenSim.Framework;\nusing OpenSim.Region.Framework.Interfaces;\nusing OpenSim.Region.Framework.Scenes;\nusing OpenSim.Region.Framework.Scenes.Serialization;\nusing System;\nusing System.Collections.Generic;\nusing PermissionMask = OpenSim.Framework.PermissionMask;\n\nnamespace OpenSim.Region.CoreModules.World.Objects.BuySell\n{\n [Extension(Path = \"/OpenSim/RegionModules\", NodeName = \"RegionModule\", Id = \"BuySellModule\")]\n public class BuySellModule : IBuySellModule, INonSharedRegionModule\n {\n// private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);\n \n protected Scene m_scene = null;\n protected IDialogModule m_dialogModule;\n \n public string Name { get { return \"Object BuySell Module\"; } }\n public Type ReplaceableInterface { get { return null; } }\n\n public void Initialise(IConfigSource source) {}\n \n public void AddRegion(Scene scene)\n {\n m_scene = scene;\n m_scene.RegisterModuleInterface(this);\n m_scene.EventManager.OnNewClient += SubscribeToClientEvents;\n }\n \n public void RemoveRegion(Scene scene) \n {\n m_scene.EventManager.OnNewClient -= SubscribeToClientEvents;\n }\n \n public void RegionLoaded(Scene scene) \n {\n m_dialogModule = scene.RequestModuleInterface();\n }\n \n public void Close() \n {\n RemoveRegion(m_scene);\n }\n \n public void SubscribeToClientEvents(IClientAPI client)\n {\n client.OnObjectSaleInfo += ObjectSaleInfo;\n }\n\n protected void ObjectSaleInfo(\n IClientAPI client, UUID agentID, UUID sessionID, uint localID, byte saleType, int salePrice)\n {\n SceneObjectPart part = m_scene.GetSceneObjectPart(localID);\n if (part == null)\n return;\n\n if (part.ParentGroup.IsDeleted)\n return;\n\n if (part.OwnerID != client.AgentId && (!m_scene.Permissions.IsGod(client.AgentId)))\n return;\n\n part = part.ParentGroup.RootPart;\n\n part.ObjectSaleType = saleType;\n part.SalePrice = salePrice;\n\n part.ParentGroup.HasGroupChanged = true;\n\n part.SendPropertiesToClient(client);\n }\n\n public bool BuyObject(IClientAPI remoteClient, UUID categoryID, uint localID, byte saleType, int salePrice)\n {\n SceneObjectPart part = m_scene.GetSceneObjectPart(localID);\n\n if (part == null)\n return false;\n\n SceneObjectGroup group = part.ParentGroup;\n\n switch (saleType)\n {\n case 1: // Sell as original (in-place sale)\n uint effectivePerms = group.GetEffectivePermissions();\n\n if ((effectivePerms & (uint)PermissionMask.Transfer) == 0)\n {\n if (m_dialogModule != null)\n m_dialogModule.SendAlertToUser(remoteClient, \"This item doesn't appear to be for sale\");\n return false;\n }\n\n group.SetOwnerId(remoteClient.AgentId);\n group.SetRootPartOwner(part, remoteClient.AgentId, remoteClient.ActiveGroupId);\n\n if (m_scene.Permissions.PropagatePermissions())\n {\n foreach (SceneObjectPart child in group.Parts)\n {\n child.Inventory.ChangeInventoryOwner(remoteClient.AgentId);\n child.TriggerScriptChangedEvent(Changed.OWNER);\n child.ApplyNextOwnerPermissions();\n }\n }\n\n part.ObjectSaleType = 0;\n part.SalePrice = 10;\n part.ClickAction = Convert.ToByte(0);\n\n group.HasGroupChanged = true;\n part.SendPropertiesToClient(remoteClient);\n part.TriggerScriptChangedEvent(Changed.OWNER);\n group.ResumeScripts();\n part.ScheduleFullUpdate();\n\n break;\n\n case 2: // Sell a copy\n Vector3 inventoryStoredPosition = new Vector3(\n Math.Min(group.AbsolutePosition.X, m_scene.RegionInfo.RegionSizeX - 6),\n Math.Min(group.AbsolutePosition.Y, m_scene.RegionInfo.RegionSizeY - 6),\n group.AbsolutePosition.Z);\n\n Vector3 originalPosition = group.AbsolutePosition;\n\n group.AbsolutePosition = inventoryStoredPosition;\n\n string sceneObjectXml = SceneObjectSerializer.ToOriginalXmlFormat(group);\n group.AbsolutePosition = originalPosition;\n\n uint perms = group.GetEffectivePermissions();\n\n if ((perms & (uint)PermissionMask.Transfer) == 0)\n {\n if (m_dialogModule != null)\n m_dialogModule.SendAlertToUser(remoteClient, \"This item doesn't appear to be for sale\");\n return false;\n }\n\n AssetBase asset = m_scene.CreateAsset(\n group.GetPartName(localID),\n group.GetPartDescription(localID),\n (sbyte)AssetType.Object,\n Utils.StringToBytes(sceneObjectXml),\n group.OwnerID);\n m_scene.AssetService.Store(asset);\n\n InventoryItemBase item = new InventoryItemBase();\n item.CreatorId = part.CreatorID.ToString();\n item.CreatorData = part.CreatorData;\n\n item.ID = UUID.Random();\n item.Owner = remoteClient.AgentId;\n item.AssetID = asset.FullID;\n item.Description = asset.Description;\n item.Name = asset.Name;\n item.AssetType = asset.Type;\n item.InvType = (int)InventoryType.Object;\n item.Folder = categoryID;\n\n PermissionsUtil.ApplyFoldedPermissions(perms, ref perms);\n\n item.BasePermissions = perms & part.NextOwnerMask;\n item.CurrentPermissions = perms & part.NextOwnerMask;\n item.NextPermissions = part.NextOwnerMask;\n item.EveryOnePermissions = part.EveryoneMask &\n part.NextOwnerMask;\n item.GroupPermissions = part.GroupMask &\n part.NextOwnerMask;\n item.Flags |= (uint)InventoryItemFlags.ObjectSlamPerm;\n item.CreationDate = Util.UnixTimeSinceEpoch();\n\n if (m_scene.AddInventoryItem(item))\n {\n remoteClient.SendInventoryItemCreateUpdate(item, 0);\n }\n else\n {\n if (m_dialogModule != null)\n m_dialogModule.SendAlertToUser(remoteClient, \"Cannot buy now. Your inventory is unavailable\");\n return false;\n }\n break;\n\n case 3: // Sell contents\n List invList = part.Inventory.GetInventoryList();\n\n bool okToSell = true;\n\n foreach (UUID invID in invList)\n {\n TaskInventoryItem item1 = part.Inventory.GetInventoryItem(invID);\n if ((item1.CurrentPermissions &\n (uint)PermissionMask.Transfer) == 0)\n {\n okToSell = false;\n break;\n }\n }\n\n if (!okToSell)\n {\n if (m_dialogModule != null)\n m_dialogModule.SendAlertToUser(\n remoteClient, \"This item's inventory doesn't appear to be for sale\");\n return false;\n }\n\n if (invList.Count > 0)\n m_scene.MoveTaskInventoryItems(remoteClient.AgentId, part.Name, part, invList);\n break;\n }\n\n return true;\n }\n }\n}\n"},"gt":{"kind":"string","value":""}}},{"rowIdx":96219,"cells":{"context":{"kind":"string","value":"using Orleans.Serialization.Buffers;\nusing Orleans.Serialization.Codecs;\nusing Orleans.Serialization.Serializers;\nusing Orleans.Serialization.TypeSystem;\nusing Orleans.Serialization.WireProtocol;\nusing System;\nusing System.Buffers;\nusing System.Collections.Concurrent;\nusing System.Runtime.Serialization;\nusing System.Security;\n\nnamespace Orleans.Serialization.ISerializableSupport\n{\n [WellKnownAlias(\"ISerializable\")]\n public class DotNetSerializableCodec : IGeneralizedCodec\n {\n public static readonly Type CodecType = typeof(DotNetSerializableCodec);\n private static readonly Type SerializableType = typeof(ISerializable);\n private readonly SerializationCallbacksFactory _serializationCallbacks;\n private readonly Func> _createConstructorDelegate;\n private readonly ConcurrentDictionary> _constructors = new();\n private readonly IFormatterConverter _formatterConverter;\n private readonly StreamingContext _streamingContext;\n private readonly SerializationEntryCodec _entrySerializer;\n private readonly TypeConverter _typeConverter;\n private readonly ValueTypeSerializerFactory _valueTypeSerializerFactory;\n\n public DotNetSerializableCodec(TypeConverter typeResolver)\n {\n _streamingContext = new StreamingContext(StreamingContextStates.All);\n _typeConverter = typeResolver;\n _entrySerializer = new SerializationEntryCodec();\n _serializationCallbacks = new SerializationCallbacksFactory();\n _formatterConverter = new FormatterConverter();\n var constructorFactory = new SerializationConstructorFactory();\n _createConstructorDelegate = constructorFactory.GetSerializationConstructorDelegate;\n\n _valueTypeSerializerFactory = new ValueTypeSerializerFactory(\n _entrySerializer,\n constructorFactory,\n _serializationCallbacks,\n _formatterConverter,\n _streamingContext);\n }\n\n [SecurityCritical]\n public void WriteField(ref Writer writer, uint fieldIdDelta, Type expectedType, object value) where TBufferWriter : IBufferWriter\n {\n if (ReferenceCodec.TryWriteReferenceField(ref writer, fieldIdDelta, expectedType, value))\n {\n return;\n }\n\n var type = value.GetType();\n writer.WriteFieldHeader(fieldIdDelta, expectedType, CodecType, WireType.TagDelimited);\n if (type.IsValueType)\n {\n var serializer = _valueTypeSerializerFactory.GetSerializer(type);\n serializer.WriteValue(ref writer, value);\n }\n else\n {\n WriteObject(ref writer, type, value);\n }\n\n writer.WriteEndObject();\n }\n\n [SecurityCritical]\n public object ReadValue(ref Reader reader, Field field)\n {\n if (field.WireType == WireType.Reference)\n {\n return ReferenceCodec.ReadReference(ref reader, field);\n }\n\n var placeholderReferenceId = ReferenceCodec.CreateRecordPlaceholder(reader.Session);\n Type type;\n var header = reader.ReadFieldHeader();\n var flags = Int32Codec.ReadValue(ref reader, header);\n if (flags == 1)\n {\n // This is an exception type, so deserialize it as an exception.\n header = reader.ReadFieldHeader();\n var typeName = StringCodec.ReadValue(ref reader, header);\n if (!_typeConverter.TryParse(typeName, out type))\n {\n return ReadFallbackException(ref reader, typeName, placeholderReferenceId);\n }\n }\n else\n {\n header = reader.ReadFieldHeader();\n type = TypeSerializerCodec.ReadValue(ref reader, header);\n }\n\n if (type.IsValueType)\n {\n var serializer = _valueTypeSerializerFactory.GetSerializer(type);\n return serializer.ReadValue(ref reader, type);\n }\n\n return ReadObject(ref reader, type, placeholderReferenceId);\n }\n\n private object ReadFallbackException(ref Reader reader, string typeName, uint placeholderReferenceId)\n {\n // Deserialize into a fallback type for unknown exceptions. This means that missing fields will not be represented.\n var result = (UnavailableExceptionFallbackException)ReadObject(ref reader, typeof(UnavailableExceptionFallbackException), placeholderReferenceId);\n result.ExceptionType = typeName;\n return result;\n }\n\n private object ReadObject(ref Reader reader, Type type, uint placeholderReferenceId)\n {\n var callbacks = _serializationCallbacks.GetReferenceTypeCallbacks(type);\n\n var info = new SerializationInfo(type, _formatterConverter);\n var result = FormatterServices.GetUninitializedObject(type);\n ReferenceCodec.RecordObject(reader.Session, result, placeholderReferenceId);\n callbacks.OnDeserializing?.Invoke(result, _streamingContext);\n\n uint fieldId = 0;\n while (true)\n {\n var header = reader.ReadFieldHeader();\n if (header.IsEndBaseOrEndObject)\n {\n break;\n }\n\n fieldId += header.FieldIdDelta;\n if (fieldId == 1)\n {\n var entry = _entrySerializer.ReadValue(ref reader, header);\n if (entry.ObjectType is { } entryType)\n {\n info.AddValue(entry.Name, entry.Value, entryType);\n }\n else\n {\n info.AddValue(entry.Name, entry.Value);\n }\n }\n else\n {\n reader.ConsumeUnknownField(header);\n }\n }\n\n var constructor = _constructors.GetOrAdd(info.ObjectType, _createConstructorDelegate);\n constructor(result, info, _streamingContext);\n callbacks.OnDeserialized?.Invoke(result, _streamingContext);\n if (result is IDeserializationCallback callback)\n {\n callback.OnDeserialization(_streamingContext.Context);\n }\n\n return result;\n }\n\n\n private void WriteObject(ref Writer writer, Type type, object value) where TBufferWriter : IBufferWriter\n {\n var callbacks = _serializationCallbacks.GetReferenceTypeCallbacks(type);\n var info = new SerializationInfo(type, _formatterConverter);\n\n // Serialize the type name according to the value populated in the SerializationInfo.\n if (value is Exception)\n {\n // Indicate that this is an exception\n Int32Codec.WriteField(ref writer, 0, typeof(int), 1);\n\n // For exceptions, the type is serialized as a string to facilitate safe deserialization.\n var typeName = _typeConverter.Format(info.ObjectType);\n StringCodec.WriteField(ref writer, 1, typeof(string), typeName);\n }\n else\n {\n // Indicate that this is not an exception\n Int32Codec.WriteField(ref writer, 0, typeof(int), 0);\n\n TypeSerializerCodec.WriteField(ref writer, 1, typeof(Type), info.ObjectType);\n }\n\n callbacks.OnSerializing?.Invoke(value, _streamingContext);\n ((ISerializable)value).GetObjectData(info, _streamingContext);\n\n var first = true;\n foreach (var field in info)\n {\n var surrogate = new SerializationEntrySurrogate\n {\n Name = field.Name,\n Value = field.Value,\n ObjectType = field.ObjectType\n };\n\n _entrySerializer.WriteField(ref writer, first ? 1 : (uint)0, SerializationEntryCodec.SerializationEntryType, surrogate);\n if (first)\n {\n first = false;\n }\n }\n\n callbacks.OnSerialized?.Invoke(value, _streamingContext);\n }\n\n [SecurityCritical]\n public bool IsSupportedType(Type type) =>\n type == CodecType || typeof(Exception).IsAssignableFrom(type) || (SerializableType.IsAssignableFrom(type) && SerializationConstructorFactory.HasSerializationConstructor(type));\n }\n}\n"},"gt":{"kind":"string","value":""}}},{"rowIdx":96220,"cells":{"context":{"kind":"string","value":"/*\n * Copyright (c) Contributors, http://opensimulator.org/\n * See CONTRIBUTORS.TXT for a full list of copyright holders.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n * * Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and/or other materials provided with the distribution.\n * * Neither the name of the OpenSimulator Project nor the\n * names of its contributors may be used to endorse or promote products\n * derived from this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY\n * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY\n * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */\n\nusing System;\nusing System.Collections.Generic;\nusing System.Reflection;\nusing System.Threading;\nusing System.Timers;\nusing log4net;\nusing OpenMetaverse;\nusing OpenSim.Framework;\nusing OpenSim.Framework.Serialization;\nusing OpenSim.Services.Interfaces;\n\nnamespace OpenSim.Region.CoreModules.World.Archiver\n{\n /// \n /// Encapsulate the asynchronous requests for the assets required for an archive operation\n /// \n class AssetsRequest\n {\n private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);\n\n enum RequestState\n {\n Initial,\n Running,\n Completed,\n Aborted\n };\n \n /// \n /// Timeout threshold if we still need assets or missing asset notifications but have stopped receiving them\n /// from the asset service\n /// \n protected const int TIMEOUT = 60 * 1000;\n\n /// \n /// If a timeout does occur, limit the amount of UUID information put to the console.\n /// \n protected const int MAX_UUID_DISPLAY_ON_TIMEOUT = 3;\n \n protected System.Timers.Timer m_requestCallbackTimer;\n\n /// \n /// State of this request\n /// \n private RequestState m_requestState = RequestState.Initial;\n \n /// \n /// uuids to request\n /// \n protected IDictionary m_uuids;\n\n /// \n /// Callback used when all the assets requested have been received.\n /// \n protected AssetsRequestCallback m_assetsRequestCallback;\n\n /// \n /// List of assets that were found. This will be passed back to the requester.\n /// \n protected List m_foundAssetUuids = new List();\n \n /// \n /// Maintain a list of assets that could not be found. This will be passed back to the requester.\n /// \n protected List m_notFoundAssetUuids = new List();\n\n /// \n /// Record the number of asset replies required so we know when we've finished\n /// \n private int m_repliesRequired;\n\n /// \n /// Asset service used to request the assets\n /// \n protected IAssetService m_assetService;\n\n protected AssetsArchiver m_assetsArchiver;\n\n protected internal AssetsRequest(\n AssetsArchiver assetsArchiver, IDictionary uuids, \n IAssetService assetService, AssetsRequestCallback assetsRequestCallback)\n {\n m_assetsArchiver = assetsArchiver;\n m_uuids = uuids;\n m_assetsRequestCallback = assetsRequestCallback;\n m_assetService = assetService;\n m_repliesRequired = uuids.Count;\n\n m_requestCallbackTimer = new System.Timers.Timer(TIMEOUT);\n m_requestCallbackTimer.AutoReset = false;\n m_requestCallbackTimer.Elapsed += new ElapsedEventHandler(OnRequestCallbackTimeout);\n }\n\n protected internal void Execute()\n {\n m_requestState = RequestState.Running;\n \n m_log.DebugFormat(\"[ARCHIVER]: AssetsRequest executed looking for {0} assets\", m_repliesRequired);\n \n // We can stop here if there are no assets to fetch\n if (m_repliesRequired == 0)\n {\n m_requestState = RequestState.Completed;\n PerformAssetsRequestCallback(null);\n return;\n }\n \n foreach (KeyValuePair kvp in m_uuids)\n {\n m_assetService.Get(kvp.Key.ToString(), kvp.Value, PreAssetRequestCallback);\n }\n\n m_requestCallbackTimer.Enabled = true;\n }\n\n protected void OnRequestCallbackTimeout(object source, ElapsedEventArgs args)\n {\n try\n {\n lock (this)\n {\n // Take care of the possibilty that this thread started but was paused just outside the lock before\n // the final request came in (assuming that such a thing is possible)\n if (m_requestState == RequestState.Completed)\n return;\n \n m_requestState = RequestState.Aborted;\n }\n\n // Calculate which uuids were not found. This is an expensive way of doing it, but this is a failure\n // case anyway.\n List uuids = new List();\n foreach (UUID uuid in m_uuids.Keys)\n {\n uuids.Add(uuid);\n }\n\n foreach (UUID uuid in m_foundAssetUuids)\n {\n uuids.Remove(uuid);\n }\n \n foreach (UUID uuid in m_notFoundAssetUuids)\n {\n uuids.Remove(uuid);\n }\n \n m_log.ErrorFormat(\n \"[ARCHIVER]: Asset service failed to return information about {0} requested assets\", uuids.Count);\n \n int i = 0;\n foreach (UUID uuid in uuids)\n {\n m_log.ErrorFormat(\"[ARCHIVER]: No information about asset {0} received\", uuid);\n \n if (++i >= MAX_UUID_DISPLAY_ON_TIMEOUT)\n break;\n }\n \n if (uuids.Count > MAX_UUID_DISPLAY_ON_TIMEOUT)\n m_log.ErrorFormat(\n \"[ARCHIVER]: (... {0} more not shown)\", uuids.Count - MAX_UUID_DISPLAY_ON_TIMEOUT);\n\n m_log.Error(\"[ARCHIVER]: OAR save aborted.\");\n }\n catch (Exception e)\n {\n m_log.ErrorFormat(\"[ARCHIVER]: Timeout handler exception {0}\", e);\n }\n finally\n {\n m_assetsArchiver.ForceClose();\n }\n }\n\n protected void PreAssetRequestCallback(string fetchedAssetID, object assetType, AssetBase fetchedAsset)\n {\n // Check for broken asset types and fix them with the AssetType gleaned by UuidGatherer\n if (fetchedAsset != null && fetchedAsset.Type == (sbyte)AssetType.Unknown)\n {\n AssetType type = (AssetType)assetType;\n m_log.InfoFormat(\"[ARCHIVER]: Rewriting broken asset type for {0} to {1}\", fetchedAsset.ID, type);\n fetchedAsset.Type = (sbyte)type;\n }\n\n AssetRequestCallback(fetchedAssetID, this, fetchedAsset);\n }\n\n /// \n /// Called back by the asset cache when it has the asset\n /// \n /// \n /// \n public void AssetRequestCallback(string id, object sender, AssetBase asset)\n {\n try\n {\n lock (this)\n {\n //m_log.DebugFormat(\"[ARCHIVER]: Received callback for asset {0}\", id);\n \n m_requestCallbackTimer.Stop();\n \n if (m_requestState == RequestState.Aborted)\n {\n m_log.WarnFormat(\n \"[ARCHIVER]: Received information about asset {0} after archive save abortion. Ignoring.\", \n id);\n\n return;\n }\n \n if (asset != null)\n {\n// m_log.DebugFormat(\"[ARCHIVER]: Writing asset {0}\", id);\n m_foundAssetUuids.Add(asset.FullID);\n m_assetsArchiver.WriteAsset(asset);\n }\n else\n {\n// m_log.DebugFormat(\"[ARCHIVER]: Recording asset {0} as not found\", id);\n m_notFoundAssetUuids.Add(new UUID(id));\n }\n \n if (m_foundAssetUuids.Count + m_notFoundAssetUuids.Count == m_repliesRequired)\n {\n m_requestState = RequestState.Completed;\n \n m_log.DebugFormat(\n \"[ARCHIVER]: Successfully added {0} assets ({1} assets notified missing)\", \n m_foundAssetUuids.Count, m_notFoundAssetUuids.Count);\n \n // We want to stop using the asset cache thread asap \n // as we now need to do the work of producing the rest of the archive\n Util.FireAndForget(PerformAssetsRequestCallback);\n }\n else\n {\n m_requestCallbackTimer.Start();\n }\n }\n }\n catch (Exception e)\n {\n m_log.ErrorFormat(\"[ARCHIVER]: AssetRequestCallback failed with {0}\", e);\n }\n }\n\n /// \n /// Perform the callback on the original requester of the assets\n /// \n protected void PerformAssetsRequestCallback(object o)\n {\n try\n {\n m_assetsRequestCallback(m_foundAssetUuids, m_notFoundAssetUuids);\n }\n catch (Exception e)\n {\n m_log.ErrorFormat(\n \"[ARCHIVER]: Terminating archive creation since asset requster callback failed with {0}\", e);\n }\n }\n }\n}\n"},"gt":{"kind":"string","value":""}}},{"rowIdx":96221,"cells":{"context":{"kind":"string","value":"//\n// System.Data.Common.Key.cs\n//\n// Author:\n// Boris Kirzner \n// Konstantin Triger (kostat@mainsoft.com)\n//\n\n/*\n * Copyright (c) 2002-2004 Mainsoft Corporation.\n *\n * Permission is hereby granted, free of charge, to any person obtaining a\n * copy of this software and associated documentation files (the \"Software\"),\n * to deal in the Software without restriction, including without limitation\n * the rights to use, copy, modify, merge, publish, distribute, sublicense,\n * and/or sell copies of the Software, and to permit persons to whom the\n * Software is furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n * DEALINGS IN THE SOFTWARE.\n */\n\nusing System;\nusing System.Collections;\n\nusing System.Text;\n\nnamespace System.Data.Common\n{\n\tenum IndexDuplicatesState { Unknown, True, False }; \n\t/// \n\t/// Summary description for Index.\n\t/// \n\tinternal class Index\n\t{\n\t\t#region Fields\n\n\t\tint[] _array;\n\t\tint _size;\n\t\tKey _key;\n\t\tint _refCount = 0;\n\t\tIndexDuplicatesState _hasDuplicates;\n\n\t\t#endregion // Fields\n\n\t\t#region Constructors\n\n\t\tinternal Index(Key key)\n\t\t{\n\t\t\t_key = key;\n\t\t\tReset();\n\t\t}\n\n\t\t#endregion // Constructors\n\n\t\t#region Properties\n\n\t\tinternal Key Key \n\t\t{\n\t\t\tget {\n\t\t\t\treturn _key;\n\t\t\t}\n\t\t}\n\n\t\tinternal int Size\n\t\t{\n\t\t\tget {\n\t\t\t\tEnsureArray();\n\t\t\t\treturn _size;\n\t\t\t}\n\t\t}\n\n\t\tinternal int RefCount\n\t\t{\n\t\t\tget {\n\t\t\t\treturn _refCount;\n\t\t\t}\n\t\t}\n\n\t\tinternal int IndexToRecord(int index){\n\t\t\treturn index < 0 ? index : Array[index];\n\t\t}\n\n\t\tprivate int[] Array\n\t\t{\n\t\t\tget {\n\t\t\t\tEnsureArray();\n\t\t\t\treturn _array;\n\t\t\t}\n\t\t}\n\n\t\tinternal bool HasDuplicates\n\t\t{\n\t\t\tget {\n\t\t\t\tif (_array == null || _hasDuplicates == IndexDuplicatesState.Unknown) {\n\t\t\t\t\tEnsureArray();\n\t\t\t\t\tif (_hasDuplicates == IndexDuplicatesState.Unknown) {\n\t\t\t\t\t\t// check for duplicates\n\t\t\t\t\t\t_hasDuplicates = IndexDuplicatesState.False;\n\t\t\t\t\t\tfor(int i = 0; i < Size - 1; i++) {\n\t\t\t\t\t\t\tif (Key.CompareRecords(Array[i],Array[i+1]) == 0) {\n\t\t\t\t\t\t\t\t_hasDuplicates = IndexDuplicatesState.True;\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn (_hasDuplicates == IndexDuplicatesState.True);\n\t\t\t}\n\t\t}\n\n\t\t#endregion // Properties\n\n\t\t#region Methods\n\n\t\tinternal int[] Duplicates {\n\t\t\tget {\n\t\t\t\tif (!HasDuplicates)\n\t\t\t\t\treturn null;\n\n\t\t\t\tArrayList dups = new ArrayList();\n\n\t\t\t\tbool inRange = false;\n\t\t\t\tfor(int i = 0; i < Size - 1; i++) {\n\t\t\t\t\tif (Key.CompareRecords(Array[i],Array[i+1]) == 0){\n\t\t\t\t\t\tif (!inRange) {\n\t\t\t\t\t\t\tdups.Add(Array[i]);\n\t\t\t\t\t\t\tinRange = true;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tdups.Add(Array[i+1]);\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t\tinRange = false;\n\t\t\t\t}\n\n\t\t\t\treturn (int[])dups.ToArray(typeof(int));\n\t\t\t}\n\t\t}\n\n\t\tprivate void EnsureArray()\n\t\t{\n\t\t\tif (_array == null) {\n\t\t\t\tRebuildIndex();\n\t\t\t}\n\t\t}\n\n\t\tinternal int[] GetAll()\n\t\t{\n\t\t\treturn Array;\n\t\t}\n\n\t\tinternal void Reset()\n\t\t{\n\t\t\t_array = null;\n\t\t}\n\n\t\tprivate void RebuildIndex()\n\t\t{\n\t\t\t// consider better capacity approximation\n\t\t\t_array = new int[Key.Table.RecordCache.CurrentCapacity];\n\t\t\t_size = 0;\n\t\t\tforeach(DataRow row in Key.Table.Rows) {\n\t\t\t\tint record = Key.GetRecord(row);\n\t\t\t\tif (record != -1) {\n\t\t\t\t\t_array[_size++] = record;\n\t\t\t\t}\n\t\t\t}\n\t\t\t_hasDuplicates = IndexDuplicatesState.False;\n\t\t\t// Note : MergeSort may update hasDuplicates to True\n\t\t\tSort();\n\t\t}\n\n\t\tprivate void Sort()\n\t\t{\n\t\t\t//QuickSort(Array,0,Size-1);\n\t\t\tMergeSort(Array,Size);\n\t\t}\n\t\t\n\t\t/*\n\t\t * Returns record number of the record equal to the key values supplied \n\t\t * in the meaning of index key, or -1 if no equal record found.\n\t\t */\n\t\tinternal int Find(object[] keys)\n\t\t{\n\t\t\tint index = FindIndex(keys);\n\t\t\treturn IndexToRecord(index);\n\t\t}\n\n\t\t/*\n\t\t * Returns record index (location) of the record equal to the key values supplied \n\t\t * in the meaning of index key, or -1 if no equal record found.\n\t\t */\n\t\tinternal int FindIndex(object[] keys)\n\t\t{\n\t\t\tif (keys == null || keys.Length != Key.Columns.Length) {\n\t\t\t\tthrow new ArgumentException(\"Expecting \" + Key.Columns.Length + \" value(s) for the key being indexed, \" +\n\t\t\t\t\t\"but received \" + ((keys == null) ? 0 : keys.Length) + \" value(s).\");\n\t\t\t}\n\n\t\t\tint tmp = Key.Table.RecordCache.NewRecord();\n\t\t\ttry {\n\t\t\t\t// init key values for temporal record\n\t\t\t\tfor(int i = 0; i < Key.Columns.Length; i++) {\n\t\t\t\t\tKey.Columns[i].DataContainer[tmp] = keys[i];\n\t\t\t\t}\n\t\t\t\treturn FindIndex(tmp);\n\t\t\t}\n//\t\t\tcatch(FormatException) {\n//\t\t\t\treturn -1;\n//\t\t\t}\n//\t\t\tcatch(InvalidCastException) {\n//\t\t\t\treturn -1;\n//\t\t\t}\n\t\t\tfinally {\n\t\t\t\tKey.Table.RecordCache.DisposeRecord(tmp);\n\t\t\t}\n\t\t}\n\n\t\t/*\n\t\t * Returns record number of the record equal to the record supplied \n\t\t * in the meaning of index key, or -1 if no equal record found.\n\t\t */\n\t\tinternal int Find(int record)\n\t\t{\n\t\t\tint index = FindIndex(record);\n\t\t\treturn IndexToRecord(index);\n\t\t}\n\n\t\t/*\n\t\t * Returns array of record numbers of the records equal equal to the key values supplied \n\t\t * in the meaning of index key, or -1 if no equal record found.\n\t\t */\n\t\tinternal int[] FindAll(object[] keys)\n\t\t{\n\t\t\tint[] indexes = FindAllIndexes(keys);\n\t\t\tIndexesToRecords(indexes);\n\t\t\treturn indexes;\n\t\t}\n\n\t\t/*\n\t\t * Returns array of indexes of the records inside the index equal equal to the key values supplied \n\t\t * in the meaning of index key, or -1 if no equal record found.\n\t\t */\n\t\tinternal int[] FindAllIndexes(object[] keys)\n\t\t{\n\t\t\tif (keys == null || keys.Length != Key.Columns.Length) {\n\t\t\t\tthrow new ArgumentException(\"Expecting \" + Key.Columns.Length + \" value(s) for the key being indexed,\" +\n\t\t\t\t\t\"but received \" + ((keys == null) ? 0 : keys.Length) + \" value(s).\");\n\t\t\t}\n\n\t\t\tint tmp = Key.Table.RecordCache.NewRecord();\n\t\t\ttry {\n\t\t\t\t// init key values for temporal record\n\t\t\t\tfor(int i = 0; i < Key.Columns.Length; i++) {\n\t\t\t\t\tKey.Columns[i].DataContainer[tmp] = keys[i];\n\t\t\t\t}\n\t\t\t\treturn FindAllIndexes(tmp);\n\t\t\t}\n\t\t\tcatch(FormatException) {\n\t\t\t\treturn new int[0];\n\t\t\t}\n\t\t\tcatch(InvalidCastException) {\n\t\t\t\treturn new int[0];\n\t\t\t}\n\t\t\tfinally {\n\t\t\t\tKey.Table.RecordCache.DisposeRecord(tmp);\n\t\t\t}\n\t\t}\n\n\t\t/*\n\t\t * Returns array of record numbers of the records equal to the record supplied \n\t\t * in the meaning of index key, or empty list if no equal records found.\n\t\t */\n\t\tinternal int[] FindAll(int record)\n\t\t{\n\t\t\tint[] indexes = FindAllIndexes(record);\n IndexesToRecords(indexes);\n\t\t\treturn indexes;\n\t\t}\n\n\t\t/*\n\t\t * Returns array of indexes of the records inside the index that equal to the record supplied \n\t\t * in the meaning of index key, or empty list if no equal records found.\n\t\t */\n\t\tinternal int[] FindAllIndexes(int record)\n\t\t{\n\t\t\tint index = FindIndex(record);\n\n\t\t\tif (index == -1) {\n\t\t\t\treturn new int[0];\n\t\t\t}\n\n\t\t\tint startIndex = index++;\n\t\t\tint endIndex = index;\n\t\t\t\n\t\t\tfor(;startIndex >= 0 && Key.CompareRecords(Array[startIndex],record) == 0;startIndex--);\n\t\t\tfor(;endIndex < Size && Key.CompareRecords(Array[endIndex],record) == 0;endIndex++);\n\t\t\t\n\t\t\tint length = endIndex - startIndex - 1;\n\t\t\tint[] indexes = new int[length];\n\t\t\t\n\t\t\tfor(int i = 0; i < length; i++) {\n\t\t\t\tindexes[i] = ++startIndex;\n\t\t\t}\n\t\t\t\n\t\t\treturn indexes;\n\t\t}\n\n\t\t/*\n\t\t * Returns index inside the array where record number of the record equal to the record supplied \n\t\t * in the meaning of index key is sored, or -1 if no equal record found.\n\t\t */\n\t\tprivate int FindIndex(int record)\n\t\t{\n\t\t\tif (Size == 0) {\n\t\t\t\treturn -1;\n\t\t\t}\n\t\t\treturn BinarySearch(Array,0,Size - 1,record);\n\t\t}\n\n\t\t/*\n\t\t * Finds exact location of the record specified\n\t\t */ \n\t\tprivate int FindIndexExact(int record)\n\t\t{\n\t\t\tint index = System.Array.BinarySearch(Array,record);\n\t\t\treturn (index > 0) ? index : -1;\n\t\t}\n\n\t\t/*\n\t\t * Returns array of records from the indexes (locations) inside the index\n\t\t */\n\t\tprivate void IndexesToRecords(int[] indexes)\n\t\t{\n\t\t\tfor(int i = 0; i < indexes.Length; i++) {\n\t\t\t\tindexes[i] = Array[indexes[i]];\n\t\t\t}\n\t\t}\n\n\t\tinternal void Delete(DataRow row)\n\t\t{\n\t\t\tint oldRecord = Key.GetRecord(row);\n\n\t\t\tDelete(oldRecord);\n\t\t}\n\n\t\tinternal void Delete(int oldRecord)\n\t\t{\n\t\t\tint index = FindIndex(oldRecord);\n\t\t\tif (index != -1) {\n\t\t\t\tif ((_hasDuplicates == IndexDuplicatesState.True)) {\n\t\t\t\t\tint c1 = 1;\n\t\t\t\t\tint c2 = 1;\n\n\t\t\t\t\tif (index > 0) {\n\t\t\t\t\t\tc1 = Key.CompareRecords(Array[index - 1],oldRecord);\n\t\t\t\t\t}\n\t\t\t\t\tif (index < Size - 1) {\n\t\t\t\t\t\tc2 = Key.CompareRecords(Array[index + 1],oldRecord);\n\t\t\t\t\t}\n\n\t\t\t\t\tif (c1 == 0 ^ c2 == 0) {\n\t\t\t\t\t\t_hasDuplicates = IndexDuplicatesState.Unknown;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tRemove(index);\n\t\t\t}\n\t\t}\n\n\t\tprivate void Remove(int index)\n\t\t{\n\t\t\tif (Size > 1) {\n\t\t\t\tSystem.Array.Copy(Array,index+1,Array,index,Size - index);\n\t\t\t}\n\t\t\t_size--;\n\t\t}\n\n\t\tinternal void Update(DataRow row,int newRecord)\n\t\t{\n\t\t\tint oldRecord = Key.GetRecord(row);\n\n\t\t\tif (oldRecord == -1 || Size == 0) {\n\t\t\t\tAdd(row,newRecord);\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tint oldIdx = FindIndex(oldRecord);\n\n\t\t\tif( oldIdx == -1 || Key.Table.RecordCache[Array[oldIdx]] != row ) {\n\t\t\t\tAdd(row,newRecord);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\t\t\n\t\t\tint newIdx = -1;\n\t\t\tint compare = Key.CompareRecords(Array[oldIdx],newRecord);\n\t\t\tint start,end;\n\n\t\t\tint c1 = 1;\n\t\t\tint c2 = 1;\n\n\t\t\tif (compare == 0) {\n\t\t\t\tif (Array[oldIdx] == newRecord) {\n\t\t\t\t\t// we deal with the same record that didn't change\n\t\t\t\t\t// in the context of current index.\n\t\t\t\t\t// so , do nothing.\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t}\n\t\t\telse {\n\t\t\t\tif ((_hasDuplicates == IndexDuplicatesState.True)) {\n\t\t\t\t\tif (oldIdx > 0) {\n\t\t\t\t\t\tc1 = Key.CompareRecords(Array[oldIdx - 1],newRecord);\n\t\t\t\t\t}\n\t\t\t\t\tif (oldIdx < Size - 1) {\n\t\t\t\t\t\tc2 = Key.CompareRecords(Array[oldIdx + 1],newRecord);\n\t\t\t\t\t}\n\n\t\t\t\t\tif ((c1 == 0 ^ c2 == 0) && compare != 0) {\n\t\t\t\t\t\t_hasDuplicates = IndexDuplicatesState.Unknown;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\t\n\t\t\tif ((oldIdx == 0 && compare > 0) || (oldIdx == (Size - 1) && compare < 0) || (compare == 0)) {\n\t\t\t\t// no need to switch cells\n\t\t\t\tnewIdx = oldIdx;\n\t\t\t}\n\t\t\telse {\n\t\t\t\tif (compare < 0) {\n\t\t\t\t\t// search after the old place\n\t\t\t\t\tstart = oldIdx + 1;\n\t\t\t\t\tend = Size - 1;\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\t// search before the old palce\n\t\t\t\t\tstart = 0;\n\t\t\t\t\tend = oldIdx - 1;\n\t\t\t\t}\n\n\t\t\t\tnewIdx = LazyBinarySearch(Array,start,end,newRecord);\t\t\t\t\t\n\n\t\t\t\tif (oldIdx < newIdx) {\n\t\t\t\t\tSystem.Array.Copy(Array,oldIdx + 1,Array,oldIdx,newIdx - oldIdx);\n\t\t\t\t}\n\t\t\t\telse if (oldIdx > newIdx){\n\t\t\t\t\tSystem.Array.Copy(Array,newIdx,Array,newIdx + 1,oldIdx - newIdx);\n\t\t\t\t}\n\t\t\t}\t\t\t\n\t\t\tArray[newIdx] = newRecord;\n\n\t\t\tif (compare != 0) {\n\t\t\t\tif (!(_hasDuplicates == IndexDuplicatesState.True)) {\n\t\t\t\t\tif (newIdx > 0) {\n\t\t\t\t\t\tc1 = Key.CompareRecords(Array[newIdx - 1],newRecord);\n\t\t\t\t\t}\n\t\t\t\t\tif (newIdx < Size - 1) {\n\t\t\t\t\t\tc2 = Key.CompareRecords(Array[newIdx + 1],newRecord);\n\t\t\t\t\t}\n\n\t\t\t\t\tif (c1 == 0 || c2 == 0) {\n\t\t\t\t\t\t_hasDuplicates = IndexDuplicatesState.True;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tprivate void Add(DataRow row,int newRecord)\n\t\t{\n\t\t\tint newIdx;\n\t\t\tif (Size == 0) {\n\t\t\t\tnewIdx = 0;\n\t\t\t}\n\t\t\telse {\n\t\t\t\tnewIdx = LazyBinarySearch(Array,0,Size - 1,newRecord);\n\t\t\t\t// if newl value is greater - insert afer old value\n\t\t\t\t// else - insert before old value\n\t\t\t\tif (Key.CompareRecords(Array[newIdx],newRecord) < 0) {\n\t\t\t\t\tnewIdx++;\n\t\t\t\t}\n\t\t\t}\n\t\t\t\t\t\n\t\t\tInsert(newIdx,newRecord);\n\n\t\t\tint c1 = 1;\n\t\t\tint c2 = 1;\n\t\t\tif (!(_hasDuplicates == IndexDuplicatesState.True)) {\n\t\t\t\tif (newIdx > 0) {\n\t\t\t\t\tc1 = Key.CompareRecords(Array[newIdx - 1],newRecord);\n\t\t\t\t}\n\t\t\t\tif (newIdx < Size - 1) {\n\t\t\t\t\tc2 = Key.CompareRecords(Array[newIdx + 1],newRecord);\n\t\t\t\t}\n\n\t\t\t\tif (c1 == 0 || c2 == 0) {\n\t\t\t\t\t_hasDuplicates = IndexDuplicatesState.True;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tprivate void Insert(int index,int r)\n\t\t{\n\t\t\tif (Array.Length == Size) {\n\t\t\t\tint[] tmp = (Size == 0) ? new int[16] : new int[Size << 1];\n\t\t\t\tSystem.Array.Copy(Array,0,tmp,0,index);\n\t\t\t\ttmp[index] = r;\n\t\t\t\tSystem.Array.Copy(Array,index,tmp,index + 1,Size - index);\n\t\t\t\t_array = tmp;\n\t\t\t}\n\t\t\telse {\n\t\t\t\tSystem.Array.Copy(Array,index,Array,index + 1,Size - index);\n\t\t\t\tArray[index] = r;\n\t\t\t}\n\t\t\t_size++;\n\t\t}\n\n\t\tprivate void MergeSort(int[] to, int length)\n {\n int[] from = new int[length];\n System.Array.Copy(to, 0, from, 0, from.Length);\n\n MergeSort(from, to, 0, from.Length);\n }\n\n private void MergeSort(int[] from, int[] to,int p, int r)\n {\n int q = (p + r) >> 1;\n\t if (q == p) {\n return;\n } \n\n MergeSort(to, from, p, q);\n MergeSort(to, from, q, r);\n\n // merge\n for (int middle = q, current = p;;) {\n\t\t\t\tint res = Key.CompareRecords(from[p],from[q]);\n if (res > 0) {\n to[current++] = from[q++];\n\n if (q == r) {\n while( p < middle) {\n to[current++] = from[p++];\n\t\t\t\t\t\t}\n break;\n }\n }\n else {\n\n\t\t\t\t\tif (res == 0) {\n\t\t\t\t\t\t_hasDuplicates = IndexDuplicatesState.True;\n\t\t\t\t\t}\n\n to[current++] = from[p++];\n\n if (p == middle) {\n while( q < r) {\n to[current++] = from[q++];\n\t\t\t\t\t\t}\n break;\n }\n }\n }\n\t\t}\n\n\t\tprivate void QuickSort(int[] a,int p,int r)\n\t\t{\n\t\t\tif (p < r) {\n\t\t\t\tint q = Partition(a,p,r);\n\t\t\t\tQuickSort(a,p,q);\n\t\t\t\tQuickSort(a,q+1,r);\n\t\t\t}\n\t\t}\n\n\t\tprivate int Partition(int[] a,int p,int r)\n\t\t{\n\t\t\tint x = a[p];\n\t\t\tint i = p - 1;\n\t\t\tint j = r + 1;\n\n\t\t\twhile(true) {\n\t\t\t\t// decrement upper limit while values are greater then border value\n\t\t\t\tdo {\n\t\t\t\t\tj--;\n\t\t\t\t}\n\t\t\t\twhile(Key.CompareRecords(a[j],x) > 0);\t//while(a[j] > x);\n\n\t\t\t\tdo {\n\t\t\t\t\ti++;\n\t\t\t\t}\n\t\t\t\twhile(Key.CompareRecords(a[i],x) < 0);\t//while(a[i] < x);\n\t\t\t\t\n\t\t\t\tif (i> 1;\n\n\t\t\tint compare = Key.CompareRecords(a[q],b);\n\t\t\tif (compare < 0) { // if (a[q] < b) {\n\t\t\t\treturn LazyBinarySearch(a,q+1,r,b);\n\t\t\t}\n\t\t\telse if (compare > 0) { // a[q] > b\n\t\t\t\treturn LazyBinarySearch(a,p,q,b);\n\t\t\t}\t\n\t\t\telse { // a[q] == b\n\t\t\t\treturn q;\n\t\t\t}\n\t\t}\n\n\t\tinternal void AddRef()\n\t\t{\n\t\t\t_refCount++;\n\t\t}\n\n\t\tinternal void RemoveRef()\n\t\t{\n\t\t\t_refCount--;\n\t\t}\n\n\t\t#endregion // Methods\n\t}\n}\n"},"gt":{"kind":"string","value":""}}},{"rowIdx":96222,"cells":{"context":{"kind":"string","value":"// Licensed to the .NET Foundation under one or more agreements.\n// The .NET Foundation licenses this file to you under the MIT license.\n// See the LICENSE file in the project root for more information.\n\nusing System.Diagnostics;\nusing System.Runtime.CompilerServices;\n\nnamespace System\n{\n // The BitConverter class contains methods for\n // converting an array of bytes to one of the base data \n // types, as well as for converting a base data type to an\n // array of bytes.\n public static class BitConverter\n {\n // This field indicates the \"endianess\" of the architecture.\n // The value is set to true if the architecture is\n // little endian; false if it is big endian.\n#if BIGENDIAN\n public static readonly bool IsLittleEndian /* = false */;\n#else\n public static readonly bool IsLittleEndian = true;\n#endif\n\n // Converts a Boolean into an array of bytes with length one.\n public static byte[] GetBytes(bool value)\n {\n byte[] r = new byte[1];\n r[0] = (value ? (byte)1 : (byte)0);\n return r;\n }\n\n // Converts a Boolean into a Span of bytes with length one.\n public static bool TryWriteBytes(Span destination, bool value)\n {\n if (destination.Length < sizeof(byte))\n return false;\n\n Unsafe.WriteUnaligned(ref destination.DangerousGetPinnableReference(), value ? (byte)1: (byte)0);\n return true;\n }\n\n // Converts a char into an array of bytes with length two.\n public static byte[] GetBytes(char value)\n {\n byte[] bytes = new byte[sizeof(char)];\n Unsafe.As(ref bytes[0]) = value;\n return bytes;\n }\n\n // Converts a char into a Span\n public static bool TryWriteBytes(Span destination, char value)\n {\n if (destination.Length < sizeof(char))\n return false;\n\n Unsafe.WriteUnaligned(ref destination.DangerousGetPinnableReference(), value);\n return true;\n }\n\n // Converts a short into an array of bytes with length\n // two.\n public static byte[] GetBytes(short value)\n {\n byte[] bytes = new byte[sizeof(short)];\n Unsafe.As(ref bytes[0]) = value;\n return bytes;\n }\n\n // Converts a short into a Span\n public static bool TryWriteBytes(Span destination, short value)\n {\n if (destination.Length < sizeof(short))\n return false;\n\n Unsafe.WriteUnaligned(ref destination.DangerousGetPinnableReference(), value);\n return true;\n }\n\n // Converts an int into an array of bytes with length \n // four.\n public static byte[] GetBytes(int value)\n {\n byte[] bytes = new byte[sizeof(int)];\n Unsafe.As(ref bytes[0]) = value;\n return bytes;\n }\n\n // Converts an int into a Span\n public static bool TryWriteBytes(Span destination, int value)\n {\n if (destination.Length < sizeof(int))\n return false;\n\n Unsafe.WriteUnaligned(ref destination.DangerousGetPinnableReference(), value);\n return true;\n }\n\n // Converts a long into an array of bytes with length \n // eight.\n public static byte[] GetBytes(long value)\n {\n byte[] bytes = new byte[sizeof(long)];\n Unsafe.As(ref bytes[0]) = value;\n return bytes;\n }\n\n // Converts a long into a Span\n public static bool TryWriteBytes(Span destination, long value)\n {\n if (destination.Length < sizeof(long))\n return false;\n\n Unsafe.WriteUnaligned(ref destination.DangerousGetPinnableReference(), value);\n return true;\n }\n\n // Converts an ushort into an array of bytes with\n // length two.\n [CLSCompliant(false)]\n public static byte[] GetBytes(ushort value)\n {\n byte[] bytes = new byte[sizeof(ushort)];\n Unsafe.As(ref bytes[0]) = value;\n return bytes;\n }\n\n // Converts a ushort into a Span\n [CLSCompliant(false)]\n public static bool TryWriteBytes(Span destination, ushort value)\n {\n if (destination.Length < sizeof(ushort))\n return false;\n\n Unsafe.WriteUnaligned(ref destination.DangerousGetPinnableReference(), value);\n return true;\n }\n\n // Converts an uint into an array of bytes with\n // length four.\n [CLSCompliant(false)]\n public static byte[] GetBytes(uint value)\n {\n byte[] bytes = new byte[sizeof(uint)];\n Unsafe.As(ref bytes[0]) = value;\n return bytes;\n }\n\n // Converts a uint into a Span\n [CLSCompliant(false)]\n public static bool TryWriteBytes(Span destination, uint value)\n {\n if (destination.Length < sizeof(uint))\n return false;\n\n Unsafe.WriteUnaligned(ref destination.DangerousGetPinnableReference(), value);\n return true;\n }\n\n // Converts an unsigned long into an array of bytes with\n // length eight.\n [CLSCompliant(false)]\n public static byte[] GetBytes(ulong value)\n {\n byte[] bytes = new byte[sizeof(ulong)];\n Unsafe.As(ref bytes[0]) = value;\n return bytes;\n }\n\n // Converts a ulong into a Span\n [CLSCompliant(false)]\n public static bool TryWriteBytes(Span destination, ulong value)\n {\n if (destination.Length < sizeof(ulong))\n return false;\n\n Unsafe.WriteUnaligned(ref destination.DangerousGetPinnableReference(), value);\n return true;\n }\n\n // Converts a float into an array of bytes with length \n // four.\n public static byte[] GetBytes(float value)\n {\n byte[] bytes = new byte[sizeof(float)];\n Unsafe.As(ref bytes[0]) = value;\n return bytes;\n }\n\n // Converts a float into a Span\n public static bool TryWriteBytes(Span destination, float value)\n {\n if (destination.Length < sizeof(float))\n return false;\n\n Unsafe.WriteUnaligned(ref destination.DangerousGetPinnableReference(), value);\n return true;\n }\n\n // Converts a double into an array of bytes with length \n // eight.\n public static byte[] GetBytes(double value)\n {\n byte[] bytes = new byte[sizeof(double)];\n Unsafe.As(ref bytes[0]) = value;\n return bytes;\n }\n\n // Converts a double into a Span\n public static bool TryWriteBytes(Span destination, double value)\n {\n if (destination.Length < sizeof(double))\n return false;\n\n Unsafe.WriteUnaligned(ref destination.DangerousGetPinnableReference(), value);\n return true;\n }\n\n // Converts an array of bytes into a char. \n public static char ToChar(byte[] value, int startIndex) => unchecked((char)ReadInt16(value, startIndex));\n\n // Converts a Span into a char\n public static char ToChar(ReadOnlySpan value)\n {\n if (value.Length < sizeof(char))\n ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.value);\n return Unsafe.ReadUnaligned(ref value.DangerousGetPinnableReference());\n }\n\n private static short ReadInt16(byte[] value, int startIndex)\n {\n if (value == null)\n ThrowHelper.ThrowArgumentNullException(ExceptionArgument.value);\n if (unchecked((uint)startIndex) >= unchecked((uint)value.Length))\n ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.startIndex, ExceptionResource.ArgumentOutOfRange_Index);\n if (startIndex > value.Length - sizeof(short))\n ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_ArrayPlusOffTooSmall, ExceptionArgument.value);\n\n return Unsafe.ReadUnaligned(ref value[startIndex]);\n }\n\n private static int ReadInt32(byte[] value, int startIndex)\n {\n if (value == null)\n ThrowHelper.ThrowArgumentNullException(ExceptionArgument.value);\n if (unchecked((uint)startIndex) >= unchecked((uint)value.Length))\n ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.startIndex, ExceptionResource.ArgumentOutOfRange_Index);\n if (startIndex > value.Length - sizeof(int))\n ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_ArrayPlusOffTooSmall, ExceptionArgument.value);\n\n return Unsafe.ReadUnaligned(ref value[startIndex]);\n }\n\n private static long ReadInt64(byte[] value, int startIndex)\n {\n if (value == null)\n ThrowHelper.ThrowArgumentNullException(ExceptionArgument.value);\n if (unchecked((uint)startIndex) >= unchecked((uint)value.Length))\n ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.startIndex, ExceptionResource.ArgumentOutOfRange_Index);\n if (startIndex > value.Length - sizeof(long))\n ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_ArrayPlusOffTooSmall, ExceptionArgument.value);\n\n return Unsafe.ReadUnaligned(ref value[startIndex]);\n }\n\n // Converts an array of bytes into a short. \n public static short ToInt16(byte[] value, int startIndex) => ReadInt16(value, startIndex);\n\n // Converts a Span into a short\n public static short ToInt16(ReadOnlySpan value)\n {\n if (value.Length < sizeof(short))\n ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.value);\n return Unsafe.ReadUnaligned(ref value.DangerousGetPinnableReference());\n }\n\n // Converts an array of bytes into an int. \n public static int ToInt32(byte[] value, int startIndex) => ReadInt32(value, startIndex);\n\n // Converts a Span into an int\n public static int ToInt32(ReadOnlySpan value)\n {\n if (value.Length < sizeof(int))\n ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.value);\n return Unsafe.ReadUnaligned(ref value.DangerousGetPinnableReference());\n }\n\n // Converts an array of bytes into a long. \n public static long ToInt64(byte[] value, int startIndex) => ReadInt64(value, startIndex);\n\n // Converts a Span into a long\n public static long ToInt64(ReadOnlySpan value)\n {\n if (value.Length < sizeof(long))\n ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.value);\n return Unsafe.ReadUnaligned(ref value.DangerousGetPinnableReference());\n }\n\n // Converts an array of bytes into an ushort.\n // \n [CLSCompliant(false)]\n public static ushort ToUInt16(byte[] value, int startIndex) => unchecked((ushort)ReadInt16(value, startIndex));\n\n // Converts a Span into a ushort\n [CLSCompliant(false)]\n public static ushort ToUInt16(ReadOnlySpan value)\n {\n if (value.Length < sizeof(ushort))\n ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.value);\n return Unsafe.ReadUnaligned(ref value.DangerousGetPinnableReference());\n }\n\n // Converts an array of bytes into an uint.\n // \n [CLSCompliant(false)]\n public static uint ToUInt32(byte[] value, int startIndex) => unchecked((uint)ReadInt32(value, startIndex));\n\n // Convert a Span into a uint\n [CLSCompliant(false)]\n public static uint ToUInt32(ReadOnlySpan value)\n {\n if (value.Length < sizeof(uint))\n ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.value);\n return Unsafe.ReadUnaligned(ref value.DangerousGetPinnableReference());\n }\n\n // Converts an array of bytes into an unsigned long.\n // \n [CLSCompliant(false)]\n public static ulong ToUInt64(byte[] value, int startIndex) => unchecked((ulong)ReadInt64(value, startIndex));\n\n // Converts a Span into an unsigned long\n [CLSCompliant(false)]\n public static ulong ToUInt64(ReadOnlySpan value)\n {\n if (value.Length < sizeof(ulong))\n ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.value);\n return Unsafe.ReadUnaligned(ref value.DangerousGetPinnableReference());\n }\n\n // Converts an array of bytes into a float. \n public static unsafe float ToSingle(byte[] value, int startIndex)\n {\n int val = ReadInt32(value, startIndex);\n return *(float*)&val;\n }\n\n // Converts a Span into a float\n public static float ToSingle(ReadOnlySpan value)\n {\n if (value.Length < sizeof(float))\n ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.value);\n return Unsafe.ReadUnaligned(ref value.DangerousGetPinnableReference());\n }\n\n // Converts an array of bytes into a double. \n public static unsafe double ToDouble(byte[] value, int startIndex)\n {\n long val = ReadInt64(value, startIndex);\n return *(double*)&val;\n }\n\n // Converts a Span into a double\n public static double ToDouble(ReadOnlySpan value)\n {\n if (value.Length < sizeof(double))\n ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.value);\n return Unsafe.ReadUnaligned(ref value.DangerousGetPinnableReference());\n }\n\n private static char GetHexValue(int i)\n {\n Debug.Assert(i >= 0 && i < 16, \"i is out of range.\");\n if (i < 10)\n {\n return (char)(i + '0');\n }\n\n return (char)(i - 10 + 'A');\n }\n\n // Converts an array of bytes into a String. \n public static string ToString(byte[] value, int startIndex, int length)\n {\n if (value == null)\n ThrowHelper.ThrowArgumentNullException(ExceptionArgument.value);\n if (startIndex < 0 || startIndex >= value.Length && startIndex > 0)\n ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.startIndex, ExceptionResource.ArgumentOutOfRange_Index);\n if (length < 0)\n throw new ArgumentOutOfRangeException(nameof(length), SR.ArgumentOutOfRange_GenericPositive);\n if (startIndex > value.Length - length)\n ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_ArrayPlusOffTooSmall, ExceptionArgument.value);\n\n if (length == 0)\n {\n return string.Empty;\n }\n\n if (length > (int.MaxValue / 3))\n {\n // (Int32.MaxValue / 3) == 715,827,882 Bytes == 699 MB\n throw new ArgumentOutOfRangeException(nameof(length), SR.Format(SR.ArgumentOutOfRange_LengthTooLarge, (int.MaxValue / 3)));\n }\n\n int chArrayLength = length * 3;\n const int StackLimit = 512; // arbitrary limit to switch from stack to heap allocation\n unsafe\n {\n if (chArrayLength < StackLimit)\n {\n char* chArrayPtr = stackalloc char[chArrayLength];\n return ToString(value, startIndex, length, chArrayPtr, chArrayLength);\n }\n else\n {\n char[] chArray = new char[chArrayLength];\n fixed (char* chArrayPtr = &chArray[0])\n return ToString(value, startIndex, length, chArrayPtr, chArrayLength);\n }\n }\n }\n\n private static unsafe string ToString(byte[] value, int startIndex, int length, char* chArray, int chArrayLength)\n {\n Debug.Assert(length > 0);\n Debug.Assert(chArrayLength == length * 3);\n\n char* p = chArray;\n int endIndex = startIndex + length;\n for (int i = startIndex; i < endIndex; i++)\n {\n byte b = value[i];\n *p++ = GetHexValue(b >> 4);\n *p++ = GetHexValue(b & 0xF);\n *p++ = '-';\n }\n\n // We don't need the last '-' character\n return new string(chArray, 0, chArrayLength - 1);\n }\n\n // Converts an array of bytes into a String. \n public static string ToString(byte[] value)\n {\n if (value == null)\n ThrowHelper.ThrowArgumentNullException(ExceptionArgument.value);\n return ToString(value, 0, value.Length);\n }\n\n // Converts an array of bytes into a String. \n public static string ToString(byte[] value, int startIndex)\n {\n if (value == null)\n ThrowHelper.ThrowArgumentNullException(ExceptionArgument.value);\n return ToString(value, startIndex, value.Length - startIndex);\n }\n\n /*==================================ToBoolean===================================\n **Action: Convert an array of bytes to a boolean value. We treat this array \n ** as if the first 4 bytes were an Int4 an operate on this value.\n **Returns: True if the Int4 value of the first 4 bytes is non-zero.\n **Arguments: value -- The byte array\n ** startIndex -- The position within the array.\n **Exceptions: See ToInt4.\n ==============================================================================*/\n // Converts an array of bytes into a boolean. \n public static bool ToBoolean(byte[] value, int startIndex)\n {\n if (value == null)\n ThrowHelper.ThrowArgumentNullException(ExceptionArgument.value);\n if (startIndex < 0)\n ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.startIndex, ExceptionResource.ArgumentOutOfRange_Index);\n if (startIndex > value.Length - 1)\n ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.startIndex, ExceptionResource.ArgumentOutOfRange_Index); // differs from other overloads, which throw base ArgumentException\n\n return value[startIndex] != 0;\n }\n\n public static bool ToBoolean(ReadOnlySpan value)\n {\n if (value.Length < sizeof(byte))\n ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.value);\n return Unsafe.ReadUnaligned(ref value.DangerousGetPinnableReference()) != 0;\n }\n\n [MethodImpl(MethodImplOptions.AggressiveInlining)]\n public static unsafe long DoubleToInt64Bits(double value)\n {\n return *((long*)&value);\n }\n\n [MethodImpl(MethodImplOptions.AggressiveInlining)]\n public static unsafe double Int64BitsToDouble(long value)\n {\n return *((double*)&value);\n }\n\n [MethodImpl(MethodImplOptions.AggressiveInlining)]\n public static unsafe int SingleToInt32Bits(float value)\n {\n return *((int*)&value);\n }\n\n [MethodImpl(MethodImplOptions.AggressiveInlining)]\n public static unsafe float Int32BitsToSingle(int value)\n {\n return *((float*)&value);\n }\n }\n}\n"},"gt":{"kind":"string","value":""}}},{"rowIdx":96223,"cells":{"context":{"kind":"string","value":"using System.Collections.Generic;\nusing Android.Content;\nusing System.Drawing;\nusing Android.Support.Design.Widget;\nusing Android.Support.V4.View;\nusing Android.Views;\nusing SciChart.Charting.Model.DataSeries;\nusing SciChart.Charting.Visuals;\nusing SciChart.Charting.Visuals.Axes;\nusing SciChart.Charting.Visuals.RenderableSeries;\nusing SciChart.Drawing.Common;\nusing Xamarin.Examples.Demo;\nusing Xamarin.Examples.Demo.Droid.Fragments.Base;\n\nnamespace Xamarin.Examples.Demo.Droid.Fragments.Examples\n{\n [ExampleDefinition(\"Dashboard Style Charts\", description:\"Beautiful stacked charts with dynamic switching between chart type\", icon: ExampleIcon.StackedColumns100)]\n public class DashboardStyleChartsFragment : ExampleBaseFragment\n {\n public TabLayout TabLayout => View.FindViewById(Resource.Id.tabLayout);\n public ViewPager ViewPager => View.FindViewById(Resource.Id.viewpager);\n\n private readonly IList _chartTypesSource = new List();\n private static readonly int[] SeriesColors = new int[DashboardDataHelper.Colors.Length];\n\n public override int ExampleLayoutId => Resource.Layout.Example_Dashboard_Style_Charts_Fragment;\n\n protected override void InitExample()\n {\n for (int i = 0; i < DashboardDataHelper.Colors.Length; i++)\n {\n int color = Resources.GetColor(DashboardDataHelper.Colors[i]);\n SeriesColors[i] = color;\n }\n\n _chartTypesSource.Add(ChartTypeModelFactory.NewHorizontallyStackedColumns(Activity));\n _chartTypesSource.Add(ChartTypeModelFactory.NewVerticallyStackedColumns(Activity, false));\n _chartTypesSource.Add(ChartTypeModelFactory.NewVerticallyStackedColumns(Activity, true));\n _chartTypesSource.Add(ChartTypeModelFactory.NewVerticallyStackedMountains(Activity, false));\n _chartTypesSource.Add(ChartTypeModelFactory.NewVerticallyStackedMountains(Activity, true));\n\n //this line fixes swiping lag of the viewPager by caching the pages\n ViewPager.OffscreenPageLimit = 5;\n ViewPager.Adapter = new ViewPagerAdapter(Activity.BaseContext, _chartTypesSource);\n TabLayout.SetupWithViewPager(ViewPager);\n }\n\n class ViewPagerAdapter : PagerAdapter\n {\n private readonly Context _context;\n private readonly IList _chartTypesSource;\n\n public ViewPagerAdapter(Context context, IList chartTypesSource)\n {\n _context = context;\n _chartTypesSource = chartTypesSource;\n }\n\n public override Java.Lang.Object InstantiateItem(ViewGroup container, int position)\n {\n var inflater = LayoutInflater.From(_context);\n var chartView = inflater.Inflate(Resource.Layout.Example_Single_Chart_Fragment, container, false);\n\n var chartTypeModel = _chartTypesSource[position];\n\n UpdateSurface(chartTypeModel, chartView);\n container.AddView(chartView);\n\n return chartView;\n }\n\n private void UpdateSurface(ChartTypeModel chartTypeModel, View chartView)\n {\n var surface = (SciChartSurface) chartView.FindViewById(Resource.Id.chart);\n var xAxis = new NumericAxis(_context);\n var yAxis = new NumericAxis(_context);\n\n var seriesCollection = chartTypeModel.SeriesCollection;\n\n using (surface.SuspendUpdates())\n {\n surface.XAxes.Add(xAxis);\n surface.YAxes.Add(yAxis);\n surface.RenderableSeries.Add(seriesCollection);\n }\n }\n\n public override void DestroyItem(ViewGroup container, int position, Java.Lang.Object @object)\n {\n container.RemoveView(container);\n }\n\n public override Java.Lang.ICharSequence GetPageTitleFormatted(int position)\n {\n var chartTypeModel = _chartTypesSource[position];\n return chartTypeModel.TypeName;\n }\n\n public override bool IsViewFromObject(View view, Java.Lang.Object @object)\n {\n return view == @object;\n }\n\n public override int Count => _chartTypesSource.Count;\n }\n\n private static class ChartTypeModelFactory\n {\n public static ChartTypeModel NewHorizontallyStackedColumns(Context context)\n {\n var seriesCollection = new HorizontallyStackedColumnsCollection();\n for (var i = 0; i < 5; i++)\n {\n var dataSeries = new XyDataSeries {SeriesName = \"Series \" + (i + 1) };\n dataSeries.Append(DashboardDataHelper.XValues, DashboardDataHelper.YValues[i]);\n\n var rSeries = new StackedColumnRenderableSeries\n {\n DataSeries = dataSeries,\n StrokeStyle = new SolidPenStyle(context, Color.FromArgb(SeriesColors[i * 2])),\n FillBrushStyle = new LinearGradientBrushStyle(0,0,0,1, Color.FromArgb(SeriesColors[i * 2 + 1]), Color.FromArgb(SeriesColors[i * 2]))\n\n };\n seriesCollection.Add(rSeries);\n }\n\n const string name = \"Stacked columns side-by-side\";\n return new ChartTypeModel(seriesCollection, name);\n }\n\n public static ChartTypeModel NewVerticallyStackedColumns(Context context, bool isOneHundredPercent)\n {\n var collection = new VerticallyStackedColumnsCollection {IsOneHundredPercent = isOneHundredPercent};\n for (var i = 0; i < 5; i++)\n {\n var dataSeries = new XyDataSeries { SeriesName = \"Series \" + (i + 1) };\n dataSeries.Append(DashboardDataHelper.XValues, DashboardDataHelper.YValues[i]);\n\n var rSeries = new StackedColumnRenderableSeries\n {\n DataSeries = dataSeries,\n StrokeStyle = new SolidPenStyle(context, Color.FromArgb(SeriesColors[i * 2])),\n FillBrushStyle = new LinearGradientBrushStyle(0, 0, 0, 1, Color.FromArgb(SeriesColors[i * 2 + 1]), Color.FromArgb(SeriesColors[i * 2]))\n\n };\n collection.Add(rSeries);\n }\n\n var name = isOneHundredPercent ? \"100% \" : \"\";\n name += \"Stacked columns\";\n return new ChartTypeModel(collection, name);\n }\n\n public static ChartTypeModel NewVerticallyStackedMountains(Context context, bool isOneHundredPercent)\n {\n var collection = new VerticallyStackedMountainsCollection {IsOneHundredPercent = isOneHundredPercent};\n for (var i = 0; i < 5; i++)\n {\n var dataSeries = new XyDataSeries {SeriesName = \"Series \" + (i + 1)};\n dataSeries.Append(DashboardDataHelper.XValues, DashboardDataHelper.YValues[i]);\n\n var rSeries = new StackedMountainRenderableSeries\n {\n DataSeries = dataSeries,\n StrokeStyle = new SolidPenStyle(context, Color.FromArgb(SeriesColors[i * 2])),\n AreaStyle = new LinearGradientBrushStyle(0, 0, 0, 1, Color.FromArgb(SeriesColors[i * 2 + 1]), Color.FromArgb(SeriesColors[i * 2]))\n\n };\n collection.Add(rSeries);\n }\n\n var name = isOneHundredPercent ? \"100% \" : \"\";\n name += \"Stacked mountains\";\n return new ChartTypeModel(collection, name);\n }\n }\n\n static class DashboardDataHelper\n {\n public static double[] XValues { get; } = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11};\n\n public static double[][] YValues { get; } =\n {\n new double[] {10, 13, 7, 16, 4, 6, 20, 14, 16, 10, 24, 11},\n new double[] {12, 17, 21, 15, 19, 18, 13, 21, 22, 20, 5, 10},\n new double[] {7, 30, 27, 24, 21, 15, 17, 26, 22, 28, 21, 22},\n new double[] {16, 10, 9, 8, 22, 14, 12, 27, 25, 23, 17, 17},\n new double[] {7, 24, 21, 11, 19, 17, 14, 27, 26, 22, 28, 16}\n };\n\n public static int[] Colors { get; } =\n {\n Resource.Color.dashboard_chart_blue_series_0, Resource.Color.dashboard_chart_blue_series_1,\n Resource.Color.dashboard_chart_orange_series_0, Resource.Color.dashboard_chart_orange_series_1,\n Resource.Color.dashboard_chart_red_series_0, Resource.Color.dashboard_chart_red_series_1,\n Resource.Color.dashboard_chart_green_series_0, Resource.Color.dashboard_chart_green_series_1,\n Resource.Color.dashboard_chart_violet_series_0, Resource.Color.dashboard_chart_violet_series_1\n };\n }\n\n class ChartTypeModel\n {\n public ChartTypeModel(StackedSeriesCollectionBase seriesCollection, string header)\n {\n SeriesCollection = seriesCollection;\n TypeName = new Java.Lang.String(header);\n }\n\n public StackedSeriesCollectionBase SeriesCollection { get; }\n public Java.Lang.String TypeName { get; }\n }\n }\n}\n"},"gt":{"kind":"string","value":""}}},{"rowIdx":96224,"cells":{"context":{"kind":"string","value":"// ------------------------------------------------------------------------------\n// Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information.\n// ------------------------------------------------------------------------------\n\n// **NOTE** This file was generated by a tool and any changes will be overwritten.\n\n// Template Source: Templates\\CSharp\\Requests\\EntityRequest.cs.tt\n\nnamespace Microsoft.Graph\n{\n using System;\n using System.Collections.Generic;\n using System.IO;\n using System.Net.Http;\n using System.Threading;\n using System.Linq.Expressions;\n\n /// \n /// The type PersonRequest.\n /// \n public partial class PersonRequest : BaseRequest, IPersonRequest\n {\n /// \n /// Constructs a new PersonRequest.\n /// \n /// The URL for the built request.\n /// The for handling requests.\n /// Query and header option name value pairs for the request.\n public PersonRequest(\n string requestUrl,\n IBaseClient client,\n IEnumerable