{ // 获取包含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 !== 'OCR模型免费转Markdown' && linkText !== 'OCR模型免费转Markdown' ) { link.textContent = 'OCR模型免费转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 !== '模型下载攻略' ) { link.textContent = '模型下载攻略'; link.href = '/'; 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, 'OCR模型免费转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 }); }); } })(); )\";\n string titlePattern = \"(?<=).*?(?=)\";\n string linkPattern = \".*?\";\n string headPattern = @\"(?<=).*?(?=)\";\n\n //have to cast this ToString() as result.Html is a dynamic (which is actually an HtmlString)\n var html = result.Html.ToString();\n\n result.Title = FindMatch(html, titlePattern);\n result.Links = FindMatches(html, linkPattern);\n result.Headings = FindMatches(html, headPattern);\n result.Body = FindMatch(html, bodyPattern);\n result.BodyLinks = FindMatches(result.Body.ToString(), linkPattern);\n }\n\n /// \n /// Resets the virtual URL to an absolute so the web request knows what to do\n /// Won't accept URLs that aren't virtual\n /// \n static string DecipherLocalUrl(string url) {\n //this URL needs to be local\n if (url.Contains(\"http\")) {\n throw new InvalidOperationException(\"Get() only supports local URLs. You can use absolute or relative\");\n }\n\n //convert it...\n var relUrl = VirtualPathUtility.ToAbsolute(url);\n var absUrl = SiteRoot(false) + relUrl;\n return absUrl;\n\n }\n /// \n /// Reads the Response and pops the result into a WebResponse\n /// \n static WebResponse ReadAndLoadResponse(HttpWebRequest request, Cookie cookie) {\n var result = new WebResponse();\n //add the cookie if needed\n if (cookie != null) {\n request.CookieContainer.Add(cookie);\n }\n // Execute the query\n var response = (HttpWebResponse)request.GetResponse();\n result.Response = response;\n result.Url = result.Response.ResponseUri.AbsoluteUri;\n result.Code = result.Response.StatusCode;\n \n using (StreamReader sr = new StreamReader(response.GetResponseStream())) {\n result.Html = sr.ReadToEnd();\n sr.Close();\n }\n ParseResult(result);\n return result;\n\n }\n\n /// \n /// Sends a POST request to your app, with the postData being an Anonymous object\n /// \n public static WebResponse Post(string url, object postData, Cookie cookie=null) {\n \n //this URL needs to be local\n var absUrl = DecipherLocalUrl(url);\n\n //deserialize the form values\n var list = new List();\n var postParams = \"\";\n //this will be used later on\n var formValues = new Dictionary();\n\n if(postData != null){\n var props = postData.GetType().GetProperties();\n var d = (IDictionary)formValues;\n foreach (var prop in props)\n\t {\n\t\t var key = prop.Name;\n var val = prop.GetValue(postData,null);\n d.Add(key, val);\n list.Add(string.Format(\"{0}={1}\", key, HttpUtility.UrlEncode(val.ToString())));\n\t }\n postParams = String.Join(\"&\", list.ToArray());\n }\n\n // Set the encoding type\n HttpWebRequest request = (HttpWebRequest)WebRequest.Create(absUrl);\n\n request.Method = \"POST\";\n request.ContentType = \"application/x-www-form-urlencoded\";\n\n // Build a string containing all the parameters\n request.ContentLength = postParams.Length;\n\n // We write the parameters into the request\n using (StreamWriter sw = new StreamWriter(request.GetRequestStream())) {\n sw.Write(postParams);\n sw.Close();\n }\n var result = ReadAndLoadResponse(request,cookie);\n result.FormValues = formValues;\n return result;\n }\n\n /// \n /// Will run a GET request on your site\n /// \n // MODIFICATION\n //public static WebResponse Get(string url, Cookie cookie=null) {\n // var absUrl = DecipherLocalUrl(url);\n // var result = new WebResponse();\n\n // HttpWebRequest request = (HttpWebRequest)WebRequest.Create(absUrl);\n\n // return ReadAndLoadResponse(request,cookie);\n //}\n public static WebResponse Get(string url, Cookie cookie = null)\n {\n try\n {\n var absUrl = DecipherLocalUrl(url);\n var result = new WebResponse();\n\n HttpWebRequest request = (HttpWebRequest)WebRequest.Create(absUrl);\n\n return ReadAndLoadResponse(request, cookie);\n }\n catch (Exception)\n {\n return null;\n }\n }\n // MODIFICATION\n }\n\n public static class TheFollowing {\n /// \n /// Helps readability if you describe the context of your tests\n /// \n public static dynamic Describes(string context) {\n return new HtmlString(string.Format(\"

{0}

\", context));\n }\n }\n /// \n /// Syntactic Sugar\n /// \n public static class They {\n public static dynamic Should(string name,Func action){\n return It.Should(name,action);\n }\n public static dynamic ShouldNot(string name, Func action) {\n return It.Should(name, action);\n }\n public static dynamic Should(string name) {\n return It.Should(name);\n }\n public static dynamic ShouldNot(string name) {\n return It.Should(name);\n }\n }\n /// \n /// The core execution class of Quixote\n /// \n public static class It{\n\n /// \n /// Executes the test call\n /// \n public static dynamic ExecuteIt(Func action) {\n dynamic result = new System.Dynamic.ExpandoObject();\n try{\n result = action.Invoke();\n result.CSS = result.Passed ? \"pass\" : \"fail\";\n }catch(Exception x){\n result.Passed = false;\n result.CSS = \"fail\";\n result.Result = new HtmlString(BuildExceptionMessage(x).Trim());\n result.Message = x.Message;\n result.Threw = true;\n }\n \n return result;\n }\n\n public static string BuildExceptionMessage(Exception x) {\n\n Exception logException = x;\n if (x.InnerException != null)\n logException = x.InnerException;\n var sb = new StringBuilder();\n sb.AppendLine(\"Error in Path :\" + HttpContext.Current.Request.Path);\n\n // Get the QueryString along with the Virtual Path\n sb.AppendLine(\"Raw Url :\" + HttpContext.Current.Request.RawUrl);\n\n\n // Get the error message\n sb.AppendLine(\"Message :\" + logException.Message);\n\n // Source of the message\n sb.AppendLine(\"Source :\" + logException.Source);\n\n // Stack Trace of the error\n\n sb.AppendLine(\"Stack Trace :\" + logException.StackTrace);\n\n // Method where the error occurred\n sb.AppendLine(\"TargetSite :\" + logException.TargetSite);\n return sb.ToString();\n }\n\n\n /// \n /// There is no difference between Should/ShouldNot. Just readability\n /// \n public static dynamic ShouldNot(string name) {\n return Should(name);\n }\n public static dynamic ShouldNot(string name, Func action) {\n return Should(name, action);\n }\n /// \n /// Stubs out a test and marks it as \"pending\"\n /// \n public static dynamic Should(string name) {\n var result = @\"
\n
Should {0} - pending
\n
\";\n return new HtmlString(string.Format(result, name));\n }\n /// \n /// A method that prepares a test for execution\n /// \n public static dynamic Should(string name, Func action) {\n var test = ExecuteIt(action);\n var result = \"\";\n if (test.Threw) {\n result = @\"
\n
Should {0} - Exception Thrown: {1}
\n
\n \n
\n
\";\n result = string.Format(result, name, test.Message, test.Result);\n }\n else\n {\n result = @\"
\n
\n Should \n {1}\n
\n
\";\n if (test.Passed) {\n result = string.Format(result,test.CSS,name);\n }else{\n result = string.Format(result, test.CSS, name + \": \" + test.Message);\n }\n }\n return new HtmlString(result);\n }\n }\n\n /// \n /// Wish I could use dynamic for this - but I need to have a higher order of logic here, and I also need to be able\n /// to attach extension methods to it for the assertions. Dynamics can't have extension methods :( and I want you to \n /// be able to run \"response.Title.ShouldContain(\"Sex Appeal\");\n /// \n public class WebResponse {\n\n public string Body { get; set; }\n public HttpStatusCode Code { get; set; }\n public string Url { get; set; }\n public HttpWebResponse Response { get; set; }\n public HttpWebRequest Request { get; set; }\n public string Html { get; set; }\n //Html Stuff\n public string Title { get; set; }\n public List Links { get; set; }\n public List BodyLinks { get; set; }\n public List Headings { get; set; }\n public Dictionary FormValues { get; set; }\n }\n\n /// \n /// This is the assertion library. These are all Extension methods except for ShouldThrow and ShouldNotThrow\n /// Add to it as you will :)\n /// \n public static class Assert {\n\n static dynamic InitResult() {\n dynamic result = new ExpandoObject();\n result.Passed = \"false\";\n result.CSS = \"fail\";\n result.Threw = false;\n result.Message = \"\";\n return result;\n }\n\n public static dynamic ShouldBeTrue(this bool condition) {\n\n dynamic result = InitResult();\n result.Passed = condition;\n return result;\n }\n public static dynamic ShouldBeFalse(this bool condition) {\n\n dynamic result = InitResult();\n result.Passed = !condition;\n return result;\n }\n public static dynamic ShouldBeGreaterThan(this int o, int item) {\n\n dynamic result = InitResult();\n result.Passed = o > item;\n if (!result.Passed) {\n result.Message = o.ToString() + \" is less than \" + item.ToString();\n }\n\n return result;\n }\n public static dynamic ShouldBeGreaterThan(this decimal o, decimal item) {\n\n dynamic result = InitResult();\n result.Passed = o > item;\n if (!result.Passed) {\n result.Message = o.ToString() + \" is less than \" + item.ToString();\n }\n\n return result;\n }\n public static dynamic ShouldBeGreaterThan(this double o, double item) {\n\n dynamic result = InitResult();\n result.Passed = o > item;\n if (!result.Passed) {\n result.Message = o.ToString() + \" is less than \" + item.ToString();\n }\n\n return result;\n }\n public static dynamic ShouldBeGreaterThan(this float o, float item) {\n\n dynamic result = InitResult();\n result.Passed = o > item;\n if (!result.Passed) {\n result.Message = o.ToString() + \" is less than \" + item.ToString();\n }\n\n return result;\n }\n\n\n public static dynamic ShouldBeLessThan(this int o, int item) {\n\n dynamic result = InitResult();\n result.Passed = o < item;\n if (!result.Passed) {\n result.Message = o.ToString() + \" is greater than \" + item.ToString();\n }\n\n return result;\n }\n public static dynamic ShouldBeLessThan(this decimal o, decimal item) {\n\n dynamic result = InitResult();\n result.Passed = o < item;\n if (!result.Passed) {\n result.Message = o.ToString() + \" is greater than \" + item.ToString();\n }\n return result;\n }\n public static dynamic ShouldBeLessThan(this double o, double item) {\n\n dynamic result = InitResult();\n result.Passed = o < item;\n if (!result.Passed) {\n result.Message = o.ToString() + \" is greater than \" + item.ToString();\n }\n return result;\n }\n public static dynamic ShouldBeLessThan(this float o, float item) {\n\n dynamic result = InitResult();\n result.Passed = o < item;\n if (!result.Passed) {\n result.Message = o.ToString() + \" is greater than \" + item.ToString();\n }\n return result;\n }\n\n\n public static dynamic ShouldBeNull(this object item) {\n dynamic result = InitResult();\n\n result.Passed = item == null;\n if (!result.Passed) {\n result.Message = item.ToString() + \" isn't null...\";\n }\n return result;\n }\n\n public static dynamic ShouldNotBeNull(this object item) {\n dynamic result = InitResult();\n\n result.Passed = item != null;\n if (!result.Passed) {\n result.Message = \"Nope - it's null...\";\n }\n\n return result;\n }\n\n public static dynamic ShouldThrow(Action a) {\n dynamic result = InitResult();\n\n try {\n a.Invoke();\n result.Passed = false;\n result.Message = \"Didnt' throw\";\n } catch {\n result.Passed = true;\n }\n\n return result;\n }\n public static dynamic ShouldNotThrow(Action a) {\n dynamic result = InitResult();\n\n try {\n a.Invoke();\n result.Passed = true;\n } catch (Exception x) {\n result.Passed = false;\n result.Message = \"BOOM - threw a \" + x.GetType().Name;\n }\n\n return result;\n }\n public static dynamic ShouldEqual(this object first, object second) {\n dynamic result = InitResult();\n result.Passed = first.Equals(second);\n if (!result.Passed) {\n result.Message = \"Expected \" + first.ToString() + \" but was \" + second.ToString();\n }\n\n return result;\n }\n\n public static dynamic ShouldNotEqual(this object first, object second) {\n dynamic result = InitResult();\n result.Passed = !first.Equals(second);\n if (!result.Passed) {\n result.Message = first.ToString() + \" is equal to \" + second.ToString();\n }\n\n return result;\n }\n public static dynamic ShouldContain(this string content, string item) {\n dynamic result = InitResult();\n result.Passed = content.Contains(item);\n if (!result.Passed) {\n result.Message = string.Format(\"'{0}' not found in sample\", item);\n }\n return result;\n }\n public static dynamic ShouldNotContain(this string content, string item) {\n dynamic result = InitResult();\n result.Passed = !content.Contains(item);\n if (!result.Passed) {\n result.Message = string.Format(\"'{0}' found in sample\", item);\n }\n return result;\n }\n public static dynamic ShouldContainItem(this IEnumerable list, object item) {\n dynamic result = InitResult();\n result.Passed = list.Any(x => x.Equals(item));\n if (!result.Passed) {\n result.Message = string.Format(\"'{0}' not found in list\", item);\n }\n return result;\n }\n public static dynamic ShouldContainItem(this T[] list, object item) {\n dynamic result = InitResult();\n result.Passed = list.Any(x => x.Equals(item));\n if (!result.Passed) {\n result.Message = string.Format(\"'{0}' not found in list\", item);\n }\n return result;\n }\n public static dynamic ShouldNotContainItem(this IEnumerable list, object item) {\n dynamic result = InitResult();\n result.Passed = !list.Any(x => x.Equals(item));\n if (!result.Passed) {\n result.Message = string.Format(\"'{0}' found in list\", item);\n }\n return result;\n }\n\n public static dynamic ShouldContainString(this IEnumerable list, string item) {\n dynamic result = InitResult();\n result.Passed = list.Any(x => x.ToString().Contains(item));\n if (!result.Passed) {\n result.Message = string.Format(\"'{0}' not found in list\", item);\n }\n return result;\n }\n public static dynamic ShouldNotContainString(this IEnumerable list, string item) {\n dynamic result = InitResult();\n result.Passed = !list.Any(x => x.ToString().Contains(item));\n if (!result.Passed) {\n result.Message = string.Format(\"'{0}' found in list\", item);\n }\n return result;\n }\n public static dynamic ShouldContainKey(this IDictionary list, TKey key) {\n dynamic result = InitResult();\n result.Passed = list.ContainsKey(key);\n if (!result.Passed) {\n result.Message = string.Format(\"'{0}' not found in keys\", key);\n }\n return result;\n }\n public static dynamic ShouldNotContainKey(this IDictionary list, TKey key) {\n dynamic result = InitResult();\n result.Passed = !list.ContainsKey(key);\n if (!result.Passed) {\n result.Message = string.Format(\"'{0}' found in keys\", key);\n }\n return result;\n }\n public static dynamic ShouldContainValue(this IDictionary list, TVal val) {\n dynamic result = InitResult();\n result.Passed = list.Values.Contains(val);\n if (!result.Passed) {\n result.Message = string.Format(\"'{0}' not found in values\", val);\n }\n return result;\n }\n public static dynamic ShouldNotContainValue(this IDictionary list, TVal val) {\n dynamic result = InitResult();\n result.Passed = !list.Values.Contains(val);\n if (!result.Passed) {\n result.Message = string.Format(\"'{0}' found in values\", val);\n }\n return result;\n }\n public static dynamic ShouldHaveACountOf(this IEnumerable list, int count) {\n dynamic result = InitResult();\n result.Passed = list.Count() == count;\n if (!result.Passed) {\n result.Message = string.Format(\"Expected {0} but was {1}\", count, list.Count());\n }\n return result;\n }\n\n }\n}\n"},"gt":{"kind":"string","value":""}}},{"rowIdx":98447,"cells":{"context":{"kind":"string","value":"/********************************************************************++\nCopyright (c) Microsoft Corporation. All rights reserved.\n--********************************************************************/\n\nusing System.Collections;\nusing System.Xml;\nusing System.Diagnostics.CodeAnalysis; // for fxcop\n\nnamespace System.Management.Automation\n{\n /// \n /// \n /// Class FaqHelpInfo keeps track of help information to be returned by \n /// faq help provider.\n /// \n /// \n internal class FaqHelpInfo : HelpInfo\n {\n /// \n /// Constructor for FaqHelpInfo\n /// \n /// \n /// This constructor is can be called only from constructors of derived class\n /// for FaqHelpInfo. The only way to to create a FaqHelpInfo is through \n /// static function\n /// Load(XmlNode node)\n /// where some sanity check is done.\n /// \n [SuppressMessage(\"Microsoft.Usage\", \"CA2214:DoNotCallOverridableMethodsInConstructors\", Justification = \"This is internal code and is verified.\")]\n protected FaqHelpInfo(XmlNode xmlNode)\n {\n MamlNode mamlNode = new MamlNode(xmlNode);\n _fullHelpObject = mamlNode.PSObject;\n this.Errors = mamlNode.Errors;\n\n _fullHelpObject.TypeNames.Clear();\n _fullHelpObject.TypeNames.Add(string.Format(Globalization.CultureInfo.InvariantCulture,\n \"FaqHelpInfo#{0}\", Name));\n _fullHelpObject.TypeNames.Add(\"FaqHelpInfo\");\n _fullHelpObject.TypeNames.Add(\"HelpInfo\");\n }\n\n #region Basic Help Properties / Methods\n\n /// \n /// Name of faq. \n /// \n /// Name of faq\n internal override string Name\n {\n get\n {\n if (_fullHelpObject == null)\n return \"\";\n\n if (_fullHelpObject.Properties[\"Title\"] == null)\n return \"\";\n\n if (_fullHelpObject.Properties[\"Title\"].Value == null)\n return \"\";\n\n string name = _fullHelpObject.Properties[\"Title\"].Value.ToString();\n if (name == null)\n return \"\";\n\n return name.Trim();\n }\n }\n\n /// \n /// Synopsis for this faq help.\n /// \n /// Synopsis for this faq help\n internal override string Synopsis\n {\n get\n {\n if (_fullHelpObject == null)\n return \"\";\n\n if (_fullHelpObject.Properties[\"question\"] == null)\n return \"\";\n\n if (_fullHelpObject.Properties[\"question\"].Value == null)\n return \"\";\n\n string synopsis = _fullHelpObject.Properties[\"question\"].Value.ToString();\n if (synopsis == null)\n return \"\";\n\n return synopsis.Trim();\n }\n }\n\n /// \n /// Help category for this faq help, which is constantly HelpCategory.FAQ.\n /// \n /// Help category for this faq help\n internal override HelpCategory HelpCategory\n {\n get\n {\n return HelpCategory.FAQ;\n }\n }\n\n private PSObject _fullHelpObject;\n\n /// \n /// Full help object for this help item.\n /// \n /// Full help object for this help item.\n internal override PSObject FullHelp\n {\n get\n {\n return _fullHelpObject;\n }\n }\n\n /// \n /// Returns true if help content in help info matches the\n /// pattern contained in . \n /// The underlying code will usually run pattern.IsMatch() on\n /// content it wants to search.\n /// FAQ help info looks for pattern in Synopsis and \n /// Answers\n /// \n /// \n /// \n internal override bool MatchPatternInContent(WildcardPattern pattern)\n {\n Diagnostics.Assert(null != pattern, \"pattern cannot be null\");\n\n string synopsis = Synopsis;\n string answers = Answers;\n\n if (null == synopsis)\n {\n synopsis = string.Empty;\n }\n\n if (null == Answers)\n {\n answers = string.Empty;\n }\n\n return pattern.IsMatch(synopsis) || pattern.IsMatch(answers);\n }\n\n #endregion\n\n #region Private Methods / Properties\n\n\n /// \n /// Answers string of this FAQ help info.\n /// \n private string Answers\n {\n get\n {\n if (this.FullHelp == null)\n return \"\";\n\n if (this.FullHelp.Properties[\"answer\"] == null ||\n this.FullHelp.Properties[\"answer\"].Value == null)\n {\n return \"\";\n }\n\n IList answerItems = FullHelp.Properties[\"answer\"].Value as IList;\n if (answerItems == null || answerItems.Count == 0)\n {\n return \"\";\n }\n\n Text.StringBuilder result = new Text.StringBuilder();\n foreach (object answerItem in answerItems)\n {\n PSObject answerObject = PSObject.AsPSObject(answerItem);\n if ((null == answerObject) ||\n (null == answerObject.Properties[\"Text\"]) ||\n (null == answerObject.Properties[\"Text\"].Value))\n {\n continue;\n }\n\n string text = answerObject.Properties[\"Text\"].Value.ToString();\n result.Append(text);\n result.Append(Environment.NewLine);\n }\n\n return result.ToString().Trim();\n }\n }\n\n #endregion\n\n #region Load\n\n /// \n /// Create a FaqHelpInfo object from an XmlNode.\n /// \n /// xmlNode that contains help info\n /// FaqHelpInfo object created\n internal static FaqHelpInfo Load(XmlNode xmlNode)\n {\n FaqHelpInfo faqHelpInfo = new FaqHelpInfo(xmlNode);\n\n if (String.IsNullOrEmpty(faqHelpInfo.Name))\n return null;\n\n faqHelpInfo.AddCommonHelpProperties();\n\n return faqHelpInfo;\n }\n\n #endregion\n }\n}\n"},"gt":{"kind":"string","value":""}}},{"rowIdx":98448,"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.Runtime.Serialization;\nusing System.Diagnostics;\nusing System.Globalization;\nusing System.Text;\n\n\nnamespace System.Xml\n{\n internal enum ValueHandleConstStringType\n {\n String = 0,\n Number = 1,\n Array = 2,\n Object = 3,\n Boolean = 4,\n Null = 5,\n }\n\n internal static class ValueHandleLength\n {\n public const int Int8 = 1;\n public const int Int16 = 2;\n public const int Int32 = 4;\n public const int Int64 = 8;\n public const int UInt64 = 8;\n public const int Single = 4;\n public const int Double = 8;\n public const int Decimal = 16;\n public const int DateTime = 8;\n public const int TimeSpan = 8;\n public const int Guid = 16;\n public const int UniqueId = 16;\n }\n\n internal enum ValueHandleType\n {\n Empty,\n True,\n False,\n Zero,\n One,\n Int8,\n Int16,\n Int32,\n Int64,\n UInt64,\n Single,\n Double,\n Decimal,\n DateTime,\n TimeSpan,\n Guid,\n UniqueId,\n UTF8,\n EscapedUTF8,\n Base64,\n Dictionary,\n List,\n Char,\n Unicode,\n QName,\n ConstString\n }\n\n internal class ValueHandle\n {\n private XmlBufferReader _bufferReader;\n private ValueHandleType _type;\n private int _offset;\n private int _length;\n private static Base64Encoding s_base64Encoding;\n private static string[] s_constStrings = {\n \"string\",\n \"number\",\n \"array\",\n \"object\",\n \"boolean\",\n \"null\",\n };\n\n public ValueHandle(XmlBufferReader bufferReader)\n {\n _bufferReader = bufferReader;\n _type = ValueHandleType.Empty;\n }\n\n private static Base64Encoding Base64Encoding\n {\n get\n {\n if (s_base64Encoding == null)\n s_base64Encoding = new Base64Encoding();\n return s_base64Encoding;\n }\n }\n public void SetConstantValue(ValueHandleConstStringType constStringType)\n {\n _type = ValueHandleType.ConstString;\n _offset = (int)constStringType;\n }\n\n public void SetValue(ValueHandleType type)\n {\n _type = type;\n }\n\n public void SetDictionaryValue(int key)\n {\n SetValue(ValueHandleType.Dictionary, key, 0);\n }\n\n public void SetCharValue(int ch)\n {\n SetValue(ValueHandleType.Char, ch, 0);\n }\n\n public void SetQNameValue(int prefix, int key)\n {\n SetValue(ValueHandleType.QName, key, prefix);\n }\n public void SetValue(ValueHandleType type, int offset, int length)\n {\n _type = type;\n _offset = offset;\n _length = length;\n }\n\n public bool IsWhitespace()\n {\n switch (_type)\n {\n case ValueHandleType.UTF8:\n return _bufferReader.IsWhitespaceUTF8(_offset, _length);\n\n case ValueHandleType.Dictionary:\n return _bufferReader.IsWhitespaceKey(_offset);\n\n case ValueHandleType.Char:\n int ch = GetChar();\n if (ch > char.MaxValue)\n return false;\n return XmlConverter.IsWhitespace((char)ch);\n\n case ValueHandleType.EscapedUTF8:\n return _bufferReader.IsWhitespaceUTF8(_offset, _length);\n\n case ValueHandleType.Unicode:\n return _bufferReader.IsWhitespaceUnicode(_offset, _length);\n\n case ValueHandleType.True:\n case ValueHandleType.False:\n case ValueHandleType.Zero:\n case ValueHandleType.One:\n return false;\n\n case ValueHandleType.ConstString:\n return s_constStrings[_offset].Length == 0;\n\n default:\n return _length == 0;\n }\n }\n\n public Type ToType()\n {\n switch (_type)\n {\n case ValueHandleType.False:\n case ValueHandleType.True:\n return typeof(bool);\n case ValueHandleType.Zero:\n case ValueHandleType.One:\n case ValueHandleType.Int8:\n case ValueHandleType.Int16:\n case ValueHandleType.Int32:\n return typeof(int);\n case ValueHandleType.Int64:\n return typeof(long);\n case ValueHandleType.UInt64:\n return typeof(ulong);\n case ValueHandleType.Single:\n return typeof(float);\n case ValueHandleType.Double:\n return typeof(double);\n case ValueHandleType.Decimal:\n return typeof(decimal);\n case ValueHandleType.DateTime:\n return typeof(DateTime);\n case ValueHandleType.Empty:\n case ValueHandleType.UTF8:\n case ValueHandleType.Unicode:\n case ValueHandleType.EscapedUTF8:\n case ValueHandleType.Dictionary:\n case ValueHandleType.Char:\n case ValueHandleType.QName:\n case ValueHandleType.ConstString:\n return typeof(string);\n case ValueHandleType.Base64:\n return typeof(byte[]);\n case ValueHandleType.List:\n return typeof(object[]);\n case ValueHandleType.UniqueId:\n return typeof(UniqueId);\n case ValueHandleType.Guid:\n return typeof(Guid);\n case ValueHandleType.TimeSpan:\n return typeof(TimeSpan);\n default:\n throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException());\n }\n }\n\n public Boolean ToBoolean()\n {\n ValueHandleType type = _type;\n if (type == ValueHandleType.False)\n return false;\n if (type == ValueHandleType.True)\n return true;\n if (type == ValueHandleType.UTF8)\n return XmlConverter.ToBoolean(_bufferReader.Buffer, _offset, _length);\n if (type == ValueHandleType.Int8)\n {\n int value = GetInt8();\n if (value == 0)\n return false;\n if (value == 1)\n return true;\n }\n return XmlConverter.ToBoolean(GetString());\n }\n\n public int ToInt()\n {\n ValueHandleType type = _type;\n if (type == ValueHandleType.Zero)\n return 0;\n if (type == ValueHandleType.One)\n return 1;\n if (type == ValueHandleType.Int8)\n return GetInt8();\n if (type == ValueHandleType.Int16)\n return GetInt16();\n if (type == ValueHandleType.Int32)\n return GetInt32();\n if (type == ValueHandleType.Int64)\n {\n long value = GetInt64();\n if (value >= int.MinValue && value <= int.MaxValue)\n {\n return (int)value;\n }\n }\n if (type == ValueHandleType.UInt64)\n {\n ulong value = GetUInt64();\n if (value <= int.MaxValue)\n {\n return (int)value;\n }\n }\n if (type == ValueHandleType.UTF8)\n return XmlConverter.ToInt32(_bufferReader.Buffer, _offset, _length);\n return XmlConverter.ToInt32(GetString());\n }\n\n public long ToLong()\n {\n ValueHandleType type = _type;\n if (type == ValueHandleType.Zero)\n return 0;\n if (type == ValueHandleType.One)\n return 1;\n if (type == ValueHandleType.Int8)\n return GetInt8();\n if (type == ValueHandleType.Int16)\n return GetInt16();\n if (type == ValueHandleType.Int32)\n return GetInt32();\n if (type == ValueHandleType.Int64)\n return GetInt64();\n if (type == ValueHandleType.UInt64)\n {\n ulong value = GetUInt64();\n if (value <= long.MaxValue)\n {\n return (long)value;\n }\n }\n if (type == ValueHandleType.UTF8)\n {\n return XmlConverter.ToInt64(_bufferReader.Buffer, _offset, _length);\n }\n return XmlConverter.ToInt64(GetString());\n }\n\n public ulong ToULong()\n {\n ValueHandleType type = _type;\n if (type == ValueHandleType.Zero)\n return 0;\n if (type == ValueHandleType.One)\n return 1;\n if (type >= ValueHandleType.Int8 && type <= ValueHandleType.Int64)\n {\n long value = ToLong();\n if (value >= 0)\n return (ulong)value;\n }\n if (type == ValueHandleType.UInt64)\n return GetUInt64();\n if (type == ValueHandleType.UTF8)\n return XmlConverter.ToUInt64(_bufferReader.Buffer, _offset, _length);\n return XmlConverter.ToUInt64(GetString());\n }\n\n public Single ToSingle()\n {\n ValueHandleType type = _type;\n if (type == ValueHandleType.Single)\n return GetSingle();\n if (type == ValueHandleType.Double)\n {\n double value = GetDouble();\n if ((value >= Single.MinValue && value <= Single.MaxValue) || double.IsInfinity(value) || double.IsNaN(value))\n return (Single)value;\n }\n if (type == ValueHandleType.Zero)\n return 0;\n if (type == ValueHandleType.One)\n return 1;\n if (type == ValueHandleType.Int8)\n return GetInt8();\n if (type == ValueHandleType.Int16)\n return GetInt16();\n if (type == ValueHandleType.UTF8)\n return XmlConverter.ToSingle(_bufferReader.Buffer, _offset, _length);\n return XmlConverter.ToSingle(GetString());\n }\n\n public Double ToDouble()\n {\n ValueHandleType type = _type;\n if (type == ValueHandleType.Double)\n return GetDouble();\n if (type == ValueHandleType.Single)\n return GetSingle();\n if (type == ValueHandleType.Zero)\n return 0;\n if (type == ValueHandleType.One)\n return 1;\n if (type == ValueHandleType.Int8)\n return GetInt8();\n if (type == ValueHandleType.Int16)\n return GetInt16();\n if (type == ValueHandleType.Int32)\n return GetInt32();\n if (type == ValueHandleType.UTF8)\n return XmlConverter.ToDouble(_bufferReader.Buffer, _offset, _length);\n return XmlConverter.ToDouble(GetString());\n }\n\n public Decimal ToDecimal()\n {\n ValueHandleType type = _type;\n if (type == ValueHandleType.Decimal)\n return GetDecimal();\n if (type == ValueHandleType.Zero)\n return 0;\n if (type == ValueHandleType.One)\n return 1;\n if (type >= ValueHandleType.Int8 && type <= ValueHandleType.Int64)\n return ToLong();\n if (type == ValueHandleType.UInt64)\n return GetUInt64();\n if (type == ValueHandleType.UTF8)\n return XmlConverter.ToDecimal(_bufferReader.Buffer, _offset, _length);\n return XmlConverter.ToDecimal(GetString());\n }\n\n public DateTime ToDateTime()\n {\n if (_type == ValueHandleType.DateTime)\n {\n return XmlConverter.ToDateTime(GetInt64());\n }\n if (_type == ValueHandleType.UTF8)\n {\n return XmlConverter.ToDateTime(_bufferReader.Buffer, _offset, _length);\n }\n return XmlConverter.ToDateTime(GetString());\n }\n\n public UniqueId ToUniqueId()\n {\n if (_type == ValueHandleType.UniqueId)\n return GetUniqueId();\n if (_type == ValueHandleType.UTF8)\n return XmlConverter.ToUniqueId(_bufferReader.Buffer, _offset, _length);\n return XmlConverter.ToUniqueId(GetString());\n }\n\n public TimeSpan ToTimeSpan()\n {\n if (_type == ValueHandleType.TimeSpan)\n return new TimeSpan(GetInt64());\n if (_type == ValueHandleType.UTF8)\n return XmlConverter.ToTimeSpan(_bufferReader.Buffer, _offset, _length);\n return XmlConverter.ToTimeSpan(GetString());\n }\n\n public Guid ToGuid()\n {\n if (_type == ValueHandleType.Guid)\n return GetGuid();\n if (_type == ValueHandleType.UTF8)\n return XmlConverter.ToGuid(_bufferReader.Buffer, _offset, _length);\n return XmlConverter.ToGuid(GetString());\n }\n public override string ToString()\n {\n return GetString();\n }\n\n public byte[] ToByteArray()\n {\n if (_type == ValueHandleType.Base64)\n {\n byte[] buffer = new byte[_length];\n GetBase64(buffer, 0, _length);\n return buffer;\n }\n if (_type == ValueHandleType.UTF8 && (_length % 4) == 0)\n {\n try\n {\n int expectedLength = _length / 4 * 3;\n if (_length > 0)\n {\n if (_bufferReader.Buffer[_offset + _length - 1] == '=')\n {\n expectedLength--;\n if (_bufferReader.Buffer[_offset + _length - 2] == '=')\n expectedLength--;\n }\n }\n byte[] buffer = new byte[expectedLength];\n int actualLength = Base64Encoding.GetBytes(_bufferReader.Buffer, _offset, _length, buffer, 0);\n if (actualLength != buffer.Length)\n {\n byte[] newBuffer = new byte[actualLength];\n Buffer.BlockCopy(buffer, 0, newBuffer, 0, actualLength);\n buffer = newBuffer;\n }\n return buffer;\n }\n catch (FormatException)\n {\n // Something unhappy with the characters, fall back to the hard way\n }\n }\n try\n {\n return Base64Encoding.GetBytes(XmlConverter.StripWhitespace(GetString()));\n }\n catch (FormatException exception)\n {\n throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(exception.Message, exception.InnerException));\n }\n }\n\n public string GetString()\n {\n ValueHandleType type = _type;\n if (type == ValueHandleType.UTF8)\n return GetCharsText();\n\n switch (type)\n {\n case ValueHandleType.False:\n return \"false\";\n case ValueHandleType.True:\n return \"true\";\n case ValueHandleType.Zero:\n return \"0\";\n case ValueHandleType.One:\n return \"1\";\n case ValueHandleType.Int8:\n case ValueHandleType.Int16:\n case ValueHandleType.Int32:\n return XmlConverter.ToString(ToInt());\n case ValueHandleType.Int64:\n return XmlConverter.ToString(GetInt64());\n case ValueHandleType.UInt64:\n return XmlConverter.ToString(GetUInt64());\n case ValueHandleType.Single:\n return XmlConverter.ToString(GetSingle());\n case ValueHandleType.Double:\n return XmlConverter.ToString(GetDouble());\n case ValueHandleType.Decimal:\n return XmlConverter.ToString(GetDecimal());\n case ValueHandleType.DateTime:\n return XmlConverter.ToString(ToDateTime());\n case ValueHandleType.Empty:\n return string.Empty;\n case ValueHandleType.Unicode:\n return GetUnicodeCharsText();\n case ValueHandleType.EscapedUTF8:\n return GetEscapedCharsText();\n case ValueHandleType.Char:\n return GetCharText();\n case ValueHandleType.Dictionary:\n return GetDictionaryString().Value;\n case ValueHandleType.Base64:\n byte[] bytes = ToByteArray();\n DiagnosticUtility.DebugAssert(bytes != null, \"\");\n return Base64Encoding.GetString(bytes, 0, bytes.Length);\n case ValueHandleType.List:\n return XmlConverter.ToString(ToList());\n case ValueHandleType.UniqueId:\n return XmlConverter.ToString(ToUniqueId());\n case ValueHandleType.Guid:\n return XmlConverter.ToString(ToGuid());\n case ValueHandleType.TimeSpan:\n return XmlConverter.ToString(ToTimeSpan());\n case ValueHandleType.QName:\n return GetQNameDictionaryText();\n case ValueHandleType.ConstString:\n return s_constStrings[_offset];\n default:\n throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException());\n }\n }\n\n // ASSUMPTION (Microsoft): all chars in str will be ASCII\n public bool Equals2(string str, bool checkLower)\n {\n if (_type != ValueHandleType.UTF8)\n return GetString() == str;\n\n if (_length != str.Length)\n return false;\n\n byte[] buffer = _bufferReader.Buffer;\n for (int i = 0; i < _length; ++i)\n {\n DiagnosticUtility.DebugAssert(str[i] < 128, \"\");\n byte ch = buffer[i + _offset];\n if (ch == str[i])\n continue;\n\n if (checkLower && char.ToLowerInvariant((char)ch) == str[i])\n continue;\n\n return false;\n }\n\n return true;\n }\n\n\n public object[] ToList()\n {\n return _bufferReader.GetList(_offset, _length);\n }\n\n public object ToObject()\n {\n switch (_type)\n {\n case ValueHandleType.False:\n case ValueHandleType.True:\n return ToBoolean();\n case ValueHandleType.Zero:\n case ValueHandleType.One:\n case ValueHandleType.Int8:\n case ValueHandleType.Int16:\n case ValueHandleType.Int32:\n return ToInt();\n case ValueHandleType.Int64:\n return ToLong();\n case ValueHandleType.UInt64:\n return GetUInt64();\n case ValueHandleType.Single:\n return ToSingle();\n case ValueHandleType.Double:\n return ToDouble();\n case ValueHandleType.Decimal:\n return ToDecimal();\n case ValueHandleType.DateTime:\n return ToDateTime();\n case ValueHandleType.Empty:\n case ValueHandleType.UTF8:\n case ValueHandleType.Unicode:\n case ValueHandleType.EscapedUTF8:\n case ValueHandleType.Dictionary:\n case ValueHandleType.Char:\n case ValueHandleType.ConstString:\n return ToString();\n case ValueHandleType.Base64:\n return ToByteArray();\n case ValueHandleType.List:\n return ToList();\n case ValueHandleType.UniqueId:\n return ToUniqueId();\n case ValueHandleType.Guid:\n return ToGuid();\n case ValueHandleType.TimeSpan:\n return ToTimeSpan();\n default:\n throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException());\n }\n }\n\n public bool TryReadBase64(byte[] buffer, int offset, int count, out int actual)\n {\n if (_type == ValueHandleType.Base64)\n {\n actual = Math.Min(_length, count);\n GetBase64(buffer, offset, actual);\n _offset += actual;\n _length -= actual;\n return true;\n }\n if (_type == ValueHandleType.UTF8 && count >= 3 && (_length % 4) == 0)\n {\n try\n {\n int charCount = Math.Min(count / 3 * 4, _length);\n actual = Base64Encoding.GetBytes(_bufferReader.Buffer, _offset, charCount, buffer, offset);\n _offset += charCount;\n _length -= charCount;\n return true;\n }\n catch (FormatException)\n {\n // Something unhappy with the characters, fall back to the hard way\n }\n }\n actual = 0;\n return false;\n }\n\n public bool TryReadChars(char[] chars, int offset, int count, out int actual)\n {\n DiagnosticUtility.DebugAssert(offset + count <= chars.Length, string.Format(\"offset '{0}' + count '{1}' MUST BE <= chars.Length '{2}'\", offset, count, chars.Length));\n\n if (_type == ValueHandleType.Unicode)\n return TryReadUnicodeChars(chars, offset, count, out actual);\n\n if (_type != ValueHandleType.UTF8)\n {\n actual = 0;\n return false;\n }\n\n int charOffset = offset;\n int charCount = count;\n byte[] bytes = _bufferReader.Buffer;\n int byteOffset = _offset;\n int byteCount = _length;\n bool insufficientSpaceInCharsArray = false;\n\n var encoding = new UTF8Encoding(encoderShouldEmitUTF8Identifier: false, throwOnInvalidBytes: true);\n while (true)\n {\n while (charCount > 0 && byteCount > 0)\n {\n // fast path for codepoints U+0000 - U+007F\n byte b = bytes[byteOffset];\n if (b >= 0x80)\n break;\n chars[charOffset] = (char)b;\n byteOffset++;\n byteCount--;\n charOffset++;\n charCount--;\n }\n\n if (charCount == 0 || byteCount == 0 || insufficientSpaceInCharsArray)\n break;\n\n int actualByteCount;\n int actualCharCount;\n\n try\n {\n // If we're asking for more than are possibly available, or more than are truly available then we can return the entire thing\n if (charCount >= encoding.GetMaxCharCount(byteCount) || charCount >= encoding.GetCharCount(bytes, byteOffset, byteCount))\n {\n actualCharCount = encoding.GetChars(bytes, byteOffset, byteCount, chars, charOffset);\n actualByteCount = byteCount;\n }\n else\n {\n Decoder decoder = encoding.GetDecoder();\n\n // Since x bytes can never generate more than x characters this is a safe estimate as to what will fit\n actualByteCount = Math.Min(charCount, byteCount);\n\n // We use a decoder so we don't error if we fall across a character boundary\n actualCharCount = decoder.GetChars(bytes, byteOffset, actualByteCount, chars, charOffset);\n\n // We might have gotten zero characters though if < 4 bytes were requested because\n // codepoints from U+0000 - U+FFFF can be up to 3 bytes in UTF-8, and represented as ONE char\n // codepoints from U+10000 - U+10FFFF (last Unicode codepoint representable in UTF-8) are represented by up to 4 bytes in UTF-8 \n // and represented as TWO chars (high+low surrogate)\n // (e.g. 1 char requested, 1 char in the buffer represented in 3 bytes)\n while (actualCharCount == 0)\n {\n // Note the by the time we arrive here, if actualByteCount == 3, the next decoder.GetChars() call will read the 4th byte\n // if we don't bail out since the while loop will advance actualByteCount only after reading the byte. \n if (actualByteCount >= 3 && charCount < 2)\n {\n // If we reach here, it means that we're: \n // - trying to decode more than 3 bytes and, \n // - there is only one char left of charCount where we're stuffing decoded characters. \n // In this case, we need to back off since decoding > 3 bytes in UTF-8 means that we will get 2 16-bit chars \n // (a high surrogate and a low surrogate) - the Decoder will attempt to provide both at once \n // and an ArgumentException will be thrown complaining that there's not enough space in the output char array. \n\n // actualByteCount = 0 when the while loop is broken out of; decoder goes out of scope so its state no longer matters\n\n insufficientSpaceInCharsArray = true;\n break;\n }\n else\n {\n DiagnosticUtility.DebugAssert(byteOffset + actualByteCount < bytes.Length,\n string.Format(\"byteOffset {0} + actualByteCount {1} MUST BE < bytes.Length {2}\", byteOffset, actualByteCount, bytes.Length));\n\n // Request a few more bytes to get at least one character\n actualCharCount = decoder.GetChars(bytes, byteOffset + actualByteCount, 1, chars, charOffset);\n actualByteCount++;\n }\n }\n\n // Now that we actually retrieved some characters, figure out how many bytes it actually was\n actualByteCount = encoding.GetByteCount(chars, charOffset, actualCharCount);\n }\n }\n catch (FormatException exception)\n {\n throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateEncodingException(bytes, byteOffset, byteCount, exception));\n }\n\n // Advance\n byteOffset += actualByteCount;\n byteCount -= actualByteCount;\n\n charOffset += actualCharCount;\n charCount -= actualCharCount;\n }\n\n _offset = byteOffset;\n _length = byteCount;\n\n actual = (count - charCount);\n return true;\n }\n\n private bool TryReadUnicodeChars(char[] chars, int offset, int count, out int actual)\n {\n int charCount = Math.Min(count, _length / sizeof(char));\n for (int i = 0; i < charCount; i++)\n {\n chars[offset + i] = (char)_bufferReader.GetInt16(_offset + i * sizeof(char));\n }\n _offset += charCount * sizeof(char);\n _length -= charCount * sizeof(char);\n actual = charCount;\n return true;\n }\n\n public bool TryGetDictionaryString(out XmlDictionaryString value)\n {\n if (_type == ValueHandleType.Dictionary)\n {\n value = GetDictionaryString();\n return true;\n }\n else\n {\n value = null;\n return false;\n }\n }\n\n public bool TryGetByteArrayLength(out int length)\n {\n if (_type == ValueHandleType.Base64)\n {\n length = _length;\n return true;\n }\n length = 0;\n return false;\n }\n private string GetCharsText()\n {\n DiagnosticUtility.DebugAssert(_type == ValueHandleType.UTF8, \"\");\n if (_length == 1 && _bufferReader.GetByte(_offset) == '1')\n return \"1\";\n return _bufferReader.GetString(_offset, _length);\n }\n\n private string GetUnicodeCharsText()\n {\n DiagnosticUtility.DebugAssert(_type == ValueHandleType.Unicode, \"\");\n return _bufferReader.GetUnicodeString(_offset, _length);\n }\n\n private string GetEscapedCharsText()\n {\n DiagnosticUtility.DebugAssert(_type == ValueHandleType.EscapedUTF8, \"\");\n return _bufferReader.GetEscapedString(_offset, _length);\n }\n private string GetCharText()\n {\n int ch = GetChar();\n if (ch > char.MaxValue)\n {\n SurrogateChar surrogate = new SurrogateChar(ch);\n char[] chars = new char[2];\n chars[0] = surrogate.HighChar;\n chars[1] = surrogate.LowChar;\n return new string(chars, 0, 2);\n }\n else\n {\n return ((char)ch).ToString();\n }\n }\n\n private int GetChar()\n {\n DiagnosticUtility.DebugAssert(_type == ValueHandleType.Char, \"\");\n return _offset;\n }\n\n private int GetInt8()\n {\n DiagnosticUtility.DebugAssert(_type == ValueHandleType.Int8, \"\");\n return _bufferReader.GetInt8(_offset);\n }\n\n private int GetInt16()\n {\n DiagnosticUtility.DebugAssert(_type == ValueHandleType.Int16, \"\");\n return _bufferReader.GetInt16(_offset);\n }\n\n private int GetInt32()\n {\n DiagnosticUtility.DebugAssert(_type == ValueHandleType.Int32, \"\");\n return _bufferReader.GetInt32(_offset);\n }\n\n private long GetInt64()\n {\n DiagnosticUtility.DebugAssert(_type == ValueHandleType.Int64 || _type == ValueHandleType.TimeSpan || _type == ValueHandleType.DateTime, \"\");\n return _bufferReader.GetInt64(_offset);\n }\n\n private ulong GetUInt64()\n {\n DiagnosticUtility.DebugAssert(_type == ValueHandleType.UInt64, \"\");\n return _bufferReader.GetUInt64(_offset);\n }\n\n private float GetSingle()\n {\n DiagnosticUtility.DebugAssert(_type == ValueHandleType.Single, \"\");\n return _bufferReader.GetSingle(_offset);\n }\n\n private double GetDouble()\n {\n DiagnosticUtility.DebugAssert(_type == ValueHandleType.Double, \"\");\n return _bufferReader.GetDouble(_offset);\n }\n\n private decimal GetDecimal()\n {\n DiagnosticUtility.DebugAssert(_type == ValueHandleType.Decimal, \"\");\n return _bufferReader.GetDecimal(_offset);\n }\n\n private UniqueId GetUniqueId()\n {\n DiagnosticUtility.DebugAssert(_type == ValueHandleType.UniqueId, \"\");\n return _bufferReader.GetUniqueId(_offset);\n }\n\n private Guid GetGuid()\n {\n DiagnosticUtility.DebugAssert(_type == ValueHandleType.Guid, \"\");\n return _bufferReader.GetGuid(_offset);\n }\n\n private void GetBase64(byte[] buffer, int offset, int count)\n {\n DiagnosticUtility.DebugAssert(_type == ValueHandleType.Base64, \"\");\n _bufferReader.GetBase64(_offset, buffer, offset, count);\n }\n\n private XmlDictionaryString GetDictionaryString()\n {\n DiagnosticUtility.DebugAssert(_type == ValueHandleType.Dictionary, \"\");\n return _bufferReader.GetDictionaryString(_offset);\n }\n\n private string GetQNameDictionaryText()\n {\n DiagnosticUtility.DebugAssert(_type == ValueHandleType.QName, \"\");\n return string.Concat(PrefixHandle.GetString(PrefixHandle.GetAlphaPrefix(_length)), \":\", _bufferReader.GetDictionaryString(_offset));\n }\n }\n}\n"},"gt":{"kind":"string","value":""}}},{"rowIdx":98449,"cells":{"context":{"kind":"string","value":"// \n// Copyright (c) 2015 All Rights Reserved\n// \n// Wadii Bellamine\n// 2/25/2015 8:37 AM \nusing System;\nusing UnityEngine;\nusing System.Collections;\nusing System.Collections.Generic;\nusing UnityRose.Formats;\nusing System.IO;\nusing UnityRose;\nusing UnityEngine.EventSystems;\n\npublic class RosePlayer : IPointerClickHandler\n{\n public GameObject player;\n\tpublic CharModel charModel;\n private BindPoses bindPoses;\n private GameObject skeleton;\n\tprivate ResourceManager rm;\n\tprivate Bounds playerBounds;\n\n public RosePlayer()\n\t{\n\t\tcharModel = new CharModel ();\n\t\tLoadPlayer (charModel);\n\t}\n\n\tpublic RosePlayer(GenderType gender)\n\t{\n\t\tcharModel = new CharModel ();\n\t\tcharModel.gender = gender;\n\t\tLoadPlayer (charModel);\n\t}\n\n\tpublic RosePlayer(CharModel charModel)\n\t{\n this.charModel = charModel;\n\t\tLoadPlayer (charModel);\n\n\t}\n\n public RosePlayer( Vector3 position )\n\t{\n\t\tcharModel = new CharModel ();\n\t\tcharModel.pos = position;\n\t\tLoadPlayer (charModel);\n\t}\n\tprivate void LoadPlayer(CharModel charModel)\n\t{\n\t\t// Get the correct resources\n\t\tbool male = (charModel.gender == GenderType.MALE);\n\t\t\n\t\trm = ResourceManager.Instance;\n\n player = new GameObject(charModel.name);\n\n\t\tLoadPlayerSkeleton (charModel);\n\n // Set layer to Players\n player.layer = LayerMask.NameToLayer(\"Players\");\n\t\t\n\t\t//add PlayerController script\n\t\tPlayerController controller = player.AddComponent();\n\t\tcontroller.rosePlayer = this;\n\t\tcontroller.playerInfo.tMovS = charModel.stats.movSpd;\n\t\t\n\t\t//add Character controller\n\t\tVector3 center = skeleton.transform.FindChild(\"b1_pelvis\").localPosition;\n\t\tcenter.y = 0.95f;\n\t\tfloat height = 1.7f;\n\t\tfloat radius = Math.Max(playerBounds.extents.x, playerBounds.extents.y) / 2.0f;\n\t\tCharacterController charController = player.AddComponent();\n\t\tcharController.center = center;\n\t\tcharController.height = height;\n\t\tcharController.radius = radius;\n\t\t\n\t\t//add collider\n\t\tCapsuleCollider c = player.AddComponent();\n\t\tc.center = center;\n\t\tc.height = height;\n\t\tc.radius = radius;\n\t\tc.direction = 1; // direction y\n\n /*\n //add event trigger\n EventTrigger eventTrigger = player.AddComponent();\n EventTrigger.Entry entry = new EventTrigger.Entry();\n entry.eventID = EventTriggerType.PointerClick;\n BaseEventData eventData = new BaseEventData(eventSystem);\n eventData.selectedObject\n entry.callback.AddListener( (eventData) => { controller.})\n */\n\n\t\t\n\t\tplayer.transform.position = charModel.pos;\n controller.SetAnimationStateMachine(charModel.rig, charModel.state);\n }\n\n public void Destroy()\n {\n GameObject.Destroy(bindPoses);\n GameObject.Destroy(skeleton);\n GameObject.Destroy(player);\n }\n\n\tprivate void LoadPlayerSkeleton( CharModel charModel)\n\t{\n\t\tLoadPlayerSkeleton(\n\t\t charModel.gender,\n\t\t\t\t\tcharModel.weapon,\n charModel.rig,\n\t\t charModel.equip.weaponID, \n\t\t charModel.equip.chestID, \n\t\t charModel.equip.handID, \n\t\t charModel.equip.footID, \n\t\t charModel.equip.hairID, \n\t\t charModel.equip.faceID, \n\t\t charModel.equip.backID, \n\t\t charModel.equip.capID,\n charModel.equip.shieldID);\n\t}\n\n\n\tprivate void LoadPlayerSkeleton(GenderType gender, WeaponType weapType, RigType rig, int weapon, int body, int arms, int foot, int hair, int face, int back, int cap, int shield)\n\t{\n\n // First destroy any children of player\n int childs = player.transform.childCount;\n\t\t\n\t\tfor (int i = childs - 1; i > 0; i--)\n\t\t\tUtils.Destroy(player.transform.GetChild(i).gameObject);\n\n\t\tUtils.Destroy (skeleton);\n\t\n if( rig == RigType.FOOT)\n\t\t skeleton = rm.loadSkeleton(gender, weapType);\n else\n skeleton = rm.loadSkeleton(gender, rig);\n\n bindPoses = rm.loadBindPoses (skeleton, gender, weapType);\n\t\tskeleton.transform.parent = player.transform;\n\t\tskeleton.transform.localPosition = new Vector3 (0, 0, 0);\n\t\tskeleton.transform.localRotation = Quaternion.Euler (new Vector3 (0, 0, 0));\n\n\n\t\t// If player has already been initialized, make sure it knows that the skeleton has changed in order to restart its state machine with new animations\n\t\tPlayerController controller = player.GetComponent ();\n\t\tif( controller != null )\n\t\t\tcontroller.OnSkeletonChange ();\n\n\t\t//load all objects\n\t\tplayerBounds = new Bounds(player.transform.position, Vector3.zero);\n\t\t\n\t\tplayerBounds.Encapsulate(LoadObject(BodyPartType.BODY, body));\n\t\tplayerBounds.Encapsulate(LoadObject(BodyPartType.ARMS, arms));\n\t\tplayerBounds.Encapsulate(LoadObject(BodyPartType.FOOT, foot));\n\t\tplayerBounds.Encapsulate(LoadObject(BodyPartType.FACE, face));\n LoadObject(BodyPartType.CAP, cap);\n\t\tString hairOffsetStr = rm.stb_cap_list.Cells[cap][34];\n int hairOffset = (hairOffsetStr == \"\") ? 0 : int.Parse(hairOffsetStr);\n\t\tplayerBounds.Encapsulate(LoadObject(BodyPartType.HAIR, hair - hair%5 + hairOffset));\n\n LoadObject(BodyPartType.SUBWEAPON, shield);\n LoadObject(BodyPartType.WEAPON, weapon);\n\t\tLoadObject(BodyPartType.BACK, back);\n\n //player.SetActive(true);\n }\n\n public void equip(BodyPartType bodyPart, int id, bool changeId = true)\n {\n\t\tif (bodyPart == BodyPartType.WEAPON) { \n\t\t\tWeaponType weapType = rm.getWeaponType (id);\n\t\t\tcharModel.equip.weaponID = id;\n\n // if this weapon is two-handed and a subweapon is equipped, unequip the subweapon first\n if ( !Utils.isOneHanded(weapType) && charModel.equip.shieldID > 0)\n equip(BodyPartType.SUBWEAPON, 0);\n\n\t\t\t// Change skeleton if weapon type is different\n\t\t\tif (weapType != charModel.weapon) {\n\t\t\t\tcharModel.weapon = weapType;\n\t\t\t\tLoadPlayerSkeleton ( charModel );\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\n // If equipping subweapon and a two-hand weapon is equipped, first unequip the 2-hand\n if (( bodyPart == BodyPartType.SUBWEAPON) && id > 0 && !Utils.isOneHanded(charModel.weapon))\n equip(BodyPartType.WEAPON, 0);\n\n \n // If equipping cap, first make sure the hair is changed to the right type\n if(bodyPart == BodyPartType.CAP)\n {\n String hairOffsetStr = rm.stb_cap_list.Cells[id][34];\n int hairOffset = (hairOffsetStr == \"\") ? 0 : int.Parse(hairOffsetStr);\n equip(BodyPartType.HAIR, charModel.equip.hairID - (charModel.equip.hairID)%5 + hairOffset, false);\n }\n\n\t\tif( changeId)\n\t\t\tcharModel.changeID(bodyPart, id);\n\n\t\tList partTransforms = Utils.findChildren (player, bodyPart.ToString());\n\n\t\tforeach (Transform partTransform in partTransforms) \n\t\t\tUtils.Destroy(partTransform.gameObject);\n\n\n\t\tLoadObject(bodyPart, id);\n\n }\n\n public void changeGender(GenderType gender)\n {\n charModel.gender = gender;\n LoadPlayerSkeleton(charModel);\n }\n\n public void changeName(string name)\n {\n charModel.name = name;\n player.name = name;\n }\n\n\n private Bounds LoadObject(BodyPartType bodyPart, int id)\n\t{\n\t\tBounds objectBounds = new Bounds(skeleton.transform.position, Vector3.zero);\n\t\tZSC zsc = rm.getZSC(charModel.gender, bodyPart);\n\n\t\tfor (int i = 0; i < zsc.Objects[id].Models.Count; i++)\n\t\t{\n\t\t\tint ModelID = zsc.Objects[id].Models[i].ModelID;\n\t\t\tint TextureID = zsc.Objects[id].Models[i].TextureID;\n\t\t\t\n\t\t\tBounds partBounds = LoadPart(bodyPart, zsc.Objects[id].Models[i].DummyIndex, zsc.Models[ModelID], zsc.Textures[TextureID].Path);\n\t\t\tobjectBounds.Encapsulate(partBounds);\n\t\t}\n\t\treturn objectBounds;\n\t}\n\n\n\tprivate Bounds LoadPart(BodyPartType bodyPart, ZSC.DummyType dummy, string zmsPath, string texPath)\n {\n zmsPath = Utils.FixPath(zmsPath);\n\t\ttexPath = Utils.FixPath (texPath).Replace (\"dds\", \"png\");\n\n // Cached load of ZMS and texture\n ResourceManager rm = ResourceManager.Instance;\n ZMS zms = (ZMS)rm.cachedLoad(zmsPath);\n Texture2D tex = (Texture2D)rm.cachedLoad(texPath);\n\n // Create material\n string shader = \"VertexLit\";\n if (bodyPart == BodyPartType.BACK)\n shader = \"Transparent/Cutout/VertexLit\";\n\n Material mat = new Material(Shader.Find(shader));\n\n mat.SetTexture(\"_MainTex\", tex);\n mat.SetColor(\"_Emission\", new Color(0.15f, 0.15f, 0.15f));\n\n GameObject modelObject = new GameObject();\n\n switch ( bodyPart )\n {\n case BodyPartType.FACE:\n case BodyPartType.HAIR:\n\t\t\t\tmodelObject.transform.parent = Utils.findChild(skeleton, \"b1_head\");\n break;\n case BodyPartType.CAP: // TODO: figure out how to fix issue of hair coming out of cap\n\t\t\t\tmodelObject.transform.parent = Utils.findChild(skeleton, \"p_06\");\n break;\n case BodyPartType.BACK:\n\t\t\t\tmodelObject.transform.parent = Utils.findChild(skeleton, \"p_03\");\n break;\n case BodyPartType.WEAPON:\n\t\t\t\tif(charModel.weapon == WeaponType.DSW || charModel.weapon == WeaponType.KATAR )\n \tmodelObject.transform.parent = Utils.findChild(skeleton, dummy == ZSC.DummyType.RightHand? \"p_00\" : \"p_01\");\n\t\t\t\telse\n\t\t\t\t\tmodelObject.transform.parent = Utils.findChild(skeleton, \"p_00\");\n break;\n case BodyPartType.SUBWEAPON:\n modelObject.transform.parent = Utils.findChild(skeleton, \"p_02\");\n break;\n default:\n\t\t\t\tmodelObject.transform.parent = skeleton.transform.parent.transform;\n break;\n }\n \n modelObject.transform.localPosition = Vector3.zero;\n modelObject.transform.localRotation = Quaternion.identity;\n modelObject.transform.localScale = Vector3.one;\n\t\tmodelObject.name = bodyPart.ToString ();\n Mesh mesh = zms.getMesh();\n if (zms.support.bones)\n {\n SkinnedMeshRenderer renderer = modelObject.AddComponent();\n\n\t\t\tmesh.bindposes = bindPoses.bindPoses;\n renderer.sharedMesh = mesh;\n renderer.material = mat;\n\t\t\trenderer.bones = bindPoses.boneTransforms;\n }\n else\n {\n modelObject.AddComponent().mesh = mesh;\n MeshRenderer renderer = modelObject.AddComponent();\n renderer.material = mat;\n }\n\n return mesh.bounds;\n\n }\n\n public void setAnimationState(States state)\n {\n charModel.state = state;\n player.GetComponent().SetAnimationState(state);\n }\n\n public void OnPointerClick(PointerEventData eventData)\n {\n Debug.Log(\"I was clicked\");\n }\n}\n"},"gt":{"kind":"string","value":""}}},{"rowIdx":98450,"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\n/*=============================================================================\n**\n**\n**\n** Purpose: Class for creating and managing a threadpool\n**\n**\n=============================================================================*/\n\nusing System.Diagnostics;\nusing System.Runtime.CompilerServices;\nusing System.Runtime.ConstrainedExecution;\nusing System.Runtime.InteropServices;\n\nnamespace System.Threading\n{\n //\n // This type is necessary because VS 2010's debugger looks for a method named _ThreadPoolWaitCallbacck.PerformWaitCallback\n // on the stack to determine if a thread is a ThreadPool thread or not. We have a better way to do this for .NET 4.5, but\n // still need to maintain compatibility with VS 2010. When compat with VS 2010 is no longer an issue, this type may be\n // removed.\n //\n internal static class _ThreadPoolWaitCallback\n {\n internal static bool PerformWaitCallback() => ThreadPoolWorkQueue.Dispatch();\n }\n\n internal sealed class RegisteredWaitHandleSafe : CriticalFinalizerObject\n {\n private static IntPtr InvalidHandle => new IntPtr(-1);\n private IntPtr registeredWaitHandle = InvalidHandle;\n private WaitHandle? m_internalWaitObject;\n private bool bReleaseNeeded = false;\n private volatile int m_lock = 0;\n\n internal IntPtr GetHandle() => registeredWaitHandle;\n\n internal void SetHandle(IntPtr handle)\n {\n registeredWaitHandle = handle;\n }\n\n internal void SetWaitObject(WaitHandle waitObject)\n {\n // needed for DangerousAddRef\n RuntimeHelpers.PrepareConstrainedRegions();\n\n m_internalWaitObject = waitObject;\n if (waitObject != null)\n {\n m_internalWaitObject.SafeWaitHandle.DangerousAddRef(ref bReleaseNeeded);\n }\n }\n\n internal bool Unregister(\n WaitHandle? waitObject // object to be notified when all callbacks to delegates have completed\n )\n {\n bool result = false;\n // needed for DangerousRelease\n RuntimeHelpers.PrepareConstrainedRegions();\n\n // lock(this) cannot be used reliably in Cer since thin lock could be\n // promoted to syncblock and that is not a guaranteed operation\n bool bLockTaken = false;\n do\n {\n if (Interlocked.CompareExchange(ref m_lock, 1, 0) == 0)\n {\n bLockTaken = true;\n try\n {\n if (ValidHandle())\n {\n result = UnregisterWaitNative(GetHandle(), waitObject?.SafeWaitHandle);\n if (result)\n {\n if (bReleaseNeeded)\n {\n Debug.Assert(m_internalWaitObject != null, \"Must be non-null for bReleaseNeeded to be true\");\n m_internalWaitObject.SafeWaitHandle.DangerousRelease();\n bReleaseNeeded = false;\n }\n // if result not true don't release/suppress here so finalizer can make another attempt\n SetHandle(InvalidHandle);\n m_internalWaitObject = null;\n GC.SuppressFinalize(this);\n }\n }\n }\n finally\n {\n m_lock = 0;\n }\n }\n Thread.SpinWait(1); // yield to processor\n }\n while (!bLockTaken);\n\n return result;\n }\n\n private bool ValidHandle() =>\n registeredWaitHandle != InvalidHandle && registeredWaitHandle != IntPtr.Zero;\n\n ~RegisteredWaitHandleSafe()\n {\n // if the app has already unregistered the wait, there is nothing to cleanup\n // we can detect this by checking the handle. Normally, there is no race condition here\n // so no need to protect reading of handle. However, if this object gets\n // resurrected and then someone does an unregister, it would introduce a race condition\n //\n // PrepareConstrainedRegions call not needed since finalizer already in Cer\n //\n // lock(this) cannot be used reliably even in Cer since thin lock could be\n // promoted to syncblock and that is not a guaranteed operation\n //\n // Note that we will not \"spin\" to get this lock. We make only a single attempt;\n // if we can't get the lock, it means some other thread is in the middle of a call\n // to Unregister, which will do the work of the finalizer anyway.\n //\n // Further, it's actually critical that we *not* wait for the lock here, because\n // the other thread that's in the middle of Unregister may be suspended for shutdown.\n // Then, during the live-object finalization phase of shutdown, this thread would\n // end up spinning forever, as the other thread would never release the lock.\n // This will result in a \"leak\" of sorts (since the handle will not be cleaned up)\n // but the process is exiting anyway.\n //\n // During AD-unload, we don't finalize live objects until all threads have been\n // aborted out of the AD. Since these locked regions are CERs, we won't abort them\n // while the lock is held. So there should be no leak on AD-unload.\n //\n if (Interlocked.CompareExchange(ref m_lock, 1, 0) == 0)\n {\n try\n {\n if (ValidHandle())\n {\n WaitHandleCleanupNative(registeredWaitHandle);\n if (bReleaseNeeded)\n {\n Debug.Assert(m_internalWaitObject != null, \"Must be non-null for bReleaseNeeded to be true\");\n m_internalWaitObject.SafeWaitHandle.DangerousRelease();\n bReleaseNeeded = false;\n }\n SetHandle(InvalidHandle);\n m_internalWaitObject = null;\n }\n }\n finally\n {\n m_lock = 0;\n }\n }\n }\n\n [MethodImpl(MethodImplOptions.InternalCall)]\n private static extern void WaitHandleCleanupNative(IntPtr handle);\n\n [MethodImpl(MethodImplOptions.InternalCall)]\n private static extern bool UnregisterWaitNative(IntPtr handle, SafeHandle? waitObject);\n }\n\n public sealed class RegisteredWaitHandle : MarshalByRefObject\n {\n private readonly RegisteredWaitHandleSafe internalRegisteredWait;\n\n internal RegisteredWaitHandle()\n {\n internalRegisteredWait = new RegisteredWaitHandleSafe();\n }\n\n internal void SetHandle(IntPtr handle)\n {\n internalRegisteredWait.SetHandle(handle);\n }\n\n internal void SetWaitObject(WaitHandle waitObject)\n {\n internalRegisteredWait.SetWaitObject(waitObject);\n }\n\n public bool Unregister(\n WaitHandle? waitObject // object to be notified when all callbacks to delegates have completed\n )\n {\n return internalRegisteredWait.Unregister(waitObject);\n }\n }\n\n public static partial class ThreadPool\n {\n // Time in ms for which ThreadPoolWorkQueue.Dispatch keeps executing work items before returning to the OS\n private const uint DispatchQuantum = 30;\n\n internal static bool KeepDispatching(int startTickCount)\n {\n // Note: this function may incorrectly return false due to TickCount overflow\n // if work item execution took around a multiple of 2^32 milliseconds (~49.7 days),\n // which is improbable.\n return (uint)(Environment.TickCount - startTickCount) < DispatchQuantum;\n }\n\n public static bool SetMaxThreads(int workerThreads, int completionPortThreads)\n {\n return\n workerThreads >= 0 &&\n completionPortThreads >= 0 &&\n SetMaxThreadsNative(workerThreads, completionPortThreads);\n }\n\n public static void GetMaxThreads(out int workerThreads, out int completionPortThreads)\n {\n GetMaxThreadsNative(out workerThreads, out completionPortThreads);\n }\n\n public static bool SetMinThreads(int workerThreads, int completionPortThreads)\n {\n return\n workerThreads >= 0 &&\n completionPortThreads >= 0 &&\n SetMinThreadsNative(workerThreads, completionPortThreads);\n }\n\n public static void GetMinThreads(out int workerThreads, out int completionPortThreads)\n {\n GetMinThreadsNative(out workerThreads, out completionPortThreads);\n }\n\n public static void GetAvailableThreads(out int workerThreads, out int completionPortThreads)\n {\n GetAvailableThreadsNative(out workerThreads, out completionPortThreads);\n }\n\n /// \n /// Gets the number of thread pool threads that currently exist.\n /// \n /// \n /// For a thread pool implementation that may have different types of threads, the count includes all types.\n /// \n public static extern int ThreadCount\n {\n [MethodImpl(MethodImplOptions.InternalCall)]\n get;\n }\n\n /// \n /// Gets the number of work items that have been processed so far.\n /// \n /// \n /// For a thread pool implementation that may have different types of work items, the count includes all types.\n /// \n public static long CompletedWorkItemCount => GetCompletedWorkItemCount();\n\n [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]\n private static extern long GetCompletedWorkItemCount();\n\n private static extern long PendingUnmanagedWorkItemCount\n {\n [MethodImpl(MethodImplOptions.InternalCall)]\n get;\n }\n\n private static RegisteredWaitHandle RegisterWaitForSingleObject( // throws RegisterWaitException\n WaitHandle waitObject,\n WaitOrTimerCallback callBack,\n object? state,\n uint millisecondsTimeOutInterval,\n bool executeOnlyOnce, // NOTE: we do not allow other options that allow the callback to be queued as an APC\n bool compressStack\n )\n {\n RegisteredWaitHandle registeredWaitHandle = new RegisteredWaitHandle();\n\n if (callBack != null)\n {\n _ThreadPoolWaitOrTimerCallback callBackHelper = new _ThreadPoolWaitOrTimerCallback(callBack, state, compressStack);\n state = (object)callBackHelper;\n // call SetWaitObject before native call so that waitObject won't be closed before threadpoolmgr registration\n // this could occur if callback were to fire before SetWaitObject does its addref\n registeredWaitHandle.SetWaitObject(waitObject);\n IntPtr nativeRegisteredWaitHandle = RegisterWaitForSingleObjectNative(waitObject,\n state,\n millisecondsTimeOutInterval,\n executeOnlyOnce,\n registeredWaitHandle);\n registeredWaitHandle.SetHandle(nativeRegisteredWaitHandle);\n }\n else\n {\n throw new ArgumentNullException(nameof(WaitOrTimerCallback));\n }\n return registeredWaitHandle;\n }\n\n [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]\n internal static extern Interop.BOOL RequestWorkerThread();\n\n [MethodImpl(MethodImplOptions.InternalCall)]\n private static extern unsafe bool PostQueuedCompletionStatus(NativeOverlapped* overlapped);\n\n [CLSCompliant(false)]\n public static unsafe bool UnsafeQueueNativeOverlapped(NativeOverlapped* overlapped) =>\n PostQueuedCompletionStatus(overlapped);\n\n // The thread pool maintains a per-appdomain managed work queue.\n // New thread pool entries are added in the managed queue.\n // The VM is responsible for the actual growing/shrinking of\n // threads.\n private static void EnsureInitialized()\n {\n if (!ThreadPoolGlobals.threadPoolInitialized)\n {\n EnsureVMInitializedCore(); // separate out to help with inlining\n }\n }\n\n [MethodImpl(MethodImplOptions.NoInlining)]\n private static void EnsureVMInitializedCore()\n {\n InitializeVMTp(ref ThreadPoolGlobals.enableWorkerTracking);\n ThreadPoolGlobals.threadPoolInitialized = true;\n }\n\n // Native methods:\n\n [MethodImpl(MethodImplOptions.InternalCall)]\n private static extern bool SetMinThreadsNative(int workerThreads, int completionPortThreads);\n\n [MethodImpl(MethodImplOptions.InternalCall)]\n private static extern bool SetMaxThreadsNative(int workerThreads, int completionPortThreads);\n\n [MethodImpl(MethodImplOptions.InternalCall)]\n private static extern void GetMinThreadsNative(out int workerThreads, out int completionPortThreads);\n\n [MethodImpl(MethodImplOptions.InternalCall)]\n private static extern void GetMaxThreadsNative(out int workerThreads, out int completionPortThreads);\n\n [MethodImpl(MethodImplOptions.InternalCall)]\n private static extern void GetAvailableThreadsNative(out int workerThreads, out int completionPortThreads);\n\n [MethodImpl(MethodImplOptions.InternalCall)]\n internal static extern bool NotifyWorkItemComplete();\n\n [MethodImpl(MethodImplOptions.InternalCall)]\n internal static extern void ReportThreadStatus(bool isWorking);\n\n internal static void NotifyWorkItemProgress()\n {\n EnsureInitialized();\n NotifyWorkItemProgressNative();\n }\n\n [MethodImpl(MethodImplOptions.InternalCall)]\n internal static extern void NotifyWorkItemProgressNative();\n\n [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]\n private static extern void InitializeVMTp(ref bool enableWorkerTracking);\n\n [MethodImpl(MethodImplOptions.InternalCall)]\n private static extern IntPtr RegisterWaitForSingleObjectNative(\n WaitHandle waitHandle,\n object state,\n uint timeOutInterval,\n bool executeOnlyOnce,\n RegisteredWaitHandle registeredWaitHandle\n );\n\n [Obsolete(\"ThreadPool.BindHandle(IntPtr) has been deprecated. Please use ThreadPool.BindHandle(SafeHandle) instead.\", false)]\n public static bool BindHandle(IntPtr osHandle)\n {\n return BindIOCompletionCallbackNative(osHandle);\n }\n\n public static bool BindHandle(SafeHandle osHandle)\n {\n if (osHandle == null)\n throw new ArgumentNullException(nameof(osHandle));\n\n bool ret = false;\n bool mustReleaseSafeHandle = false;\n RuntimeHelpers.PrepareConstrainedRegions();\n try\n {\n osHandle.DangerousAddRef(ref mustReleaseSafeHandle);\n ret = BindIOCompletionCallbackNative(osHandle.DangerousGetHandle());\n }\n finally\n {\n if (mustReleaseSafeHandle)\n osHandle.DangerousRelease();\n }\n return ret;\n }\n\n [MethodImpl(MethodImplOptions.InternalCall)]\n private static extern bool BindIOCompletionCallbackNative(IntPtr fileHandle);\n }\n}\n"},"gt":{"kind":"string","value":""}}},{"rowIdx":98451,"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\nusing System;\nusing System.Collections.Generic;\nusing System.IO;\nusing System.Threading.Tasks;\nusing Microsoft.AspNetCore.Http;\nusing Microsoft.Extensions.Primitives;\nusing Microsoft.Net.Http.Headers;\nusing Xunit;\n\nnamespace Microsoft.AspNetCore.Mvc.Formatters\n{\n public class OutputFormatterTests\n {\n [Fact]\n public void CanWriteResult_ForNullContentType_UsesFirstEntryInSupportedContentTypes()\n {\n // Arrange\n var context = new OutputFormatterWriteContext(\n new DefaultHttpContext(),\n new TestHttpResponseStreamWriterFactory().CreateWriter,\n objectType: null,\n @object: null);\n\n var formatter = new TestOutputFormatter();\n\n // Act\n var result = formatter.CanWriteResult(context);\n\n // Assert\n Assert.True(result);\n Assert.Equal(formatter.SupportedMediaTypes[0].ToString(), context.ContentType.ToString());\n }\n\n [Fact]\n public void GetSupportedContentTypes_ReturnsNull_ForUnsupportedType()\n {\n // Arrange\n var formatter = new TypeSpecificFormatter();\n formatter.SupportedMediaTypes.Add(MediaTypeHeaderValue.Parse(\"application/json\"));\n formatter.SupportedTypes.Add(typeof(int));\n\n // Act\n var contentTypes = formatter.GetSupportedContentTypes(\n contentType: null,\n objectType: typeof(string));\n\n // Assert\n Assert.Null(contentTypes);\n }\n\n [Fact]\n public void CanWrite_ReturnsFalse_ForUnsupportedType()\n {\n // Arrange\n var formatter = new TypeSpecificFormatter();\n formatter.SupportedMediaTypes.Add(MediaTypeHeaderValue.Parse(\"application/json\"));\n formatter.SupportedTypes.Add(typeof(int));\n\n var context = new OutputFormatterWriteContext(\n new DefaultHttpContext(),\n new TestHttpResponseStreamWriterFactory().CreateWriter,\n typeof(string),\n \"Hello, world!\")\n {\n ContentType = new StringSegment(formatter.SupportedMediaTypes[0].ToString()),\n };\n\n // Act\n var result = formatter.CanWriteResult(context);\n\n // Assert\n Assert.False(result);\n }\n\n [Theory]\n [InlineData(true, true)]\n [InlineData(false, false)]\n public void CanWriteResult_MatchesWildcardsOnlyWhenContentTypeProvidedByServer(\n bool contentTypeProvidedByServer, bool shouldMatchWildcards)\n {\n // Arrange\n var formatter = new TypeSpecificFormatter();\n formatter.SupportedMediaTypes.Add(MediaTypeHeaderValue.Parse(\"application/*+xml\"));\n formatter.SupportedMediaTypes.Add(MediaTypeHeaderValue.Parse(\"application/*+json\"));\n formatter.SupportedTypes.Add(typeof(string));\n\n var requestedContentType = \"application/vnd.test.entity+json;v=2\";\n var context = new OutputFormatterWriteContext(\n new DefaultHttpContext(),\n new TestHttpResponseStreamWriterFactory().CreateWriter,\n typeof(string),\n \"Hello, world!\")\n {\n ContentType = new StringSegment(requestedContentType),\n ContentTypeIsServerDefined = contentTypeProvidedByServer,\n };\n\n // Act\n var result = formatter.CanWriteResult(context);\n\n // Assert\n Assert.Equal(shouldMatchWildcards, result);\n Assert.Equal(requestedContentType, context.ContentType.ToString());\n }\n\n [Fact]\n public void GetSupportedContentTypes_ReturnsAllNonWildcardContentTypes_WithContentTypeNull()\n {\n // Arrange\n var formatter = new TestOutputFormatter();\n formatter.SupportedMediaTypes.Clear();\n formatter.SupportedMediaTypes.Add(MediaTypeHeaderValue.Parse(\"application/json\"));\n formatter.SupportedMediaTypes.Add(MediaTypeHeaderValue.Parse(\"*/*\"));\n formatter.SupportedMediaTypes.Add(MediaTypeHeaderValue.Parse(\"text/*\"));\n formatter.SupportedMediaTypes.Add(MediaTypeHeaderValue.Parse(\"text/plain;*\"));\n formatter.SupportedMediaTypes.Add(MediaTypeHeaderValue.Parse(\"application/xml\"));\n\n // Act\n var contentTypes = formatter.GetSupportedContentTypes(\n contentType: null,\n objectType: typeof(string));\n\n // Assert\n Assert.Equal(2, contentTypes.Count);\n Assert.Single(contentTypes, ct => ct.ToString() == \"application/json\");\n Assert.Single(contentTypes, ct => ct.ToString() == \"application/xml\");\n }\n\n [Fact]\n public void GetSupportedContentTypes_ReturnsMoreSpecificMatchingContentTypes_WithContentType()\n {\n // Arrange\n var formatter = new TestOutputFormatter();\n\n formatter.SupportedMediaTypes.Clear();\n formatter.SupportedMediaTypes.Add(MediaTypeHeaderValue.Parse(\"application/json\"));\n formatter.SupportedMediaTypes.Add(MediaTypeHeaderValue.Parse(\"text/xml\"));\n\n // Act\n var contentTypes = formatter.GetSupportedContentTypes(\n \"application/*\",\n typeof(int));\n\n // Assert\n var contentType = Assert.Single(contentTypes);\n Assert.Equal(\"application/json\", contentType.ToString());\n }\n\n [Fact]\n public void GetSupportedContentTypes_ReturnsMatchingWildcardContentTypes_WithContentType()\n {\n // Arrange\n var formatter = new TestOutputFormatter();\n\n formatter.SupportedMediaTypes.Clear();\n formatter.SupportedMediaTypes.Add(MediaTypeHeaderValue.Parse(\"application/json\"));\n formatter.SupportedMediaTypes.Add(MediaTypeHeaderValue.Parse(\"application/*+json\"));\n formatter.SupportedMediaTypes.Add(MediaTypeHeaderValue.Parse(\"text/xml\"));\n\n // Act\n var contentTypes = formatter.GetSupportedContentTypes(\n \"application/vnd.test+json;v=2\",\n typeof(int));\n\n // Assert\n var contentType = Assert.Single(contentTypes);\n Assert.Equal(\"application/vnd.test+json;v=2\", contentType.ToString());\n }\n\n [Fact]\n public void GetSupportedContentTypes_ReturnsMatchingContentTypes_NoMatches()\n {\n // Arrange\n var formatter = new TestOutputFormatter();\n\n formatter.SupportedMediaTypes.Clear();\n formatter.SupportedMediaTypes.Add(MediaTypeHeaderValue.Parse(\"application/*+xml\"));\n formatter.SupportedMediaTypes.Add(MediaTypeHeaderValue.Parse(\"text/xml\"));\n\n // Act\n var contentTypes = formatter.GetSupportedContentTypes(\n \"application/vnd.test+bson\",\n typeof(int));\n\n // Assert\n Assert.Null(contentTypes);\n }\n\n private class TypeSpecificFormatter : OutputFormatter\n {\n public List SupportedTypes { get; } = new List();\n\n protected override bool CanWriteType(Type type)\n {\n return SupportedTypes.Contains(type);\n }\n\n public override Task WriteResponseBodyAsync(OutputFormatterWriteContext context)\n {\n throw new NotImplementedException();\n }\n }\n\n [Fact]\n public void CanWrite_ThrowsInvalidOperationException_IfMediaTypesListIsEmpty()\n {\n // Arrange\n var formatter = new TestOutputFormatter();\n formatter.SupportedMediaTypes.Clear();\n\n var context = new OutputFormatterWriteContext(\n new DefaultHttpContext(),\n (s, e) => new StreamWriter(s, e),\n typeof(object),\n new object());\n\n // Act & Assert\n Assert.Throws(() => formatter.CanWriteResult(context));\n }\n\n [Fact]\n public void GetSupportedContentTypes_ThrowsInvalidOperationException_IfMediaTypesListIsEmpty()\n {\n // Arrange\n var formatter = new TestOutputFormatter();\n formatter.SupportedMediaTypes.Clear();\n\n // Act & Assert\n Assert.Throws(\n () => formatter.GetSupportedContentTypes(\"application/json\", typeof(object)));\n }\n\n private class TestOutputFormatter : OutputFormatter\n {\n public TestOutputFormatter()\n {\n SupportedMediaTypes.Add(\"application/acceptCharset\");\n }\n\n public override Task WriteResponseBodyAsync(OutputFormatterWriteContext context)\n {\n return Task.FromResult(true);\n }\n }\n }\n}\n"},"gt":{"kind":"string","value":""}}},{"rowIdx":98452,"cells":{"context":{"kind":"string","value":"using UnityEngine;\nusing System.Collections;\nusing System.Collections.Generic;\nusing System.Linq;\nusing UnityEngine.Extensions;\nusing UnityEngine.UI.Windows.Components;\nusing UnityEngine.UI.Windows.Extensions;\nusing UnityEngine.UI.Extensions;\nusing ME.UAB;\n\nnamespace UnityEngine.UI.Windows.Types {\n\n\t[ExecuteInEditMode()]\n\tpublic class LayoutWindowType : WindowBase {\n\t\t\n\t\tpublic Layouts layouts;\n\n\t\t// Current Layout\n\t\t[HideInInspector][SerializeField]\n\t\tprivate Layout layout;\n\n\t\tpublic override void ApplyOrientationIndexDirect(int index) {\n\n\t\t\tbase.ApplyOrientationIndexDirect(index);\n\n\t\t\tif (this.layouts.IsValid(index) == true) {\n\n\t\t\t\tthis.layouts.ApplyOrientationIndex(index);\n\n\t\t\t}\n\n\t\t}\n\n\t\tpublic override void ApplyOrientationIndex(int index) {\n\n\t\t\tbase.ApplyOrientationIndex(index);\n\n\t\t\t// Is new orientation supported?\n\t\t\tif (this.layouts.IsSupported() == true && this.layouts.IsValid(index) == true) {\n\n\t\t\t\t// Reload window\n\t\t\t\tif (this.GetState() == WindowObjectState.Shown) {\n\n\t\t\t\t\tSystem.Action onHideEnd = () => {\n\n\t\t\t\t\t\tME.Coroutines.Run(this.ApplyOrientationIndex_YIELD(index));\n\n\t\t\t\t\t};\n\n\t\t\t\t\t// Hide\n\t\t\t\t\tthis.skipRecycle = true;\n\t\t\t\t\tif (this.Hide(onHideEnd) == false) {\n\n\t\t\t\t\t\tUnityEngine.Events.UnityAction action = null;\n\t\t\t\t\t\taction = () => {\n\n\t\t\t\t\t\t\tthis.events.onEveryInstance.Unregister(WindowEventType.OnHideEndLate, action);\n\t\t\t\t\t\t\tonHideEnd.Invoke();\n\n\t\t\t\t\t\t};\n\t\t\t\t\t\tthis.events.onEveryInstance.Register(WindowEventType.OnHideEndLate, action);\n\n\t\t\t\t\t}\n\n\t\t\t\t} else {\n\n\t\t\t\t\tDebug.LogWarning(string.Format(\"Window `{0}` is not in `Shown` state, this behaviour currently unsupported.\", this.name));\n\t\t\t\t\t\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t}\n\n\t\tprivate IEnumerator ApplyOrientationIndex_YIELD(int index) {\n\n\t\t\tyield return 0;\n\n\t\t\tthis.skipRecycle = false;\n\t\t\tthis.layouts.ApplyOrientationIndex(index);\n\t\t\t// Reinit\n\t\t\tthis.setup = false;\n\t\t\tthis.Init(this.initialParameters, () => {\n\n\t\t\t\tthis.Show();\n\n\t\t\t}, async: false);\n\n\t\t}\n\n\t\tpublic Layout GetCurrentLayout() {\n\n\t\t\treturn this.layouts.GetCurrentLayout();\n\n\t\t}\n\n\t\tnew public LayoutWindowType GetWindow() {\n\t\t\t\n\t\t\treturn base.GetWindow() as LayoutWindowType;\n\t\t\t\n\t\t}\n\t\t\n\t\tpublic override Canvas GetCanvas() {\n\n\t\t\tvar layoutInstance = this.GetCurrentLayout().GetLayoutInstance();\n\t\t\tif (layoutInstance == null) return null;\n\n\t\t\treturn layoutInstance.canvas;\n\t\t\t\n\t\t}\n\n\t\tpublic override CanvasScaler GetCanvasScaler() {\n\n\t\t\tvar layoutInstance = this.GetCurrentLayout().GetLayoutInstance();\n\t\t\tif (layoutInstance == null) return null;\n\n\t\t\treturn layoutInstance.canvasScaler;\n\n\t\t}\n\n\t\tpublic void GetLayoutComponent(out T component, LayoutTag tag = LayoutTag.None) where T : WindowComponent {\n\t\t\t\n\t\t\tcomponent = this.GetLayoutComponent(tag);\n\t\t\t\n\t\t}\n\n\t\tpublic T GetLayoutComponent(LayoutTag tag = LayoutTag.None) where T : WindowComponent {\n\t\t\t\n\t\t\treturn this.GetCurrentLayout().Get(tag);\n\t\t\t\n\t\t}\n\t\t\n\t\tpublic override Vector2 GetSize() {\n\n\t\t\tvar layoutInstance = this.GetCurrentLayout().GetLayoutInstance();\n\t\t\tif (layoutInstance == null) return Vector2.zero;\n\n\t\t\treturn layoutInstance.GetSize();\n\t\t\t\n\t\t}\n\n\t\tpublic WindowLayoutElement GetLayoutContainer(LayoutTag tag) {\n\n\t\t\treturn this.GetCurrentLayout().GetContainer(tag);\n\n\t\t}\n\n\t\tpublic override int GetSortingOrder() {\n\t\t\t\n\t\t\treturn this.GetCurrentLayout().GetSortingOrder();\n\t\t\t\n\t\t}\n\t\t\n\t\tpublic override float GetLayoutAnimationDuration(bool forward) {\n\t\t\t\n\t\t\treturn this.GetCurrentLayout().GetAnimationDuration(forward);\n\t\t\t\n\t\t}\n\t\t\n\t\tpublic override Rect GetRect() {\n\n\t\t\tvar bounds = base.GetRect();\n\t\t\t//var root = this.layout.GetLayoutInstance().root;\n\t\t\tvar baseSubElements = this.GetCurrentLayout().GetLayoutInstance().GetSubComponents();\n\t\t\tif (baseSubElements.Count == 1) {\n\n\t\t\t\tvar baseLayoutElement = baseSubElements[0];\n\t\t\t\tvar subElements = baseLayoutElement.GetSubComponents();\n\t\t\t\tif (subElements.Count == 1) {\n\n\t\t\t\t\tvar layoutElement = subElements[0];\n\n\t\t\t\t\tVector3[] corners = new Vector3[4];\n\t\t\t\t\t(layoutElement.transform as RectTransform).GetWorldCorners(corners);\n\n\t\t\t\t\tvar leftBottom = this.workCamera.WorldToScreenPoint(corners[0]);\n\t\t\t\t\tvar leftTop = this.workCamera.WorldToScreenPoint(corners[1]);\n\t\t\t\t\tvar rightTop = this.workCamera.WorldToScreenPoint(corners[2]);\n\t\t\t\t\tvar rightBottom = this.workCamera.WorldToScreenPoint(corners[3]);\n\n\t\t\t\t\tbounds = new Rect(new Vector2(leftTop.x, leftTop.y), new Vector2(rightBottom.x - leftBottom.x, rightTop.y - rightBottom.y));\n\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t\treturn bounds;\n\n\t\t}\n\n\t\tpublic override Transform GetLayoutRoot() {\n\t\t\t\n\t\t\treturn this.GetCurrentLayout().GetRoot();\n\t\t\t\n\t\t}\n\n\t\tprotected override void MoveLayout(Vector2 delta) {\n\n\t\t\tvar layout = this.GetCurrentLayout();\n\t\t\tif (layout != null) layout.GetLayoutInstance().root.Move(delta);\n\n\t\t}\n\t\t\n\t\tpublic override void OnLocalizationChanged() {\n\t\t\t\n\t\t\tbase.OnLocalizationChanged();\n\t\t\t\n\t\t\tvar layout = this.GetCurrentLayout();\n\t\t\tif (layout != null) layout.OnLocalizationChanged();\n\t\t\t\n\t\t}\n\n\t\tpublic override void OnManualEvent(T data) {\n\n\t\t\tbase.OnManualEvent(data);\n\n\t\t\tvar layout = this.GetCurrentLayout();\n\t\t\tif (layout != null) layout.OnManualEvent(data);\n\n\t\t}\n\n\t\tprotected override void DoLayoutInit(float depth, int raycastPriority, int orderInLayer, System.Action callback, bool async) {\n\n\t\t\tvar layout = this.GetCurrentLayout();\n\t\t\tif (layout != null) layout.Create(this, this.transform, depth, raycastPriority, orderInLayer, () => {\n\n\t\t\t\tthis.GetCurrentLayout().DoInit();\n\t\t\t\tif (callback != null) callback.Invoke();\n\n\t\t\t}, async);\n\n\t\t}\n\n\t\tprotected override void DoLayoutDeinit(System.Action callback) {\n\n\t\t\tvar layout = this.GetCurrentLayout();\n\t\t\tif (layout != null) layout.DoDeinit(callback);\n\n\t\t}\n\n\t\tprotected override void DoLayoutShowBegin(AppearanceParameters parameters) {\n\n\t\t\t//this.layout.DoWindowOpen();\n\t\t\tvar layout = this.GetCurrentLayout();\n\t\t\tif (layout != null) layout.DoShowBegin(parameters);\n\n\t\t}\n\n\t\tprotected override void DoLayoutShowEnd(AppearanceParameters parameters) {\n\n\t\t\tvar layout = this.GetCurrentLayout();\n\t\t\tif (layout != null) layout.DoShowEnd(parameters);\n\n\t\t}\n\n\t\tprotected override void DoLayoutHideBegin(AppearanceParameters parameters) {\n\t\t\t\n\t\t\t//this.layout.DoWindowClose();\n\t\t\tvar layout = this.GetCurrentLayout();\n\t\t\tif (layout != null) layout.DoHideBegin(parameters);\n\n\t\t}\n\n\t\tprotected override void DoLayoutHideEnd(AppearanceParameters parameters) {\n\n\t\t\tvar layout = this.GetCurrentLayout();\n\t\t\tif (layout != null) layout.DoHideEnd(parameters);\n\n\t\t}\n\n\t\tprotected override void DoLayoutWindowLayoutComplete() {\n\n\t\t\tvar layout = this.GetCurrentLayout();\n\t\t\tif (layout != null) layout.DoWindowLayoutComplete();\n\n\t\t}\n\n\t\tprotected override void DoLayoutWindowOpen() {\n\n\t\t\tvar layout = this.GetCurrentLayout();\n\t\t\tif (layout != null) layout.DoWindowOpen();\n\n\t\t}\n\n\t\tprotected override void DoLayoutWindowClose() {\n\n\t\t\tvar layout = this.GetCurrentLayout();\n\t\t\tif (layout != null) layout.DoWindowClose();\n\n\t\t}\n\n\t\tprotected override void DoLayoutWindowActive() {\n\n\t\t\tvar layout = this.GetCurrentLayout();\n\t\t\tif (layout != null) layout.DoWindowActive();\n\n\t\t}\n\n\t\tprotected override void DoLayoutWindowInactive() {\n\n\t\t\tvar layout = this.GetCurrentLayout();\n\t\t\tif (layout != null) layout.DoWindowInactive();\n\n\t\t}\n\n\t\tprotected override void DoLayoutUnload() {\n\n\t\t\tvar layout = this.GetCurrentLayout();\n\t\t\tif (layout != null) layout.DoWindowUnload();\n\n\t\t}\n\n\t\t#if UNITY_EDITOR\n\t\tpublic override void OnValidateEditor() {\n\t\t\t\n\t\t\tbase.OnValidateEditor();\n\n\t\t\tthis.layouts.OnValidateEditor(this, this.layout);\n\n\t\t\tif (this.GetCurrentLayout() == null) return;\n\n\t\t\tthis.GetCurrentLayout().Update_EDITOR(this);\n\t\t\t\n\t\t}\n\t\t#endif\n\n\t}\n\n\t[System.Serializable]\n\tpublic class Layouts {\n\n\t\tpublic string[] types;\t\t// horizontal, vertical\n\t\tpublic Layout[] layouts;\t// \n\t\t//[System.NonSerialized]\n\t\tpublic int currentLayoutIndex;\n\n\t\tpublic Layout GetCurrentLayout() {\n\n\t\t\tif (this.layouts == null || this.layouts.Length == 0) return null;\n\n\t\t\tif (this.currentLayoutIndex < 0 || this.currentLayoutIndex >= this.layouts.Length) {\n\n\t\t\t\treturn this.layouts[0];\n\n\t\t\t}\n\n\t\t\treturn this.layouts[this.currentLayoutIndex];\n\n\t\t}\n\n\t\tpublic bool IsSupported() {\n\n\t\t\treturn this.IsValid(0) == true || this.IsValid(1) == true;\n\n\t\t}\n\n\t\tpublic bool IsValid(int index) {\n\n\t\t\tif (index < 0 || index >= this.layouts.Length) {\n\n\t\t\t\treturn false;\n\n\t\t\t}\n\n\t\t\treturn this.layouts[index].enabled;\n\n\t\t}\n\n\t\tpublic void ApplyOrientationIndex(int index) {\n\n\t\t\tthis.currentLayoutIndex = index;\n\n\t\t}\n\n\t\t#if UNITY_EDITOR\n\t\tpublic void OnValidateEditor(LayoutWindowType root, Layout layout) {\n\n\t\t\tif (this.layouts == null || this.layouts.Length == 0 || this.layouts[0] == null) {\n\n\t\t\t\t// Setup as default\n\t\t\t\tthis.types = new string[2];\n\t\t\t\tthis.types[0] = \"Horizontal\";\n\t\t\t\tthis.types[1] = \"Vertical\";\n\n\t\t\t\tthis.layouts = new Layout[2];\n\t\t\t\tthis.layouts[0] = layout;\n\t\t\t\tlayout.enabled = true;\n\t\t\t\tthis.layouts[1] = new Layout();\n\n\t\t\t\tUnityEditor.EditorUtility.SetDirty(root);\n\n\t\t\t}\n\n\t\t}\n\t\t#endif\n\n\t}\n\n\t[System.Serializable]\n\tpublic class Layout : IWindowEventsController, ILoadableResource, ILoadableReference {\n\n\t\tpublic bool enabled;\n\n\t\tprivate class ComponentComparer : IEqualityComparer {\n\t\t\t\n\t\t\tpublic bool Equals(Component x, Component y) {\n\t\t\t\t\n\t\t\t\tif (Object.ReferenceEquals(x, y)) return true;\n\t\t\t\t\n\t\t\t\tif (Object.ReferenceEquals(x, null) || Object.ReferenceEquals(y, null)) return false;\n\t\t\t\t\n\t\t\t\treturn x.tag == y.tag;\n\t\t\t\t\n\t\t\t}\n\t\t\t\n\t\t\tpublic int GetHashCode(Component component) {\n\t\t\t\t\n\t\t\t\tif (Object.ReferenceEquals(component, null)) return 0;\n\t\t\t\t\n\t\t\t\treturn component.tag.GetHashCode();\n\t\t\t\t\n\t\t\t}\n\t\t\t\n\t\t}\n\n\t\t[System.Serializable]\n\t\tpublic class Component : ILoadableResource, ILoadableReference {\n\t\t\t\n\t\t\t#if UNITY_EDITOR\n\t\t\tpublic string description;\n\t\t\tpublic void UpdateDescription(LayoutWindowType layoutWindow) {\n\n\t\t\t\tif (layoutWindow != null &&\n\t\t\t\t\tlayoutWindow.GetCurrentLayout().layout != null) {\n\n\t\t\t\t\tvar element = layoutWindow.GetCurrentLayout().layout.GetRootByTag(this.tag);\n\t\t\t\t\tif (element != null) {\n\n\t\t\t\t\t\tthis.description = element.comment;\n\n\t\t\t\t\t}\n\n\t\t\t\t}\n\n\t\t\t}\n\t\t\t#endif\n\n\t\t\t[ReadOnly]\n\t\t\tpublic LayoutTag tag;\n\t\t\t#if UNITY_EDITOR\n\t\t\tpublic WindowComponent component;\n\t\t\t#endif\n\t\t\tpublic ResourceMono componentResource;\n\t\t\tpublic WindowComponent componentNoResource;\n\t\t\tpublic int sortingOrder = 0;\n\t\t\tpublic WindowComponentParametersBase componentParameters;\n\n\t\t\t#if UNITY_EDITOR\n\t\t\tpublic bool editorParametersFoldout;\n\t\t\tpublic IParametersEditor componentParametersEditor;\n\t\t\t#endif\n\n\t\t\tpublic Component(LayoutTag tag) {\n\n\t\t\t\tthis.tag = tag;\n\t\t\t\t\n\t\t\t}\n\n\t\t\tpublic IResourceReference GetReference() {\n\n\t\t\t\treturn this.window;\n\n\t\t\t}\n\t\t\t\n\t\t\tpublic ResourceBase GetResource() {\n\n\t\t\t\treturn this.componentResource;\n\n\t\t\t}\n\n\t\t\t#if UNITY_EDITOR\n\t\t\tpublic WindowComponentParametersBase OnComponentChanged(WindowBase window, WindowComponent newComponent) {\n\n\t\t\t\tvar hasChanged = (newComponent != this.component);\n\t\t\t\tthis.component = newComponent;\n\n\t\t\t\tWindowComponentParametersBase instance = null;\n\t\t\t\tif (hasChanged == true) {\n\n\t\t\t\t\tif (newComponent == null) {\n\n\t\t\t\t\t\tthis.componentResource.ResetToDefault();\n\n\t\t\t\t\t}\n\n\t\t\t\t\tif (this.componentParameters != null) {\n\t\t\t\t\t\t\n\t\t\t\t\t\tvar link = this.componentParameters;\n\t\t\t\t\t\t//UnityEditor.EditorApplication.delayCall += () => {\n\t\t\t\t\t\t\n\t\t\t\t\t\tObject.DestroyImmediate(link, allowDestroyingAssets: true);\n\t\t\t\t\t\t\n\t\t\t\t\t\t//};\n\t\t\t\t\t\t\n\t\t\t\t\t}\n\n\t\t\t\t\tinstance = Layout.AddParametersFor(window, this.component);\n\t\t\t\t\tthis.componentParameters = instance;\n\n\t\t\t\t\tthis.OnValidate();\n\n\t\t\t\t} else {\n\n\t\t\t\t\tinstance = this.componentParameters;\n\n\t\t\t\t}\n\n\t\t\t\treturn instance;\n\n\t\t\t}\n\n\t\t\tprivate IPreviewEditor editor;\n\t\t\tpublic void OnPreviewGUI(Rect rect, GUIStyle background) {\n\n\t\t\t\tif (this.component != null) {\n\n\t\t\t\t\tif (this.editor == null) this.editor = UnityEditor.Editor.CreateEditor(this.component) as IPreviewEditor;\n\t\t\t\t\tif (this.editor != null) {\n\n\t\t\t\t\t\tthis.editor.OnPreviewGUI(rect, background);\n\n\t\t\t\t\t}\n\n\t\t\t\t}\n\t\t\t\t\n\t\t\t}\n\n\t\t\tpublic void OnValidate() {\n\n\t\t\t\t#if UNITY_EDITOR\n\t\t\t\tif (UnityEditor.EditorApplication.isUpdating == true) return;\n\t\t\t\t#endif\n\n\t\t\t\t/*\n\t\t\t\tif (this.componentParameters != null) {\n\n\t\t\t\t\tif (this.componentParameters.GetFlags() == 0x0) {\n\n\t\t\t\t\t\t// no flags = no parameters\n\t\t\t\t\t\tvar link = this.componentParameters;\n\t\t\t\t\t\tUnityEditor.EditorApplication.delayCall += () => {\n\n\t\t\t\t\t\t\tObject.DestroyImmediate(link, allowDestroyingAssets: true);\n\n\t\t\t\t\t\t};\n\n\t\t\t\t\t}\n\n\t\t\t\t}*/\n\n\t\t\t\tif (this.componentResource == null) this.componentResource = new ResourceMono();\n\t\t\t\tthis.componentResource.Validate(this.component);\n\n\t\t\t\tif (this.componentResource.IsLoadable() == false) {\n\n\t\t\t\t\tthis.componentNoResource = this.component;\n\n\t\t\t\t} else {\n\n\t\t\t\t\tthis.componentNoResource = null;\n\n\t\t\t\t}\n\n\t\t\t}\n\t\t\t#endif\n\n\t\t\t[HideInInspector][System.NonSerialized]\n\t\t\tprivate IWindowEventsAsync instance;\n\t\t\t\n\t\t\t[HideInInspector][System.NonSerialized]\n\t\t\tprivate IWindowComponentLayout root;\n\t\t\t\n\t\t\t[HideInInspector][System.NonSerialized]\n\t\t\tprivate WindowBase window;\n\n\t\t\tprivate bool stopped = false;\n\n\t\t\tpublic void SetComponent(WindowComponent component) {\n\n\t\t\t\tthis.componentNoResource = component;\n\n\t\t\t}\n\n\t\t\tpublic void SetComponent(ResourceMono resource) {\n\n\t\t\t\tthis.componentResource = resource;\n\n\t\t\t}\n\n\t\t\tpublic void Create(WindowBase window, WindowLayoutElement root, System.Action callback = null, bool async = false, System.Action onItem = null) {\n\n\t\t\t\tif (this.stopped == true) return;\n\n\t\t\t\tthis.window = window;\n\t\t\t\tthis.root = root;\n\n\t\t\t\tSystem.Action onLoaded = (component) => {\n\n\t\t\t\t\tif (this.stopped == true) return;\n\n\t\t\t\t\tif (component == null && this.root == null) {\n\n\t\t\t\t\t\tif (callback != null) callback.Invoke(null);\n\t\t\t\t\t\treturn;\n\n\t\t\t\t\t}\n\n\t\t\t\t\tif (component == null) {\n\n\t\t\t\t\t\tthis.root.Setup(null, this);\n\t\t\t\t\t\tif (callback != null) callback.Invoke(null);\n\t\t\t\t\t\treturn;\n\n\t\t\t\t\t}\n\n\t\t\t\t\t//Debug.Log(\"Unpack component: \" + component.name);\n\t\t\t\t\tvar instance = component.Spawn(activeByDefault: false);\n\t\t\t\t\t//instance.SetComponentState(WindowObjectState.NotInitialized);\n\t\t\t\t\tinstance.SetParent(root, setTransformAsSource: false, worldPositionStays: false);\n\t\t\t\t\tinstance.SetTransformAs();\n\n\t\t\t\t\tif (this.componentParameters != null) {\n\n\t\t\t\t\t\tinstance.Setup(this.componentParameters);\n\n\t\t\t\t\t}\n\n\t\t\t\t\tvar rect = instance.transform as RectTransform;\n\t\t\t\t\tif (rect != null) {\n\n\t\t\t\t\t\trect.sizeDelta = (component.transform as RectTransform).sizeDelta;\n\t\t\t\t\t\trect.anchoredPosition = (component.transform as RectTransform).anchoredPosition;\n\t\t\t\t\t\t\n\t\t\t\t\t}\n\n\t\t\t\t\tthis.root.Setup(instance, this);\n\t\t\t\t\tinstance.Setup(window);\n\t\t\t\t\t\n\t\t\t\t\tif (instance.autoRegisterInRoot == true && root.autoRegisterSubComponents == true) {\n\n\t\t\t\t\t\troot.RegisterSubComponent(instance);\n\n\t\t\t\t\t}\n\n\t\t\t\t\tinstance.transform.SetSiblingIndex(this.sortingOrder);\n\n\t\t\t\t\tthis.instance = instance;\n\t\t\t\t\tinstance.DoLoad(async, onItem, () => {\n\n\t\t\t\t\t\tif (this.stopped == true) return;\n\n\t\t\t\t\t\t//if (instance != null) instance.gameObject.SetActive(true);\n\t\t\t\t\t\tif (callback != null) callback.Invoke(this.instance as WindowComponent);\n\n\t\t\t\t\t});\n\n\t\t\t\t};\n\n\t\t\t\tWindowComponent loadedComponent = null;\n\t\t\t\tif (this.componentResource.IsLoadable() == true) {\n\n\t\t\t\t\tWindowSystemResources.LoadRefCounter(this, (component) => {\n\t\t\t\t\t\t\n\t\t\t\t\t\tloadedComponent = component;\n\t\t\t\t\t\tonLoaded.Invoke(loadedComponent);\n\n\t\t\t\t\t\tWindowSystemResources.Unload(this, this.GetResource(), resetController: false);\n\n\t\t\t\t\t}, () => {\n\t\t\t\t\t\t\n\t\t\t\t\t\t#if UNITY_EDITOR\n\t\t\t\t\t\tDebug.LogWarningFormat(\"[ Layout ] Resource request failed {0} [{1}].\", UnityEditor.AssetDatabase.GetAssetPath(this.component.GetInstanceID()), window.name);\n\t\t\t\t\t\t#endif\n\n\t\t\t\t\t}, async);\n\t\t\t\t\treturn;\n\n\t\t\t\t} else {\n\n\t\t\t\t\tloadedComponent = this.componentNoResource;\n\t\t\t\t\t#if UNITY_EDITOR\n\t\t\t\t\tif (loadedComponent != null) Debug.LogWarningFormat(\"[ Layout ] Resource `{0}` [{1}] should be placed in `Resources` folder to be loaded/unloaded automaticaly. Window `{2}` requested this resource. This warning shown in editor only.\", loadedComponent.name, UnityEditor.AssetDatabase.GetAssetPath(loadedComponent.GetInstanceID()), window.name);\n\t\t\t\t\t#endif\n\n\t\t\t\t}\n\n\t\t\t\tonLoaded.Invoke(loadedComponent);\n\n\t\t\t}\n\n\t\t\tpublic void StopCreate() {\n\n\t\t\t\tthis.stopped = true;\n\n\t\t\t}\n\n\t\t\tpublic void Unload() {\n\n\t\t\t\t//Debug.Log(\"Unload: \" + this.componentResource.GetId() + \" :: \" + this.componentResource.assetPath);\n\n\t\t\t\tWindowSystemResources.UnloadResource_INTERNAL(this.GetReference(), this.componentResource);\n\n\t\t\t\tif (this.root != null) this.root.OnWindowUnload();\n\n\t\t\t\tthis.instance = null;\n\t\t\t\tthis.root = null;\n\t\t\t\tthis.window = null;\n\n\t\t\t\t/*if (this.componentResource.loadableResource == true) {\n\n\t\t\t\t\tthis.componentResource.Unload();\n\n\t\t\t\t} else {\n\n\t\t\t\t\t// Resource was not load via Resources.Load(), so it can't be unload properly\n\n\t\t\t\t}*/\n\n\t\t\t}\n\n\t\t\tpublic WindowLayoutElement GetContainer() {\n\n\t\t\t\treturn this.root as WindowLayoutElement;\n\n\t\t\t}\n\n\t\t\tpublic T Get(LayoutTag tag = LayoutTag.None) where T : WindowComponent {\n\t\t\t\t\n\t\t\t\tif (tag != LayoutTag.None) {\n\t\t\t\t\t\n\t\t\t\t\tif (this.tag != tag) return null;\n\t\t\t\t\t\n\t\t\t\t}\n\n\t\t\t\tif (this.instance is LinkerComponent) {\n\n\t\t\t\t\treturn (this.instance as LinkerComponent).Get();\n\n\t\t\t\t}\n\n\t\t\t\treturn this.instance as T;\n\t\t\t\t\n\t\t\t}\n\t\t\t\n\t\t\tpublic float GetDuration(bool forward) {\n\t\t\t\t\n\t\t\t\tvar root = this.root as IWindowAnimation;\n\t\t\t\tif (root == null) return 0f;\n\n\t\t\t\treturn root.GetAnimationDuration(forward);\n\t\t\t\t\n\t\t\t}\n\n\t\t}\n\n\t\t#region Scale\n\t\tpublic WindowLayout.ScaleMode scaleMode;\n\t\tpublic Vector2 fixedScaleResolution = new Vector2(1024f, 768f);\n\t\tpublic float matchWidthOrHeight = 0f;\n\t\tpublic WindowLayoutPreferences layoutPreferences;\n\t\tpublic bool allowCustomLayoutPreferences = true;\n\t\t#endregion\n\n\t\t#region Layout\n\t\t#if UNITY_EDITOR\n\t\t[BundleIgnore]\n\t\tpublic WindowLayout layout;\n\t\t#endif\n\t\t[SerializeField] private WindowLayout layoutNoResource;\n\t\t[SerializeField] private ResourceAuto layoutResource;\n\t\t#endregion\n\n\t\t#region Components\n\t\tpublic Component[] components;\n\t\t#endregion\n\n\t\t#region Runtime\n\t\tprivate WindowBase window;\n\t\t[System.NonSerialized]\n\t\tprivate IWindowEventsController instance;\n\t\tprivate bool stopped = false;\n\t\t#endregion\n\n\t\tpublic IResourceReference GetReference() {\n\n\t\t\treturn this.window;\n\n\t\t}\n\n\t\tpublic ResourceBase GetResource() {\n\n\t\t\treturn this.layoutResource;\n\n\t\t}\n\n\t\tpublic void Create(WindowBase window, Transform root, float depth, int raycastPriority, int orderInLayer, System.Action callback, bool async) {\n\n\t\t\tif (this.stopped == true) return;\n\n\t\t\tthis.window = window;\n\n\t\t\tSystem.Action onLoaded = (layout) => {\n\n\t\t\t\tif (this.stopped == true) return;\n\n\t\t\t\tvar instance = layout.Spawn(activeByDefault: false);\n\t\t\t\tinstance.transform.SetParent(root);\n\t\t\t\tinstance.transform.localPosition = Vector3.zero;\n\t\t\t\tinstance.transform.localRotation = Quaternion.identity;\n\t\t\t\tinstance.transform.localScale = Vector3.one;\n\t\t\t\t\n\t\t\t\tvar rect = instance.transform as RectTransform;\n\t\t\t\trect.sizeDelta = (layout.transform as RectTransform).sizeDelta;\n\t\t\t\trect.anchoredPosition = (layout.transform as RectTransform).anchoredPosition;\n\n\t\t\t\tvar layoutPreferences = this.layoutPreferences;\n\t\t\t\tif (this.allowCustomLayoutPreferences == true) {\n\n\t\t\t\t\tlayoutPreferences = WindowSystem.GetCustomLayoutPreferences() ?? this.layoutPreferences;\n\n\t\t\t\t}\n\n\t\t\t\tinstance.Setup(window);\n\t\t\t\tinstance.Init(depth, raycastPriority, orderInLayer);\n\t\t\t\tinstance.SetLayoutPreferences(this.scaleMode, this.fixedScaleResolution, layoutPreferences);\n\n\t\t\t\tthis.instance = instance;\n\n\t\t\t\tME.Utilities.CallInSequence(() => {\n\n\t\t\t\t\tif (this.stopped == true) return;\n\n\t\t\t\t\tinstance.gameObject.SetActive(true);\n\t\t\t\t\tcallback.Invoke();\n\n\t\t\t\t}, this.components, (component, c) => {\n\t\t\t\t\t\n\t\t\t\t\tcomponent.Create(window, instance.GetRootByTag(component.tag), (comp) => c.Invoke(), async);\n\n\t\t\t\t}, waitPrevious: true);\n\n\t\t\t};\n\n\t\t\tWindowLayout loadedComponent = null;\n\t\t\tif (this.layoutResource.IsLoadable() == true) {\n\t\t\t\t\n\t\t\t\tWindowSystemResources.LoadRefCounter(this, (layout) => {\n\t\t\t\t\t\n\t\t\t\t\tloadedComponent = layout;\n\t\t\t\t\tonLoaded.Invoke(loadedComponent);\n\n\t\t\t\t\tWindowSystemResources.Unload(this, this.GetResource(), resetController: false);\n\n\t\t\t\t}, () => {\n\n\t\t\t\t\t#if UNITY_EDITOR\n\t\t\t\t\tDebug.LogWarningFormat(\"[ Layout ] Resource request failed {0} [{1}].\", UnityEditor.AssetDatabase.GetAssetPath(this.layout.GetInstanceID()), window.name);\n\t\t\t\t\t#endif\n\n\t\t\t\t}, async);\n\t\t\t\treturn;\n\n\t\t\t} else {\n\n\t\t\t\tloadedComponent = this.layoutNoResource;\n\t\t\t\t#if UNITY_EDITOR\n\t\t\t\tif (loadedComponent != null) Debug.LogWarningFormat(\"[ Layout ] Resource `{0}` [{1}] should be placed in `Resources` folder to be loaded/unloaded automaticaly. Window `{2}` requested this resource. This warning shown in editor only.\", loadedComponent.name, UnityEditor.AssetDatabase.GetAssetPath(loadedComponent.GetInstanceID()), window.name);\n\t\t\t\t#endif\n\n\t\t\t}\n\n\t\t\tonLoaded.Invoke(loadedComponent);\n\n\t\t}\n\n\t\tpublic void StopCreate() {\n\n\t\t\t//Debug.Log(\"StopCreate: \" + this.window + \" :: \" + this.window.GetLastState() + \" :: \" + this.window.preferences.createPool);\n\t\t\tif ((this.window.GetLastState() == WindowObjectState.NotInitialized || this.window.GetLastState() == WindowObjectState.Initializing) && this.window.preferences.createPool == false) {\n\n\t\t\t\tthis.stopped = true;\n\n\t\t\t\tfor (int i = 0; i < this.components.Length; ++i) {\n\n\t\t\t\t\tthis.components[i].StopCreate();\n\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t}\n\n\t\tpublic void Unload() {\n\n\t\t\tfor (int i = 0; i < this.components.Length; ++i) {\n\n\t\t\t\tthis.components[i].Unload();\n\n\t\t\t}\n\n\t\t\tWindowSystemResources.UnloadResource_INTERNAL(this.GetReference(), this.layoutResource);\n\n\t\t\tthis.window = null;\n\n\t\t}\n\n\t\tpublic void SetCustomLayoutPreferences(WindowLayoutPreferences layoutPreferences) {\n\n\t\t\tif (this.allowCustomLayoutPreferences == true) {\n\n\t\t\t\tthis.GetLayoutInstance().SetLayoutPreferences(this.scaleMode, this.fixedScaleResolution, layoutPreferences);\n\n\t\t\t}\n\n\t\t}\n\n\t\tpublic WindowLayout GetLayoutInstance() {\n\n\t\t\treturn this.instance as WindowLayout;\n\n\t\t}\n\n\t\tpublic float GetAnimationDuration(bool forward) {\n\t\t\t\n\t\t\tvar maxDuration = 0f;\n\t\t\tforeach (var component in this.components) {\n\t\t\t\t\n\t\t\t\tvar d = component.GetDuration(forward);\n\t\t\t\tif (d >= maxDuration) {\n\t\t\t\t\t\n\t\t\t\t\tmaxDuration = d;\n\t\t\t\t\t\n\t\t\t\t}\n\t\t\t\t\n\t\t\t}\n\t\t\t\n\t\t\treturn maxDuration;\n\t\t\t\n\t\t}\n\t\t\n\t\tpublic Transform GetRoot() {\n\n\t\t\tvar instance = this.GetLayoutInstance();\n\t\t\treturn (instance != null ? instance.transform : null);\n\t\t\t\n\t\t}\n\n\t\tpublic WindowLayoutElement GetContainer(LayoutTag tag) {\n\n\t\t\tvar component = this.components.FirstOrDefault((c) => c.tag == tag);\n\t\t\tif (component != null) return component.GetContainer();\n\n\t\t\treturn null;\n\n\t\t}\n\n\t\tpublic T Get(LayoutTag tag = LayoutTag.None) where T : WindowComponent {\n\t\t\t\n\t\t\tfor (var i = 0; i < this.components.Length; ++i) {\n\t\t\t\t\n\t\t\t\tvar item = this.components[i].Get(tag);\n\t\t\t\tif (item != null) return item;\n\t\t\t\t\n\t\t\t}\n\t\t\t\n\t\t\treturn default(T);\n\t\t\t\n\t\t}\n\n\t\tpublic int GetSortingOrder() {\n\t\t\t\n\t\t\treturn this.GetLayoutInstance().canvas.sortingOrder;\n\t\t\t\n\t\t}\n\t\t\n\t\t// Events\n\t\tpublic void OnLocalizationChanged() {\n\t\t\t\n\t\t\tif (this.instance != null) this.GetLayoutInstance().OnLocalizationChanged();\n\t\t\t\n\t\t}\n\t\t\n\t\tpublic void OnManualEvent(T data) where T : IManualEvent {\n\t\t\t\n\t\t\tif (this.instance != null) this.GetLayoutInstance().OnManualEvent(data);\n\t\t\t\n\t\t}\n\n\t\tpublic void DoWindowLayoutComplete() {\n\n\t\t\tif (this.instance != null) this.instance.DoWindowLayoutComplete();\n\n\t\t}\n\n\t\tpublic void DoWindowOpen() {\n\n\t\t\tif (this.instance != null) this.instance.DoWindowOpen();\n\n\t\t}\n\n\t\tpublic void DoWindowClose() {\n\n\t\t\tif (this.instance != null) this.instance.DoWindowClose();\n\n\t\t}\n\n\t\tpublic void DoWindowActive() {\n\n\t\t\tif (this.instance != null) this.instance.DoWindowActive();\n\n\t\t}\n\n\t\tpublic void DoWindowInactive() {\n\n\t\t\tif (this.instance != null) this.instance.DoWindowInactive();\n\n\t\t}\n\n\t\t#region Base Events\n\t\t// Base Events\n\t\tpublic void DoInit() {\n\n\t\t\tif (this.instance != null) this.instance.DoInit();\n\n\t\t}\n\n\t\tpublic void DoDeinit(System.Action callback) {\n\n\t\t\tif (this.instance != null) this.instance.DoDeinit(callback);\n\n\t\t\tthis.instance = null;\n\t\t\tthis.components = null;\n\n\t\t}\n\n\t\tpublic void DoShowBegin(AppearanceParameters parameters) {\n\n\t\t\tif (this.instance != null) this.instance.DoShowBegin(parameters);\n\n\t\t}\n\n\t\tpublic void DoShowEnd(AppearanceParameters parameters) {\n\n\t\t\tif (this.instance != null) {\n\n\t\t\t\tthis.instance.DoShowEnd(parameters);\n\t\t\t\tCanvasUpdater.ForceUpdate(this.GetLayoutInstance().canvas, this.GetLayoutInstance().canvasScaler);\n\n\t\t\t}\n\n\t\t}\n\n\t\tpublic void DoHideBegin(AppearanceParameters parameters) {\n\n\t\t\tthis.StopCreate();\n\t\t\tif (this.instance != null) this.instance.DoHideBegin(parameters); \n\n\t\t}\n\n\t\tpublic void DoHideEnd(AppearanceParameters parameters) {\n\n\t\t\tif (this.instance != null) this.instance.DoHideEnd(parameters);\n\n\t\t}\n\n\t\tpublic void DoWindowUnload() {\n\n\t\t\tif (this.instance != null) {\n\n\t\t\t\tthis.instance.DoWindowUnload();\n\t\t\t\tthis.Unload();\n\n\t\t\t}\n\n\t\t}\n\t\t#endregion\n\t\t\n\t\tpublic static WindowComponentParametersBase AddParametersFor(WindowBase window, WindowComponent component) {\n\n\t\t\treturn Layout.AddParametersFor(window.gameObject, component);\n\n\t\t}\n\n\t\tpublic static WindowComponentParametersBase AddParametersFor(GameObject obj, WindowComponent component) {\n\n\t\t\tif (component == null) return null;\n\n\t\t\t// Find the type\n\t\t\tvar type = System.Type.GetType(string.Format(\"{0}Parameters\", component.GetType().FullName), throwOnError: false, ignoreCase: false);\n\t\t\tif (type == null) return null;\n\n\t\t\t// Add component\n\t\t\tvar instance = obj.AddComponent(type);\n\t\t\tinstance.hideFlags = HideFlags.HideInInspector;\n\t\t\treturn instance as WindowComponentParametersBase;\n\n\t\t}\n\n\t\t#if UNITY_EDITOR\n\t\tprivate List tags = new List();\n\t\tinternal void Update_EDITOR(LayoutWindowType layoutWindow) {\n\t\t\t\n\t\t\tif (this.layout == null) return;\n\t\t\t\n\t\t\tthis.layout.GetTags(this.tags);\n\n\t\t\tforeach (var tag in this.tags) {\n\n\t\t\t\tthis.AddComponentLink(tag);\n\n\t\t\t}\n\n\t\t\tthis.components = this.components.Distinct(new ComponentComparer()).ToArray();\n\n\t\t\t// Used\n\t\t\tfor (int i = 0; i < this.components.Length; ++i) {\n\n\t\t\t\tthis.components[i].OnValidate();\n\n\t\t\t\tthis.components[i].UpdateDescription(layoutWindow);\n\n\t\t\t\tvar index = this.tags.IndexOf(this.components[i].tag);\n\t\t\t\tif (index == -1) {\n\t\t\t\t\t\n\t\t\t\t\tthis.RemoveComponentLink(this.components[i].tag);\n\t\t\t\t\tcontinue;\n\t\t\t\t\t\n\t\t\t\t}\n\t\t\t\tthis.tags.RemoveAt(index);\n\n\t\t\t}\n\n\t\t\tthis.layoutResource.tempObject = this.layout;\n\t\t\tthis.layoutResource.Validate();\n\t\t\tthis.layoutNoResource = (this.layoutResource.IsLoadable() == true ? null : this.layout);\n\n\t\t}\n\t\t\n\t\tprivate void RemoveComponentLink(LayoutTag tag) {\n\t\t\t\n\t\t\tthis.components = this.components.Where((c) => c.tag != tag).ToArray();\n\t\t\t\n\t\t}\n\t\t\n\t\tprivate void AddComponentLink(LayoutTag tag) {\n\t\t\t\n\t\t\tvar list = this.components.ToList();\n\t\t\tlist.Add(new Component(tag));\n\t\t\tthis.components = list.ToArray();\n\t\t\t\n\t\t}\n\t\t#endif\n\t\t\n\t}\n\n}\n"},"gt":{"kind":"string","value":""}}},{"rowIdx":98453,"cells":{"context":{"kind":"string","value":"#region License\n\n// Distributed under the MIT License\n// ============================================================\n// Copyright (c) 2019 Hotcakes Commerce, LLC\n// Copyright (c) 2020 Upendo Ventures, LLC\n// \n// Permission is hereby granted, free of charge, to any person obtaining a copy of this software \n// and associated documentation files (the \"Software\"), to deal in the Software without restriction, \n// including without limitation the rights to use, copy, modify, merge, publish, distribute, \n// sublicense, and/or sell 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 all copies or \n// 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\n#endregion\n\nusing System;\nusing Hotcakes.Commerce;\nusing Hotcakes.Commerce.Utilities;\nusing Hotcakes.Modules.Core.Admin.AppCode;\nusing Hotcakes.Web;\n\nnamespace Hotcakes.Modules.Core.Admin.Controls\n{\n partial class DateRangePicker : HccUserControl\n {\n private const string DATEFORMAT = \"MM/dd/yyyy\";\n\n #region Fields\n\n private readonly DateRange _range = new DateRange();\n\n public class RangeTypeChangedEventArgs : EventArgs\n {\n }\n\n public delegate void RangeTypeChangedDelegate(object sender, RangeTypeChangedEventArgs e);\n\n public event RangeTypeChangedDelegate RangeTypeChanged;\n\n #endregion\n\n #region Properties\n\n public string FormItemCssClass { get; set; }\n\n public string LabelText\n {\n get { return lblDateRangeLabel.Text; }\n set { lblDateRangeLabel.Text = value; }\n }\n\n public bool Enabled\n {\n get { return lstRangeType.Enabled; }\n set { lstRangeType.Enabled = value; }\n }\n\n public bool HideButton\n {\n get { return !btnShow.Visible; }\n set { btnShow.Visible = !value; }\n }\n\n public DateRangeType RangeType\n {\n get { return (DateRangeType) int.Parse(lstRangeType.SelectedValue); }\n set\n {\n if (lstRangeType.Items.FindByValue(((int) value).ToString()) != null)\n {\n lstRangeType.SelectedValue = ((int) value).ToString();\n }\n }\n }\n\n public DateTime StartDate\n {\n get\n {\n if (RangeType == DateRangeType.Custom)\n {\n var date = DateTime.Parse(radStartDate.Text.Trim());\n return date.ZeroOutTime();\n }\n _range.RangeType = RangeType;\n\n if (RangeType != DateRangeType.AllDates)\n return _range.StartDate;\n return DateTime.MinValue;\n }\n set\n {\n radStartDate.Text = value.ToString(DATEFORMAT);\n RangeType = DateRangeType.Custom;\n }\n }\n\n public DateTime EndDate\n {\n get\n {\n if (RangeType == DateRangeType.Custom)\n {\n var date = DateTime.Parse(radStartDate.Text.Trim());\n return date.MaxOutTime();\n }\n _range.RangeType = RangeType;\n if (RangeType != DateRangeType.AllDates)\n return _range.EndDate;\n return DateTime.MaxValue;\n }\n set\n {\n radEndDate.Text = value.ToString(DATEFORMAT);\n RangeType = DateRangeType.Custom;\n }\n }\n\n #endregion\n\n #region Event Handlers\n\n public DateRangePicker()\n {\n FormItemCssClass = \"hcFormItemHor\";\n }\n\n protected override void OnInit(EventArgs e)\n {\n base.OnInit(e);\n btnShow.Click += btnShow_Click;\n }\n\n protected override void OnLoad(EventArgs e)\n {\n base.OnLoad(e);\n\n if (!IsPostBack)\n {\n lstRangeType_SelectedIndexChanged(this, EventArgs.Empty);\n }\n }\n\n protected void btnShow_Click(object sender, EventArgs e)\n {\n if (RangeTypeChanged != null)\n {\n RangeTypeChanged(this, new RangeTypeChangedEventArgs());\n }\n }\n\n protected void lstRangeType_SelectedIndexChanged(object sender, EventArgs e)\n {\n if (RangeTypeChanged != null)\n {\n RangeTypeChanged(this, new RangeTypeChangedEventArgs());\n }\n }\n\n protected override void OnPreRender(EventArgs e)\n {\n base.OnPreRender(e);\n\n if (RangeType != DateRangeType.Custom)\n {\n radStartDate.Text = StartDate.ToString(DATEFORMAT);\n radEndDate.Text = EndDate.ToString(DATEFORMAT);\n }\n\n pnlCustom.Visible = lstRangeType.SelectedValue == ((int) DateRangeType.Custom).ToString();\n }\n\n #endregion\n\n #region Public Methods\n\n public DateTime GetStartDateUtc(HotcakesApplication hccApp)\n {\n DateTime result;\n\n if (RangeType == DateRangeType.Custom)\n {\n var date = DateTime.Parse(radStartDate.Text.Trim());\n result = date.ZeroOutTime();\n }\n else\n {\n _range.RangeType = RangeType;\n ;\n _range.CalculateDatesFromType(DateHelper.ConvertUtcToStoreTime(hccApp));\n result = _range.StartDate;\n }\n\n return DateHelper.ConvertStoreTimeToUtc(hccApp, result);\n }\n\n public DateTime GetEndDateUtc(HotcakesApplication hccApp)\n {\n DateTime result;\n if (RangeType == DateRangeType.Custom)\n {\n var date = DateTime.Parse(radStartDate.Text.Trim());\n result = date.MaxOutTime();\n }\n else\n {\n _range.RangeType = RangeType;\n _range.CalculateDatesFromType(DateHelper.ConvertUtcToStoreTime(hccApp));\n result = _range.EndDate;\n }\n\n return DateHelper.ConvertStoreTimeToUtc(hccApp, result);\n }\n\n #endregion\n }\n}\n"},"gt":{"kind":"string","value":""}}},{"rowIdx":98454,"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.Net;\nusing System.Reflection;\nusing Nini.Config;\nusing log4net;\nusing OpenSim.Framework;\nusing OpenSim.Framework.Console;\nusing OpenSim.Data;\nusing OpenSim.Server.Base;\nusing OpenSim.Services.Interfaces;\nusing GridRegion = OpenSim.Services.Interfaces.GridRegion;\nusing OpenMetaverse;\n\nnamespace OpenSim.Services.GridService\n{\n public class GridService : GridServiceBase, IGridService\n {\n private static readonly ILog m_log =\n LogManager.GetLogger(\n MethodBase.GetCurrentMethod().DeclaringType);\n\n private bool m_DeleteOnUnregister = true;\n private static GridService m_RootInstance = null;\n protected IConfigSource m_config;\n protected static HypergridLinker m_HypergridLinker;\n\n protected IAuthenticationService m_AuthenticationService = null;\n protected bool m_AllowDuplicateNames = false;\n protected bool m_AllowHypergridMapSearch = false;\n\n public GridService(IConfigSource config)\n : base(config)\n {\n m_log.DebugFormat(\"[GRID SERVICE]: Starting...\");\n\n m_config = config;\n IConfig gridConfig = config.Configs[\"GridService\"];\n if (gridConfig != null)\n {\n m_DeleteOnUnregister = gridConfig.GetBoolean(\"DeleteOnUnregister\", true);\n \n string authService = gridConfig.GetString(\"AuthenticationService\", String.Empty);\n\n if (authService != String.Empty)\n {\n Object[] args = new Object[] { config };\n m_AuthenticationService = ServerUtils.LoadPlugin(authService, args);\n }\n m_AllowDuplicateNames = gridConfig.GetBoolean(\"AllowDuplicateNames\", m_AllowDuplicateNames);\n m_AllowHypergridMapSearch = gridConfig.GetBoolean(\"AllowHypergridMapSearch\", m_AllowHypergridMapSearch);\n }\n \n if (m_RootInstance == null)\n {\n m_RootInstance = this;\n\n if (MainConsole.Instance != null)\n {\n MainConsole.Instance.Commands.AddCommand(\"grid\", true,\n \"show region\",\n \"show region \",\n \"Show details on a region\",\n String.Empty,\n HandleShowRegion);\n\n MainConsole.Instance.Commands.AddCommand(\"grid\", true,\n \"set region flags\",\n \"set region flags \",\n \"Set database flags for region\",\n String.Empty,\n HandleSetFlags);\n }\n m_HypergridLinker = new HypergridLinker(m_config, this, m_Database);\n }\n }\n\n #region IGridService\n\n public string RegisterRegion(UUID scopeID, GridRegion regionInfos)\n {\n IConfig gridConfig = m_config.Configs[\"GridService\"];\n // This needs better sanity testing. What if regionInfo is registering in\n // overlapping coords?\n RegionData region = m_Database.Get(regionInfos.RegionLocX, regionInfos.RegionLocY, scopeID);\n if (region != null)\n {\n // There is a preexisting record\n //\n // Get it's flags\n //\n OpenSim.Data.RegionFlags rflags = (OpenSim.Data.RegionFlags)Convert.ToInt32(region.Data[\"flags\"]);\n\n // Is this a reservation?\n //\n if ((rflags & OpenSim.Data.RegionFlags.Reservation) != 0)\n {\n // Regions reserved for the null key cannot be taken.\n if ((string)region.Data[\"PrincipalID\"] == UUID.Zero.ToString())\n return \"Region location is reserved\";\n\n // Treat it as an auth request\n //\n // NOTE: Fudging the flags value here, so these flags\n // should not be used elsewhere. Don't optimize\n // this with the later retrieval of the same flags!\n rflags |= OpenSim.Data.RegionFlags.Authenticate;\n }\n\n if ((rflags & OpenSim.Data.RegionFlags.Authenticate) != 0)\n {\n // Can we authenticate at all?\n //\n if (m_AuthenticationService == null)\n return \"No authentication possible\";\n\n if (!m_AuthenticationService.Verify(new UUID(region.Data[\"PrincipalID\"].ToString()), regionInfos.Token, 30))\n return \"Bad authentication\";\n }\n }\n\n if ((region != null) && (region.RegionID != regionInfos.RegionID))\n {\n m_log.WarnFormat(\"[GRID SERVICE]: Region {0} tried to register in coordinates {1}, {2} which are already in use in scope {3}.\", \n regionInfos.RegionID, regionInfos.RegionLocX, regionInfos.RegionLocY, scopeID);\n return \"Region overlaps another region\";\n }\n if ((region != null) && (region.RegionID == regionInfos.RegionID) && \n ((region.posX != regionInfos.RegionLocX) || (region.posY != regionInfos.RegionLocY)))\n {\n if ((Convert.ToInt32(region.Data[\"flags\"]) & (int)OpenSim.Data.RegionFlags.NoMove) != 0)\n return \"Can't move this region\";\n\n // Region reregistering in other coordinates. Delete the old entry\n m_log.DebugFormat(\"[GRID SERVICE]: Region {0} ({1}) was previously registered at {2}-{3}. Deleting old entry.\",\n regionInfos.RegionName, regionInfos.RegionID, regionInfos.RegionLocX, regionInfos.RegionLocY);\n\n try\n {\n m_Database.Delete(regionInfos.RegionID);\n }\n catch (Exception e)\n {\n m_log.DebugFormat(\"[GRID SERVICE]: Database exception: {0}\", e);\n }\n }\n\n if (!m_AllowDuplicateNames)\n {\n List dupe = m_Database.Get(regionInfos.RegionName, scopeID);\n if (dupe != null && dupe.Count > 0)\n {\n foreach (RegionData d in dupe)\n {\n if (d.RegionID != regionInfos.RegionID)\n {\n m_log.WarnFormat(\"[GRID SERVICE]: Region {0} tried to register duplicate name with ID {1}.\", \n regionInfos.RegionName, regionInfos.RegionID);\n return \"Duplicate region name\";\n }\n }\n }\n }\n\n // Everything is ok, let's register\n RegionData rdata = RegionInfo2RegionData(regionInfos);\n rdata.ScopeID = scopeID;\n \n if (region != null)\n {\n int oldFlags = Convert.ToInt32(region.Data[\"flags\"]);\n if ((oldFlags & (int)OpenSim.Data.RegionFlags.LockedOut) != 0)\n return \"Region locked out\";\n\n oldFlags &= ~(int)OpenSim.Data.RegionFlags.Reservation;\n\n rdata.Data[\"flags\"] = oldFlags.ToString(); // Preserve flags\n }\n else\n {\n rdata.Data[\"flags\"] = \"0\";\n if ((gridConfig != null) && rdata.RegionName != string.Empty)\n {\n int newFlags = 0;\n string regionName = rdata.RegionName.Trim().Replace(' ', '_');\n newFlags = ParseFlags(newFlags, gridConfig.GetString(\"DefaultRegionFlags\", String.Empty));\n newFlags = ParseFlags(newFlags, gridConfig.GetString(\"Region_\" + regionName, String.Empty));\n newFlags = ParseFlags(newFlags, gridConfig.GetString(\"Region_\" + rdata.RegionID.ToString(), String.Empty));\n rdata.Data[\"flags\"] = newFlags.ToString();\n }\n }\n\n int flags = Convert.ToInt32(rdata.Data[\"flags\"]);\n flags |= (int)OpenSim.Data.RegionFlags.RegionOnline;\n rdata.Data[\"flags\"] = flags.ToString();\n\n try\n {\n rdata.Data[\"last_seen\"] = Util.UnixTimeSinceEpoch();\n m_Database.Store(rdata);\n }\n catch (Exception e)\n {\n m_log.DebugFormat(\"[GRID SERVICE]: Database exception: {0}\", e);\n }\n\n m_log.DebugFormat(\"[GRID SERVICE]: Region {0} ({1}) registered successfully at {2}-{3}\", \n regionInfos.RegionName, regionInfos.RegionID, regionInfos.RegionLocX, regionInfos.RegionLocY);\n\n return String.Empty;\n }\n\n public bool DeregisterRegion(UUID regionID)\n {\n m_log.DebugFormat(\"[GRID SERVICE]: Region {0} deregistered\", regionID);\n RegionData region = m_Database.Get(regionID, UUID.Zero);\n if (region == null)\n return false;\n\n int flags = Convert.ToInt32(region.Data[\"flags\"]);\n\n if (!m_DeleteOnUnregister || (flags & (int)OpenSim.Data.RegionFlags.Persistent) != 0)\n {\n flags &= ~(int)OpenSim.Data.RegionFlags.RegionOnline;\n region.Data[\"flags\"] = flags.ToString();\n region.Data[\"last_seen\"] = Util.UnixTimeSinceEpoch();\n try\n {\n m_Database.Store(region);\n }\n catch (Exception e)\n {\n m_log.DebugFormat(\"[GRID SERVICE]: Database exception: {0}\", e);\n }\n\n return true;\n\n }\n\n return m_Database.Delete(regionID);\n }\n\n public List GetNeighbours(UUID scopeID, UUID regionID)\n {\n List rinfos = new List();\n RegionData region = m_Database.Get(regionID, scopeID);\n if (region != null)\n {\n // Not really? Maybe?\n List rdatas = m_Database.Get(region.posX - (int)Constants.RegionSize - 1, region.posY - (int)Constants.RegionSize - 1, \n region.posX + (int)Constants.RegionSize + 1, region.posY + (int)Constants.RegionSize + 1, scopeID);\n\n foreach (RegionData rdata in rdatas)\n if (rdata.RegionID != regionID)\n {\n int flags = Convert.ToInt32(rdata.Data[\"flags\"]);\n if ((flags & (int)Data.RegionFlags.Hyperlink) == 0) // no hyperlinks as neighbours\n rinfos.Add(RegionData2RegionInfo(rdata));\n }\n\n }\n m_log.DebugFormat(\"[GRID SERVICE]: region {0} has {1} neighours\", region.RegionName, rinfos.Count);\n return rinfos;\n }\n\n public GridRegion GetRegionByUUID(UUID scopeID, UUID regionID)\n {\n RegionData rdata = m_Database.Get(regionID, scopeID);\n if (rdata != null)\n return RegionData2RegionInfo(rdata);\n\n return null;\n }\n\n public GridRegion GetRegionByPosition(UUID scopeID, int x, int y)\n {\n int snapX = (int)(x / Constants.RegionSize) * (int)Constants.RegionSize;\n int snapY = (int)(y / Constants.RegionSize) * (int)Constants.RegionSize;\n RegionData rdata = m_Database.Get(snapX, snapY, scopeID);\n if (rdata != null)\n return RegionData2RegionInfo(rdata);\n\n return null;\n }\n\n public GridRegion GetRegionByName(UUID scopeID, string regionName)\n {\n List rdatas = m_Database.Get(regionName + \"%\", scopeID);\n if ((rdatas != null) && (rdatas.Count > 0))\n return RegionData2RegionInfo(rdatas[0]); // get the first\n\n return null;\n }\n\n public List GetRegionsByName(UUID scopeID, string name, int maxNumber)\n {\n m_log.DebugFormat(\"[GRID SERVICE]: GetRegionsByName {0}\", name);\n\n List rdatas = m_Database.Get(name + \"%\", scopeID);\n\n int count = 0;\n List rinfos = new List();\n\n if (rdatas != null)\n {\n m_log.DebugFormat(\"[GRID SERVICE]: Found {0} regions\", rdatas.Count);\n foreach (RegionData rdata in rdatas)\n {\n if (count++ < maxNumber)\n rinfos.Add(RegionData2RegionInfo(rdata));\n }\n }\n\n if (m_AllowHypergridMapSearch && (rdatas == null || (rdatas != null && rdatas.Count == 0)) && name.Contains(\".\"))\n {\n GridRegion r = m_HypergridLinker.LinkRegion(scopeID, name);\n if (r != null)\n rinfos.Add(r);\n }\n\n return rinfos;\n }\n\n public List GetRegionRange(UUID scopeID, int xmin, int xmax, int ymin, int ymax)\n {\n int xminSnap = (int)(xmin / Constants.RegionSize) * (int)Constants.RegionSize;\n int xmaxSnap = (int)(xmax / Constants.RegionSize) * (int)Constants.RegionSize;\n int yminSnap = (int)(ymin / Constants.RegionSize) * (int)Constants.RegionSize;\n int ymaxSnap = (int)(ymax / Constants.RegionSize) * (int)Constants.RegionSize;\n\n List rdatas = m_Database.Get(xminSnap, yminSnap, xmaxSnap, ymaxSnap, scopeID);\n List rinfos = new List();\n foreach (RegionData rdata in rdatas)\n rinfos.Add(RegionData2RegionInfo(rdata));\n\n return rinfos;\n }\n\n #endregion\n\n #region Data structure conversions\n\n public RegionData RegionInfo2RegionData(GridRegion rinfo)\n {\n RegionData rdata = new RegionData();\n rdata.posX = (int)rinfo.RegionLocX;\n rdata.posY = (int)rinfo.RegionLocY;\n rdata.RegionID = rinfo.RegionID;\n rdata.RegionName = rinfo.RegionName;\n rdata.Data = rinfo.ToKeyValuePairs();\n rdata.Data[\"regionHandle\"] = Utils.UIntsToLong((uint)rdata.posX, (uint)rdata.posY);\n rdata.Data[\"owner_uuid\"] = rinfo.EstateOwner.ToString();\n return rdata;\n }\n\n public GridRegion RegionData2RegionInfo(RegionData rdata)\n {\n GridRegion rinfo = new GridRegion(rdata.Data);\n rinfo.RegionLocX = rdata.posX;\n rinfo.RegionLocY = rdata.posY;\n rinfo.RegionID = rdata.RegionID;\n rinfo.RegionName = rdata.RegionName;\n rinfo.ScopeID = rdata.ScopeID;\n\n return rinfo;\n }\n\n #endregion \n\n public List GetDefaultRegions(UUID scopeID)\n {\n List ret = new List();\n\n List regions = m_Database.GetDefaultRegions(scopeID);\n\n foreach (RegionData r in regions)\n {\n if ((Convert.ToInt32(r.Data[\"flags\"]) & (int)OpenSim.Data.RegionFlags.RegionOnline) != 0)\n ret.Add(RegionData2RegionInfo(r));\n }\n\n m_log.DebugFormat(\"[GRID SERVICE]: GetDefaultRegions returning {0} regions\", ret.Count);\n return ret;\n }\n\n public List GetFallbackRegions(UUID scopeID, int x, int y)\n {\n List ret = new List();\n\n List regions = m_Database.GetFallbackRegions(scopeID, x, y);\n\n foreach (RegionData r in regions)\n {\n if ((Convert.ToInt32(r.Data[\"flags\"]) & (int)OpenSim.Data.RegionFlags.RegionOnline) != 0)\n ret.Add(RegionData2RegionInfo(r));\n }\n\n m_log.DebugFormat(\"[GRID SERVICE]: Fallback returned {0} regions\", ret.Count);\n return ret;\n }\n\n public List GetHyperlinks(UUID scopeID)\n {\n List ret = new List();\n\n List regions = m_Database.GetHyperlinks(scopeID);\n\n foreach (RegionData r in regions)\n {\n if ((Convert.ToInt32(r.Data[\"flags\"]) & (int)OpenSim.Data.RegionFlags.RegionOnline) != 0)\n ret.Add(RegionData2RegionInfo(r));\n }\n\n m_log.DebugFormat(\"[GRID SERVICE]: Hyperlinks returned {0} regions\", ret.Count);\n return ret;\n }\n \n public int GetRegionFlags(UUID scopeID, UUID regionID)\n {\n RegionData region = m_Database.Get(regionID, scopeID);\n\n if (region != null)\n {\n int flags = Convert.ToInt32(region.Data[\"flags\"]);\n //m_log.DebugFormat(\"[GRID SERVICE]: Request for flags of {0}: {1}\", regionID, flags);\n return flags;\n }\n else\n return -1;\n }\n\n private void HandleShowRegion(string module, string[] cmd)\n {\n if (cmd.Length != 3)\n {\n MainConsole.Instance.Output(\"Syntax: show region \");\n return;\n }\n List regions = m_Database.Get(cmd[2], UUID.Zero);\n if (regions == null || regions.Count < 1)\n {\n MainConsole.Instance.Output(\"Region not found\");\n return;\n }\n\n MainConsole.Instance.Output(\"Region Name Region UUID\");\n MainConsole.Instance.Output(\"Location URI\");\n MainConsole.Instance.Output(\"Owner ID Flags\");\n MainConsole.Instance.Output(\"-------------------------------------------------------------------------------\");\n foreach (RegionData r in regions)\n {\n OpenSim.Data.RegionFlags flags = (OpenSim.Data.RegionFlags)Convert.ToInt32(r.Data[\"flags\"]);\n MainConsole.Instance.Output(String.Format(\"{0,-20} {1}\\n{2,-20} {3}\\n{4,-39} {5}\\n\\n\",\n r.RegionName, r.RegionID,\n String.Format(\"{0},{1}\", r.posX, r.posY), \"http://\" + r.Data[\"serverIP\"].ToString() + \":\" + r.Data[\"serverPort\"].ToString(),\n r.Data[\"owner_uuid\"].ToString(), flags.ToString()));\n }\n return;\n }\n\n private int ParseFlags(int prev, string flags)\n {\n OpenSim.Data.RegionFlags f = (OpenSim.Data.RegionFlags)prev;\n\n string[] parts = flags.Split(new char[] {',', ' '}, StringSplitOptions.RemoveEmptyEntries);\n\n foreach (string p in parts)\n {\n int val;\n\n try\n {\n if (p.StartsWith(\"+\"))\n {\n val = (int)Enum.Parse(typeof(OpenSim.Data.RegionFlags), p.Substring(1));\n f |= (OpenSim.Data.RegionFlags)val;\n }\n else if (p.StartsWith(\"-\"))\n {\n val = (int)Enum.Parse(typeof(OpenSim.Data.RegionFlags), p.Substring(1));\n f &= ~(OpenSim.Data.RegionFlags)val;\n }\n else\n {\n val = (int)Enum.Parse(typeof(OpenSim.Data.RegionFlags), p);\n f |= (OpenSim.Data.RegionFlags)val;\n }\n }\n catch (Exception)\n {\n MainConsole.Instance.Output(\"Error in flag specification: \" + p);\n }\n }\n\n return (int)f;\n }\n\n private void HandleSetFlags(string module, string[] cmd)\n {\n if (cmd.Length < 5)\n {\n MainConsole.Instance.Output(\"Syntax: set region flags \");\n return;\n }\n\n List regions = m_Database.Get(cmd[3], UUID.Zero);\n if (regions == null || regions.Count < 1)\n {\n MainConsole.Instance.Output(\"Region not found\");\n return;\n }\n\n foreach (RegionData r in regions)\n {\n int flags = Convert.ToInt32(r.Data[\"flags\"]);\n flags = ParseFlags(flags, cmd[4]);\n r.Data[\"flags\"] = flags.ToString();\n OpenSim.Data.RegionFlags f = (OpenSim.Data.RegionFlags)flags;\n\n MainConsole.Instance.Output(String.Format(\"Set region {0} to {1}\", r.RegionName, f));\n m_Database.Store(r);\n }\n }\n }\n}\n"},"gt":{"kind":"string","value":""}}},{"rowIdx":98455,"cells":{"context":{"kind":"string","value":"namespace android.content.pm\n{\n\t[global::MonoJavaBridge.JavaClass(typeof(global::android.content.pm.PackageManager_))]\n\tpublic abstract partial class PackageManager : java.lang.Object\n\t{\n\t\tinternal new static global::MonoJavaBridge.JniGlobalHandle staticClass;\n\t\tprotected PackageManager(global::MonoJavaBridge.JNIEnv @__env) : base(@__env)\n\t\t{\n\t\t}\n\t\t[global::MonoJavaBridge.JavaClass()]\n\t\tpublic partial class NameNotFoundException : android.util.AndroidException\n\t\t{\n\t\t\tinternal new static global::MonoJavaBridge.JniGlobalHandle staticClass;\n\t\t\tprotected NameNotFoundException(global::MonoJavaBridge.JNIEnv @__env) : base(@__env)\n\t\t\t{\n\t\t\t}\n\t\t\tprivate static global::MonoJavaBridge.MethodId _m0;\n\t\t\tpublic NameNotFoundException() : base(global::MonoJavaBridge.JNIEnv.ThreadEnv)\n\t\t\t{\n\t\t\t\tglobal::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;\n\t\t\t\tif (global::android.content.pm.PackageManager.NameNotFoundException._m0.native == global::System.IntPtr.Zero)\n\t\t\t\t\tglobal::android.content.pm.PackageManager.NameNotFoundException._m0 = @__env.GetMethodIDNoThrow(global::android.content.pm.PackageManager.NameNotFoundException.staticClass, \"\", \"()V\");\n\t\t\t\tglobal::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.content.pm.PackageManager.NameNotFoundException.staticClass, global::android.content.pm.PackageManager.NameNotFoundException._m0);\n\t\t\t\tInit(@__env, handle);\n\t\t\t}\n\t\t\tprivate static global::MonoJavaBridge.MethodId _m1;\n\t\t\tpublic NameNotFoundException(java.lang.String arg0) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv)\n\t\t\t{\n\t\t\t\tglobal::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;\n\t\t\t\tif (global::android.content.pm.PackageManager.NameNotFoundException._m1.native == global::System.IntPtr.Zero)\n\t\t\t\t\tglobal::android.content.pm.PackageManager.NameNotFoundException._m1 = @__env.GetMethodIDNoThrow(global::android.content.pm.PackageManager.NameNotFoundException.staticClass, \"\", \"(Ljava/lang/String;)V\");\n\t\t\t\tglobal::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.content.pm.PackageManager.NameNotFoundException.staticClass, global::android.content.pm.PackageManager.NameNotFoundException._m1, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));\n\t\t\t\tInit(@__env, handle);\n\t\t\t}\n\t\t\tstatic NameNotFoundException()\n\t\t\t{\n\t\t\t\tglobal::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;\n\t\t\t\tglobal::android.content.pm.PackageManager.NameNotFoundException.staticClass = @__env.NewGlobalRef(@__env.FindClass(\"android/content/pm/PackageManager$NameNotFoundException\"));\n\t\t\t}\n\t\t}\n\t\tprivate static global::MonoJavaBridge.MethodId _m0;\n\t\tpublic abstract int checkPermission(java.lang.String arg0, java.lang.String arg1);\n\t\tprivate static global::MonoJavaBridge.MethodId _m1;\n\t\tpublic abstract global::android.content.pm.PackageInfo getPackageInfo(java.lang.String arg0, int arg1);\n\t\tprivate static global::MonoJavaBridge.MethodId _m2;\n\t\tpublic abstract global::android.content.pm.ApplicationInfo getApplicationInfo(java.lang.String arg0, int arg1);\n\t\tprivate static global::MonoJavaBridge.MethodId _m3;\n\t\tpublic abstract global::java.lang.CharSequence getText(java.lang.String arg0, int arg1, android.content.pm.ApplicationInfo arg2);\n\t\tprivate static global::MonoJavaBridge.MethodId _m4;\n\t\tpublic abstract global::android.content.pm.ResolveInfo resolveActivity(android.content.Intent arg0, int arg1);\n\t\tprivate static global::MonoJavaBridge.MethodId _m5;\n\t\tpublic abstract global::android.graphics.drawable.Drawable getDrawable(java.lang.String arg0, int arg1, android.content.pm.ApplicationInfo arg2);\n\t\tprivate static global::MonoJavaBridge.MethodId _m6;\n\t\tpublic abstract global::android.content.res.XmlResourceParser getXml(java.lang.String arg0, int arg1, android.content.pm.ApplicationInfo arg2);\n\t\tprivate static global::MonoJavaBridge.MethodId _m7;\n\t\tpublic abstract global::java.lang.String[] currentToCanonicalPackageNames(java.lang.String[] arg0);\n\t\tprivate static global::MonoJavaBridge.MethodId _m8;\n\t\tpublic abstract global::java.lang.String[] canonicalToCurrentPackageNames(java.lang.String[] arg0);\n\t\tprivate static global::MonoJavaBridge.MethodId _m9;\n\t\tpublic abstract global::android.content.Intent getLaunchIntentForPackage(java.lang.String arg0);\n\t\tprivate static global::MonoJavaBridge.MethodId _m10;\n\t\tpublic abstract int[] getPackageGids(java.lang.String arg0);\n\t\tprivate static global::MonoJavaBridge.MethodId _m11;\n\t\tpublic abstract global::android.content.pm.PermissionInfo getPermissionInfo(java.lang.String arg0, int arg1);\n\t\tprivate static global::MonoJavaBridge.MethodId _m12;\n\t\tpublic abstract global::java.util.List queryPermissionsByGroup(java.lang.String arg0, int arg1);\n\t\tprivate static global::MonoJavaBridge.MethodId _m13;\n\t\tpublic abstract global::android.content.pm.PermissionGroupInfo getPermissionGroupInfo(java.lang.String arg0, int arg1);\n\t\tprivate static global::MonoJavaBridge.MethodId _m14;\n\t\tpublic abstract global::java.util.List getAllPermissionGroups(int arg0);\n\t\tprivate static global::MonoJavaBridge.MethodId _m15;\n\t\tpublic abstract global::android.content.pm.ActivityInfo getActivityInfo(android.content.ComponentName arg0, int arg1);\n\t\tprivate static global::MonoJavaBridge.MethodId _m16;\n\t\tpublic abstract global::android.content.pm.ActivityInfo getReceiverInfo(android.content.ComponentName arg0, int arg1);\n\t\tprivate static global::MonoJavaBridge.MethodId _m17;\n\t\tpublic abstract global::android.content.pm.ServiceInfo getServiceInfo(android.content.ComponentName arg0, int arg1);\n\t\tprivate static global::MonoJavaBridge.MethodId _m18;\n\t\tpublic abstract global::java.util.List getInstalledPackages(int arg0);\n\t\tprivate static global::MonoJavaBridge.MethodId _m19;\n\t\tpublic abstract bool addPermission(android.content.pm.PermissionInfo arg0);\n\t\tprivate static global::MonoJavaBridge.MethodId _m20;\n\t\tpublic abstract bool addPermissionAsync(android.content.pm.PermissionInfo arg0);\n\t\tprivate static global::MonoJavaBridge.MethodId _m21;\n\t\tpublic abstract void removePermission(java.lang.String arg0);\n\t\tprivate static global::MonoJavaBridge.MethodId _m22;\n\t\tpublic abstract int checkSignatures(java.lang.String arg0, java.lang.String arg1);\n\t\tprivate static global::MonoJavaBridge.MethodId _m23;\n\t\tpublic abstract int checkSignatures(int arg0, int arg1);\n\t\tprivate static global::MonoJavaBridge.MethodId _m24;\n\t\tpublic abstract global::java.lang.String[] getPackagesForUid(int arg0);\n\t\tprivate static global::MonoJavaBridge.MethodId _m25;\n\t\tpublic abstract global::java.lang.String getNameForUid(int arg0);\n\t\tprivate static global::MonoJavaBridge.MethodId _m26;\n\t\tpublic abstract global::java.util.List getInstalledApplications(int arg0);\n\t\tprivate static global::MonoJavaBridge.MethodId _m27;\n\t\tpublic abstract global::java.lang.String[] getSystemSharedLibraryNames();\n\t\tprivate static global::MonoJavaBridge.MethodId _m28;\n\t\tpublic abstract global::android.content.pm.FeatureInfo[] getSystemAvailableFeatures();\n\t\tprivate static global::MonoJavaBridge.MethodId _m29;\n\t\tpublic abstract bool hasSystemFeature(java.lang.String arg0);\n\t\tprivate static global::MonoJavaBridge.MethodId _m30;\n\t\tpublic abstract global::java.util.List queryIntentActivities(android.content.Intent arg0, int arg1);\n\t\tprivate static global::MonoJavaBridge.MethodId _m31;\n\t\tpublic abstract global::java.util.List queryIntentActivityOptions(android.content.ComponentName arg0, android.content.Intent[] arg1, android.content.Intent arg2, int arg3);\n\t\tprivate static global::MonoJavaBridge.MethodId _m32;\n\t\tpublic abstract global::java.util.List queryBroadcastReceivers(android.content.Intent arg0, int arg1);\n\t\tprivate static global::MonoJavaBridge.MethodId _m33;\n\t\tpublic abstract global::android.content.pm.ResolveInfo resolveService(android.content.Intent arg0, int arg1);\n\t\tprivate static global::MonoJavaBridge.MethodId _m34;\n\t\tpublic abstract global::java.util.List queryIntentServices(android.content.Intent arg0, int arg1);\n\t\tprivate static global::MonoJavaBridge.MethodId _m35;\n\t\tpublic abstract global::android.content.pm.ProviderInfo resolveContentProvider(java.lang.String arg0, int arg1);\n\t\tprivate static global::MonoJavaBridge.MethodId _m36;\n\t\tpublic abstract global::java.util.List queryContentProviders(java.lang.String arg0, int arg1, int arg2);\n\t\tprivate static global::MonoJavaBridge.MethodId _m37;\n\t\tpublic abstract global::android.content.pm.InstrumentationInfo getInstrumentationInfo(android.content.ComponentName arg0, int arg1);\n\t\tprivate static global::MonoJavaBridge.MethodId _m38;\n\t\tpublic abstract global::java.util.List queryInstrumentation(java.lang.String arg0, int arg1);\n\t\tprivate static global::MonoJavaBridge.MethodId _m39;\n\t\tpublic abstract global::android.graphics.drawable.Drawable getActivityIcon(android.content.Intent arg0);\n\t\tprivate static global::MonoJavaBridge.MethodId _m40;\n\t\tpublic abstract global::android.graphics.drawable.Drawable getActivityIcon(android.content.ComponentName arg0);\n\t\tprivate static global::MonoJavaBridge.MethodId _m41;\n\t\tpublic abstract global::android.graphics.drawable.Drawable getDefaultActivityIcon();\n\t\tprivate static global::MonoJavaBridge.MethodId _m42;\n\t\tpublic abstract global::android.graphics.drawable.Drawable getApplicationIcon(android.content.pm.ApplicationInfo arg0);\n\t\tprivate static global::MonoJavaBridge.MethodId _m43;\n\t\tpublic abstract global::android.graphics.drawable.Drawable getApplicationIcon(java.lang.String arg0);\n\t\tprivate static global::MonoJavaBridge.MethodId _m44;\n\t\tpublic abstract global::java.lang.CharSequence getApplicationLabel(android.content.pm.ApplicationInfo arg0);\n\t\tprivate static global::MonoJavaBridge.MethodId _m45;\n\t\tpublic abstract global::android.content.res.Resources getResourcesForActivity(android.content.ComponentName arg0);\n\t\tprivate static global::MonoJavaBridge.MethodId _m46;\n\t\tpublic abstract global::android.content.res.Resources getResourcesForApplication(java.lang.String arg0);\n\t\tprivate static global::MonoJavaBridge.MethodId _m47;\n\t\tpublic abstract global::android.content.res.Resources getResourcesForApplication(android.content.pm.ApplicationInfo arg0);\n\t\tprivate static global::MonoJavaBridge.MethodId _m48;\n\t\tpublic virtual global::android.content.pm.PackageInfo getPackageArchiveInfo(java.lang.String arg0, int arg1)\n\t\t{\n\t\t\treturn global::MonoJavaBridge.JavaBridge.CallObjectMethod(this, global::android.content.pm.PackageManager.staticClass, \"getPackageArchiveInfo\", \"(Ljava/lang/String;I)Landroid/content/pm/PackageInfo;\", ref global::android.content.pm.PackageManager._m48, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)) as android.content.pm.PackageInfo;\n\t\t}\n\t\tprivate static global::MonoJavaBridge.MethodId _m49;\n\t\tpublic abstract global::java.lang.String getInstallerPackageName(java.lang.String arg0);\n\t\tprivate static global::MonoJavaBridge.MethodId _m50;\n\t\tpublic abstract void addPackageToPreferred(java.lang.String arg0);\n\t\tprivate static global::MonoJavaBridge.MethodId _m51;\n\t\tpublic abstract void removePackageFromPreferred(java.lang.String arg0);\n\t\tprivate static global::MonoJavaBridge.MethodId _m52;\n\t\tpublic abstract global::java.util.List getPreferredPackages(int arg0);\n\t\tprivate static global::MonoJavaBridge.MethodId _m53;\n\t\tpublic abstract void addPreferredActivity(android.content.IntentFilter arg0, int arg1, android.content.ComponentName[] arg2, android.content.ComponentName arg3);\n\t\tprivate static global::MonoJavaBridge.MethodId _m54;\n\t\tpublic abstract void clearPackagePreferredActivities(java.lang.String arg0);\n\t\tprivate static global::MonoJavaBridge.MethodId _m55;\n\t\tpublic abstract int getPreferredActivities(java.util.List arg0, java.util.List arg1, java.lang.String arg2);\n\t\tprivate static global::MonoJavaBridge.MethodId _m56;\n\t\tpublic abstract void setComponentEnabledSetting(android.content.ComponentName arg0, int arg1, int arg2);\n\t\tprivate static global::MonoJavaBridge.MethodId _m57;\n\t\tpublic abstract int getComponentEnabledSetting(android.content.ComponentName arg0);\n\t\tprivate static global::MonoJavaBridge.MethodId _m58;\n\t\tpublic abstract void setApplicationEnabledSetting(java.lang.String arg0, int arg1, int arg2);\n\t\tprivate static global::MonoJavaBridge.MethodId _m59;\n\t\tpublic abstract int getApplicationEnabledSetting(java.lang.String arg0);\n\t\tprivate static global::MonoJavaBridge.MethodId _m60;\n\t\tpublic abstract bool isSafeMode();\n\t\tprivate static global::MonoJavaBridge.MethodId _m61;\n\t\tpublic PackageManager() : base(global::MonoJavaBridge.JNIEnv.ThreadEnv)\n\t\t{\n\t\t\tglobal::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;\n\t\t\tif (global::android.content.pm.PackageManager._m61.native == global::System.IntPtr.Zero)\n\t\t\t\tglobal::android.content.pm.PackageManager._m61 = @__env.GetMethodIDNoThrow(global::android.content.pm.PackageManager.staticClass, \"\", \"()V\");\n\t\t\tglobal::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.content.pm.PackageManager.staticClass, global::android.content.pm.PackageManager._m61);\n\t\t\tInit(@__env, handle);\n\t\t}\n\t\tpublic static int GET_ACTIVITIES\n\t\t{\n\t\t\tget\n\t\t\t{\n\t\t\t\treturn 1;\n\t\t\t}\n\t\t}\n\t\tpublic static int GET_RECEIVERS\n\t\t{\n\t\t\tget\n\t\t\t{\n\t\t\t\treturn 2;\n\t\t\t}\n\t\t}\n\t\tpublic static int GET_SERVICES\n\t\t{\n\t\t\tget\n\t\t\t{\n\t\t\t\treturn 4;\n\t\t\t}\n\t\t}\n\t\tpublic static int GET_PROVIDERS\n\t\t{\n\t\t\tget\n\t\t\t{\n\t\t\t\treturn 8;\n\t\t\t}\n\t\t}\n\t\tpublic static int GET_INSTRUMENTATION\n\t\t{\n\t\t\tget\n\t\t\t{\n\t\t\t\treturn 16;\n\t\t\t}\n\t\t}\n\t\tpublic static int GET_INTENT_FILTERS\n\t\t{\n\t\t\tget\n\t\t\t{\n\t\t\t\treturn 32;\n\t\t\t}\n\t\t}\n\t\tpublic static int GET_SIGNATURES\n\t\t{\n\t\t\tget\n\t\t\t{\n\t\t\t\treturn 64;\n\t\t\t}\n\t\t}\n\t\tpublic static int GET_RESOLVED_FILTER\n\t\t{\n\t\t\tget\n\t\t\t{\n\t\t\t\treturn 64;\n\t\t\t}\n\t\t}\n\t\tpublic static int GET_META_DATA\n\t\t{\n\t\t\tget\n\t\t\t{\n\t\t\t\treturn 128;\n\t\t\t}\n\t\t}\n\t\tpublic static int GET_GIDS\n\t\t{\n\t\t\tget\n\t\t\t{\n\t\t\t\treturn 256;\n\t\t\t}\n\t\t}\n\t\tpublic static int GET_DISABLED_COMPONENTS\n\t\t{\n\t\t\tget\n\t\t\t{\n\t\t\t\treturn 512;\n\t\t\t}\n\t\t}\n\t\tpublic static int GET_SHARED_LIBRARY_FILES\n\t\t{\n\t\t\tget\n\t\t\t{\n\t\t\t\treturn 1024;\n\t\t\t}\n\t\t}\n\t\tpublic static int GET_URI_PERMISSION_PATTERNS\n\t\t{\n\t\t\tget\n\t\t\t{\n\t\t\t\treturn 2048;\n\t\t\t}\n\t\t}\n\t\tpublic static int GET_PERMISSIONS\n\t\t{\n\t\t\tget\n\t\t\t{\n\t\t\t\treturn 4096;\n\t\t\t}\n\t\t}\n\t\tpublic static int GET_UNINSTALLED_PACKAGES\n\t\t{\n\t\t\tget\n\t\t\t{\n\t\t\t\treturn 8192;\n\t\t\t}\n\t\t}\n\t\tpublic static int GET_CONFIGURATIONS\n\t\t{\n\t\t\tget\n\t\t\t{\n\t\t\t\treturn 16384;\n\t\t\t}\n\t\t}\n\t\tpublic static int MATCH_DEFAULT_ONLY\n\t\t{\n\t\t\tget\n\t\t\t{\n\t\t\t\treturn 65536;\n\t\t\t}\n\t\t}\n\t\tpublic static int PERMISSION_GRANTED\n\t\t{\n\t\t\tget\n\t\t\t{\n\t\t\t\treturn 0;\n\t\t\t}\n\t\t}\n\t\tpublic static int PERMISSION_DENIED\n\t\t{\n\t\t\tget\n\t\t\t{\n\t\t\t\treturn -1;\n\t\t\t}\n\t\t}\n\t\tpublic static int SIGNATURE_MATCH\n\t\t{\n\t\t\tget\n\t\t\t{\n\t\t\t\treturn 0;\n\t\t\t}\n\t\t}\n\t\tpublic static int SIGNATURE_NEITHER_SIGNED\n\t\t{\n\t\t\tget\n\t\t\t{\n\t\t\t\treturn 1;\n\t\t\t}\n\t\t}\n\t\tpublic static int SIGNATURE_FIRST_NOT_SIGNED\n\t\t{\n\t\t\tget\n\t\t\t{\n\t\t\t\treturn -1;\n\t\t\t}\n\t\t}\n\t\tpublic static int SIGNATURE_SECOND_NOT_SIGNED\n\t\t{\n\t\t\tget\n\t\t\t{\n\t\t\t\treturn -2;\n\t\t\t}\n\t\t}\n\t\tpublic static int SIGNATURE_NO_MATCH\n\t\t{\n\t\t\tget\n\t\t\t{\n\t\t\t\treturn -3;\n\t\t\t}\n\t\t}\n\t\tpublic static int SIGNATURE_UNKNOWN_PACKAGE\n\t\t{\n\t\t\tget\n\t\t\t{\n\t\t\t\treturn -4;\n\t\t\t}\n\t\t}\n\t\tpublic static int COMPONENT_ENABLED_STATE_DEFAULT\n\t\t{\n\t\t\tget\n\t\t\t{\n\t\t\t\treturn 0;\n\t\t\t}\n\t\t}\n\t\tpublic static int COMPONENT_ENABLED_STATE_ENABLED\n\t\t{\n\t\t\tget\n\t\t\t{\n\t\t\t\treturn 1;\n\t\t\t}\n\t\t}\n\t\tpublic static int COMPONENT_ENABLED_STATE_DISABLED\n\t\t{\n\t\t\tget\n\t\t\t{\n\t\t\t\treturn 2;\n\t\t\t}\n\t\t}\n\t\tpublic static int DONT_KILL_APP\n\t\t{\n\t\t\tget\n\t\t\t{\n\t\t\t\treturn 1;\n\t\t\t}\n\t\t}\n\t\tpublic static global::java.lang.String FEATURE_BLUETOOTH\n\t\t{\n\t\t\tget\n\t\t\t{\n\t\t\t\treturn \"android.hardware.bluetooth\";\n\t\t\t}\n\t\t}\n\t\tpublic static global::java.lang.String FEATURE_CAMERA\n\t\t{\n\t\t\tget\n\t\t\t{\n\t\t\t\treturn \"android.hardware.camera\";\n\t\t\t}\n\t\t}\n\t\tpublic static global::java.lang.String FEATURE_CAMERA_AUTOFOCUS\n\t\t{\n\t\t\tget\n\t\t\t{\n\t\t\t\treturn \"android.hardware.camera.autofocus\";\n\t\t\t}\n\t\t}\n\t\tpublic static global::java.lang.String FEATURE_CAMERA_FLASH\n\t\t{\n\t\t\tget\n\t\t\t{\n\t\t\t\treturn \"android.hardware.camera.flash\";\n\t\t\t}\n\t\t}\n\t\tpublic static global::java.lang.String FEATURE_LOCATION\n\t\t{\n\t\t\tget\n\t\t\t{\n\t\t\t\treturn \"android.hardware.location\";\n\t\t\t}\n\t\t}\n\t\tpublic static global::java.lang.String FEATURE_LOCATION_GPS\n\t\t{\n\t\t\tget\n\t\t\t{\n\t\t\t\treturn \"android.hardware.location.gps\";\n\t\t\t}\n\t\t}\n\t\tpublic static global::java.lang.String FEATURE_LOCATION_NETWORK\n\t\t{\n\t\t\tget\n\t\t\t{\n\t\t\t\treturn \"android.hardware.location.network\";\n\t\t\t}\n\t\t}\n\t\tpublic static global::java.lang.String FEATURE_MICROPHONE\n\t\t{\n\t\t\tget\n\t\t\t{\n\t\t\t\treturn \"android.hardware.microphone\";\n\t\t\t}\n\t\t}\n\t\tpublic static global::java.lang.String FEATURE_SENSOR_COMPASS\n\t\t{\n\t\t\tget\n\t\t\t{\n\t\t\t\treturn \"android.hardware.sensor.compass\";\n\t\t\t}\n\t\t}\n\t\tpublic static global::java.lang.String FEATURE_SENSOR_ACCELEROMETER\n\t\t{\n\t\t\tget\n\t\t\t{\n\t\t\t\treturn \"android.hardware.sensor.accelerometer\";\n\t\t\t}\n\t\t}\n\t\tpublic static global::java.lang.String FEATURE_SENSOR_LIGHT\n\t\t{\n\t\t\tget\n\t\t\t{\n\t\t\t\treturn \"android.hardware.sensor.light\";\n\t\t\t}\n\t\t}\n\t\tpublic static global::java.lang.String FEATURE_SENSOR_PROXIMITY\n\t\t{\n\t\t\tget\n\t\t\t{\n\t\t\t\treturn \"android.hardware.sensor.proximity\";\n\t\t\t}\n\t\t}\n\t\tpublic static global::java.lang.String FEATURE_TELEPHONY\n\t\t{\n\t\t\tget\n\t\t\t{\n\t\t\t\treturn \"android.hardware.telephony\";\n\t\t\t}\n\t\t}\n\t\tpublic static global::java.lang.String FEATURE_TELEPHONY_CDMA\n\t\t{\n\t\t\tget\n\t\t\t{\n\t\t\t\treturn \"android.hardware.telephony.cdma\";\n\t\t\t}\n\t\t}\n\t\tpublic static global::java.lang.String FEATURE_TELEPHONY_GSM\n\t\t{\n\t\t\tget\n\t\t\t{\n\t\t\t\treturn \"android.hardware.telephony.gsm\";\n\t\t\t}\n\t\t}\n\t\tpublic static global::java.lang.String FEATURE_TOUCHSCREEN\n\t\t{\n\t\t\tget\n\t\t\t{\n\t\t\t\treturn \"android.hardware.touchscreen\";\n\t\t\t}\n\t\t}\n\t\tpublic static global::java.lang.String FEATURE_TOUCHSCREEN_MULTITOUCH\n\t\t{\n\t\t\tget\n\t\t\t{\n\t\t\t\treturn \"android.hardware.touchscreen.multitouch\";\n\t\t\t}\n\t\t}\n\t\tpublic static global::java.lang.String FEATURE_TOUCHSCREEN_MULTITOUCH_DISTINCT\n\t\t{\n\t\t\tget\n\t\t\t{\n\t\t\t\treturn \"android.hardware.touchscreen.multitouch.distinct\";\n\t\t\t}\n\t\t}\n\t\tpublic static global::java.lang.String FEATURE_LIVE_WALLPAPER\n\t\t{\n\t\t\tget\n\t\t\t{\n\t\t\t\treturn \"android.software.live_wallpaper\";\n\t\t\t}\n\t\t}\n\t\tpublic static global::java.lang.String FEATURE_WIFI\n\t\t{\n\t\t\tget\n\t\t\t{\n\t\t\t\treturn \"android.hardware.wifi\";\n\t\t\t}\n\t\t}\n\t\tstatic PackageManager()\n\t\t{\n\t\t\tglobal::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;\n\t\t\tglobal::android.content.pm.PackageManager.staticClass = @__env.NewGlobalRef(@__env.FindClass(\"android/content/pm/PackageManager\"));\n\t\t}\n\t}\n\n\t[global::MonoJavaBridge.JavaProxy(typeof(global::android.content.pm.PackageManager))]\n\tinternal sealed partial class PackageManager_ : android.content.pm.PackageManager\n\t{\n\t\tinternal new static global::MonoJavaBridge.JniGlobalHandle staticClass;\n\t\tinternal PackageManager_(global::MonoJavaBridge.JNIEnv @__env) : base(@__env)\n\t\t{\n\t\t}\n\t\tprivate static global::MonoJavaBridge.MethodId _m0;\n\t\tpublic override int checkPermission(java.lang.String arg0, java.lang.String arg1)\n\t\t{\n\t\t\treturn global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::android.content.pm.PackageManager_.staticClass, \"checkPermission\", \"(Ljava/lang/String;Ljava/lang/String;)I\", ref global::android.content.pm.PackageManager_._m0, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));\n\t\t}\n\t\tprivate static global::MonoJavaBridge.MethodId _m1;\n\t\tpublic override global::android.content.pm.PackageInfo getPackageInfo(java.lang.String arg0, int arg1)\n\t\t{\n\t\t\treturn global::MonoJavaBridge.JavaBridge.CallObjectMethod(this, global::android.content.pm.PackageManager_.staticClass, \"getPackageInfo\", \"(Ljava/lang/String;I)Landroid/content/pm/PackageInfo;\", ref global::android.content.pm.PackageManager_._m1, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)) as android.content.pm.PackageInfo;\n\t\t}\n\t\tprivate static global::MonoJavaBridge.MethodId _m2;\n\t\tpublic override global::android.content.pm.ApplicationInfo getApplicationInfo(java.lang.String arg0, int arg1)\n\t\t{\n\t\t\treturn global::MonoJavaBridge.JavaBridge.CallObjectMethod(this, global::android.content.pm.PackageManager_.staticClass, \"getApplicationInfo\", \"(Ljava/lang/String;I)Landroid/content/pm/ApplicationInfo;\", ref global::android.content.pm.PackageManager_._m2, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)) as android.content.pm.ApplicationInfo;\n\t\t}\n\t\tprivate static global::MonoJavaBridge.MethodId _m3;\n\t\tpublic override global::java.lang.CharSequence getText(java.lang.String arg0, int arg1, android.content.pm.ApplicationInfo arg2)\n\t\t{\n\t\t\treturn global::MonoJavaBridge.JavaBridge.CallIJavaObjectMethod(this, global::android.content.pm.PackageManager_.staticClass, \"getText\", \"(Ljava/lang/String;ILandroid/content/pm/ApplicationInfo;)Ljava/lang/CharSequence;\", ref global::android.content.pm.PackageManager_._m3, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2)) as java.lang.CharSequence;\n\t\t}\n\t\tprivate static global::MonoJavaBridge.MethodId _m4;\n\t\tpublic override global::android.content.pm.ResolveInfo resolveActivity(android.content.Intent arg0, int arg1)\n\t\t{\n\t\t\treturn global::MonoJavaBridge.JavaBridge.CallObjectMethod(this, global::android.content.pm.PackageManager_.staticClass, \"resolveActivity\", \"(Landroid/content/Intent;I)Landroid/content/pm/ResolveInfo;\", ref global::android.content.pm.PackageManager_._m4, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)) as android.content.pm.ResolveInfo;\n\t\t}\n\t\tprivate static global::MonoJavaBridge.MethodId _m5;\n\t\tpublic override global::android.graphics.drawable.Drawable getDrawable(java.lang.String arg0, int arg1, android.content.pm.ApplicationInfo arg2)\n\t\t{\n\t\t\treturn global::MonoJavaBridge.JavaBridge.CallObjectMethod(this, global::android.content.pm.PackageManager_.staticClass, \"getDrawable\", \"(Ljava/lang/String;ILandroid/content/pm/ApplicationInfo;)Landroid/graphics/drawable/Drawable;\", ref global::android.content.pm.PackageManager_._m5, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2)) as android.graphics.drawable.Drawable;\n\t\t}\n\t\tprivate static global::MonoJavaBridge.MethodId _m6;\n\t\tpublic override global::android.content.res.XmlResourceParser getXml(java.lang.String arg0, int arg1, android.content.pm.ApplicationInfo arg2)\n\t\t{\n\t\t\treturn global::MonoJavaBridge.JavaBridge.CallIJavaObjectMethod(this, global::android.content.pm.PackageManager_.staticClass, \"getXml\", \"(Ljava/lang/String;ILandroid/content/pm/ApplicationInfo;)Landroid/content/res/XmlResourceParser;\", ref global::android.content.pm.PackageManager_._m6, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2)) as android.content.res.XmlResourceParser;\n\t\t}\n\t\tprivate static global::MonoJavaBridge.MethodId _m7;\n\t\tpublic override global::java.lang.String[] currentToCanonicalPackageNames(java.lang.String[] arg0)\n\t\t{\n\t\t\treturn global::MonoJavaBridge.JavaBridge.CallArrayObjectMethod(this, global::android.content.pm.PackageManager_.staticClass, \"currentToCanonicalPackageNames\", \"([Ljava/lang/String;)[Ljava/lang/String;\", ref global::android.content.pm.PackageManager_._m7, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)) as java.lang.String[];\n\t\t}\n\t\tprivate static global::MonoJavaBridge.MethodId _m8;\n\t\tpublic override global::java.lang.String[] canonicalToCurrentPackageNames(java.lang.String[] arg0)\n\t\t{\n\t\t\treturn global::MonoJavaBridge.JavaBridge.CallArrayObjectMethod(this, global::android.content.pm.PackageManager_.staticClass, \"canonicalToCurrentPackageNames\", \"([Ljava/lang/String;)[Ljava/lang/String;\", ref global::android.content.pm.PackageManager_._m8, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)) as java.lang.String[];\n\t\t}\n\t\tprivate static global::MonoJavaBridge.MethodId _m9;\n\t\tpublic override global::android.content.Intent getLaunchIntentForPackage(java.lang.String arg0)\n\t\t{\n\t\t\treturn global::MonoJavaBridge.JavaBridge.CallObjectMethod(this, global::android.content.pm.PackageManager_.staticClass, \"getLaunchIntentForPackage\", \"(Ljava/lang/String;)Landroid/content/Intent;\", ref global::android.content.pm.PackageManager_._m9, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)) as android.content.Intent;\n\t\t}\n\t\tprivate static global::MonoJavaBridge.MethodId _m10;\n\t\tpublic override int[] getPackageGids(java.lang.String arg0)\n\t\t{\n\t\t\treturn global::MonoJavaBridge.JavaBridge.CallArrayObjectMethod(this, global::android.content.pm.PackageManager_.staticClass, \"getPackageGids\", \"(Ljava/lang/String;)[I\", ref global::android.content.pm.PackageManager_._m10, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)) as int[];\n\t\t}\n\t\tprivate static global::MonoJavaBridge.MethodId _m11;\n\t\tpublic override global::android.content.pm.PermissionInfo getPermissionInfo(java.lang.String arg0, int arg1)\n\t\t{\n\t\t\treturn global::MonoJavaBridge.JavaBridge.CallObjectMethod(this, global::android.content.pm.PackageManager_.staticClass, \"getPermissionInfo\", \"(Ljava/lang/String;I)Landroid/content/pm/PermissionInfo;\", ref global::android.content.pm.PackageManager_._m11, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)) as android.content.pm.PermissionInfo;\n\t\t}\n\t\tprivate static global::MonoJavaBridge.MethodId _m12;\n\t\tpublic override global::java.util.List queryPermissionsByGroup(java.lang.String arg0, int arg1)\n\t\t{\n\t\t\treturn global::MonoJavaBridge.JavaBridge.CallIJavaObjectMethod(this, global::android.content.pm.PackageManager_.staticClass, \"queryPermissionsByGroup\", \"(Ljava/lang/String;I)Ljava/util/List;\", ref global::android.content.pm.PackageManager_._m12, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)) as java.util.List;\n\t\t}\n\t\tprivate static global::MonoJavaBridge.MethodId _m13;\n\t\tpublic override global::android.content.pm.PermissionGroupInfo getPermissionGroupInfo(java.lang.String arg0, int arg1)\n\t\t{\n\t\t\treturn global::MonoJavaBridge.JavaBridge.CallObjectMethod(this, global::android.content.pm.PackageManager_.staticClass, \"getPermissionGroupInfo\", \"(Ljava/lang/String;I)Landroid/content/pm/PermissionGroupInfo;\", ref global::android.content.pm.PackageManager_._m13, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)) as android.content.pm.PermissionGroupInfo;\n\t\t}\n\t\tprivate static global::MonoJavaBridge.MethodId _m14;\n\t\tpublic override global::java.util.List getAllPermissionGroups(int arg0)\n\t\t{\n\t\t\treturn global::MonoJavaBridge.JavaBridge.CallIJavaObjectMethod(this, global::android.content.pm.PackageManager_.staticClass, \"getAllPermissionGroups\", \"(I)Ljava/util/List;\", ref global::android.content.pm.PackageManager_._m14, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)) as java.util.List;\n\t\t}\n\t\tprivate static global::MonoJavaBridge.MethodId _m15;\n\t\tpublic override global::android.content.pm.ActivityInfo getActivityInfo(android.content.ComponentName arg0, int arg1)\n\t\t{\n\t\t\treturn global::MonoJavaBridge.JavaBridge.CallObjectMethod(this, global::android.content.pm.PackageManager_.staticClass, \"getActivityInfo\", \"(Landroid/content/ComponentName;I)Landroid/content/pm/ActivityInfo;\", ref global::android.content.pm.PackageManager_._m15, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)) as android.content.pm.ActivityInfo;\n\t\t}\n\t\tprivate static global::MonoJavaBridge.MethodId _m16;\n\t\tpublic override global::android.content.pm.ActivityInfo getReceiverInfo(android.content.ComponentName arg0, int arg1)\n\t\t{\n\t\t\treturn global::MonoJavaBridge.JavaBridge.CallObjectMethod(this, global::android.content.pm.PackageManager_.staticClass, \"getReceiverInfo\", \"(Landroid/content/ComponentName;I)Landroid/content/pm/ActivityInfo;\", ref global::android.content.pm.PackageManager_._m16, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)) as android.content.pm.ActivityInfo;\n\t\t}\n\t\tprivate static global::MonoJavaBridge.MethodId _m17;\n\t\tpublic override global::android.content.pm.ServiceInfo getServiceInfo(android.content.ComponentName arg0, int arg1)\n\t\t{\n\t\t\treturn global::MonoJavaBridge.JavaBridge.CallObjectMethod(this, global::android.content.pm.PackageManager_.staticClass, \"getServiceInfo\", \"(Landroid/content/ComponentName;I)Landroid/content/pm/ServiceInfo;\", ref global::android.content.pm.PackageManager_._m17, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)) as android.content.pm.ServiceInfo;\n\t\t}\n\t\tprivate static global::MonoJavaBridge.MethodId _m18;\n\t\tpublic override global::java.util.List getInstalledPackages(int arg0)\n\t\t{\n\t\t\treturn global::MonoJavaBridge.JavaBridge.CallIJavaObjectMethod(this, global::android.content.pm.PackageManager_.staticClass, \"getInstalledPackages\", \"(I)Ljava/util/List;\", ref global::android.content.pm.PackageManager_._m18, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)) as java.util.List;\n\t\t}\n\t\tprivate static global::MonoJavaBridge.MethodId _m19;\n\t\tpublic override bool addPermission(android.content.pm.PermissionInfo arg0)\n\t\t{\n\t\t\treturn global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::android.content.pm.PackageManager_.staticClass, \"addPermission\", \"(Landroid/content/pm/PermissionInfo;)Z\", ref global::android.content.pm.PackageManager_._m19, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));\n\t\t}\n\t\tprivate static global::MonoJavaBridge.MethodId _m20;\n\t\tpublic override bool addPermissionAsync(android.content.pm.PermissionInfo arg0)\n\t\t{\n\t\t\treturn global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::android.content.pm.PackageManager_.staticClass, \"addPermissionAsync\", \"(Landroid/content/pm/PermissionInfo;)Z\", ref global::android.content.pm.PackageManager_._m20, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));\n\t\t}\n\t\tprivate static global::MonoJavaBridge.MethodId _m21;\n\t\tpublic override void removePermission(java.lang.String arg0)\n\t\t{\n\t\t\tglobal::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.content.pm.PackageManager_.staticClass, \"removePermission\", \"(Ljava/lang/String;)V\", ref global::android.content.pm.PackageManager_._m21, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));\n\t\t}\n\t\tprivate static global::MonoJavaBridge.MethodId _m22;\n\t\tpublic override int checkSignatures(java.lang.String arg0, java.lang.String arg1)\n\t\t{\n\t\t\treturn global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::android.content.pm.PackageManager_.staticClass, \"checkSignatures\", \"(Ljava/lang/String;Ljava/lang/String;)I\", ref global::android.content.pm.PackageManager_._m22, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));\n\t\t}\n\t\tprivate static global::MonoJavaBridge.MethodId _m23;\n\t\tpublic override int checkSignatures(int arg0, int arg1)\n\t\t{\n\t\t\treturn global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::android.content.pm.PackageManager_.staticClass, \"checkSignatures\", \"(II)I\", ref global::android.content.pm.PackageManager_._m23, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));\n\t\t}\n\t\tprivate static global::MonoJavaBridge.MethodId _m24;\n\t\tpublic override global::java.lang.String[] getPackagesForUid(int arg0)\n\t\t{\n\t\t\treturn global::MonoJavaBridge.JavaBridge.CallArrayObjectMethod(this, global::android.content.pm.PackageManager_.staticClass, \"getPackagesForUid\", \"(I)[Ljava/lang/String;\", ref global::android.content.pm.PackageManager_._m24, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)) as java.lang.String[];\n\t\t}\n\t\tprivate static global::MonoJavaBridge.MethodId _m25;\n\t\tpublic override global::java.lang.String getNameForUid(int arg0)\n\t\t{\n\t\t\treturn global::MonoJavaBridge.JavaBridge.CallSealedClassObjectMethod(this, global::android.content.pm.PackageManager_.staticClass, \"getNameForUid\", \"(I)Ljava/lang/String;\", ref global::android.content.pm.PackageManager_._m25, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)) as java.lang.String;\n\t\t}\n\t\tprivate static global::MonoJavaBridge.MethodId _m26;\n\t\tpublic override global::java.util.List getInstalledApplications(int arg0)\n\t\t{\n\t\t\treturn global::MonoJavaBridge.JavaBridge.CallIJavaObjectMethod(this, global::android.content.pm.PackageManager_.staticClass, \"getInstalledApplications\", \"(I)Ljava/util/List;\", ref global::android.content.pm.PackageManager_._m26, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)) as java.util.List;\n\t\t}\n\t\tprivate static global::MonoJavaBridge.MethodId _m27;\n\t\tpublic override global::java.lang.String[] getSystemSharedLibraryNames()\n\t\t{\n\t\t\treturn global::MonoJavaBridge.JavaBridge.CallArrayObjectMethod(this, global::android.content.pm.PackageManager_.staticClass, \"getSystemSharedLibraryNames\", \"()[Ljava/lang/String;\", ref global::android.content.pm.PackageManager_._m27) as java.lang.String[];\n\t\t}\n\t\tprivate static global::MonoJavaBridge.MethodId _m28;\n\t\tpublic override global::android.content.pm.FeatureInfo[] getSystemAvailableFeatures()\n\t\t{\n\t\t\treturn global::MonoJavaBridge.JavaBridge.CallArrayObjectMethod(this, global::android.content.pm.PackageManager_.staticClass, \"getSystemAvailableFeatures\", \"()[Landroid/content/pm/FeatureInfo;\", ref global::android.content.pm.PackageManager_._m28) as android.content.pm.FeatureInfo[];\n\t\t}\n\t\tprivate static global::MonoJavaBridge.MethodId _m29;\n\t\tpublic override bool hasSystemFeature(java.lang.String arg0)\n\t\t{\n\t\t\treturn global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::android.content.pm.PackageManager_.staticClass, \"hasSystemFeature\", \"(Ljava/lang/String;)Z\", ref global::android.content.pm.PackageManager_._m29, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));\n\t\t}\n\t\tprivate static global::MonoJavaBridge.MethodId _m30;\n\t\tpublic override global::java.util.List queryIntentActivities(android.content.Intent arg0, int arg1)\n\t\t{\n\t\t\treturn global::MonoJavaBridge.JavaBridge.CallIJavaObjectMethod(this, global::android.content.pm.PackageManager_.staticClass, \"queryIntentActivities\", \"(Landroid/content/Intent;I)Ljava/util/List;\", ref global::android.content.pm.PackageManager_._m30, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)) as java.util.List;\n\t\t}\n\t\tprivate static global::MonoJavaBridge.MethodId _m31;\n\t\tpublic override global::java.util.List queryIntentActivityOptions(android.content.ComponentName arg0, android.content.Intent[] arg1, android.content.Intent arg2, int arg3)\n\t\t{\n\t\t\treturn global::MonoJavaBridge.JavaBridge.CallIJavaObjectMethod(this, global::android.content.pm.PackageManager_.staticClass, \"queryIntentActivityOptions\", \"(Landroid/content/ComponentName;[Landroid/content/Intent;Landroid/content/Intent;I)Ljava/util/List;\", ref global::android.content.pm.PackageManager_._m31, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3)) as java.util.List;\n\t\t}\n\t\tprivate static global::MonoJavaBridge.MethodId _m32;\n\t\tpublic override global::java.util.List queryBroadcastReceivers(android.content.Intent arg0, int arg1)\n\t\t{\n\t\t\treturn global::MonoJavaBridge.JavaBridge.CallIJavaObjectMethod(this, global::android.content.pm.PackageManager_.staticClass, \"queryBroadcastReceivers\", \"(Landroid/content/Intent;I)Ljava/util/List;\", ref global::android.content.pm.PackageManager_._m32, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)) as java.util.List;\n\t\t}\n\t\tprivate static global::MonoJavaBridge.MethodId _m33;\n\t\tpublic override global::android.content.pm.ResolveInfo resolveService(android.content.Intent arg0, int arg1)\n\t\t{\n\t\t\treturn global::MonoJavaBridge.JavaBridge.CallObjectMethod(this, global::android.content.pm.PackageManager_.staticClass, \"resolveService\", \"(Landroid/content/Intent;I)Landroid/content/pm/ResolveInfo;\", ref global::android.content.pm.PackageManager_._m33, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)) as android.content.pm.ResolveInfo;\n\t\t}\n\t\tprivate static global::MonoJavaBridge.MethodId _m34;\n\t\tpublic override global::java.util.List queryIntentServices(android.content.Intent arg0, int arg1)\n\t\t{\n\t\t\treturn global::MonoJavaBridge.JavaBridge.CallIJavaObjectMethod(this, global::android.content.pm.PackageManager_.staticClass, \"queryIntentServices\", \"(Landroid/content/Intent;I)Ljava/util/List;\", ref global::android.content.pm.PackageManager_._m34, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)) as java.util.List;\n\t\t}\n\t\tprivate static global::MonoJavaBridge.MethodId _m35;\n\t\tpublic override global::android.content.pm.ProviderInfo resolveContentProvider(java.lang.String arg0, int arg1)\n\t\t{\n\t\t\treturn global::MonoJavaBridge.JavaBridge.CallSealedClassObjectMethod(this, global::android.content.pm.PackageManager_.staticClass, \"resolveContentProvider\", \"(Ljava/lang/String;I)Landroid/content/pm/ProviderInfo;\", ref global::android.content.pm.PackageManager_._m35, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)) as android.content.pm.ProviderInfo;\n\t\t}\n\t\tprivate static global::MonoJavaBridge.MethodId _m36;\n\t\tpublic override global::java.util.List queryContentProviders(java.lang.String arg0, int arg1, int arg2)\n\t\t{\n\t\t\treturn global::MonoJavaBridge.JavaBridge.CallIJavaObjectMethod(this, global::android.content.pm.PackageManager_.staticClass, \"queryContentProviders\", \"(Ljava/lang/String;II)Ljava/util/List;\", ref global::android.content.pm.PackageManager_._m36, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2)) as java.util.List;\n\t\t}\n\t\tprivate static global::MonoJavaBridge.MethodId _m37;\n\t\tpublic override global::android.content.pm.InstrumentationInfo getInstrumentationInfo(android.content.ComponentName arg0, int arg1)\n\t\t{\n\t\t\treturn global::MonoJavaBridge.JavaBridge.CallObjectMethod(this, global::android.content.pm.PackageManager_.staticClass, \"getInstrumentationInfo\", \"(Landroid/content/ComponentName;I)Landroid/content/pm/InstrumentationInfo;\", ref global::android.content.pm.PackageManager_._m37, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)) as android.content.pm.InstrumentationInfo;\n\t\t}\n\t\tprivate static global::MonoJavaBridge.MethodId _m38;\n\t\tpublic override global::java.util.List queryInstrumentation(java.lang.String arg0, int arg1)\n\t\t{\n\t\t\treturn global::MonoJavaBridge.JavaBridge.CallIJavaObjectMethod(this, global::android.content.pm.PackageManager_.staticClass, \"queryInstrumentation\", \"(Ljava/lang/String;I)Ljava/util/List;\", ref global::android.content.pm.PackageManager_._m38, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)) as java.util.List;\n\t\t}\n\t\tprivate static global::MonoJavaBridge.MethodId _m39;\n\t\tpublic override global::android.graphics.drawable.Drawable getActivityIcon(android.content.Intent arg0)\n\t\t{\n\t\t\treturn global::MonoJavaBridge.JavaBridge.CallObjectMethod(this, global::android.content.pm.PackageManager_.staticClass, \"getActivityIcon\", \"(Landroid/content/Intent;)Landroid/graphics/drawable/Drawable;\", ref global::android.content.pm.PackageManager_._m39, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)) as android.graphics.drawable.Drawable;\n\t\t}\n\t\tprivate static global::MonoJavaBridge.MethodId _m40;\n\t\tpublic override global::android.graphics.drawable.Drawable getActivityIcon(android.content.ComponentName arg0)\n\t\t{\n\t\t\treturn global::MonoJavaBridge.JavaBridge.CallObjectMethod(this, global::android.content.pm.PackageManager_.staticClass, \"getActivityIcon\", \"(Landroid/content/ComponentName;)Landroid/graphics/drawable/Drawable;\", ref global::android.content.pm.PackageManager_._m40, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)) as android.graphics.drawable.Drawable;\n\t\t}\n\t\tprivate static global::MonoJavaBridge.MethodId _m41;\n\t\tpublic override global::android.graphics.drawable.Drawable getDefaultActivityIcon()\n\t\t{\n\t\t\treturn global::MonoJavaBridge.JavaBridge.CallObjectMethod(this, global::android.content.pm.PackageManager_.staticClass, \"getDefaultActivityIcon\", \"()Landroid/graphics/drawable/Drawable;\", ref global::android.content.pm.PackageManager_._m41) as android.graphics.drawable.Drawable;\n\t\t}\n\t\tprivate static global::MonoJavaBridge.MethodId _m42;\n\t\tpublic override global::android.graphics.drawable.Drawable getApplicationIcon(android.content.pm.ApplicationInfo arg0)\n\t\t{\n\t\t\treturn global::MonoJavaBridge.JavaBridge.CallObjectMethod(this, global::android.content.pm.PackageManager_.staticClass, \"getApplicationIcon\", \"(Landroid/content/pm/ApplicationInfo;)Landroid/graphics/drawable/Drawable;\", ref global::android.content.pm.PackageManager_._m42, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)) as android.graphics.drawable.Drawable;\n\t\t}\n\t\tprivate static global::MonoJavaBridge.MethodId _m43;\n\t\tpublic override global::android.graphics.drawable.Drawable getApplicationIcon(java.lang.String arg0)\n\t\t{\n\t\t\treturn global::MonoJavaBridge.JavaBridge.CallObjectMethod(this, global::android.content.pm.PackageManager_.staticClass, \"getApplicationIcon\", \"(Ljava/lang/String;)Landroid/graphics/drawable/Drawable;\", ref global::android.content.pm.PackageManager_._m43, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)) as android.graphics.drawable.Drawable;\n\t\t}\n\t\tprivate static global::MonoJavaBridge.MethodId _m44;\n\t\tpublic override global::java.lang.CharSequence getApplicationLabel(android.content.pm.ApplicationInfo arg0)\n\t\t{\n\t\t\treturn global::MonoJavaBridge.JavaBridge.CallIJavaObjectMethod(this, global::android.content.pm.PackageManager_.staticClass, \"getApplicationLabel\", \"(Landroid/content/pm/ApplicationInfo;)Ljava/lang/CharSequence;\", ref global::android.content.pm.PackageManager_._m44, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)) as java.lang.CharSequence;\n\t\t}\n\t\tprivate static global::MonoJavaBridge.MethodId _m45;\n\t\tpublic override global::android.content.res.Resources getResourcesForActivity(android.content.ComponentName arg0)\n\t\t{\n\t\t\treturn global::MonoJavaBridge.JavaBridge.CallObjectMethod(this, global::android.content.pm.PackageManager_.staticClass, \"getResourcesForActivity\", \"(Landroid/content/ComponentName;)Landroid/content/res/Resources;\", ref global::android.content.pm.PackageManager_._m45, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)) as android.content.res.Resources;\n\t\t}\n\t\tprivate static global::MonoJavaBridge.MethodId _m46;\n\t\tpublic override global::android.content.res.Resources getResourcesForApplication(java.lang.String arg0)\n\t\t{\n\t\t\treturn global::MonoJavaBridge.JavaBridge.CallObjectMethod(this, global::android.content.pm.PackageManager_.staticClass, \"getResourcesForApplication\", \"(Ljava/lang/String;)Landroid/content/res/Resources;\", ref global::android.content.pm.PackageManager_._m46, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)) as android.content.res.Resources;\n\t\t}\n\t\tprivate static global::MonoJavaBridge.MethodId _m47;\n\t\tpublic override global::android.content.res.Resources getResourcesForApplication(android.content.pm.ApplicationInfo arg0)\n\t\t{\n\t\t\treturn global::MonoJavaBridge.JavaBridge.CallObjectMethod(this, global::android.content.pm.PackageManager_.staticClass, \"getResourcesForApplication\", \"(Landroid/content/pm/ApplicationInfo;)Landroid/content/res/Resources;\", ref global::android.content.pm.PackageManager_._m47, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)) as android.content.res.Resources;\n\t\t}\n\t\tprivate static global::MonoJavaBridge.MethodId _m48;\n\t\tpublic override global::java.lang.String getInstallerPackageName(java.lang.String arg0)\n\t\t{\n\t\t\treturn global::MonoJavaBridge.JavaBridge.CallSealedClassObjectMethod(this, global::android.content.pm.PackageManager_.staticClass, \"getInstallerPackageName\", \"(Ljava/lang/String;)Ljava/lang/String;\", ref global::android.content.pm.PackageManager_._m48, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)) as java.lang.String;\n\t\t}\n\t\tprivate static global::MonoJavaBridge.MethodId _m49;\n\t\tpublic override void addPackageToPreferred(java.lang.String arg0)\n\t\t{\n\t\t\tglobal::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.content.pm.PackageManager_.staticClass, \"addPackageToPreferred\", \"(Ljava/lang/String;)V\", ref global::android.content.pm.PackageManager_._m49, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));\n\t\t}\n\t\tprivate static global::MonoJavaBridge.MethodId _m50;\n\t\tpublic override void removePackageFromPreferred(java.lang.String arg0)\n\t\t{\n\t\t\tglobal::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.content.pm.PackageManager_.staticClass, \"removePackageFromPreferred\", \"(Ljava/lang/String;)V\", ref global::android.content.pm.PackageManager_._m50, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));\n\t\t}\n\t\tprivate static global::MonoJavaBridge.MethodId _m51;\n\t\tpublic override global::java.util.List getPreferredPackages(int arg0)\n\t\t{\n\t\t\treturn global::MonoJavaBridge.JavaBridge.CallIJavaObjectMethod(this, global::android.content.pm.PackageManager_.staticClass, \"getPreferredPackages\", \"(I)Ljava/util/List;\", ref global::android.content.pm.PackageManager_._m51, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)) as java.util.List;\n\t\t}\n\t\tprivate static global::MonoJavaBridge.MethodId _m52;\n\t\tpublic override void addPreferredActivity(android.content.IntentFilter arg0, int arg1, android.content.ComponentName[] arg2, android.content.ComponentName arg3)\n\t\t{\n\t\t\tglobal::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.content.pm.PackageManager_.staticClass, \"addPreferredActivity\", \"(Landroid/content/IntentFilter;I[Landroid/content/ComponentName;Landroid/content/ComponentName;)V\", ref global::android.content.pm.PackageManager_._m52, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3));\n\t\t}\n\t\tprivate static global::MonoJavaBridge.MethodId _m53;\n\t\tpublic override void clearPackagePreferredActivities(java.lang.String arg0)\n\t\t{\n\t\t\tglobal::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.content.pm.PackageManager_.staticClass, \"clearPackagePreferredActivities\", \"(Ljava/lang/String;)V\", ref global::android.content.pm.PackageManager_._m53, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));\n\t\t}\n\t\tprivate static global::MonoJavaBridge.MethodId _m54;\n\t\tpublic override int getPreferredActivities(java.util.List arg0, java.util.List arg1, java.lang.String arg2)\n\t\t{\n\t\t\treturn global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::android.content.pm.PackageManager_.staticClass, \"getPreferredActivities\", \"(Ljava/util/List;Ljava/util/List;Ljava/lang/String;)I\", ref global::android.content.pm.PackageManager_._m54, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2));\n\t\t}\n\t\tprivate static global::MonoJavaBridge.MethodId _m55;\n\t\tpublic override void setComponentEnabledSetting(android.content.ComponentName arg0, int arg1, int arg2)\n\t\t{\n\t\t\tglobal::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.content.pm.PackageManager_.staticClass, \"setComponentEnabledSetting\", \"(Landroid/content/ComponentName;II)V\", ref global::android.content.pm.PackageManager_._m55, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2));\n\t\t}\n\t\tprivate static global::MonoJavaBridge.MethodId _m56;\n\t\tpublic override int getComponentEnabledSetting(android.content.ComponentName arg0)\n\t\t{\n\t\t\treturn global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::android.content.pm.PackageManager_.staticClass, \"getComponentEnabledSetting\", \"(Landroid/content/ComponentName;)I\", ref global::android.content.pm.PackageManager_._m56, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));\n\t\t}\n\t\tprivate static global::MonoJavaBridge.MethodId _m57;\n\t\tpublic override void setApplicationEnabledSetting(java.lang.String arg0, int arg1, int arg2)\n\t\t{\n\t\t\tglobal::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.content.pm.PackageManager_.staticClass, \"setApplicationEnabledSetting\", \"(Ljava/lang/String;II)V\", ref global::android.content.pm.PackageManager_._m57, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2));\n\t\t}\n\t\tprivate static global::MonoJavaBridge.MethodId _m58;\n\t\tpublic override int getApplicationEnabledSetting(java.lang.String arg0)\n\t\t{\n\t\t\treturn global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::android.content.pm.PackageManager_.staticClass, \"getApplicationEnabledSetting\", \"(Ljava/lang/String;)I\", ref global::android.content.pm.PackageManager_._m58, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));\n\t\t}\n\t\tprivate static global::MonoJavaBridge.MethodId _m59;\n\t\tpublic override bool isSafeMode()\n\t\t{\n\t\t\treturn global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::android.content.pm.PackageManager_.staticClass, \"isSafeMode\", \"()Z\", ref global::android.content.pm.PackageManager_._m59);\n\t\t}\n\t\tstatic PackageManager_()\n\t\t{\n\t\t\tglobal::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;\n\t\t\tglobal::android.content.pm.PackageManager_.staticClass = @__env.NewGlobalRef(@__env.FindClass(\"android/content/pm/PackageManager\"));\n\t\t}\n\t}\n}\n"},"gt":{"kind":"string","value":""}}},{"rowIdx":98456,"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.Collections;\nusing System.Collections.Generic;\nusing System.Diagnostics;\nusing System.Runtime.InteropServices;\nusing System.Threading;\n\nnamespace System.IO\n{\n /// Provides an implementation of FileSystem for Unix systems.\n internal sealed partial class UnixFileSystem : FileSystem\n {\n internal const int DefaultBufferSize = 4096;\n\n public override int MaxPath { get { return Interop.Sys.MaxPath; } }\n\n public override int MaxDirectoryPath { get { return Interop.Sys.MaxPath; } }\n\n public override void CopyFile(string sourceFullPath, string destFullPath, bool overwrite)\n {\n // The destination path may just be a directory into which the file should be copied.\n // If it is, append the filename from the source onto the destination directory\n if (DirectoryExists(destFullPath))\n {\n destFullPath = Path.Combine(destFullPath, Path.GetFileName(sourceFullPath));\n }\n\n // Copy the contents of the file from the source to the destination, creating the destination in the process\n using (var src = new FileStream(sourceFullPath, FileMode.Open, FileAccess.Read, FileShare.Read, DefaultBufferSize, FileOptions.None))\n using (var dst = new FileStream(destFullPath, overwrite ? FileMode.Create : FileMode.CreateNew, FileAccess.ReadWrite, FileShare.None, DefaultBufferSize, FileOptions.None))\n {\n Interop.CheckIo(Interop.Sys.CopyFile(src.SafeFileHandle, dst.SafeFileHandle));\n }\n }\n\n public override void ReplaceFile(string sourceFullPath, string destFullPath, string destBackupFullPath, bool ignoreMetadataErrors)\n {\n if (destBackupFullPath != null)\n {\n // We're backing up the destination file to the backup file, so we need to first delete the backup\n // file, if it exists. If deletion fails for a reason other than the file not existing, fail.\n if (Interop.Sys.Unlink(destBackupFullPath) != 0)\n {\n Interop.ErrorInfo errno = Interop.Sys.GetLastErrorInfo();\n if (errno.Error != Interop.Error.ENOENT)\n {\n throw Interop.GetExceptionForIoErrno(errno, destBackupFullPath);\n }\n }\n\n // Now that the backup is gone, link the backup to point to the same file as destination.\n // This way, we don't lose any data in the destination file, no copy is necessary, etc.\n Interop.CheckIo(Interop.Sys.Link(destFullPath, destBackupFullPath), destFullPath);\n }\n else\n {\n // There is no backup file. Just make sure the destination file exists, throwing if it doesn't.\n Interop.Sys.FileStatus ignored;\n if (Interop.Sys.Stat(destFullPath, out ignored) != 0)\n {\n Interop.ErrorInfo errno = Interop.Sys.GetLastErrorInfo();\n if (errno.Error == Interop.Error.ENOENT)\n {\n throw Interop.GetExceptionForIoErrno(errno, destBackupFullPath);\n }\n }\n }\n\n // Finally, rename the source to the destination, overwriting the destination.\n Interop.CheckIo(Interop.Sys.Rename(sourceFullPath, destFullPath));\n }\n\n public override void MoveFile(string sourceFullPath, string destFullPath)\n {\n // The desired behavior for Move(source, dest) is to not overwrite the destination file\n // if it exists. Since rename(source, dest) will replace the file at 'dest' if it exists,\n // link/unlink are used instead. However, if the source path and the dest path refer to\n // the same file, then do a rename rather than a link and an unlink. This is important\n // for case-insensitive file systems (e.g. renaming a file in a way that just changes casing),\n // so that we support changing the casing in the naming of the file. If this fails in any\n // way (e.g. source file doesn't exist, dest file doesn't exist, rename fails, etc.), we\n // just fall back to trying the link/unlink approach and generating any exceptional messages\n // from there as necessary.\n Interop.Sys.FileStatus sourceStat, destStat;\n if (Interop.Sys.LStat(sourceFullPath, out sourceStat) == 0 && // source file exists\n Interop.Sys.LStat(destFullPath, out destStat) == 0 && // dest file exists\n sourceStat.Dev == destStat.Dev && // source and dest are on the same device\n sourceStat.Ino == destStat.Ino && // and source and dest are the same file on that device\n Interop.Sys.Rename(sourceFullPath, destFullPath) == 0) // try the rename\n {\n // Renamed successfully.\n return;\n }\n\n if (Interop.Sys.Link(sourceFullPath, destFullPath) < 0)\n {\n // If link fails, we can fall back to doing a full copy, but we'll only do so for\n // cases where we expect link could fail but such a copy could succeed. We don't\n // want to do so for all errors, because the copy could incur a lot of cost\n // even if we know it'll eventually fail, e.g. EROFS means that the source file\n // system is read-only and couldn't support the link being added, but if it's\n // read-only, then the move should fail any way due to an inability to delete\n // the source file.\n Interop.ErrorInfo errorInfo = Interop.Sys.GetLastErrorInfo();\n if (errorInfo.Error == Interop.Error.EXDEV || // rename fails across devices / mount points\n errorInfo.Error == Interop.Error.EPERM || // permissions might not allow creating hard links even if a copy would work\n errorInfo.Error == Interop.Error.EOPNOTSUPP || // links aren't supported by the source file system\n errorInfo.Error == Interop.Error.EMLINK) // too many hard links to the source file\n {\n CopyFile(sourceFullPath, destFullPath, overwrite: false);\n }\n else\n {\n // The operation failed. Within reason, try to determine which path caused the problem \n // so we can throw a detailed exception.\n string path = null;\n bool isDirectory = false;\n if (errorInfo.Error == Interop.Error.ENOENT)\n {\n if (!Directory.Exists(Path.GetDirectoryName(destFullPath)))\n {\n // The parent directory of destFile can't be found.\n // Windows distinguishes between whether the directory or the file isn't found,\n // and throws a different exception in these cases. We attempt to approximate that\n // here; there is a race condition here, where something could change between\n // when the error occurs and our checks, but it's the best we can do, and the\n // worst case in such a race condition (which could occur if the file system is\n // being manipulated concurrently with these checks) is that we throw a\n // FileNotFoundException instead of DirectoryNotFoundexception.\n path = destFullPath;\n isDirectory = true;\n }\n else\n {\n path = sourceFullPath;\n }\n }\n else if (errorInfo.Error == Interop.Error.EEXIST)\n {\n path = destFullPath;\n }\n\n throw Interop.GetExceptionForIoErrno(errorInfo, path, isDirectory);\n }\n }\n DeleteFile(sourceFullPath);\n }\n\n public override void DeleteFile(string fullPath)\n {\n if (Interop.Sys.Unlink(fullPath) < 0)\n {\n Interop.ErrorInfo errorInfo = Interop.Sys.GetLastErrorInfo();\n // ENOENT means it already doesn't exist; nop\n if (errorInfo.Error != Interop.Error.ENOENT)\n {\n if (errorInfo.Error == Interop.Error.EISDIR)\n errorInfo = Interop.Error.EACCES.Info();\n throw Interop.GetExceptionForIoErrno(errorInfo, fullPath);\n }\n }\n }\n\n public override void CreateDirectory(string fullPath)\n {\n // NOTE: This logic is primarily just carried forward from Win32FileSystem.CreateDirectory.\n\n int length = fullPath.Length;\n\n // We need to trim the trailing slash or the code will try to create 2 directories of the same name.\n if (length >= 2 && PathHelpers.EndsInDirectorySeparator(fullPath))\n {\n length--;\n }\n\n // For paths that are only // or /// \n if (length == 2 && PathInternal.IsDirectorySeparator(fullPath[1]))\n {\n throw new IOException(SR.Format(SR.IO_CannotCreateDirectory, fullPath));\n }\n\n // We can save a bunch of work if the directory we want to create already exists.\n if (DirectoryExists(fullPath))\n {\n return;\n }\n\n // Attempt to figure out which directories don't exist, and only create the ones we need.\n bool somepathexists = false;\n Stack stackDir = new Stack();\n int lengthRoot = PathInternal.GetRootLength(fullPath);\n if (length > lengthRoot)\n {\n int i = length - 1;\n while (i >= lengthRoot && !somepathexists)\n {\n string dir = fullPath.Substring(0, i + 1);\n if (!DirectoryExists(dir)) // Create only the ones missing\n {\n stackDir.Push(dir);\n }\n else\n {\n somepathexists = true;\n }\n\n while (i > lengthRoot && !PathInternal.IsDirectorySeparator(fullPath[i]))\n {\n i--;\n }\n i--;\n }\n }\n\n int count = stackDir.Count;\n if (count == 0 && !somepathexists)\n {\n string root = Directory.InternalGetDirectoryRoot(fullPath);\n if (!DirectoryExists(root))\n {\n throw Interop.GetExceptionForIoErrno(Interop.Error.ENOENT.Info(), fullPath, isDirectory: true);\n }\n return;\n }\n\n // Create all the directories\n int result = 0;\n Interop.ErrorInfo firstError = default(Interop.ErrorInfo);\n string errorString = fullPath;\n while (stackDir.Count > 0)\n {\n string name = stackDir.Pop();\n if (name.Length >= MaxDirectoryPath)\n {\n throw new PathTooLongException(SR.IO_PathTooLong);\n }\n\n // The mkdir command uses 0777 by default (it'll be AND'd with the process umask internally).\n // We do the same.\n result = Interop.Sys.MkDir(name, (int)Interop.Sys.Permissions.Mask);\n if (result < 0 && firstError.Error == 0)\n {\n Interop.ErrorInfo errorInfo = Interop.Sys.GetLastErrorInfo();\n\n // While we tried to avoid creating directories that don't\n // exist above, there are a few cases that can fail, e.g.\n // a race condition where another process or thread creates\n // the directory first, or there's a file at the location.\n if (errorInfo.Error != Interop.Error.EEXIST)\n {\n firstError = errorInfo;\n }\n else if (FileExists(name) || (!DirectoryExists(name, out errorInfo) && errorInfo.Error == Interop.Error.EACCES))\n {\n // If there's a file in this directory's place, or if we have ERROR_ACCESS_DENIED when checking if the directory already exists throw.\n firstError = errorInfo;\n errorString = name;\n }\n }\n }\n\n // Only throw an exception if creating the exact directory we wanted failed to work correctly.\n if (result < 0 && firstError.Error != 0)\n {\n throw Interop.GetExceptionForIoErrno(firstError, errorString, isDirectory: true);\n }\n }\n\n public override void MoveDirectory(string sourceFullPath, string destFullPath)\n {\n // Windows doesn't care if you try and copy a file via \"MoveDirectory\"...\n if (FileExists(sourceFullPath))\n {\n // ... but it doesn't like the source to have a trailing slash ...\n\n // On Windows we end up with ERROR_INVALID_NAME, which is\n // \"The filename, directory name, or volume label syntax is incorrect.\"\n //\n // This surfaces as a IOException, if we let it go beyond here it would\n // give DirectoryNotFound.\n\n if (PathHelpers.EndsInDirectorySeparator(sourceFullPath))\n throw new IOException(SR.Format(SR.IO_PathNotFound_Path, sourceFullPath));\n\n // ... but it doesn't care if the destination has a trailing separator.\n destFullPath = PathHelpers.TrimEndingDirectorySeparator(destFullPath);\n }\n\n if (Interop.Sys.Rename(sourceFullPath, destFullPath) < 0)\n {\n Interop.ErrorInfo errorInfo = Interop.Sys.GetLastErrorInfo();\n switch (errorInfo.Error)\n {\n case Interop.Error.EACCES: // match Win32 exception\n throw new IOException(SR.Format(SR.UnauthorizedAccess_IODenied_Path, sourceFullPath), errorInfo.RawErrno);\n default:\n throw Interop.GetExceptionForIoErrno(errorInfo, sourceFullPath, isDirectory: true);\n }\n }\n }\n\n public override void RemoveDirectory(string fullPath, bool recursive)\n {\n var di = new DirectoryInfo(fullPath);\n if (!di.Exists)\n {\n throw Interop.GetExceptionForIoErrno(Interop.Error.ENOENT.Info(), fullPath, isDirectory: true);\n }\n RemoveDirectoryInternal(di, recursive, throwOnTopLevelDirectoryNotFound: true);\n }\n\n private void RemoveDirectoryInternal(DirectoryInfo directory, bool recursive, bool throwOnTopLevelDirectoryNotFound)\n {\n Exception firstException = null;\n\n if ((directory.Attributes & FileAttributes.ReparsePoint) != 0)\n {\n DeleteFile(directory.FullName);\n return;\n }\n\n if (recursive)\n {\n try\n {\n foreach (string item in EnumeratePaths(directory.FullName, \"*\", SearchOption.TopDirectoryOnly, SearchTarget.Both))\n {\n if (!ShouldIgnoreDirectory(Path.GetFileName(item)))\n {\n try\n {\n var childDirectory = new DirectoryInfo(item);\n if (childDirectory.Exists)\n {\n RemoveDirectoryInternal(childDirectory, recursive, throwOnTopLevelDirectoryNotFound: false);\n }\n else\n {\n DeleteFile(item);\n }\n }\n catch (Exception exc)\n {\n if (firstException != null)\n {\n firstException = exc;\n }\n }\n }\n }\n }\n catch (Exception exc)\n {\n if (firstException != null)\n {\n firstException = exc;\n }\n }\n\n if (firstException != null)\n {\n throw firstException;\n }\n }\n\n if (Interop.Sys.RmDir(directory.FullName) < 0)\n {\n Interop.ErrorInfo errorInfo = Interop.Sys.GetLastErrorInfo();\n switch (errorInfo.Error)\n {\n case Interop.Error.EACCES:\n case Interop.Error.EPERM:\n case Interop.Error.EROFS:\n case Interop.Error.EISDIR:\n throw new IOException(SR.Format(SR.UnauthorizedAccess_IODenied_Path, directory.FullName)); // match Win32 exception\n case Interop.Error.ENOENT:\n if (!throwOnTopLevelDirectoryNotFound)\n {\n return;\n }\n goto default;\n default:\n throw Interop.GetExceptionForIoErrno(errorInfo, directory.FullName, isDirectory: true);\n }\n }\n }\n\n public override bool DirectoryExists(string fullPath)\n {\n Interop.ErrorInfo ignored;\n return DirectoryExists(fullPath, out ignored);\n }\n\n private static bool DirectoryExists(string fullPath, out Interop.ErrorInfo errorInfo)\n {\n return FileExists(fullPath, Interop.Sys.FileTypes.S_IFDIR, out errorInfo);\n }\n\n public override bool FileExists(string fullPath)\n {\n Interop.ErrorInfo ignored;\n\n // Windows doesn't care about the trailing separator\n return FileExists(PathHelpers.TrimEndingDirectorySeparator(fullPath), Interop.Sys.FileTypes.S_IFREG, out ignored);\n }\n\n private static bool FileExists(string fullPath, int fileType, out Interop.ErrorInfo errorInfo)\n {\n Debug.Assert(fileType == Interop.Sys.FileTypes.S_IFREG || fileType == Interop.Sys.FileTypes.S_IFDIR);\n\n Interop.Sys.FileStatus fileinfo;\n errorInfo = default(Interop.ErrorInfo);\n\n // First use stat, as we want to follow symlinks. If that fails, it could be because the symlink\n // is broken, we don't have permissions, etc., in which case fall back to using LStat to evaluate\n // based on the symlink itself.\n if (Interop.Sys.Stat(fullPath, out fileinfo) < 0 &&\n Interop.Sys.LStat(fullPath, out fileinfo) < 0)\n {\n errorInfo = Interop.Sys.GetLastErrorInfo();\n return false;\n }\n\n // Something exists at this path. If the caller is asking for a directory, return true if it's\n // a directory and false for everything else. If the caller is asking for a file, return false for\n // a directory and true for everything else.\n return\n (fileType == Interop.Sys.FileTypes.S_IFDIR) ==\n ((fileinfo.Mode & Interop.Sys.FileTypes.S_IFMT) == Interop.Sys.FileTypes.S_IFDIR);\n }\n\n public override IEnumerable EnumeratePaths(string path, string searchPattern, SearchOption searchOption, SearchTarget searchTarget)\n {\n return new FileSystemEnumerable(path, searchPattern, searchOption, searchTarget, (p, _) => p);\n }\n\n public override IEnumerable EnumerateFileSystemInfos(string fullPath, string searchPattern, SearchOption searchOption, SearchTarget searchTarget)\n {\n switch (searchTarget)\n {\n case SearchTarget.Files:\n return new FileSystemEnumerable(fullPath, searchPattern, searchOption, searchTarget, (path, isDir) =>\n {\n var info = new FileInfo(path, null);\n info.Refresh();\n return info;\n });\n case SearchTarget.Directories:\n return new FileSystemEnumerable(fullPath, searchPattern, searchOption, searchTarget, (path, isDir) =>\n {\n var info = new DirectoryInfo(path, null);\n info.Refresh();\n return info;\n });\n default:\n return new FileSystemEnumerable(fullPath, searchPattern, searchOption, searchTarget, (path, isDir) =>\n {\n var info = isDir ?\n (FileSystemInfo)new DirectoryInfo(path, null) :\n (FileSystemInfo)new FileInfo(path, null);\n info.Refresh();\n return info;\n });\n }\n }\n\n private sealed class FileSystemEnumerable : IEnumerable\n {\n private readonly PathPair _initialDirectory;\n private readonly string _searchPattern;\n private readonly SearchOption _searchOption;\n private readonly bool _includeFiles;\n private readonly bool _includeDirectories;\n private readonly Func _translateResult;\n private IEnumerator _firstEnumerator;\n\n internal FileSystemEnumerable(\n string userPath, string searchPattern,\n SearchOption searchOption, SearchTarget searchTarget,\n Func translateResult)\n {\n // Basic validation of the input path\n if (userPath == null)\n {\n throw new ArgumentNullException(\"path\");\n }\n if (string.IsNullOrWhiteSpace(userPath))\n {\n throw new ArgumentException(SR.Argument_EmptyPath, \"path\");\n }\n\n // Validate and normalize the search pattern. If after doing so it's empty,\n // matching Win32 behavior we can skip all additional validation and effectively\n // return an empty enumerable.\n searchPattern = NormalizeSearchPattern(searchPattern);\n if (searchPattern.Length > 0)\n {\n PathHelpers.CheckSearchPattern(searchPattern);\n PathHelpers.ThrowIfEmptyOrRootedPath(searchPattern);\n\n // If the search pattern contains any paths, make sure we factor those into \n // the user path, and then trim them off.\n int lastSlash = searchPattern.LastIndexOf(Path.DirectorySeparatorChar);\n if (lastSlash >= 0)\n {\n if (lastSlash >= 1)\n {\n userPath = Path.Combine(userPath, searchPattern.Substring(0, lastSlash));\n }\n searchPattern = searchPattern.Substring(lastSlash + 1);\n }\n\n // Typically we shouldn't see either of these cases, an upfront check is much faster\n foreach (char c in searchPattern)\n {\n if (c == '\\\\' || c == '[')\n {\n // We need to escape any escape characters in the search pattern\n searchPattern = searchPattern.Replace(@\"\\\", @\"\\\\\");\n\n // And then escape '[' to prevent it being picked up as a wildcard\n searchPattern = searchPattern.Replace(@\"[\", @\"\\[\");\n break;\n }\n }\n\n string fullPath = Path.GetFullPath(userPath);\n\n // Store everything for the enumerator\n _initialDirectory = new PathPair(userPath, fullPath);\n _searchPattern = searchPattern;\n _searchOption = searchOption;\n _includeFiles = (searchTarget & SearchTarget.Files) != 0;\n _includeDirectories = (searchTarget & SearchTarget.Directories) != 0;\n _translateResult = translateResult;\n }\n\n // Open the first enumerator so that any errors are propagated synchronously.\n _firstEnumerator = Enumerate();\n }\n\n public IEnumerator GetEnumerator()\n {\n return Interlocked.Exchange(ref _firstEnumerator, null) ?? Enumerate();\n }\n\n IEnumerator IEnumerable.GetEnumerator()\n {\n return GetEnumerator();\n }\n\n private IEnumerator Enumerate()\n {\n return Enumerate(\n _initialDirectory.FullPath != null ? \n OpenDirectory(_initialDirectory.FullPath) : \n null);\n }\n\n private IEnumerator Enumerate(Microsoft.Win32.SafeHandles.SafeDirectoryHandle dirHandle)\n {\n if (dirHandle == null)\n {\n // Empty search\n yield break;\n }\n\n Debug.Assert(!dirHandle.IsInvalid);\n Debug.Assert(!dirHandle.IsClosed);\n\n // Maintain a stack of the directories to explore, in the case of SearchOption.AllDirectories\n // Lazily-initialized only if we find subdirectories that will be explored.\n Stack toExplore = null;\n PathPair dirPath = _initialDirectory;\n while (dirHandle != null)\n {\n try\n {\n // Read each entry from the enumerator\n Interop.Sys.DirectoryEntry dirent;\n while (Interop.Sys.ReadDir(dirHandle, out dirent) == 0)\n {\n // Get from the dir entry whether the entry is a file or directory.\n // We classify everything as a file unless we know it to be a directory.\n bool isDir;\n if (dirent.InodeType == Interop.Sys.NodeType.DT_DIR)\n {\n // We know it's a directory.\n isDir = true;\n }\n else if (dirent.InodeType == Interop.Sys.NodeType.DT_LNK || dirent.InodeType == Interop.Sys.NodeType.DT_UNKNOWN)\n {\n // It's a symlink or unknown: stat to it to see if we can resolve it to a directory.\n // If we can't (e.g. symlink to a file, broken symlink, etc.), we'll just treat it as a file.\n Interop.ErrorInfo errnoIgnored;\n isDir = DirectoryExists(Path.Combine(dirPath.FullPath, dirent.InodeName), out errnoIgnored);\n }\n else\n {\n // Otherwise, treat it as a file. This includes regular files, FIFOs, etc.\n isDir = false;\n }\n\n // Yield the result if the user has asked for it. In the case of directories,\n // always explore it by pushing it onto the stack, regardless of whether\n // we're returning directories.\n if (isDir)\n {\n if (!ShouldIgnoreDirectory(dirent.InodeName))\n {\n string userPath = null;\n if (_searchOption == SearchOption.AllDirectories)\n {\n if (toExplore == null)\n {\n toExplore = new Stack();\n }\n userPath = Path.Combine(dirPath.UserPath, dirent.InodeName);\n toExplore.Push(new PathPair(userPath, Path.Combine(dirPath.FullPath, dirent.InodeName)));\n }\n if (_includeDirectories &&\n Interop.Sys.FnMatch(_searchPattern, dirent.InodeName, Interop.Sys.FnMatchFlags.FNM_NONE) == 0)\n {\n yield return _translateResult(userPath ?? Path.Combine(dirPath.UserPath, dirent.InodeName), /*isDirectory*/true);\n }\n }\n }\n else if (_includeFiles &&\n Interop.Sys.FnMatch(_searchPattern, dirent.InodeName, Interop.Sys.FnMatchFlags.FNM_NONE) == 0)\n {\n yield return _translateResult(Path.Combine(dirPath.UserPath, dirent.InodeName), /*isDirectory*/false);\n }\n }\n }\n finally\n {\n // Close the directory enumerator\n dirHandle.Dispose();\n dirHandle = null;\n }\n\n if (toExplore != null && toExplore.Count > 0)\n {\n // Open the next directory.\n dirPath = toExplore.Pop();\n dirHandle = OpenDirectory(dirPath.FullPath);\n }\n }\n }\n\n private static string NormalizeSearchPattern(string searchPattern)\n {\n if (searchPattern == \".\" || searchPattern == \"*.*\")\n {\n searchPattern = \"*\";\n }\n else if (PathHelpers.EndsInDirectorySeparator(searchPattern))\n {\n searchPattern += \"*\";\n }\n\n return searchPattern;\n }\n\n private static Microsoft.Win32.SafeHandles.SafeDirectoryHandle OpenDirectory(string fullPath)\n {\n Microsoft.Win32.SafeHandles.SafeDirectoryHandle handle = Interop.Sys.OpenDir(fullPath);\n if (handle.IsInvalid)\n {\n throw Interop.GetExceptionForIoErrno(Interop.Sys.GetLastErrorInfo(), fullPath, isDirectory: true);\n }\n return handle;\n }\n }\n\n /// Determines whether the specified directory name should be ignored.\n /// The name to evaluate.\n /// true if the name is \".\" or \"..\"; otherwise, false.\n private static bool ShouldIgnoreDirectory(string name)\n {\n return name == \".\" || name == \"..\";\n }\n\n public override string GetCurrentDirectory()\n {\n return Interop.Sys.GetCwd();\n }\n\n public override void SetCurrentDirectory(string fullPath)\n {\n Interop.CheckIo(Interop.Sys.ChDir(fullPath), fullPath, isDirectory:true);\n }\n\n public override FileAttributes GetAttributes(string fullPath)\n {\n FileAttributes attributes = new FileInfo(fullPath, null).Attributes;\n\n if (attributes == (FileAttributes)(-1))\n FileSystemInfo.ThrowNotFound(fullPath);\n\n return attributes;\n }\n\n public override void SetAttributes(string fullPath, FileAttributes attributes)\n {\n new FileInfo(fullPath, null).Attributes = attributes;\n }\n\n public override DateTimeOffset GetCreationTime(string fullPath)\n {\n return new FileInfo(fullPath, null).CreationTime;\n }\n\n public override void SetCreationTime(string fullPath, DateTimeOffset time, bool asDirectory)\n {\n IFileSystemObject info = asDirectory ?\n (IFileSystemObject)new DirectoryInfo(fullPath, null) :\n (IFileSystemObject)new FileInfo(fullPath, null);\n\n info.CreationTime = time;\n }\n\n public override DateTimeOffset GetLastAccessTime(string fullPath)\n {\n return new FileInfo(fullPath, null).LastAccessTime;\n }\n\n public override void SetLastAccessTime(string fullPath, DateTimeOffset time, bool asDirectory)\n {\n IFileSystemObject info = asDirectory ?\n (IFileSystemObject)new DirectoryInfo(fullPath, null) :\n (IFileSystemObject)new FileInfo(fullPath, null);\n\n info.LastAccessTime = time;\n }\n\n public override DateTimeOffset GetLastWriteTime(string fullPath)\n {\n return new FileInfo(fullPath, null).LastWriteTime;\n }\n\n public override void SetLastWriteTime(string fullPath, DateTimeOffset time, bool asDirectory)\n {\n IFileSystemObject info = asDirectory ?\n (IFileSystemObject)new DirectoryInfo(fullPath, null) :\n (IFileSystemObject)new FileInfo(fullPath, null);\n\n info.LastWriteTime = time;\n }\n\n public override IFileSystemObject GetFileSystemInfo(string fullPath, bool asDirectory)\n {\n return asDirectory ?\n (IFileSystemObject)new DirectoryInfo(fullPath, null) :\n (IFileSystemObject)new FileInfo(fullPath, null);\n }\n\n public override string[] GetLogicalDrives()\n {\n return DriveInfoInternal.GetLogicalDrives();\n }\n }\n}\n"},"gt":{"kind":"string","value":""}}},{"rowIdx":98457,"cells":{"context":{"kind":"string","value":"using Lucene.Net.Diagnostics;\nusing System;\nusing System.Collections.Generic;\nusing System.Diagnostics;\n\nnamespace Lucene.Net.Index\n{\n /*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements. See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License. You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n using ByteRunAutomaton = Lucene.Net.Util.Automaton.ByteRunAutomaton;\n using BytesRef = Lucene.Net.Util.BytesRef;\n using CompiledAutomaton = Lucene.Net.Util.Automaton.CompiledAutomaton;\n using Int32sRef = Lucene.Net.Util.Int32sRef;\n using StringHelper = Lucene.Net.Util.StringHelper;\n using Transition = Lucene.Net.Util.Automaton.Transition;\n\n /// \n /// A that enumerates terms based upon what is accepted by a\n /// DFA.\n /// \n /// The algorithm is such:\n /// \n /// As long as matches are successful, keep reading sequentially.\n /// When a match fails, skip to the next string in lexicographic order that\n /// does not enter a reject state.\n /// \n /// \n /// The algorithm does not attempt to actually skip to the next string that is\n /// completely accepted. this is not possible when the language accepted by the\n /// FSM is not finite (i.e. * operator).\n /// \n /// @lucene.experimental\n /// \n internal class AutomatonTermsEnum : FilteredTermsEnum\n {\n // a tableized array-based form of the DFA\n private readonly ByteRunAutomaton runAutomaton;\n\n // common suffix of the automaton\n private readonly BytesRef commonSuffixRef;\n\n // true if the automaton accepts a finite language\n private readonly bool? finite;\n\n // array of sorted transitions for each state, indexed by state number\n private readonly Transition[][] allTransitions;\n\n // for path tracking: each long records gen when we last\n // visited the state; we use gens to avoid having to clear\n private readonly long[] visited;\n\n private long curGen;\n\n // the reference used for seeking forwards through the term dictionary\n private readonly BytesRef seekBytesRef = new BytesRef(10);\n\n // true if we are enumerating an infinite portion of the DFA.\n // in this case it is faster to drive the query based on the terms dictionary.\n // when this is true, linearUpperBound indicate the end of range\n // of terms where we should simply do sequential reads instead.\n private bool linear = false;\n\n private readonly BytesRef linearUpperBound = new BytesRef(10);\n private readonly IComparer termComp;\n\n /// \n /// Construct an enumerator based upon an automaton, enumerating the specified\n /// field, working on a supplied \n /// \n /// @lucene.experimental\n /// \n /// TermsEnum \n /// CompiledAutomaton \n public AutomatonTermsEnum(TermsEnum tenum, CompiledAutomaton compiled)\n : base(tenum)\n {\n this.finite = compiled.Finite;\n this.runAutomaton = compiled.RunAutomaton;\n if (Debugging.AssertsEnabled) Debugging.Assert(this.runAutomaton != null);\n this.commonSuffixRef = compiled.CommonSuffixRef;\n this.allTransitions = compiled.SortedTransitions;\n\n // used for path tracking, where each bit is a numbered state.\n visited = new long[runAutomaton.Count];\n\n termComp = Comparer;\n }\n\n /// \n /// Returns true if the term matches the automaton. Also stashes away the term\n /// to assist with smart enumeration.\n /// \n protected override AcceptStatus Accept(BytesRef term)\n {\n if (commonSuffixRef == null || StringHelper.EndsWith(term, commonSuffixRef))\n {\n if (runAutomaton.Run(term.Bytes, term.Offset, term.Length))\n {\n return linear ? AcceptStatus.YES : AcceptStatus.YES_AND_SEEK;\n }\n else\n {\n return (linear && termComp.Compare(term, linearUpperBound) < 0) ? AcceptStatus.NO : AcceptStatus.NO_AND_SEEK;\n }\n }\n else\n {\n return (linear && termComp.Compare(term, linearUpperBound) < 0) ? AcceptStatus.NO : AcceptStatus.NO_AND_SEEK;\n }\n }\n\n protected override BytesRef NextSeekTerm(BytesRef term)\n {\n //System.out.println(\"ATE.nextSeekTerm term=\" + term);\n if (term == null)\n {\n if (Debugging.AssertsEnabled) Debugging.Assert(seekBytesRef.Length == 0);\n // return the empty term, as its valid\n if (runAutomaton.IsAccept(runAutomaton.InitialState))\n {\n return seekBytesRef;\n }\n }\n else\n {\n seekBytesRef.CopyBytes(term);\n }\n\n // seek to the next possible string;\n if (NextString())\n {\n return seekBytesRef; // reposition\n }\n else\n {\n return null; // no more possible strings can match\n }\n }\n\n /// \n /// Sets the enum to operate in linear fashion, as we have found\n /// a looping transition at position: we set an upper bound and\n /// act like a for this portion of the term space.\n /// \n private void SetLinear(int position)\n {\n if (Debugging.AssertsEnabled) Debugging.Assert(linear == false);\n\n int state = runAutomaton.InitialState;\n int maxInterval = 0xff;\n for (int i = 0; i < position; i++)\n {\n state = runAutomaton.Step(state, seekBytesRef.Bytes[i] & 0xff);\n if (Debugging.AssertsEnabled) Debugging.Assert(state >= 0,\"state={0}\", state);\n }\n for (int i = 0; i < allTransitions[state].Length; i++)\n {\n Transition t = allTransitions[state][i];\n if (t.Min <= (seekBytesRef.Bytes[position] & 0xff) && (seekBytesRef.Bytes[position] & 0xff) <= t.Max)\n {\n maxInterval = t.Max;\n break;\n }\n }\n // 0xff terms don't get the optimization... not worth the trouble.\n if (maxInterval != 0xff)\n {\n maxInterval++;\n }\n int length = position + 1; // value + maxTransition\n if (linearUpperBound.Bytes.Length < length)\n {\n linearUpperBound.Bytes = new byte[length];\n }\n Array.Copy(seekBytesRef.Bytes, 0, linearUpperBound.Bytes, 0, position);\n linearUpperBound.Bytes[position] = (byte)maxInterval;\n linearUpperBound.Length = length;\n\n linear = true;\n }\n\n private readonly Int32sRef savedStates = new Int32sRef(10);\n\n /// \n /// Increments the byte buffer to the next string in binary order after s that will not put\n /// the machine into a reject state. If such a string does not exist, returns\n /// false.\n /// \n /// The correctness of this method depends upon the automaton being deterministic,\n /// and having no transitions to dead states.\n /// \n /// true if more possible solutions exist for the DFA \n private bool NextString()\n {\n int state;\n int pos = 0;\n savedStates.Grow(seekBytesRef.Length + 1);\n int[] states = savedStates.Int32s;\n states[0] = runAutomaton.InitialState;\n\n while (true)\n {\n curGen++;\n linear = false;\n // walk the automaton until a character is rejected.\n for (state = states[pos]; pos < seekBytesRef.Length; pos++)\n {\n visited[state] = curGen;\n int nextState = runAutomaton.Step(state, seekBytesRef.Bytes[pos] & 0xff);\n if (nextState == -1)\n {\n break;\n }\n states[pos + 1] = nextState;\n // we found a loop, record it for faster enumeration\n if ((finite == false) && !linear && visited[nextState] == curGen)\n {\n SetLinear(pos);\n }\n state = nextState;\n }\n\n // take the useful portion, and the last non-reject state, and attempt to\n // append characters that will match.\n if (NextString(state, pos))\n {\n return true;\n } // no more solutions exist from this useful portion, backtrack\n else\n {\n if ((pos = Backtrack(pos)) < 0) // no more solutions at all\n {\n return false;\n }\n int newState = runAutomaton.Step(states[pos], seekBytesRef.Bytes[pos] & 0xff);\n if (newState >= 0 && runAutomaton.IsAccept(newState))\n /* String is good to go as-is */\n {\n return true;\n }\n /* else advance further */\n // TODO: paranoia? if we backtrack thru an infinite DFA, the loop detection is important!\n // for now, restart from scratch for all infinite DFAs\n if (finite == false)\n {\n pos = 0;\n }\n }\n }\n }\n\n /// \n /// Returns the next string in lexicographic order that will not put\n /// the machine into a reject state.\n /// \n /// This method traverses the DFA from the given position in the string,\n /// starting at the given state.\n /// \n /// If this cannot satisfy the machine, returns false. This method will\n /// walk the minimal path, in lexicographic order, as long as possible.\n /// \n /// If this method returns false, then there might still be more solutions,\n /// it is necessary to backtrack to find out.\n /// \n /// current non-reject state \n /// useful portion of the string \n /// true if more possible solutions exist for the DFA from this\n /// position \n private bool NextString(int state, int position)\n {\n /*\n * the next lexicographic character must be greater than the existing\n * character, if it exists.\n */\n int c = 0;\n if (position < seekBytesRef.Length)\n {\n c = seekBytesRef.Bytes[position] & 0xff;\n // if the next byte is 0xff and is not part of the useful portion,\n // then by definition it puts us in a reject state, and therefore this\n // path is dead. there cannot be any higher transitions. backtrack.\n if (c++ == 0xff)\n {\n return false;\n }\n }\n\n seekBytesRef.Length = position;\n visited[state] = curGen;\n\n Transition[] transitions = allTransitions[state];\n\n // find the minimal path (lexicographic order) that is >= c\n\n for (int i = 0; i < transitions.Length; i++)\n {\n Transition transition = transitions[i];\n if (transition.Max >= c)\n {\n int nextChar = Math.Max(c, transition.Min);\n // append either the next sequential char, or the minimum transition\n seekBytesRef.Grow(seekBytesRef.Length + 1);\n seekBytesRef.Length++;\n seekBytesRef.Bytes[seekBytesRef.Length - 1] = (byte)nextChar;\n state = transition.Dest.Number;\n /*\n * as long as is possible, continue down the minimal path in\n * lexicographic order. if a loop or accept state is encountered, stop.\n */\n while (visited[state] != curGen && !runAutomaton.IsAccept(state))\n {\n visited[state] = curGen;\n /*\n * Note: we work with a DFA with no transitions to dead states.\n * so the below is ok, if it is not an accept state,\n * then there MUST be at least one transition.\n */\n transition = allTransitions[state][0];\n state = transition.Dest.Number;\n\n // append the minimum transition\n seekBytesRef.Grow(seekBytesRef.Length + 1);\n seekBytesRef.Length++;\n seekBytesRef.Bytes[seekBytesRef.Length - 1] = (byte)transition.Min;\n\n // we found a loop, record it for faster enumeration\n if ((finite == false) && !linear && visited[state] == curGen)\n {\n SetLinear(seekBytesRef.Length - 1);\n }\n }\n return true;\n }\n }\n return false;\n }\n\n /// \n /// Attempts to backtrack thru the string after encountering a dead end\n /// at some given position. Returns false if no more possible strings\n /// can match.\n /// \n /// current position in the input string \n /// position &gt;=0 if more possible solutions exist for the DFA \n private int Backtrack(int position)\n {\n while (position-- > 0)\n {\n int nextChar = seekBytesRef.Bytes[position] & 0xff;\n // if a character is 0xff its a dead-end too,\n // because there is no higher character in binary sort order.\n if (nextChar++ != 0xff)\n {\n seekBytesRef.Bytes[position] = (byte)nextChar;\n seekBytesRef.Length = position + 1;\n return position;\n }\n }\n return -1; // all solutions exhausted\n }\n }\n}\n"},"gt":{"kind":"string","value":""}}},{"rowIdx":98458,"cells":{"context":{"kind":"string","value":"using System;\nusing System.Collections.Generic;\nusing System.ComponentModel;\nusing System.Data;\nusing System.Diagnostics.CodeAnalysis;\nusing System.Linq;\nusing NetGore;\nusing NetGore.IO;\n\nnamespace DemoGame\n{\n /// \n /// Represents a unique ID for a User's account.\n /// \n [Serializable]\n [TypeConverter(typeof(AccountIDTypeConverter))]\n public struct AccountID : IComparable, IConvertible, IFormattable, IComparable, IEquatable\n {\n /// \n /// Represents the largest possible value of AccountID. This field is constant.\n /// \n public const int MaxValue = int.MaxValue;\n\n /// \n /// Represents the smallest possible value of AccountID. This field is constant.\n /// \n public const int MinValue = int.MinValue;\n\n /// \n /// The underlying value. This contains the actual value of the struct instance.\n /// \n readonly int _value;\n\n /// \n /// Initializes a new instance of the struct.\n /// \n /// Value to assign to the new AccountID.\n /// value is out of range.\n public AccountID(int value)\n {\n if (value < MinValue || value > MaxValue)\n throw new ArgumentOutOfRangeException(\"value\");\n\n _value = value;\n }\n\n /// \n /// Indicates whether this instance and a specified object are equal.\n /// \n /// Another object to compare to.\n /// \n /// True if and this instance are the same type and represent the same value; otherwise, false.\n /// \n public bool Equals(AccountID other)\n {\n return other._value == _value;\n }\n\n /// \n /// Indicates whether this instance and a specified object are equal.\n /// \n /// Another object to compare to.\n /// \n /// True if and this instance are the same type and represent the same value; otherwise, false.\n /// \n public override bool Equals(object obj)\n {\n return obj is AccountID && this == (AccountID)obj;\n }\n\n /// \n /// Returns the hash code for this instance.\n /// \n /// \n /// A 32-bit signed integer that is the hash code for this instance.\n /// \n public override int GetHashCode()\n {\n return _value.GetHashCode();\n }\n\n /// \n /// Gets the raw internal value of this AccountID.\n /// \n /// The raw internal value.\n [SuppressMessage(\"Microsoft.Design\", \"CA1024:UsePropertiesWhereAppropriate\")]\n public int GetRawValue()\n {\n return _value;\n }\n\n /// \n /// Reads an AccountID from an IValueReader.\n /// \n /// IValueReader to read from.\n /// Unique name of the value to read.\n /// The AccountID read from the IValueReader.\n public static AccountID Read(IValueReader reader, string name)\n {\n var value = reader.ReadInt(name);\n return new AccountID(value);\n }\n\n /// \n /// Reads an AccountID from an .\n /// \n /// to get the value from.\n /// The index of the field to find.\n /// The AccountID read from the .\n public static AccountID Read(IDataRecord r, int i)\n {\n var value = r.GetValue(i);\n if (value is int)\n return new AccountID((int)value);\n\n var convertedValue = Convert.ToInt32(value);\n return new AccountID(convertedValue);\n }\n\n /// \n /// Reads an AccountID from an .\n /// \n /// to get the value from.\n /// The name of the field to find.\n /// The AccountID read from the .\n public static AccountID Read(IDataRecord reader, string name)\n {\n return Read(reader, reader.GetOrdinal(name));\n }\n\n /// \n /// Reads an AccountID from an BitStream.\n /// \n /// BitStream to read from.\n /// The AccountID read from the BitStream.\n public static AccountID Read(BitStream bitStream)\n {\n var value = bitStream.ReadInt();\n return new AccountID(value);\n }\n\n /// \n /// Converts the numeric value of this instance to its equivalent string representation.\n /// \n /// The string representation of the value of this instance, consisting of a sequence\n /// of digits ranging from 0 to 9, without leading zeroes.\n public override string ToString()\n {\n return _value.ToString();\n }\n\n /// \n /// Writes the AccountID to an IValueWriter.\n /// \n /// IValueWriter to write to.\n /// Unique name of the AccountID that will be used to distinguish it\n /// from other values when reading.\n public void Write(IValueWriter writer, string name)\n {\n writer.Write(name, _value);\n }\n\n /// \n /// Writes the AccountID to an IValueWriter.\n /// \n /// BitStream to write to.\n public void Write(BitStream bitStream)\n {\n bitStream.Write(_value);\n }\n\n #region IComparable Members\n\n /// \n /// Compares the current object with another object of the same type.\n /// \n /// An object to compare with this object.\n /// \n /// A 32-bit signed integer that indicates the relative order of the objects being compared.\n /// The return value has the following meanings: \n /// Value \n /// Meaning \n /// Less than zero \n /// This object is less than the parameter.\n /// Zero \n /// This object is equal to . \n /// Greater than zero \n /// This object is greater than . \n /// \n public int CompareTo(AccountID other)\n {\n return _value.CompareTo(other._value);\n }\n\n #endregion\n\n #region IComparable Members\n\n /// \n /// Compares the current object with another object of the same type.\n /// \n /// An object to compare with this object.\n /// \n /// A 32-bit signed integer that indicates the relative order of the objects being compared. The return value has the following meanings: \n /// Value \n /// Meaning \n /// Less than zero \n /// This object is less than the parameter.\n /// Zero \n /// This object is equal to . \n /// Greater than zero \n /// This object is greater than . \n /// \n public int CompareTo(int other)\n {\n return _value.CompareTo(other);\n }\n\n #endregion\n\n #region IConvertible Members\n\n /// \n /// Returns the for this instance.\n /// \n /// \n /// The enumerated constant that is the of the class or value type that implements this interface.\n /// \n public TypeCode GetTypeCode()\n {\n return _value.GetTypeCode();\n }\n\n /// \n /// Converts the value of this instance to an equivalent Boolean value using the specified culture-specific formatting information.\n /// \n /// An interface implementation\n /// that supplies culture-specific formatting information.\n /// \n /// A Boolean value equivalent to the value of this instance.\n /// \n bool IConvertible.ToBoolean(IFormatProvider provider)\n {\n return ((IConvertible)_value).ToBoolean(provider);\n }\n\n /// \n /// Converts the value of this instance to an equivalent 8-bit unsigned integer using the specified culture-specific formatting information.\n /// \n /// An interface implementation that supplies\n /// culture-specific formatting information.\n /// \n /// An 8-bit unsigned integer equivalent to the value of this instance.\n /// \n byte IConvertible.ToByte(IFormatProvider provider)\n {\n return ((IConvertible)_value).ToByte(provider);\n }\n\n /// \n /// Converts the value of this instance to an equivalent Unicode character using the specified culture-specific formatting information.\n /// \n /// An interface implementation that supplies\n /// culture-specific formatting information.\n /// \n /// A Unicode character equivalent to the value of this instance.\n /// \n char IConvertible.ToChar(IFormatProvider provider)\n {\n return ((IConvertible)_value).ToChar(provider);\n }\n\n /// \n /// Converts the value of this instance to an equivalent using the specified culture-specific formatting information.\n /// \n /// An interface implementation that supplies\n /// culture-specific formatting information.\n /// \n /// A instance equivalent to the value of this instance.\n /// \n DateTime IConvertible.ToDateTime(IFormatProvider provider)\n {\n return ((IConvertible)_value).ToDateTime(provider);\n }\n\n /// \n /// Converts the value of this instance to an equivalent number using the specified culture-specific formatting information.\n /// \n /// An interface implementation that supplies\n /// culture-specific formatting information. \n /// \n /// A number equivalent to the value of this instance.\n /// \n decimal IConvertible.ToDecimal(IFormatProvider provider)\n {\n return ((IConvertible)_value).ToDecimal(provider);\n }\n\n /// \n /// Converts the value of this instance to an equivalent double-precision floating-point number using the specified culture-specific formatting information.\n /// \n /// An interface implementation that supplies\n /// culture-specific formatting information.\n /// \n /// A double-precision floating-point number equivalent to the value of this instance.\n /// \n double IConvertible.ToDouble(IFormatProvider provider)\n {\n return ((IConvertible)_value).ToDouble(provider);\n }\n\n /// \n /// Converts the value of this instance to an equivalent 16-bit signed integer using the specified culture-specific formatting information.\n /// \n /// An interface implementation that supplies\n /// culture-specific formatting information.\n /// \n /// An 16-bit signed integer equivalent to the value of this instance.\n /// \n short IConvertible.ToInt16(IFormatProvider provider)\n {\n return ((IConvertible)_value).ToInt16(provider);\n }\n\n /// \n /// Converts the value of this instance to an equivalent 32-bit signed integer using the specified culture-specific formatting information.\n /// \n /// An interface implementation that supplies\n /// culture-specific formatting information.\n /// \n /// An 32-bit signed integer equivalent to the value of this instance.\n /// \n int IConvertible.ToInt32(IFormatProvider provider)\n {\n return ((IConvertible)_value).ToInt32(provider);\n }\n\n /// \n /// Converts the value of this instance to an equivalent 64-bit signed integer using the specified culture-specific formatting information.\n /// \n /// An interface implementation that supplies\n /// culture-specific formatting information.\n /// \n /// An 64-bit signed integer equivalent to the value of this instance.\n /// \n long IConvertible.ToInt64(IFormatProvider provider)\n {\n return ((IConvertible)_value).ToInt64(provider);\n }\n\n /// \n /// Converts the value of this instance to an equivalent 8-bit signed integer using the specified culture-specific formatting information.\n /// \n /// An interface implementation that supplies\n /// culture-specific formatting information.\n /// \n /// An 8-bit signed integer equivalent to the value of this instance.\n /// \n sbyte IConvertible.ToSByte(IFormatProvider provider)\n {\n return ((IConvertible)_value).ToSByte(provider);\n }\n\n /// \n /// Converts the value of this instance to an equivalent single-precision floating-point number using the specified culture-specific formatting information.\n /// \n /// An interface implementation that supplies\n /// culture-specific formatting information. \n /// \n /// A single-precision floating-point number equivalent to the value of this instance.\n /// \n float IConvertible.ToSingle(IFormatProvider provider)\n {\n return ((IConvertible)_value).ToSingle(provider);\n }\n\n /// \n /// Converts the value of this instance to an equivalent using the specified culture-specific formatting information.\n /// \n /// An interface implementation that supplies\n /// culture-specific formatting information.\n /// \n /// A instance equivalent to the value of this instance.\n /// \n public string ToString(IFormatProvider provider)\n {\n return ((IConvertible)_value).ToString(provider);\n }\n\n /// \n /// Converts the value of this instance to an of the specified that has an equivalent value, using the specified culture-specific formatting information.\n /// \n /// The to which the value of this instance is converted.\n /// An interface implementation that supplies\n /// culture-specific formatting information.\n /// \n /// An instance of type whose value is equivalent to the value of this instance.\n /// \n object IConvertible.ToType(Type conversionType, IFormatProvider provider)\n {\n return ((IConvertible)_value).ToType(conversionType, provider);\n }\n\n /// \n /// Converts the value of this instance to an equivalent 16-bit unsigned integer using the specified culture-specific formatting information.\n /// \n /// An interface implementation that supplies\n /// culture-specific formatting information.\n /// \n /// An 16-bit unsigned integer equivalent to the value of this instance.\n /// \n ushort IConvertible.ToUInt16(IFormatProvider provider)\n {\n return ((IConvertible)_value).ToUInt16(provider);\n }\n\n /// \n /// Converts the value of this instance to an equivalent 32-bit unsigned integer using the specified culture-specific formatting information.\n /// \n /// An interface implementation that supplies\n /// culture-specific formatting information.\n /// \n /// An 32-bit unsigned integer equivalent to the value of this instance.\n /// \n uint IConvertible.ToUInt32(IFormatProvider provider)\n {\n return ((IConvertible)_value).ToUInt32(provider);\n }\n\n /// \n /// Converts the value of this instance to an equivalent 64-bit unsigned integer using the specified culture-specific formatting information.\n /// \n /// An interface implementation that supplies\n /// culture-specific formatting information.\n /// \n /// An 64-bit unsigned integer equivalent to the value of this instance.\n /// \n ulong IConvertible.ToUInt64(IFormatProvider provider)\n {\n return ((IConvertible)_value).ToUInt64(provider);\n }\n\n #endregion\n\n #region IEquatable Members\n\n /// \n /// Indicates whether the current object is equal to another object of the same type.\n /// \n /// An object to compare with this object.\n /// \n /// true if the current object is equal to the parameter; otherwise, false.\n /// \n public bool Equals(int other)\n {\n return _value.Equals(other);\n }\n\n #endregion\n\n #region IFormattable Members\n\n /// \n /// Formats the value of the current instance using the specified format.\n /// \n /// The specifying the format to use.\n /// -or- \n /// null to use the default format defined for the type of the implementation. \n /// \n /// The to use to format the value.\n /// -or- \n /// null to obtain the numeric format information from the current locale setting of the operating system. \n /// \n /// \n /// A containing the value of the current instance in the specified format.\n /// \n public string ToString(string format, IFormatProvider formatProvider)\n {\n return _value.ToString(format, formatProvider);\n }\n\n #endregion\n\n /// \n /// Implements operator ++.\n /// \n /// The AccountID to increment.\n /// The incremented AccountID.\n public static AccountID operator ++(AccountID l)\n {\n return new AccountID(l._value + 1);\n }\n\n /// \n /// Implements operator --.\n /// \n /// The AccountID to decrement.\n /// The decremented AccountID.\n public static AccountID operator --(AccountID l)\n {\n return new AccountID(l._value - 1);\n }\n\n /// \n /// Implements operator +.\n /// \n /// Left side argument.\n /// Right side argument.\n /// Result of the left side plus the right side.\n public static AccountID operator +(AccountID left, AccountID right)\n {\n return new AccountID(left._value + right._value);\n }\n\n /// \n /// Implements operator -.\n /// \n /// Left side argument.\n /// Right side argument.\n /// Result of the left side minus the right side.\n public static AccountID operator -(AccountID left, AccountID right)\n {\n return new AccountID(left._value - right._value);\n }\n\n /// \n /// Implements operator ==.\n /// \n /// Left side argument.\n /// Right side argument.\n /// If the two arguments are equal.\n public static bool operator ==(AccountID left, int right)\n {\n return left._value == right;\n }\n\n /// \n /// Implements operator !=.\n /// \n /// Left side argument.\n /// Right side argument.\n /// If the two arguments are not equal.\n public static bool operator !=(AccountID left, int right)\n {\n return left._value != right;\n }\n\n /// \n /// Implements operator ==.\n /// \n /// Left side argument.\n /// Right side argument.\n /// If the two arguments are equal.\n public static bool operator ==(int left, AccountID right)\n {\n return left == right._value;\n }\n\n /// \n /// Implements operator !=.\n /// \n /// Left side argument.\n /// Right side argument.\n /// If the two arguments are not equal.\n public static bool operator !=(int left, AccountID right)\n {\n return left != right._value;\n }\n\n /// \n /// Casts a AccountID to an Int32.\n /// \n /// AccountID to cast.\n /// The Int32.\n public static explicit operator int(AccountID AccountID)\n {\n return AccountID._value;\n }\n\n /// \n /// Casts an Int32 to a AccountID.\n /// \n /// Int32 to cast.\n /// The AccountID.\n public static explicit operator AccountID(int value)\n {\n return new AccountID(value);\n }\n\n /// \n /// Implements the operator &gt;.\n /// \n /// Left side argument.\n /// Right side argument.\n /// If the left argument is greater than the right.\n public static bool operator >(int left, AccountID right)\n {\n return left > right._value;\n }\n\n /// \n /// Implements the operator &lt;.\n /// \n /// Left side argument.\n /// Right side argument.\n /// If the right argument is greater than the left.\n public static bool operator <(int left, AccountID right)\n {\n return left < right._value;\n }\n\n /// \n /// Implements the operator &gt;.\n /// \n /// Left side argument.\n /// Right side argument.\n /// If the left argument is greater than the right.\n public static bool operator >(AccountID left, AccountID right)\n {\n return left._value > right._value;\n }\n\n /// \n /// Implements the operator &lt;.\n /// \n /// Left side argument.\n /// Right side argument.\n /// If the right argument is greater than the left.\n public static bool operator <(AccountID left, AccountID right)\n {\n return left._value < right._value;\n }\n\n /// \n /// Implements the operator &gt;.\n /// \n /// Left side argument.\n /// Right side argument.\n /// If the left argument is greater than the right.\n public static bool operator >(AccountID left, int right)\n {\n return left._value > right;\n }\n\n /// \n /// Implements the operator &lt;.\n /// \n /// Left side argument.\n /// Right side argument.\n /// If the right argument is greater than the left.\n public static bool operator <(AccountID left, int right)\n {\n return left._value < right;\n }\n\n /// \n /// Implements the operator &gt;=.\n /// \n /// Left side argument.\n /// Right side argument.\n /// If the left argument is greater than or equal to the right.\n public static bool operator >=(int left, AccountID right)\n {\n return left >= right._value;\n }\n\n /// \n /// Implements the operator &lt;=.\n /// \n /// Left side argument.\n /// Right side argument.\n /// If the right argument is greater than or equal to the left.\n public static bool operator <=(int left, AccountID right)\n {\n return left <= right._value;\n }\n\n /// \n /// Implements the operator &gt;=.\n /// \n /// Left side argument.\n /// Right side argument.\n /// If the left argument is greater than or equal to the right.\n public static bool operator >=(AccountID left, int right)\n {\n return left._value >= right;\n }\n\n /// \n /// Implements the operator &lt;=.\n /// \n /// Left side argument.\n /// Right side argument.\n /// If the right argument is greater than or equal to the left.\n public static bool operator <=(AccountID left, int right)\n {\n return left._value <= right;\n }\n\n /// \n /// Implements the operator &gt;=.\n /// \n /// Left side argument.\n /// Right side argument.\n /// If the left argument is greater than or equal to the right.\n public static bool operator >=(AccountID left, AccountID right)\n {\n return left._value >= right._value;\n }\n\n /// \n /// Implements the operator &lt;=.\n /// \n /// Left side argument.\n /// Right side argument.\n /// If the right argument is greater than or equal to the left.\n public static bool operator <=(AccountID left, AccountID right)\n {\n return left._value <= right._value;\n }\n\n /// \n /// Implements operator !=.\n /// \n /// Left side argument.\n /// Right side argument.\n /// If the two arguments are not equal.\n public static bool operator !=(AccountID left, AccountID right)\n {\n return left._value != right._value;\n }\n\n /// \n /// Implements operator ==.\n /// \n /// Left side argument.\n /// Right side argument.\n /// If the two arguments are equal.\n public static bool operator ==(AccountID left, AccountID right)\n {\n return left._value == right._value;\n }\n }\n\n /// \n /// Adds extensions to some data I/O objects for performing Read and Write operations for the AccountID.\n /// All of the operations are implemented in the AccountID struct. These extensions are provided\n /// purely for the convenience of accessing all the I/O operations from the same place.\n /// \n public static class AccountIDReadWriteExtensions\n {\n /// \n /// Gets the value in the entry at the given as type AccountID.\n /// \n /// The key Type.\n /// The .\n /// The key for the value to get.\n /// The value at the given parsed as a AccountID.\n public static AccountID AsAccountID(this IDictionary dict, T key)\n {\n return Parser.Invariant.ParseAccountID(dict[key]);\n }\n\n /// \n /// Tries to get the value in the entry at the given as type AccountID.\n /// \n /// The key Type.\n /// The IDictionary.\n /// The key for the value to get.\n /// The value to use if the value at the could not be parsed.\n /// The value at the given parsed as an int, or the\n /// if the did not exist in the \n /// or the value at the given could not be parsed.\n public static AccountID AsAccountID(this IDictionary dict, T key, AccountID defaultValue)\n {\n string value;\n if (!dict.TryGetValue(key, out value))\n return defaultValue;\n\n AccountID parsed;\n if (!Parser.Invariant.TryParse(value, out parsed))\n return defaultValue;\n\n return parsed;\n }\n\n /// \n /// Reads the AccountID from an .\n /// \n /// to read the AccountID from.\n /// The field index to read.\n /// The AccountID read from the .\n public static AccountID GetAccountID(this IDataRecord r, int i)\n {\n return AccountID.Read(r, i);\n }\n\n /// \n /// Reads the AccountID from an .\n /// \n /// to read the AccountID from.\n /// The name of the field to read the value from.\n /// The AccountID read from the .\n public static AccountID GetAccountID(this IDataRecord r, string name)\n {\n return AccountID.Read(r, name);\n }\n\n /// \n /// Parses the AccountID from a string.\n /// \n /// The Parser to use.\n /// The string to parse.\n /// The AccountID parsed from the string.\n public static AccountID ParseAccountID(this Parser parser, string value)\n {\n return new AccountID(parser.ParseInt(value));\n }\n\n /// \n /// Reads the AccountID from a BitStream.\n /// \n /// BitStream to read the AccountID from.\n /// The AccountID read from the BitStream.\n public static AccountID ReadAccountID(this BitStream bitStream)\n {\n return AccountID.Read(bitStream);\n }\n\n /// \n /// Reads the AccountID from an IValueReader.\n /// \n /// IValueReader to read the AccountID from.\n /// The unique name of the value to read.\n /// The AccountID read from the IValueReader.\n public static AccountID ReadAccountID(this IValueReader valueReader, string name)\n {\n return AccountID.Read(valueReader, name);\n }\n\n /// \n /// Tries to parse the AccountID from a string.\n /// \n /// The Parser to use.\n /// The string to parse.\n /// If this method returns true, contains the parsed AccountID.\n /// True if the parsing was successfully; otherwise false.\n public static bool TryParse(this Parser parser, string value, out AccountID outValue)\n {\n int tmp;\n var ret = parser.TryParse(value, out tmp);\n outValue = new AccountID(tmp);\n return ret;\n }\n\n /// \n /// Writes a AccountID to a BitStream.\n /// \n /// BitStream to write to.\n /// AccountID to write.\n public static void Write(this BitStream bitStream, AccountID value)\n {\n value.Write(bitStream);\n }\n\n /// \n /// Writes a AccountID to a IValueWriter.\n /// \n /// IValueWriter to write to.\n /// Unique name of the AccountID that will be used to distinguish it\n /// from other values when reading.\n /// AccountID to write.\n public static void Write(this IValueWriter valueWriter, string name, AccountID value)\n {\n value.Write(valueWriter, name);\n }\n }\n}\n"},"gt":{"kind":"string","value":""}}},{"rowIdx":98459,"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.Data;\nusing System.Drawing;\nusing System.IO;\nusing System.Reflection;\nusing System.Threading;\nusing log4net;\nusing MySql.Data.MySqlClient;\nusing OpenMetaverse;\nusing OpenSim.Framework;\nusing OpenSim.Region.Framework.Interfaces;\nusing OpenSim.Region.Framework.Scenes;\n\nnamespace OpenSim.Data.MySQL\n{\n /// \n /// A MySQL Interface for the Region Server\n /// \n public class MySQLDataStore : IRegionDataStore\n {\n private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);\n\n private string m_ConnectionString;\n\n private MySqlConnection m_Connection = null;\n\n public void Initialise(string connectionString)\n {\n m_ConnectionString = connectionString;\n\n m_Connection = new MySqlConnection(m_ConnectionString);\n\n m_Connection.Open();\n\n // Apply new Migrations\n //\n Assembly assem = GetType().Assembly;\n Migration m = new Migration(m_Connection, assem, \"RegionStore\");\n m.Update();\n\n // Clean dropped attachments\n //\n MySqlCommand cmd = m_Connection.CreateCommand();\n cmd.CommandText = \"delete from prims, primshapes using prims \" +\n \"left join primshapes on prims.uuid = primshapes.uuid \" +\n \"where PCode = 9 and State <> 0\";\n ExecuteNonQuery(cmd);\n cmd.Dispose();\n }\n\n private IDataReader ExecuteReader(MySqlCommand c)\n {\n IDataReader r = null;\n bool errorSeen = false;\n\n while (true)\n {\n try\n {\n r = c.ExecuteReader();\n }\n catch (Exception)\n {\n Thread.Sleep(500);\n\n m_Connection.Close();\n m_Connection = (MySqlConnection) ((ICloneable)m_Connection).Clone();\n m_Connection.Open();\n c.Connection = m_Connection;\n\n if (!errorSeen)\n {\n errorSeen = true;\n continue;\n }\n throw;\n }\n\n break;\n }\n\n return r;\n }\n\n private void ExecuteNonQuery(MySqlCommand c)\n {\n bool errorSeen = false;\n\n while (true)\n {\n try\n {\n c.ExecuteNonQuery();\n }\n catch (Exception)\n {\n Thread.Sleep(500);\n\n m_Connection.Close();\n m_Connection = (MySqlConnection) ((ICloneable)m_Connection).Clone();\n m_Connection.Open();\n c.Connection = m_Connection;\n\n if (!errorSeen)\n {\n errorSeen = true;\n continue;\n }\n throw;\n }\n\n break;\n }\n }\n\n public void Dispose() {}\n\n public void StoreObject(SceneObjectGroup obj, UUID regionUUID)\n {\n uint flags = obj.RootPart.GetEffectiveObjectFlags();\n\n // Eligibility check\n //\n if ((flags & (uint)PrimFlags.Temporary) != 0)\n return;\n if ((flags & (uint)PrimFlags.TemporaryOnRez) != 0)\n return;\n\n lock (m_Connection)\n {\n MySqlCommand cmd = m_Connection.CreateCommand();\n\n foreach (SceneObjectPart prim in obj.Children.Values)\n {\n cmd.Parameters.Clear();\n\n cmd.CommandText = \"replace into prims (\"+\n \"UUID, CreationDate, \"+\n \"Name, Text, Description, \"+\n \"SitName, TouchName, ObjectFlags, \"+\n \"OwnerMask, NextOwnerMask, GroupMask, \"+\n \"EveryoneMask, BaseMask, PositionX, \"+\n \"PositionY, PositionZ, GroupPositionX, \"+\n \"GroupPositionY, GroupPositionZ, VelocityX, \"+\n \"VelocityY, VelocityZ, AngularVelocityX, \"+\n \"AngularVelocityY, AngularVelocityZ, \"+\n \"AccelerationX, AccelerationY, \"+\n \"AccelerationZ, RotationX, \"+\n \"RotationY, RotationZ, \"+\n \"RotationW, SitTargetOffsetX, \"+\n \"SitTargetOffsetY, SitTargetOffsetZ, \"+\n \"SitTargetOrientW, SitTargetOrientX, \"+\n \"SitTargetOrientY, SitTargetOrientZ, \"+\n \"RegionUUID, CreatorID, \"+\n \"OwnerID, GroupID, \"+\n \"LastOwnerID, SceneGroupID, \"+\n \"PayPrice, PayButton1, \"+\n \"PayButton2, PayButton3, \"+\n \"PayButton4, LoopedSound, \"+\n \"LoopedSoundGain, TextureAnimation, \"+\n \"OmegaX, OmegaY, OmegaZ, \"+\n \"CameraEyeOffsetX, CameraEyeOffsetY, \"+\n \"CameraEyeOffsetZ, CameraAtOffsetX, \"+\n \"CameraAtOffsetY, CameraAtOffsetZ, \"+\n \"ForceMouselook, ScriptAccessPin, \"+\n \"AllowedDrop, DieAtEdge, \"+\n \"SalePrice, SaleType, \"+\n \"ColorR, ColorG, ColorB, ColorA, \"+\n \"ParticleSystem, ClickAction, Material, \"+\n \"CollisionSound, CollisionSoundVolume, \"+\n \"PassTouches, \"+\n \"LinkNumber) values (\" + \"?UUID, \"+\n \"?CreationDate, ?Name, ?Text, \"+\n \"?Description, ?SitName, ?TouchName, \"+\n \"?ObjectFlags, ?OwnerMask, ?NextOwnerMask, \"+\n \"?GroupMask, ?EveryoneMask, ?BaseMask, \"+\n \"?PositionX, ?PositionY, ?PositionZ, \"+\n \"?GroupPositionX, ?GroupPositionY, \"+\n \"?GroupPositionZ, ?VelocityX, \"+\n \"?VelocityY, ?VelocityZ, ?AngularVelocityX, \"+\n \"?AngularVelocityY, ?AngularVelocityZ, \"+\n \"?AccelerationX, ?AccelerationY, \"+\n \"?AccelerationZ, ?RotationX, \"+\n \"?RotationY, ?RotationZ, \"+\n \"?RotationW, ?SitTargetOffsetX, \"+\n \"?SitTargetOffsetY, ?SitTargetOffsetZ, \"+\n \"?SitTargetOrientW, ?SitTargetOrientX, \"+\n \"?SitTargetOrientY, ?SitTargetOrientZ, \"+\n \"?RegionUUID, ?CreatorID, ?OwnerID, \"+\n \"?GroupID, ?LastOwnerID, ?SceneGroupID, \"+\n \"?PayPrice, ?PayButton1, ?PayButton2, \"+\n \"?PayButton3, ?PayButton4, ?LoopedSound, \"+\n \"?LoopedSoundGain, ?TextureAnimation, \"+\n \"?OmegaX, ?OmegaY, ?OmegaZ, \"+\n \"?CameraEyeOffsetX, ?CameraEyeOffsetY, \"+\n \"?CameraEyeOffsetZ, ?CameraAtOffsetX, \"+\n \"?CameraAtOffsetY, ?CameraAtOffsetZ, \"+\n \"?ForceMouselook, ?ScriptAccessPin, \"+\n \"?AllowedDrop, ?DieAtEdge, ?SalePrice, \"+\n \"?SaleType, ?ColorR, ?ColorG, \"+\n \"?ColorB, ?ColorA, ?ParticleSystem, \"+\n \"?ClickAction, ?Material, ?CollisionSound, \"+\n \"?CollisionSoundVolume, ?PassTouches, ?LinkNumber)\";\n\n FillPrimCommand(cmd, prim, obj.UUID, regionUUID);\n\n ExecuteNonQuery(cmd);\n\n cmd.Parameters.Clear();\n\n cmd.CommandText = \"replace into primshapes (\"+\n \"UUID, Shape, ScaleX, ScaleY, \"+\n \"ScaleZ, PCode, PathBegin, PathEnd, \"+\n \"PathScaleX, PathScaleY, PathShearX, \"+\n \"PathShearY, PathSkew, PathCurve, \"+\n \"PathRadiusOffset, PathRevolutions, \"+\n \"PathTaperX, PathTaperY, PathTwist, \"+\n \"PathTwistBegin, ProfileBegin, ProfileEnd, \"+\n \"ProfileCurve, ProfileHollow, Texture, \"+\n \"ExtraParams, State) values (?UUID, \"+\n \"?Shape, ?ScaleX, ?ScaleY, ?ScaleZ, \"+\n \"?PCode, ?PathBegin, ?PathEnd, \"+\n \"?PathScaleX, ?PathScaleY, \"+\n \"?PathShearX, ?PathShearY, \"+\n \"?PathSkew, ?PathCurve, ?PathRadiusOffset, \"+\n \"?PathRevolutions, ?PathTaperX, \"+\n \"?PathTaperY, ?PathTwist, \"+\n \"?PathTwistBegin, ?ProfileBegin, \"+\n \"?ProfileEnd, ?ProfileCurve, \"+\n \"?ProfileHollow, ?Texture, ?ExtraParams, \"+\n \"?State)\";\n\n FillShapeCommand(cmd, prim);\n\n ExecuteNonQuery(cmd);\n }\n cmd.Dispose();\n }\n }\n\n public void RemoveObject(UUID obj, UUID regionUUID)\n {\n // Formerly, this used to check the region UUID.\n // That makes no sense, as we remove the contents of a prim\n // unconditionally, but the prim dependent on the region ID.\n // So, we would destroy an object and cause hard to detect\n // issues if we delete the contents only. Deleting it all may\n // cause the loss of a prim, but is cleaner.\n // It's also faster because it uses the primary key.\n //\n lock (m_Connection)\n {\n MySqlCommand cmd = m_Connection.CreateCommand();\n\n cmd.CommandText = \"select UUID from prims where \"+\n \"SceneGroupID= ?UUID\";\n\n cmd.Parameters.AddWithValue(\"UUID\", obj.ToString());\n\n List uuids = new List();\n\n IDataReader reader = ExecuteReader(cmd);\n\n try\n {\n while (reader.Read())\n {\n uuids.Add(new UUID(reader[\"UUID\"].ToString()));\n }\n }\n finally\n {\n reader.Close();\n }\n\n // delete the main prims\n cmd.CommandText = \"delete from prims where SceneGroupID= ?UUID\";\n ExecuteNonQuery(cmd);\n cmd.Dispose();\n\n // there is no way this should be < 1 unless there is\n // a very corrupt database, but in that case be extra\n // safe anyway.\n if (uuids.Count > 0) \n {\n RemoveShapes(uuids);\n RemoveItems(uuids);\n }\n }\n }\n\n /// \n /// Remove all persisted items of the given prim.\n /// The caller must acquire the necessrary synchronization locks\n /// \n /// the Item UUID\n private void RemoveItems(UUID uuid)\n {\n lock (m_Connection)\n {\n MySqlCommand cmd = m_Connection.CreateCommand();\n\n cmd.CommandText = \"delete from primitems where \" +\n \"PrimID = ?PrimID\";\n\n cmd.Parameters.AddWithValue(\"PrimID\", uuid.ToString());\n\n ExecuteNonQuery(cmd);\n cmd.Dispose();\n }\n }\n\n\n /// \n /// Remove all persisted shapes for a list of prims\n /// The caller must acquire the necessrary synchronization locks\n /// \n /// the list of UUIDs\n private void RemoveShapes(List uuids)\n {\n lock (m_Connection)\n {\n string sql = \"delete from primshapes where \";\n MySqlCommand cmd = m_Connection.CreateCommand();\n \n for (int i = 0; i < uuids.Count; i++)\n {\n if ((i + 1) == uuids.Count) \n {// end of the list\n sql += \"(UUID = ?UUID\" + i + \")\";\n }\n else\n {\n sql += \"(UUID = ?UUID\" + i + \") or \";\n }\n }\n cmd.CommandText = sql;\n\n for (int i = 0; i < uuids.Count; i++)\n {\n cmd.Parameters.AddWithValue(\"UUID\" + i, uuids[i].ToString());\n }\n\n ExecuteNonQuery(cmd);\n cmd.Dispose();\n }\n }\n\n /// \n /// Remove all persisted items for a list of prims\n /// The caller must acquire the necessrary synchronization locks\n /// \n /// the list of UUIDs\n private void RemoveItems(List uuids)\n {\n lock (m_Connection)\n {\n string sql = \"delete from primitems where \";\n MySqlCommand cmd = m_Connection.CreateCommand();\n \n for (int i = 0; i < uuids.Count; i++)\n {\n if ((i + 1) == uuids.Count) \n {// end of the list\n sql += \"(PrimID = ?PrimID\" + i + \")\";\n }\n else\n {\n sql += \"(PrimID = ?PrimID\" + i + \") or \";\n }\n }\n cmd.CommandText = sql;\n\n for (int i = 0; i < uuids.Count; i++)\n {\n cmd.Parameters.AddWithValue(\"PrimID\" + i, uuids[i].ToString());\n }\n\n ExecuteNonQuery(cmd);\n cmd.Dispose();\n }\n }\n\n public List LoadObjects(UUID regionUUID)\n {\n UUID lastGroupID = UUID.Zero;\n List objects = new List();\n List prims = new List();\n SceneObjectGroup grp = null;\n\n lock (m_Connection)\n {\n MySqlCommand cmd = m_Connection.CreateCommand();\n\n cmd.CommandText = \"select *, \" +\n \"case when prims.UUID = SceneGroupID \" +\n \"then 0 else 1 end as sort from prims \" +\n \"left join primshapes on prims.UUID = primshapes.UUID \"+\n \"where RegionUUID = ?RegionUUID \" +\n \"order by SceneGroupID asc, sort asc, LinkNumber asc\";\n \n cmd.Parameters.AddWithValue(\"RegionUUID\", regionUUID.ToString());\n\n IDataReader reader = ExecuteReader(cmd);\n\n try\n {\n while (reader.Read())\n {\n SceneObjectPart prim = BuildPrim(reader);\n if (reader[\"Shape\"] is DBNull)\n prim.Shape = PrimitiveBaseShape.Default;\n else\n prim.Shape = BuildShape(reader);\n\n prims.Add(prim);\n\n UUID groupID = new UUID(reader[\"SceneGroupID\"].ToString());\n\n if (groupID != lastGroupID) // New SOG\n {\n if (grp != null)\n objects.Add(grp);\n\n lastGroupID = groupID;\n \n // There sometimes exist OpenSim bugs that 'orphan groups' so that none of the prims are\n // recorded as the root prim (for which the UUID must equal the persisted group UUID). In\n // this case, force the UUID to be the same as the group UUID so that at least these can be\n // deleted (we need to change the UUID so that any other prims in the linkset can also be \n // deleted).\n if (prim.UUID != groupID && groupID != UUID.Zero)\n {\n m_log.WarnFormat(\n \"[REGION DB]: Found root prim {0} {1} at {2} where group was actually {3}. Forcing UUID to group UUID\", \n prim.Name, prim.UUID, prim.GroupPosition, groupID);\n \n prim.UUID = groupID;\n } \n\n grp = new SceneObjectGroup(prim);\n }\n else\n {\n // Black magic to preserve link numbers\n //\n int link = prim.LinkNum;\n\n grp.AddPart(prim);\n\n if (link != 0)\n prim.LinkNum = link;\n }\n }\n }\n finally\n {\n reader.Close();\n }\n\n if (grp != null)\n objects.Add(grp);\n cmd.Dispose();\n }\n\n foreach (SceneObjectPart part in prims)\n LoadItems(part);\n\n m_log.DebugFormat(\"[REGION DB]: Loaded {0} objects using {1} prims\", objects.Count, prims.Count);\n\n return objects;\n }\n\n /// \n /// Load in a prim's persisted inventory.\n /// \n /// The prim \n private void LoadItems(SceneObjectPart prim)\n {\n lock (m_Connection)\n {\n MySqlCommand cmd = m_Connection.CreateCommand();\n\n cmd.CommandText = \"select * from primitems where \"+\n \"PrimID = ?PrimID\";\n\n cmd.Parameters.AddWithValue(\"PrimID\", prim.UUID.ToString());\n\n IDataReader reader = ExecuteReader(cmd);\n List inventory =\n new List();\n\n try\n {\n while (reader.Read())\n {\n TaskInventoryItem item = BuildItem(reader);\n\n item.ParentID = prim.UUID; // Values in database are\n // often wrong\n inventory.Add(item);\n }\n }\n finally\n {\n reader.Close();\n }\n\n cmd.Dispose();\n prim.Inventory.RestoreInventoryItems(inventory);\n }\n }\n\n public void StoreTerrain(double[,] ter, UUID regionID)\n {\n m_log.Info(\"[REGION DB]: Storing terrain\");\n\n lock (m_Connection)\n {\n MySqlCommand cmd = m_Connection.CreateCommand();\n\n cmd.CommandText = \"delete from terrain where \" +\n \"RegionUUID = ?RegionUUID\";\n cmd.Parameters.AddWithValue(\"RegionUUID\", regionID.ToString());\n\n ExecuteNonQuery(cmd);\n \n cmd.CommandText = \"insert into terrain (RegionUUID, \" +\n \"Revision, Heightfield) values (?RegionUUID, \" +\n \"1, ?Heightfield)\";\n\n cmd.Parameters.AddWithValue(\"Heightfield\",\n SerializeTerrain(ter));\n \n ExecuteNonQuery(cmd);\n cmd.Dispose();\n }\n }\n\n public double[,] LoadTerrain(UUID regionID)\n {\n double[,] terrain = null;\n\n lock (m_Connection)\n {\n MySqlCommand cmd = m_Connection.CreateCommand();\n cmd.CommandText = \"select RegionUUID, Revision, Heightfield \" +\n \"from terrain where RegionUUID = ?RegionUUID \"+\n \"order by Revision desc limit 1\";\n cmd.Parameters.AddWithValue(\"RegionUUID\", regionID.ToString());\n\n IDataReader reader = ExecuteReader(cmd);\n\n try\n {\n while (reader.Read())\n {\n terrain = new double[(int)Constants.RegionSize, (int)Constants.RegionSize];\n terrain.Initialize();\n\n MemoryStream mstr = new MemoryStream((byte[]) reader[\"Heightfield\"]);\n int rev = 0;\n\n BinaryReader br = new BinaryReader(mstr);\n for (int x = 0; x < (int)Constants.RegionSize; x++)\n {\n for (int y = 0; y < (int)Constants.RegionSize; y++)\n {\n terrain[x, y] = br.ReadDouble();\n }\n rev = Convert.ToInt32(reader[\"Revision\"]);\n }\n m_log.InfoFormat(\"[REGION DB]: Loaded terrain \" +\n \"revision r{0}\", rev);\n }\n }\n finally\n {\n reader.Close();\n }\n cmd.Dispose();\n }\n\n return terrain;\n }\n\n public void RemoveLandObject(UUID globalID)\n {\n lock (m_Connection)\n {\n MySqlCommand cmd = m_Connection.CreateCommand();\n\n cmd.CommandText = \"delete from land where UUID = ?UUID\";\n\n cmd.Parameters.AddWithValue(\"UUID\", globalID.ToString());\n\n ExecuteNonQuery(cmd);\n cmd.Dispose();\n }\n }\n\n public void StoreLandObject(ILandObject parcel)\n {\n lock (m_Connection)\n {\n MySqlCommand cmd = m_Connection.CreateCommand();\n\n cmd.CommandText = \"replace into land (UUID, RegionUUID, \" +\n \"LocalLandID, Bitmap, Name, Description, \" +\n \"OwnerUUID, IsGroupOwned, Area, AuctionID, \" +\n \"Category, ClaimDate, ClaimPrice, GroupUUID, \" +\n \"SalePrice, LandStatus, LandFlags, LandingType, \" +\n \"MediaAutoScale, MediaTextureUUID, MediaURL, \" +\n \"MusicURL, PassHours, PassPrice, SnapshotUUID, \" +\n \"UserLocationX, UserLocationY, UserLocationZ, \" +\n \"UserLookAtX, UserLookAtY, UserLookAtZ, \" +\n \"AuthbuyerID, OtherCleanTime, Dwell) values (\" +\n \"?UUID, ?RegionUUID, \" +\n \"?LocalLandID, ?Bitmap, ?Name, ?Description, \" +\n \"?OwnerUUID, ?IsGroupOwned, ?Area, ?AuctionID, \" +\n \"?Category, ?ClaimDate, ?ClaimPrice, ?GroupUUID, \" +\n \"?SalePrice, ?LandStatus, ?LandFlags, ?LandingType, \" +\n \"?MediaAutoScale, ?MediaTextureUUID, ?MediaURL, \" +\n \"?MusicURL, ?PassHours, ?PassPrice, ?SnapshotUUID, \" +\n \"?UserLocationX, ?UserLocationY, ?UserLocationZ, \" +\n \"?UserLookAtX, ?UserLookAtY, ?UserLookAtZ, \" +\n \"?AuthbuyerID, ?OtherCleanTime, ?Dwell)\";\n\n FillLandCommand(cmd, parcel.landData, parcel.regionUUID);\n\n ExecuteNonQuery(cmd);\n\n cmd.CommandText = \"delete from landaccesslist where \" +\n \"LandUUID = ?UUID\";\n\n ExecuteNonQuery(cmd);\n\n cmd.Parameters.Clear();\n cmd.CommandText = \"insert into landaccesslist (LandUUID, \" +\n \"AccessUUID, Flags) values (?LandUUID, ?AccessUUID, \" +\n \"?Flags)\";\n\n foreach (ParcelManager.ParcelAccessEntry entry in\n parcel.landData.ParcelAccessList)\n {\n FillLandAccessCommand(cmd, entry, parcel.landData.GlobalID);\n ExecuteNonQuery(cmd);\n cmd.Parameters.Clear();\n }\n cmd.Dispose();\n }\n }\n\n public RegionSettings LoadRegionSettings(UUID regionUUID)\n {\n RegionSettings rs = null;\n\n lock (m_Connection)\n {\n MySqlCommand cmd = m_Connection.CreateCommand();\n\n cmd.CommandText = \"select * from regionsettings where \" +\n \"regionUUID = ?RegionUUID\";\n cmd.Parameters.AddWithValue(\"regionUUID\", regionUUID);\n\n IDataReader reader = ExecuteReader(cmd);\n\n try\n {\n if (reader.Read())\n {\n rs = BuildRegionSettings(reader);\n rs.OnSave += StoreRegionSettings;\n }\n else\n {\n rs = new RegionSettings();\n rs.RegionUUID = regionUUID;\n rs.OnSave += StoreRegionSettings;\n\n StoreRegionSettings(rs);\n }\n }\n finally\n {\n reader.Close();\n }\n cmd.Dispose();\n }\n\n return rs;\n }\n\n public void StoreRegionSettings(RegionSettings rs)\n {\n lock (m_Connection)\n {\n MySqlCommand cmd = m_Connection.CreateCommand();\n\n cmd.CommandText = \"replace into regionsettings (regionUUID, \" +\n \"block_terraform, block_fly, allow_damage, \" +\n \"restrict_pushing, allow_land_resell, \" +\n \"allow_land_join_divide, block_show_in_search, \" +\n \"agent_limit, object_bonus, maturity, \" +\n \"disable_scripts, disable_collisions, \" +\n \"disable_physics, terrain_texture_1, \" +\n \"terrain_texture_2, terrain_texture_3, \" +\n \"terrain_texture_4, elevation_1_nw, \" +\n \"elevation_2_nw, elevation_1_ne, \" +\n \"elevation_2_ne, elevation_1_se, \"+\n \"elevation_2_se, elevation_1_sw, \"+\n \"elevation_2_sw, water_height, \" +\n \"terrain_raise_limit, terrain_lower_limit, \" +\n \"use_estate_sun, fixed_sun, sun_position, \" +\n \"covenant, Sandbox, sunvectorx, sunvectory, \" +\n \"sunvectorz, loaded_creation_datetime, \" +\n \"loaded_creation_id) values ( ?RegionUUID, ?BlockTerraform, \" +\n \"?BlockFly, ?AllowDamage, ?RestrictPushing, \" +\n \"?AllowLandResell, ?AllowLandJoinDivide, \" +\n \"?BlockShowInSearch, ?AgentLimit, ?ObjectBonus, \" +\n \"?Maturity, ?DisableScripts, ?DisableCollisions, \" +\n \"?DisablePhysics, ?TerrainTexture1, \" +\n \"?TerrainTexture2, ?TerrainTexture3, \" +\n \"?TerrainTexture4, ?Elevation1NW, ?Elevation2NW, \" +\n \"?Elevation1NE, ?Elevation2NE, ?Elevation1SE, \" +\n \"?Elevation2SE, ?Elevation1SW, ?Elevation2SW, \" +\n \"?WaterHeight, ?TerrainRaiseLimit, \" +\n \"?TerrainLowerLimit, ?UseEstateSun, ?FixedSun, \" +\n \"?SunPosition, ?Covenant, ?Sandbox, \" +\n \"?SunVectorX, ?SunVectorY, ?SunVectorZ, \" +\n \"?LoadedCreationDateTime, ?LoadedCreationID)\";\n\n FillRegionSettingsCommand(cmd, rs);\n\n ExecuteNonQuery(cmd);\n cmd.Dispose();\n\n }\n }\n\n public List LoadLandObjects(UUID regionUUID)\n {\n List landData = new List();\n\n lock (m_Connection)\n {\n MySqlCommand cmd = m_Connection.CreateCommand();\n\n cmd.CommandText = \"select * from land where \" +\n \"RegionUUID = ?RegionUUID\";\n\n cmd.Parameters.AddWithValue(\"RegionUUID\", regionUUID.ToString());\n\n IDataReader reader = ExecuteReader(cmd);\n\n try\n {\n while (reader.Read())\n {\n LandData newLand = BuildLandData(reader);\n landData.Add(newLand);\n }\n }\n finally\n {\n reader.Close();\n }\n\n foreach (LandData land in landData)\n {\n cmd.Parameters.Clear();\n\n cmd.CommandText = \"select * from landaccesslist \" +\n \"where LandUUID = ?LandUUID\";\n\n cmd.Parameters.AddWithValue(\"LandUUID\", land.GlobalID.ToString());\n\n reader = ExecuteReader(cmd);\n\n try\n {\n while (reader.Read())\n {\n land.ParcelAccessList.Add(BuildLandAccessData(reader));\n }\n }\n finally\n {\n reader.Close();\n }\n }\n cmd.Dispose();\n }\n\n return landData;\n }\n\n public void Shutdown()\n {\n }\n\n private SceneObjectPart BuildPrim(IDataReader row)\n {\n SceneObjectPart prim = new SceneObjectPart();\n prim.UUID = new UUID((String) row[\"UUID\"]);\n // explicit conversion of integers is required, which sort\n // of sucks. No idea if there is a shortcut here or not.\n prim.CreationDate = Convert.ToInt32(row[\"CreationDate\"]);\n if (row[\"Name\"] != DBNull.Value)\n prim.Name = (String)row[\"Name\"];\n else\n prim.Name = string.Empty;\n // various text fields\n prim.Text = (String) row[\"Text\"];\n prim.Color = Color.FromArgb(Convert.ToInt32(row[\"ColorA\"]),\n Convert.ToInt32(row[\"ColorR\"]),\n Convert.ToInt32(row[\"ColorG\"]),\n Convert.ToInt32(row[\"ColorB\"]));\n prim.Description = (String) row[\"Description\"];\n prim.SitName = (String) row[\"SitName\"];\n prim.TouchName = (String) row[\"TouchName\"];\n // permissions\n prim.ObjectFlags = Convert.ToUInt32(row[\"ObjectFlags\"]);\n prim.CreatorID = new UUID((String) row[\"CreatorID\"]);\n prim.OwnerID = new UUID((String) row[\"OwnerID\"]);\n prim.GroupID = new UUID((String) row[\"GroupID\"]);\n prim.LastOwnerID = new UUID((String) row[\"LastOwnerID\"]);\n prim.OwnerMask = Convert.ToUInt32(row[\"OwnerMask\"]);\n prim.NextOwnerMask = Convert.ToUInt32(row[\"NextOwnerMask\"]);\n prim.GroupMask = Convert.ToUInt32(row[\"GroupMask\"]);\n prim.EveryoneMask = Convert.ToUInt32(row[\"EveryoneMask\"]);\n prim.BaseMask = Convert.ToUInt32(row[\"BaseMask\"]);\n // vectors\n prim.OffsetPosition = new Vector3(\n Convert.ToSingle(row[\"PositionX\"]),\n Convert.ToSingle(row[\"PositionY\"]),\n Convert.ToSingle(row[\"PositionZ\"])\n );\n prim.GroupPosition = new Vector3(\n Convert.ToSingle(row[\"GroupPositionX\"]),\n Convert.ToSingle(row[\"GroupPositionY\"]),\n Convert.ToSingle(row[\"GroupPositionZ\"])\n );\n prim.Velocity = new Vector3(\n Convert.ToSingle(row[\"VelocityX\"]),\n Convert.ToSingle(row[\"VelocityY\"]),\n Convert.ToSingle(row[\"VelocityZ\"])\n );\n prim.AngularVelocity = new Vector3(\n Convert.ToSingle(row[\"AngularVelocityX\"]),\n Convert.ToSingle(row[\"AngularVelocityY\"]),\n Convert.ToSingle(row[\"AngularVelocityZ\"])\n );\n prim.Acceleration = new Vector3(\n Convert.ToSingle(row[\"AccelerationX\"]),\n Convert.ToSingle(row[\"AccelerationY\"]),\n Convert.ToSingle(row[\"AccelerationZ\"])\n );\n // quaternions\n prim.RotationOffset = new Quaternion(\n Convert.ToSingle(row[\"RotationX\"]),\n Convert.ToSingle(row[\"RotationY\"]),\n Convert.ToSingle(row[\"RotationZ\"]),\n Convert.ToSingle(row[\"RotationW\"])\n );\n prim.SitTargetPositionLL = new Vector3(\n Convert.ToSingle(row[\"SitTargetOffsetX\"]),\n Convert.ToSingle(row[\"SitTargetOffsetY\"]),\n Convert.ToSingle(row[\"SitTargetOffsetZ\"])\n );\n prim.SitTargetOrientationLL = new Quaternion(\n Convert.ToSingle(row[\"SitTargetOrientX\"]),\n Convert.ToSingle(row[\"SitTargetOrientY\"]),\n Convert.ToSingle(row[\"SitTargetOrientZ\"]),\n Convert.ToSingle(row[\"SitTargetOrientW\"])\n );\n\n prim.PayPrice[0] = Convert.ToInt32(row[\"PayPrice\"]);\n prim.PayPrice[1] = Convert.ToInt32(row[\"PayButton1\"]);\n prim.PayPrice[2] = Convert.ToInt32(row[\"PayButton2\"]);\n prim.PayPrice[3] = Convert.ToInt32(row[\"PayButton3\"]);\n prim.PayPrice[4] = Convert.ToInt32(row[\"PayButton4\"]);\n\n prim.Sound = new UUID(row[\"LoopedSound\"].ToString());\n prim.SoundGain = Convert.ToSingle(row[\"LoopedSoundGain\"]);\n prim.SoundFlags = 1; // If it's persisted at all, it's looped\n\n if (!(row[\"TextureAnimation\"] is DBNull))\n prim.TextureAnimation = (Byte[])row[\"TextureAnimation\"];\n if (!(row[\"ParticleSystem\"] is DBNull))\n prim.ParticleSystem = (Byte[])row[\"ParticleSystem\"];\n\n prim.RotationalVelocity = new Vector3(\n Convert.ToSingle(row[\"OmegaX\"]),\n Convert.ToSingle(row[\"OmegaY\"]),\n Convert.ToSingle(row[\"OmegaZ\"])\n );\n\n prim.SetCameraEyeOffset(new Vector3(\n Convert.ToSingle(row[\"CameraEyeOffsetX\"]),\n Convert.ToSingle(row[\"CameraEyeOffsetY\"]),\n Convert.ToSingle(row[\"CameraEyeOffsetZ\"])\n ));\n\n prim.SetCameraAtOffset(new Vector3(\n Convert.ToSingle(row[\"CameraAtOffsetX\"]),\n Convert.ToSingle(row[\"CameraAtOffsetY\"]),\n Convert.ToSingle(row[\"CameraAtOffsetZ\"])\n ));\n\n if (Convert.ToInt16(row[\"ForceMouselook\"]) != 0)\n prim.SetForceMouselook(true);\n\n prim.ScriptAccessPin = Convert.ToInt32(row[\"ScriptAccessPin\"]);\n\n if (Convert.ToInt16(row[\"AllowedDrop\"]) != 0)\n prim.AllowedDrop = true;\n\n if (Convert.ToInt16(row[\"DieAtEdge\"]) != 0)\n prim.DIE_AT_EDGE = true;\n\n prim.SalePrice = Convert.ToInt32(row[\"SalePrice\"]);\n prim.ObjectSaleType = unchecked((byte)Convert.ToSByte(row[\"SaleType\"]));\n\n prim.Material = unchecked((byte)Convert.ToSByte(row[\"Material\"]));\n\n if (!(row[\"ClickAction\"] is DBNull))\n prim.ClickAction = unchecked((byte)Convert.ToSByte(row[\"ClickAction\"]));\n\n prim.CollisionSound = new UUID(row[\"CollisionSound\"].ToString());\n prim.CollisionSoundVolume = Convert.ToSingle(row[\"CollisionSoundVolume\"]);\n \n if (Convert.ToInt16(row[\"PassTouches\"]) != 0)\n prim.PassTouches = true;\n prim.LinkNum = Convert.ToInt32(row[\"LinkNumber\"]);\n\n return prim;\n }\n\n\n /// \n /// Build a prim inventory item from the persisted data.\n /// \n /// \n /// \n private static TaskInventoryItem BuildItem(IDataReader row)\n {\n TaskInventoryItem taskItem = new TaskInventoryItem();\n\n taskItem.ItemID = new UUID((String)row[\"itemID\"]);\n taskItem.ParentPartID = new UUID((String)row[\"primID\"]);\n taskItem.AssetID = new UUID((String)row[\"assetID\"]);\n taskItem.ParentID = new UUID((String)row[\"parentFolderID\"]);\n\n taskItem.InvType = Convert.ToInt32(row[\"invType\"]);\n taskItem.Type = Convert.ToInt32(row[\"assetType\"]);\n\n taskItem.Name = (String)row[\"name\"];\n taskItem.Description = (String)row[\"description\"];\n taskItem.CreationDate = Convert.ToUInt32(row[\"creationDate\"]);\n taskItem.CreatorID = new UUID((String)row[\"creatorID\"]);\n taskItem.OwnerID = new UUID((String)row[\"ownerID\"]);\n taskItem.LastOwnerID = new UUID((String)row[\"lastOwnerID\"]);\n taskItem.GroupID = new UUID((String)row[\"groupID\"]);\n\n taskItem.NextPermissions = Convert.ToUInt32(row[\"nextPermissions\"]);\n taskItem.CurrentPermissions = Convert.ToUInt32(row[\"currentPermissions\"]);\n taskItem.BasePermissions = Convert.ToUInt32(row[\"basePermissions\"]);\n taskItem.EveryonePermissions = Convert.ToUInt32(row[\"everyonePermissions\"]);\n taskItem.GroupPermissions = Convert.ToUInt32(row[\"groupPermissions\"]);\n taskItem.Flags = Convert.ToUInt32(row[\"flags\"]);\n\n return taskItem;\n }\n\n private static RegionSettings BuildRegionSettings(IDataReader row)\n {\n RegionSettings newSettings = new RegionSettings();\n\n newSettings.RegionUUID = new UUID((string) row[\"regionUUID\"]);\n newSettings.BlockTerraform = Convert.ToBoolean(row[\"block_terraform\"]);\n newSettings.AllowDamage = Convert.ToBoolean(row[\"allow_damage\"]);\n newSettings.BlockFly = Convert.ToBoolean(row[\"block_fly\"]);\n newSettings.RestrictPushing = Convert.ToBoolean(row[\"restrict_pushing\"]);\n newSettings.AllowLandResell = Convert.ToBoolean(row[\"allow_land_resell\"]);\n newSettings.AllowLandJoinDivide = Convert.ToBoolean(row[\"allow_land_join_divide\"]);\n newSettings.BlockShowInSearch = Convert.ToBoolean(row[\"block_show_in_search\"]);\n newSettings.AgentLimit = Convert.ToInt32(row[\"agent_limit\"]);\n newSettings.ObjectBonus = Convert.ToDouble(row[\"object_bonus\"]);\n newSettings.Maturity = Convert.ToInt32(row[\"maturity\"]);\n newSettings.DisableScripts = Convert.ToBoolean(row[\"disable_scripts\"]);\n newSettings.DisableCollisions = Convert.ToBoolean(row[\"disable_collisions\"]);\n newSettings.DisablePhysics = Convert.ToBoolean(row[\"disable_physics\"]);\n newSettings.TerrainTexture1 = new UUID((String) row[\"terrain_texture_1\"]);\n newSettings.TerrainTexture2 = new UUID((String) row[\"terrain_texture_2\"]);\n newSettings.TerrainTexture3 = new UUID((String) row[\"terrain_texture_3\"]);\n newSettings.TerrainTexture4 = new UUID((String) row[\"terrain_texture_4\"]);\n newSettings.Elevation1NW = Convert.ToDouble(row[\"elevation_1_nw\"]);\n newSettings.Elevation2NW = Convert.ToDouble(row[\"elevation_2_nw\"]);\n newSettings.Elevation1NE = Convert.ToDouble(row[\"elevation_1_ne\"]);\n newSettings.Elevation2NE = Convert.ToDouble(row[\"elevation_2_ne\"]);\n newSettings.Elevation1SE = Convert.ToDouble(row[\"elevation_1_se\"]);\n newSettings.Elevation2SE = Convert.ToDouble(row[\"elevation_2_se\"]);\n newSettings.Elevation1SW = Convert.ToDouble(row[\"elevation_1_sw\"]);\n newSettings.Elevation2SW = Convert.ToDouble(row[\"elevation_2_sw\"]);\n newSettings.WaterHeight = Convert.ToDouble(row[\"water_height\"]);\n newSettings.TerrainRaiseLimit = Convert.ToDouble(row[\"terrain_raise_limit\"]);\n newSettings.TerrainLowerLimit = Convert.ToDouble(row[\"terrain_lower_limit\"]);\n newSettings.UseEstateSun = Convert.ToBoolean(row[\"use_estate_sun\"]);\n newSettings.Sandbox = Convert.ToBoolean(row[\"sandbox\"]);\n newSettings.SunVector = new Vector3 (\n Convert.ToSingle(row[\"sunvectorx\"]),\n Convert.ToSingle(row[\"sunvectory\"]),\n Convert.ToSingle(row[\"sunvectorz\"])\n );\n newSettings.FixedSun = Convert.ToBoolean(row[\"fixed_sun\"]);\n newSettings.SunPosition = Convert.ToDouble(row[\"sun_position\"]);\n newSettings.Covenant = new UUID((String) row[\"covenant\"]);\n\n newSettings.LoadedCreationDateTime = Convert.ToInt32(row[\"loaded_creation_datetime\"]);\n \n if (row[\"loaded_creation_id\"] is DBNull)\n newSettings.LoadedCreationID = \"\";\n else \n newSettings.LoadedCreationID = (String) row[\"loaded_creation_id\"];\n\n return newSettings;\n }\n\n /// \n ///\n /// \n /// \n /// \n private static LandData BuildLandData(IDataReader row)\n {\n LandData newData = new LandData();\n\n newData.GlobalID = new UUID((String) row[\"UUID\"]);\n newData.LocalID = Convert.ToInt32(row[\"LocalLandID\"]);\n\n // Bitmap is a byte[512]\n newData.Bitmap = (Byte[]) row[\"Bitmap\"];\n\n newData.Name = (String) row[\"Name\"];\n newData.Description = (String) row[\"Description\"];\n newData.OwnerID = new UUID((String)row[\"OwnerUUID\"]);\n newData.IsGroupOwned = Convert.ToBoolean(row[\"IsGroupOwned\"]);\n newData.Area = Convert.ToInt32(row[\"Area\"]);\n newData.AuctionID = Convert.ToUInt32(row[\"AuctionID\"]); //Unimplemented\n newData.Category = (ParcelCategory) Convert.ToInt32(row[\"Category\"]);\n //Enum libsecondlife.Parcel.ParcelCategory\n newData.ClaimDate = Convert.ToInt32(row[\"ClaimDate\"]);\n newData.ClaimPrice = Convert.ToInt32(row[\"ClaimPrice\"]);\n newData.GroupID = new UUID((String) row[\"GroupUUID\"]);\n newData.SalePrice = Convert.ToInt32(row[\"SalePrice\"]);\n newData.Status = (ParcelStatus) Convert.ToInt32(row[\"LandStatus\"]);\n //Enum. libsecondlife.Parcel.ParcelStatus\n newData.Flags = Convert.ToUInt32(row[\"LandFlags\"]);\n newData.LandingType = Convert.ToByte(row[\"LandingType\"]);\n newData.MediaAutoScale = Convert.ToByte(row[\"MediaAutoScale\"]);\n newData.MediaID = new UUID((String) row[\"MediaTextureUUID\"]);\n newData.MediaURL = (String) row[\"MediaURL\"];\n newData.MusicURL = (String) row[\"MusicURL\"];\n newData.PassHours = Convert.ToSingle(row[\"PassHours\"]);\n newData.PassPrice = Convert.ToInt32(row[\"PassPrice\"]);\n UUID authedbuyer = UUID.Zero;\n UUID snapshotID = UUID.Zero;\n\n UUID.TryParse((string)row[\"AuthBuyerID\"], out authedbuyer);\n UUID.TryParse((string)row[\"SnapshotUUID\"], out snapshotID);\n newData.OtherCleanTime = Convert.ToInt32(row[\"OtherCleanTime\"]);\n newData.Dwell = Convert.ToInt32(row[\"Dwell\"]);\n\n newData.AuthBuyerID = authedbuyer;\n newData.SnapshotID = snapshotID;\n try\n {\n newData.UserLocation =\n new Vector3(Convert.ToSingle(row[\"UserLocationX\"]), Convert.ToSingle(row[\"UserLocationY\"]),\n Convert.ToSingle(row[\"UserLocationZ\"]));\n newData.UserLookAt =\n new Vector3(Convert.ToSingle(row[\"UserLookAtX\"]), Convert.ToSingle(row[\"UserLookAtY\"]),\n Convert.ToSingle(row[\"UserLookAtZ\"]));\n }\n catch (InvalidCastException)\n {\n newData.UserLocation = Vector3.Zero;\n newData.UserLookAt = Vector3.Zero;\n m_log.ErrorFormat(\"[PARCEL]: unable to get parcel telehub settings for {1}\", newData.Name);\n }\n\n newData.ParcelAccessList = new List();\n\n return newData;\n }\n\n /// \n ///\n /// \n /// \n /// \n private static ParcelManager.ParcelAccessEntry BuildLandAccessData(IDataReader row)\n {\n ParcelManager.ParcelAccessEntry entry = new ParcelManager.ParcelAccessEntry();\n entry.AgentID = new UUID((string) row[\"AccessUUID\"]);\n entry.Flags = (AccessList) Convert.ToInt32(row[\"Flags\"]);\n entry.Time = new DateTime();\n return entry;\n }\n\n /// \n ///\n /// \n /// \n /// \n private static Array SerializeTerrain(double[,] val)\n {\n MemoryStream str = new MemoryStream(((int)Constants.RegionSize * (int)Constants.RegionSize) *sizeof (double));\n BinaryWriter bw = new BinaryWriter(str);\n\n // TODO: COMPATIBILITY - Add byte-order conversions\n for (int x = 0; x < (int)Constants.RegionSize; x++)\n for (int y = 0; y < (int)Constants.RegionSize; y++)\n {\n double height = val[x, y];\n if (height == 0.0)\n height = double.Epsilon;\n\n bw.Write(height);\n }\n\n return str.ToArray();\n }\n\n /// \n /// Fill the prim command with prim values\n /// \n /// \n /// \n /// \n /// \n private void FillPrimCommand(MySqlCommand cmd, SceneObjectPart prim, UUID sceneGroupID, UUID regionUUID)\n {\n cmd.Parameters.AddWithValue(\"UUID\", prim.UUID.ToString());\n cmd.Parameters.AddWithValue(\"RegionUUID\", regionUUID.ToString());\n cmd.Parameters.AddWithValue(\"CreationDate\", prim.CreationDate);\n cmd.Parameters.AddWithValue(\"Name\", prim.Name);\n cmd.Parameters.AddWithValue(\"SceneGroupID\", sceneGroupID.ToString());\n // the UUID of the root part for this SceneObjectGroup\n // various text fields\n cmd.Parameters.AddWithValue(\"Text\", prim.Text);\n cmd.Parameters.AddWithValue(\"ColorR\", prim.Color.R);\n cmd.Parameters.AddWithValue(\"ColorG\", prim.Color.G);\n cmd.Parameters.AddWithValue(\"ColorB\", prim.Color.B);\n cmd.Parameters.AddWithValue(\"ColorA\", prim.Color.A);\n cmd.Parameters.AddWithValue(\"Description\", prim.Description);\n cmd.Parameters.AddWithValue(\"SitName\", prim.SitName);\n cmd.Parameters.AddWithValue(\"TouchName\", prim.TouchName);\n // permissions\n cmd.Parameters.AddWithValue(\"ObjectFlags\", prim.ObjectFlags);\n cmd.Parameters.AddWithValue(\"CreatorID\", prim.CreatorID.ToString());\n cmd.Parameters.AddWithValue(\"OwnerID\", prim.OwnerID.ToString());\n cmd.Parameters.AddWithValue(\"GroupID\", prim.GroupID.ToString());\n cmd.Parameters.AddWithValue(\"LastOwnerID\", prim.LastOwnerID.ToString());\n cmd.Parameters.AddWithValue(\"OwnerMask\", prim.OwnerMask);\n cmd.Parameters.AddWithValue(\"NextOwnerMask\", prim.NextOwnerMask);\n cmd.Parameters.AddWithValue(\"GroupMask\", prim.GroupMask);\n cmd.Parameters.AddWithValue(\"EveryoneMask\", prim.EveryoneMask);\n cmd.Parameters.AddWithValue(\"BaseMask\", prim.BaseMask);\n // vectors\n cmd.Parameters.AddWithValue(\"PositionX\", (double)prim.OffsetPosition.X);\n cmd.Parameters.AddWithValue(\"PositionY\", (double)prim.OffsetPosition.Y);\n cmd.Parameters.AddWithValue(\"PositionZ\", (double)prim.OffsetPosition.Z);\n cmd.Parameters.AddWithValue(\"GroupPositionX\", (double)prim.GroupPosition.X);\n cmd.Parameters.AddWithValue(\"GroupPositionY\", (double)prim.GroupPosition.Y);\n cmd.Parameters.AddWithValue(\"GroupPositionZ\", (double)prim.GroupPosition.Z);\n cmd.Parameters.AddWithValue(\"VelocityX\", (double)prim.Velocity.X);\n cmd.Parameters.AddWithValue(\"VelocityY\", (double)prim.Velocity.Y);\n cmd.Parameters.AddWithValue(\"VelocityZ\", (double)prim.Velocity.Z);\n cmd.Parameters.AddWithValue(\"AngularVelocityX\", (double)prim.AngularVelocity.X);\n cmd.Parameters.AddWithValue(\"AngularVelocityY\", (double)prim.AngularVelocity.Y);\n cmd.Parameters.AddWithValue(\"AngularVelocityZ\", (double)prim.AngularVelocity.Z);\n cmd.Parameters.AddWithValue(\"AccelerationX\", (double)prim.Acceleration.X);\n cmd.Parameters.AddWithValue(\"AccelerationY\", (double)prim.Acceleration.Y);\n cmd.Parameters.AddWithValue(\"AccelerationZ\", (double)prim.Acceleration.Z);\n // quaternions\n cmd.Parameters.AddWithValue(\"RotationX\", (double)prim.RotationOffset.X);\n cmd.Parameters.AddWithValue(\"RotationY\", (double)prim.RotationOffset.Y);\n cmd.Parameters.AddWithValue(\"RotationZ\", (double)prim.RotationOffset.Z);\n cmd.Parameters.AddWithValue(\"RotationW\", (double)prim.RotationOffset.W);\n\n // Sit target\n Vector3 sitTargetPos = prim.SitTargetPositionLL;\n cmd.Parameters.AddWithValue(\"SitTargetOffsetX\", (double)sitTargetPos.X);\n cmd.Parameters.AddWithValue(\"SitTargetOffsetY\", (double)sitTargetPos.Y);\n cmd.Parameters.AddWithValue(\"SitTargetOffsetZ\", (double)sitTargetPos.Z);\n\n Quaternion sitTargetOrient = prim.SitTargetOrientationLL;\n cmd.Parameters.AddWithValue(\"SitTargetOrientW\", (double)sitTargetOrient.W);\n cmd.Parameters.AddWithValue(\"SitTargetOrientX\", (double)sitTargetOrient.X);\n cmd.Parameters.AddWithValue(\"SitTargetOrientY\", (double)sitTargetOrient.Y);\n cmd.Parameters.AddWithValue(\"SitTargetOrientZ\", (double)sitTargetOrient.Z);\n\n cmd.Parameters.AddWithValue(\"PayPrice\", prim.PayPrice[0]);\n cmd.Parameters.AddWithValue(\"PayButton1\", prim.PayPrice[1]);\n cmd.Parameters.AddWithValue(\"PayButton2\", prim.PayPrice[2]);\n cmd.Parameters.AddWithValue(\"PayButton3\", prim.PayPrice[3]);\n cmd.Parameters.AddWithValue(\"PayButton4\", prim.PayPrice[4]);\n\n if ((prim.SoundFlags & 1) != 0) // Looped\n {\n cmd.Parameters.AddWithValue(\"LoopedSound\", prim.Sound.ToString());\n cmd.Parameters.AddWithValue(\"LoopedSoundGain\", prim.SoundGain);\n }\n else\n {\n cmd.Parameters.AddWithValue(\"LoopedSound\", UUID.Zero);\n cmd.Parameters.AddWithValue(\"LoopedSoundGain\", 0.0f);\n }\n\n cmd.Parameters.AddWithValue(\"TextureAnimation\", prim.TextureAnimation);\n cmd.Parameters.AddWithValue(\"ParticleSystem\", prim.ParticleSystem);\n\n cmd.Parameters.AddWithValue(\"OmegaX\", (double)prim.RotationalVelocity.X);\n cmd.Parameters.AddWithValue(\"OmegaY\", (double)prim.RotationalVelocity.Y);\n cmd.Parameters.AddWithValue(\"OmegaZ\", (double)prim.RotationalVelocity.Z);\n\n cmd.Parameters.AddWithValue(\"CameraEyeOffsetX\", (double)prim.GetCameraEyeOffset().X);\n cmd.Parameters.AddWithValue(\"CameraEyeOffsetY\", (double)prim.GetCameraEyeOffset().Y);\n cmd.Parameters.AddWithValue(\"CameraEyeOffsetZ\", (double)prim.GetCameraEyeOffset().Z);\n\n cmd.Parameters.AddWithValue(\"CameraAtOffsetX\", (double)prim.GetCameraAtOffset().X);\n cmd.Parameters.AddWithValue(\"CameraAtOffsetY\", (double)prim.GetCameraAtOffset().Y);\n cmd.Parameters.AddWithValue(\"CameraAtOffsetZ\", (double)prim.GetCameraAtOffset().Z);\n\n if (prim.GetForceMouselook())\n cmd.Parameters.AddWithValue(\"ForceMouselook\", 1);\n else\n cmd.Parameters.AddWithValue(\"ForceMouselook\", 0);\n\n cmd.Parameters.AddWithValue(\"ScriptAccessPin\", prim.ScriptAccessPin);\n\n if (prim.AllowedDrop)\n cmd.Parameters.AddWithValue(\"AllowedDrop\", 1);\n else\n cmd.Parameters.AddWithValue(\"AllowedDrop\", 0);\n\n if (prim.DIE_AT_EDGE)\n cmd.Parameters.AddWithValue(\"DieAtEdge\", 1);\n else\n cmd.Parameters.AddWithValue(\"DieAtEdge\", 0);\n\n cmd.Parameters.AddWithValue(\"SalePrice\", prim.SalePrice);\n cmd.Parameters.AddWithValue(\"SaleType\", unchecked((sbyte)(prim.ObjectSaleType)));\n\n byte clickAction = prim.ClickAction;\n cmd.Parameters.AddWithValue(\"ClickAction\", unchecked((sbyte)(clickAction)));\n\n cmd.Parameters.AddWithValue(\"Material\", unchecked((sbyte)(prim.Material)));\n\n cmd.Parameters.AddWithValue(\"CollisionSound\", prim.CollisionSound.ToString());\n cmd.Parameters.AddWithValue(\"CollisionSoundVolume\", prim.CollisionSoundVolume);\n\n if (prim.PassTouches)\n cmd.Parameters.AddWithValue(\"PassTouches\", 1);\n else\n cmd.Parameters.AddWithValue(\"PassTouches\", 0);\n\n cmd.Parameters.AddWithValue(\"LinkNumber\", prim.LinkNum);\n }\n\n /// \n ///\n /// \n /// \n /// \n private static void FillItemCommand(MySqlCommand cmd, TaskInventoryItem taskItem)\n {\n cmd.Parameters.AddWithValue(\"itemID\", taskItem.ItemID);\n cmd.Parameters.AddWithValue(\"primID\", taskItem.ParentPartID);\n cmd.Parameters.AddWithValue(\"assetID\", taskItem.AssetID);\n cmd.Parameters.AddWithValue(\"parentFolderID\", taskItem.ParentID);\n\n cmd.Parameters.AddWithValue(\"invType\", taskItem.InvType);\n cmd.Parameters.AddWithValue(\"assetType\", taskItem.Type);\n\n cmd.Parameters.AddWithValue(\"name\", taskItem.Name);\n cmd.Parameters.AddWithValue(\"description\", taskItem.Description);\n cmd.Parameters.AddWithValue(\"creationDate\", taskItem.CreationDate);\n cmd.Parameters.AddWithValue(\"creatorID\", taskItem.CreatorID);\n cmd.Parameters.AddWithValue(\"ownerID\", taskItem.OwnerID);\n cmd.Parameters.AddWithValue(\"lastOwnerID\", taskItem.LastOwnerID);\n cmd.Parameters.AddWithValue(\"groupID\", taskItem.GroupID);\n cmd.Parameters.AddWithValue(\"nextPermissions\", taskItem.NextPermissions);\n cmd.Parameters.AddWithValue(\"currentPermissions\", taskItem.CurrentPermissions);\n cmd.Parameters.AddWithValue(\"basePermissions\", taskItem.BasePermissions);\n cmd.Parameters.AddWithValue(\"everyonePermissions\", taskItem.EveryonePermissions);\n cmd.Parameters.AddWithValue(\"groupPermissions\", taskItem.GroupPermissions);\n cmd.Parameters.AddWithValue(\"flags\", taskItem.Flags);\n }\n\n /// \n ///\n /// \n private static void FillRegionSettingsCommand(MySqlCommand cmd, RegionSettings settings)\n {\n cmd.Parameters.AddWithValue(\"RegionUUID\", settings.RegionUUID.ToString());\n cmd.Parameters.AddWithValue(\"BlockTerraform\", settings.BlockTerraform);\n cmd.Parameters.AddWithValue(\"BlockFly\", settings.BlockFly);\n cmd.Parameters.AddWithValue(\"AllowDamage\", settings.AllowDamage);\n cmd.Parameters.AddWithValue(\"RestrictPushing\", settings.RestrictPushing);\n cmd.Parameters.AddWithValue(\"AllowLandResell\", settings.AllowLandResell);\n cmd.Parameters.AddWithValue(\"AllowLandJoinDivide\", settings.AllowLandJoinDivide);\n cmd.Parameters.AddWithValue(\"BlockShowInSearch\", settings.BlockShowInSearch);\n cmd.Parameters.AddWithValue(\"AgentLimit\", settings.AgentLimit);\n cmd.Parameters.AddWithValue(\"ObjectBonus\", settings.ObjectBonus);\n cmd.Parameters.AddWithValue(\"Maturity\", settings.Maturity);\n cmd.Parameters.AddWithValue(\"DisableScripts\", settings.DisableScripts);\n cmd.Parameters.AddWithValue(\"DisableCollisions\", settings.DisableCollisions);\n cmd.Parameters.AddWithValue(\"DisablePhysics\", settings.DisablePhysics);\n cmd.Parameters.AddWithValue(\"TerrainTexture1\", settings.TerrainTexture1.ToString());\n cmd.Parameters.AddWithValue(\"TerrainTexture2\", settings.TerrainTexture2.ToString());\n cmd.Parameters.AddWithValue(\"TerrainTexture3\", settings.TerrainTexture3.ToString());\n cmd.Parameters.AddWithValue(\"TerrainTexture4\", settings.TerrainTexture4.ToString());\n cmd.Parameters.AddWithValue(\"Elevation1NW\", settings.Elevation1NW);\n cmd.Parameters.AddWithValue(\"Elevation2NW\", settings.Elevation2NW);\n cmd.Parameters.AddWithValue(\"Elevation1NE\", settings.Elevation1NE);\n cmd.Parameters.AddWithValue(\"Elevation2NE\", settings.Elevation2NE);\n cmd.Parameters.AddWithValue(\"Elevation1SE\", settings.Elevation1SE);\n cmd.Parameters.AddWithValue(\"Elevation2SE\", settings.Elevation2SE);\n cmd.Parameters.AddWithValue(\"Elevation1SW\", settings.Elevation1SW);\n cmd.Parameters.AddWithValue(\"Elevation2SW\", settings.Elevation2SW);\n cmd.Parameters.AddWithValue(\"WaterHeight\", settings.WaterHeight);\n cmd.Parameters.AddWithValue(\"TerrainRaiseLimit\", settings.TerrainRaiseLimit);\n cmd.Parameters.AddWithValue(\"TerrainLowerLimit\", settings.TerrainLowerLimit);\n cmd.Parameters.AddWithValue(\"UseEstateSun\", settings.UseEstateSun);\n cmd.Parameters.AddWithValue(\"Sandbox\", settings.Sandbox);\n cmd.Parameters.AddWithValue(\"SunVectorX\", settings.SunVector.X);\n cmd.Parameters.AddWithValue(\"SunVectorY\", settings.SunVector.Y);\n cmd.Parameters.AddWithValue(\"SunVectorZ\", settings.SunVector.Z);\n cmd.Parameters.AddWithValue(\"FixedSun\", settings.FixedSun);\n cmd.Parameters.AddWithValue(\"SunPosition\", settings.SunPosition);\n cmd.Parameters.AddWithValue(\"Covenant\", settings.Covenant.ToString());\n cmd.Parameters.AddWithValue(\"LoadedCreationDateTime\", settings.LoadedCreationDateTime);\n cmd.Parameters.AddWithValue(\"LoadedCreationID\", settings.LoadedCreationID);\n\n }\n\n /// \n ///\n /// \n /// \n /// \n /// \n private static void FillLandCommand(MySqlCommand cmd, LandData land, UUID regionUUID)\n {\n cmd.Parameters.AddWithValue(\"UUID\", land.GlobalID.ToString());\n cmd.Parameters.AddWithValue(\"RegionUUID\", regionUUID.ToString());\n cmd.Parameters.AddWithValue(\"LocalLandID\", land.LocalID);\n\n // Bitmap is a byte[512]\n cmd.Parameters.AddWithValue(\"Bitmap\", land.Bitmap);\n\n cmd.Parameters.AddWithValue(\"Name\", land.Name);\n cmd.Parameters.AddWithValue(\"Description\", land.Description);\n cmd.Parameters.AddWithValue(\"OwnerUUID\", land.OwnerID.ToString());\n cmd.Parameters.AddWithValue(\"IsGroupOwned\", land.IsGroupOwned);\n cmd.Parameters.AddWithValue(\"Area\", land.Area);\n cmd.Parameters.AddWithValue(\"AuctionID\", land.AuctionID); //Unemplemented\n cmd.Parameters.AddWithValue(\"Category\", land.Category); //Enum libsecondlife.Parcel.ParcelCategory\n cmd.Parameters.AddWithValue(\"ClaimDate\", land.ClaimDate);\n cmd.Parameters.AddWithValue(\"ClaimPrice\", land.ClaimPrice);\n cmd.Parameters.AddWithValue(\"GroupUUID\", land.GroupID.ToString());\n cmd.Parameters.AddWithValue(\"SalePrice\", land.SalePrice);\n cmd.Parameters.AddWithValue(\"LandStatus\", land.Status); //Enum. libsecondlife.Parcel.ParcelStatus\n cmd.Parameters.AddWithValue(\"LandFlags\", land.Flags);\n cmd.Parameters.AddWithValue(\"LandingType\", land.LandingType);\n cmd.Parameters.AddWithValue(\"MediaAutoScale\", land.MediaAutoScale);\n cmd.Parameters.AddWithValue(\"MediaTextureUUID\", land.MediaID.ToString());\n cmd.Parameters.AddWithValue(\"MediaURL\", land.MediaURL);\n cmd.Parameters.AddWithValue(\"MusicURL\", land.MusicURL);\n cmd.Parameters.AddWithValue(\"PassHours\", land.PassHours);\n cmd.Parameters.AddWithValue(\"PassPrice\", land.PassPrice);\n cmd.Parameters.AddWithValue(\"SnapshotUUID\", land.SnapshotID.ToString());\n cmd.Parameters.AddWithValue(\"UserLocationX\", land.UserLocation.X);\n cmd.Parameters.AddWithValue(\"UserLocationY\", land.UserLocation.Y);\n cmd.Parameters.AddWithValue(\"UserLocationZ\", land.UserLocation.Z);\n cmd.Parameters.AddWithValue(\"UserLookAtX\", land.UserLookAt.X);\n cmd.Parameters.AddWithValue(\"UserLookAtY\", land.UserLookAt.Y);\n cmd.Parameters.AddWithValue(\"UserLookAtZ\", land.UserLookAt.Z);\n cmd.Parameters.AddWithValue(\"AuthBuyerID\", land.AuthBuyerID);\n cmd.Parameters.AddWithValue(\"OtherCleanTime\", land.OtherCleanTime);\n cmd.Parameters.AddWithValue(\"Dwell\", land.Dwell);\n }\n\n /// \n ///\n /// \n /// \n /// \n /// \n private static void FillLandAccessCommand(MySqlCommand cmd, ParcelManager.ParcelAccessEntry entry, UUID parcelID)\n {\n cmd.Parameters.AddWithValue(\"LandUUID\", parcelID.ToString());\n cmd.Parameters.AddWithValue(\"AccessUUID\", entry.AgentID.ToString());\n cmd.Parameters.AddWithValue(\"Flags\", entry.Flags);\n }\n\n /// \n ///\n /// \n /// \n /// \n private PrimitiveBaseShape BuildShape(IDataReader row)\n {\n PrimitiveBaseShape s = new PrimitiveBaseShape();\n s.Scale = new Vector3(\n Convert.ToSingle(row[\"ScaleX\"]),\n Convert.ToSingle(row[\"ScaleY\"]),\n Convert.ToSingle(row[\"ScaleZ\"])\n );\n // paths\n s.PCode = Convert.ToByte(row[\"PCode\"]);\n s.PathBegin = Convert.ToUInt16(row[\"PathBegin\"]);\n s.PathEnd = Convert.ToUInt16(row[\"PathEnd\"]);\n s.PathScaleX = Convert.ToByte(row[\"PathScaleX\"]);\n s.PathScaleY = Convert.ToByte(row[\"PathScaleY\"]);\n s.PathShearX = Convert.ToByte(row[\"PathShearX\"]);\n s.PathShearY = Convert.ToByte(row[\"PathShearY\"]);\n s.PathSkew = Convert.ToSByte(row[\"PathSkew\"]);\n s.PathCurve = Convert.ToByte(row[\"PathCurve\"]);\n s.PathRadiusOffset = Convert.ToSByte(row[\"PathRadiusOffset\"]);\n s.PathRevolutions = Convert.ToByte(row[\"PathRevolutions\"]);\n s.PathTaperX = Convert.ToSByte(row[\"PathTaperX\"]);\n s.PathTaperY = Convert.ToSByte(row[\"PathTaperY\"]);\n s.PathTwist = Convert.ToSByte(row[\"PathTwist\"]);\n s.PathTwistBegin = Convert.ToSByte(row[\"PathTwistBegin\"]);\n // profile\n s.ProfileBegin = Convert.ToUInt16(row[\"ProfileBegin\"]);\n s.ProfileEnd = Convert.ToUInt16(row[\"ProfileEnd\"]);\n s.ProfileCurve = Convert.ToByte(row[\"ProfileCurve\"]);\n s.ProfileHollow = Convert.ToUInt16(row[\"ProfileHollow\"]);\n byte[] textureEntry = (byte[]) row[\"Texture\"];\n s.TextureEntry = textureEntry;\n\n s.ExtraParams = (byte[]) row[\"ExtraParams\"];\n\n s.State = Convert.ToByte(row[\"State\"]);\n\n return s;\n }\n\n /// \n ///\n /// \n /// \n /// \n private void FillShapeCommand(MySqlCommand cmd, SceneObjectPart prim)\n {\n PrimitiveBaseShape s = prim.Shape;\n cmd.Parameters.AddWithValue(\"UUID\", prim.UUID.ToString());\n // shape is an enum\n cmd.Parameters.AddWithValue(\"Shape\", 0);\n // vectors\n cmd.Parameters.AddWithValue(\"ScaleX\", (double)s.Scale.X);\n cmd.Parameters.AddWithValue(\"ScaleY\", (double)s.Scale.Y);\n cmd.Parameters.AddWithValue(\"ScaleZ\", (double)s.Scale.Z);\n // paths\n cmd.Parameters.AddWithValue(\"PCode\", s.PCode);\n cmd.Parameters.AddWithValue(\"PathBegin\", s.PathBegin);\n cmd.Parameters.AddWithValue(\"PathEnd\", s.PathEnd);\n cmd.Parameters.AddWithValue(\"PathScaleX\", s.PathScaleX);\n cmd.Parameters.AddWithValue(\"PathScaleY\", s.PathScaleY);\n cmd.Parameters.AddWithValue(\"PathShearX\", s.PathShearX);\n cmd.Parameters.AddWithValue(\"PathShearY\", s.PathShearY);\n cmd.Parameters.AddWithValue(\"PathSkew\", s.PathSkew);\n cmd.Parameters.AddWithValue(\"PathCurve\", s.PathCurve);\n cmd.Parameters.AddWithValue(\"PathRadiusOffset\", s.PathRadiusOffset);\n cmd.Parameters.AddWithValue(\"PathRevolutions\", s.PathRevolutions);\n cmd.Parameters.AddWithValue(\"PathTaperX\", s.PathTaperX);\n cmd.Parameters.AddWithValue(\"PathTaperY\", s.PathTaperY);\n cmd.Parameters.AddWithValue(\"PathTwist\", s.PathTwist);\n cmd.Parameters.AddWithValue(\"PathTwistBegin\", s.PathTwistBegin);\n // profile\n cmd.Parameters.AddWithValue(\"ProfileBegin\", s.ProfileBegin);\n cmd.Parameters.AddWithValue(\"ProfileEnd\", s.ProfileEnd);\n cmd.Parameters.AddWithValue(\"ProfileCurve\", s.ProfileCurve);\n cmd.Parameters.AddWithValue(\"ProfileHollow\", s.ProfileHollow);\n cmd.Parameters.AddWithValue(\"Texture\", s.TextureEntry);\n cmd.Parameters.AddWithValue(\"ExtraParams\", s.ExtraParams);\n cmd.Parameters.AddWithValue(\"State\", s.State);\n }\n\n public void StorePrimInventory(UUID primID, ICollection items)\n {\n lock (m_Connection)\n {\n RemoveItems(primID);\n\n MySqlCommand cmd = m_Connection.CreateCommand();\n\n if (items.Count == 0)\n return;\n\n cmd.CommandText = \"insert into primitems (\"+\n \"invType, assetType, name, \"+\n \"description, creationDate, nextPermissions, \"+\n \"currentPermissions, basePermissions, \"+\n \"everyonePermissions, groupPermissions, \"+\n \"flags, itemID, primID, assetID, \"+\n \"parentFolderID, creatorID, ownerID, \"+\n \"groupID, lastOwnerID) values (?invType, \"+\n \"?assetType, ?name, ?description, \"+\n \"?creationDate, ?nextPermissions, \"+\n \"?currentPermissions, ?basePermissions, \"+\n \"?everyonePermissions, ?groupPermissions, \"+\n \"?flags, ?itemID, ?primID, ?assetID, \"+\n \"?parentFolderID, ?creatorID, ?ownerID, \"+\n \"?groupID, ?lastOwnerID)\";\n\n foreach (TaskInventoryItem item in items)\n {\n cmd.Parameters.Clear();\n\n FillItemCommand(cmd, item);\n\n ExecuteNonQuery(cmd);\n }\n \n cmd.Dispose();\n }\n }\n }\n}\n"},"gt":{"kind":"string","value":""}}},{"rowIdx":98460,"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\nnamespace System.Runtime.Serialization\n{\n using System;\n using System.Collections;\n using System.Diagnostics;\n using System.Collections.Generic;\n using System.IO;\n using System.Globalization;\n using System.Reflection;\n using System.Threading;\n using System.Xml;\n using DataContractDictionary = System.Collections.Generic.Dictionary;\n using System.Security;\n using System.Linq;\n\n#if USE_REFEMIT || NET_NATIVE\n public sealed class ClassDataContract : DataContract\n#else\n internal sealed class ClassDataContract : DataContract\n#endif\n {\n /// \n /// Review - XmlDictionaryString(s) representing the XML namespaces for class members.\n /// statically cached and used from IL generated code. should ideally be Critical.\n /// marked SecurityRequiresReview to be callable from transparent IL generated code. \n /// not changed to property to avoid regressing performance; any changes to initalization should be reviewed.\n /// \n public XmlDictionaryString[] ContractNamespaces;\n /// \n /// Review - XmlDictionaryString(s) representing the XML element names for class members.\n /// statically cached and used from IL generated code. should ideally be Critical.\n /// marked SecurityRequiresReview to be callable from transparent IL generated code. \n /// not changed to property to avoid regressing performance; any changes to initalization should be reviewed.\n /// \n public XmlDictionaryString[] MemberNames;\n /// \n /// Review - XmlDictionaryString(s) representing the XML namespaces for class members.\n /// statically cached and used when calling IL generated code. should ideally be Critical.\n /// marked SecurityRequiresReview to be callable from transparent code. \n /// not changed to property to avoid regressing performance; any changes to initalization should be reviewed.\n /// \n public XmlDictionaryString[] MemberNamespaces;\n [SecurityCritical]\n /// \n /// Critical - XmlDictionaryString representing the XML namespaces for members of class.\n /// statically cached and used from IL generated code.\n /// \n private XmlDictionaryString[] _childElementNamespaces;\n [SecurityCritical]\n\n /// \n /// Critical - holds instance of CriticalHelper which keeps state that is cached statically for serialization. \n /// Static fields are marked SecurityCritical or readonly to prevent\n /// data from being modified or leaked to other components in appdomain.\n /// \n private ClassDataContractCriticalHelper _helper;\n\n private bool _isScriptObject;\n\n#if NET_NATIVE\n public ClassDataContract() : base(new ClassDataContractCriticalHelper())\n {\n InitClassDataContract();\n }\n#endif\n\n /// \n /// Critical - initializes SecurityCritical field 'helper'\n /// Safe - doesn't leak anything\n /// \n [SecuritySafeCritical]\n internal ClassDataContract(Type type) : base(new ClassDataContractCriticalHelper(type))\n {\n InitClassDataContract();\n }\n [SecuritySafeCritical]\n\n /// \n /// Critical - initializes SecurityCritical field 'helper'\n /// Safe - doesn't leak anything\n /// \n private ClassDataContract(Type type, XmlDictionaryString ns, string[] memberNames) : base(new ClassDataContractCriticalHelper(type, ns, memberNames))\n {\n InitClassDataContract();\n }\n [SecurityCritical]\n\n /// \n /// Critical - initializes SecurityCritical fields; called from all constructors\n /// \n private void InitClassDataContract()\n {\n _helper = base.Helper as ClassDataContractCriticalHelper;\n this.ContractNamespaces = _helper.ContractNamespaces;\n this.MemberNames = _helper.MemberNames;\n this.MemberNamespaces = _helper.MemberNamespaces;\n _isScriptObject = _helper.IsScriptObject;\n }\n\n internal ClassDataContract BaseContract\n {\n /// \n /// Critical - fetches the critical baseContract property\n /// Safe - baseContract only needs to be protected for write\n /// \n [SecuritySafeCritical]\n get\n { return _helper.BaseContract; }\n }\n\n internal List Members\n {\n /// \n /// Critical - fetches the critical members property\n /// Safe - members only needs to be protected for write\n /// \n [SecuritySafeCritical]\n get\n { return _helper.Members; }\n }\n\n public XmlDictionaryString[] ChildElementNamespaces\n {\n /// \n /// Critical - fetches the critical childElementNamespaces property\n /// Safe - childElementNamespaces only needs to be protected for write; initialized in getter if null\n /// \n [SecuritySafeCritical]\n get\n {\n if (_childElementNamespaces == null)\n {\n lock (this)\n {\n if (_childElementNamespaces == null)\n {\n if (_helper.ChildElementNamespaces == null)\n {\n XmlDictionaryString[] tempChildElementamespaces = CreateChildElementNamespaces();\n Interlocked.MemoryBarrier();\n _helper.ChildElementNamespaces = tempChildElementamespaces;\n }\n _childElementNamespaces = _helper.ChildElementNamespaces;\n }\n }\n }\n return _childElementNamespaces;\n }\n#if NET_NATIVE\n set\n {\n _childElementNamespaces = value;\n }\n#endif\n }\n\n internal MethodInfo OnSerializing\n {\n /// \n /// Critical - fetches the critical onSerializing property\n /// Safe - onSerializing only needs to be protected for write\n /// \n [SecuritySafeCritical]\n get\n { return _helper.OnSerializing; }\n }\n\n internal MethodInfo OnSerialized\n {\n /// \n /// Critical - fetches the critical onSerialized property\n /// Safe - onSerialized only needs to be protected for write\n /// \n [SecuritySafeCritical]\n get\n { return _helper.OnSerialized; }\n }\n\n internal MethodInfo OnDeserializing\n {\n /// \n /// Critical - fetches the critical onDeserializing property\n /// Safe - onDeserializing only needs to be protected for write\n /// \n [SecuritySafeCritical]\n get\n { return _helper.OnDeserializing; }\n }\n\n internal MethodInfo OnDeserialized\n {\n /// \n /// Critical - fetches the critical onDeserialized property\n /// Safe - onDeserialized only needs to be protected for write\n /// \n [SecuritySafeCritical]\n get\n { return _helper.OnDeserialized; }\n }\n\n#if !NET_NATIVE\n public override DataContractDictionary KnownDataContracts\n {\n /// \n /// Critical - fetches the critical knownDataContracts property\n /// Safe - knownDataContracts only needs to be protected for write\n /// \n [SecuritySafeCritical]\n get\n { return _helper.KnownDataContracts; }\n }\n#endif\n\n internal bool IsNonAttributedType\n {\n /// \n /// Critical - fetches the critical IsNonAttributedType property\n /// Safe - IsNonAttributedType only needs to be protected for write\n /// \n [SecuritySafeCritical]\n get\n { return _helper.IsNonAttributedType; }\n }\n\n#if NET_NATIVE\n public bool HasDataContract\n {\n [SecuritySafeCritical]\n get\n { return _helper.HasDataContract; }\n set { _helper.HasDataContract = value; }\n }\n\n public bool HasExtensionData\n {\n [SecuritySafeCritical]\n get\n { return _helper.HasExtensionData; }\n set { _helper.HasExtensionData = value; }\n }\n#endif\n\n internal bool IsKeyValuePairAdapter\n {\n [SecuritySafeCritical]\n get\n { return _helper.IsKeyValuePairAdapter; }\n }\n\n internal Type[] KeyValuePairGenericArguments\n {\n [SecuritySafeCritical]\n get\n { return _helper.KeyValuePairGenericArguments; }\n }\n\n internal ConstructorInfo KeyValuePairAdapterConstructorInfo\n {\n [SecuritySafeCritical]\n get\n { return _helper.KeyValuePairAdapterConstructorInfo; }\n }\n\n internal MethodInfo GetKeyValuePairMethodInfo\n {\n [SecuritySafeCritical]\n get\n { return _helper.GetKeyValuePairMethodInfo; }\n }\n\n /// \n /// Critical - fetches information about which constructor should be used to initialize non-attributed types that are valid for serialization\n /// Safe - only needs to be protected for write\n /// \n [SecuritySafeCritical]\n internal ConstructorInfo GetNonAttributedTypeConstructor()\n {\n return _helper.GetNonAttributedTypeConstructor();\n }\n\n#if !NET_NATIVE\n internal XmlFormatClassWriterDelegate XmlFormatWriterDelegate\n {\n /// \n /// Critical - fetches the critical xmlFormatWriterDelegate property\n /// Safe - xmlFormatWriterDelegate only needs to be protected for write; initialized in getter if null\n /// \n [SecuritySafeCritical]\n get\n {\n if (_helper.XmlFormatWriterDelegate == null)\n {\n lock (this)\n {\n if (_helper.XmlFormatWriterDelegate == null)\n {\n XmlFormatClassWriterDelegate tempDelegate = new XmlFormatWriterGenerator().GenerateClassWriter(this);\n Interlocked.MemoryBarrier();\n _helper.XmlFormatWriterDelegate = tempDelegate;\n }\n }\n }\n return _helper.XmlFormatWriterDelegate;\n }\n }\n#else\n public XmlFormatClassWriterDelegate XmlFormatWriterDelegate { get; set; }\n#endif\n\n#if !NET_NATIVE\n internal XmlFormatClassReaderDelegate XmlFormatReaderDelegate\n {\n /// \n /// Critical - fetches the critical xmlFormatReaderDelegate property\n /// Safe - xmlFormatReaderDelegate only needs to be protected for write; initialized in getter if null\n /// \n [SecuritySafeCritical]\n get\n {\n if (_helper.XmlFormatReaderDelegate == null)\n {\n lock (this)\n {\n if (_helper.XmlFormatReaderDelegate == null)\n {\n XmlFormatClassReaderDelegate tempDelegate = new XmlFormatReaderGenerator().GenerateClassReader(this);\n Interlocked.MemoryBarrier();\n _helper.XmlFormatReaderDelegate = tempDelegate;\n }\n }\n }\n return _helper.XmlFormatReaderDelegate;\n }\n }\n#else\n public XmlFormatClassReaderDelegate XmlFormatReaderDelegate { get; set; }\n#endif\n\n internal static ClassDataContract CreateClassDataContractForKeyValue(Type type, XmlDictionaryString ns, string[] memberNames)\n {\n#if !NET_NATIVE\n return new ClassDataContract(type, ns, memberNames);\n#else\n ClassDataContract cdc = (ClassDataContract)DataContract.GetDataContractFromGeneratedAssembly(type);\n ClassDataContract cloned = cdc.Clone();\n cloned.UpdateNamespaceAndMembers(type, ns, memberNames);\n return cloned;\n#endif\n }\n\n internal static void CheckAndAddMember(List members, DataMember memberContract, Dictionary memberNamesTable)\n {\n DataMember existingMemberContract;\n if (memberNamesTable.TryGetValue(memberContract.Name, out existingMemberContract))\n {\n Type declaringType = memberContract.MemberInfo.DeclaringType;\n DataContract.ThrowInvalidDataContractException(\n SR.Format((declaringType.GetTypeInfo().IsEnum ? SR.DupEnumMemberValue : SR.DupMemberName),\n existingMemberContract.MemberInfo.Name,\n memberContract.MemberInfo.Name,\n DataContract.GetClrTypeFullName(declaringType),\n memberContract.Name),\n declaringType);\n }\n memberNamesTable.Add(memberContract.Name, memberContract);\n members.Add(memberContract);\n }\n\n internal static XmlDictionaryString GetChildNamespaceToDeclare(DataContract dataContract, Type childType, XmlDictionary dictionary)\n {\n childType = DataContract.UnwrapNullableType(childType);\n if (!childType.GetTypeInfo().IsEnum && !Globals.TypeOfIXmlSerializable.IsAssignableFrom(childType)\n && DataContract.GetBuiltInDataContract(childType) == null && childType != Globals.TypeOfDBNull)\n {\n string ns = DataContract.GetStableName(childType).Namespace;\n if (ns.Length > 0 && ns != dataContract.Namespace.Value)\n return dictionary.Add(ns);\n }\n return null;\n }\n\n private static bool IsArraySegment(Type t)\n {\n return t.GetTypeInfo().IsGenericType && (t.GetGenericTypeDefinition() == typeof(ArraySegment<>));\n }\n\n /// \n /// RequiresReview - callers may need to depend on isNonAttributedType for a security decision\n /// isNonAttributedType must be calculated correctly\n /// IsNonAttributedTypeValidForSerialization is used as part of the isNonAttributedType calculation and\n /// is therefore marked SRR\n /// Safe - does not let caller influence isNonAttributedType calculation; no harm in leaking value\n /// \n static internal bool IsNonAttributedTypeValidForSerialization(Type type)\n {\n if (type.IsArray)\n return false;\n\n if (type.GetTypeInfo().IsEnum)\n return false;\n\n if (type.IsGenericParameter)\n return false;\n\n if (Globals.TypeOfIXmlSerializable.IsAssignableFrom(type))\n return false;\n\n if (type.IsPointer)\n return false;\n\n if (type.GetTypeInfo().IsDefined(Globals.TypeOfCollectionDataContractAttribute, false))\n return false;\n\n Type[] interfaceTypes = type.GetInterfaces();\n\n if (!IsArraySegment(type))\n {\n foreach (Type interfaceType in interfaceTypes)\n {\n if (CollectionDataContract.IsCollectionInterface(interfaceType))\n return false;\n }\n }\n\n\n if (type.GetTypeInfo().IsDefined(Globals.TypeOfDataContractAttribute, false))\n return false;\n if (type.GetTypeInfo().IsValueType)\n {\n return type.GetTypeInfo().IsVisible;\n }\n else\n {\n return (type.GetTypeInfo().IsVisible &&\n type.GetConstructor(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public, Array.Empty()) != null);\n }\n }\n\n private static string[] s_knownSerializableTypeNames = new string[] {\n \"System.Collections.Queue\",\n \"System.Collections.Stack\",\n \"System.Globalization.CultureInfo\",\n \"System.Version\",\n \"System.Collections.Generic.KeyValuePair`2\",\n \"System.Collections.Generic.Queue`1\",\n \"System.Collections.Generic.Stack`1\",\n \"System.Collections.ObjectModel.ReadOnlyCollection`1\",\n \"System.Collections.ObjectModel.ReadOnlyDictionary`2\",\n \"System.Tuple`1\",\n \"System.Tuple`2\",\n \"System.Tuple`3\",\n \"System.Tuple`4\",\n \"System.Tuple`5\",\n \"System.Tuple`6\",\n \"System.Tuple`7\",\n \"System.Tuple`8\",\n };\n\n internal static bool IsKnownSerializableType(Type type)\n {\n // Applies to known types that DCS understands how to serialize/deserialize\n //\n\n // Ajdust for generic type\n if (type.GetTypeInfo().IsGenericType && !type.GetTypeInfo().IsGenericTypeDefinition)\n {\n type = type.GetGenericTypeDefinition();\n }\n\n // Check for known types\n if (Enumerable.Contains(s_knownSerializableTypeNames, type.FullName))\n {\n return true;\n }\n //Enable ClassDataContract to give support to Exceptions.\n if (Globals.TypeOfException.IsAssignableFrom(type))\n return true;\n\n return false;\n }\n\n private XmlDictionaryString[] CreateChildElementNamespaces()\n {\n if (Members == null)\n return null;\n\n XmlDictionaryString[] baseChildElementNamespaces = null;\n if (this.BaseContract != null)\n baseChildElementNamespaces = this.BaseContract.ChildElementNamespaces;\n int baseChildElementNamespaceCount = (baseChildElementNamespaces != null) ? baseChildElementNamespaces.Length : 0;\n XmlDictionaryString[] childElementNamespaces = new XmlDictionaryString[Members.Count + baseChildElementNamespaceCount];\n if (baseChildElementNamespaceCount > 0)\n Array.Copy(baseChildElementNamespaces, 0, childElementNamespaces, 0, baseChildElementNamespaces.Length);\n\n XmlDictionary dictionary = new XmlDictionary();\n for (int i = 0; i < this.Members.Count; i++)\n {\n childElementNamespaces[i + baseChildElementNamespaceCount] = GetChildNamespaceToDeclare(this, this.Members[i].MemberType, dictionary);\n }\n\n return childElementNamespaces;\n }\n [SecuritySafeCritical]\n\n /// \n /// Critical - calls critical method on helper\n /// Safe - doesn't leak anything\n /// \n private void EnsureMethodsImported()\n {\n _helper.EnsureMethodsImported();\n }\n\n public override void WriteXmlValue(XmlWriterDelegator xmlWriter, object obj, XmlObjectSerializerWriteContext context)\n {\n if (_isScriptObject)\n {\n throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.Format(SR.UnexpectedContractType, DataContract.GetClrTypeFullName(this.GetType()), DataContract.GetClrTypeFullName(UnderlyingType))));\n }\n XmlFormatWriterDelegate(xmlWriter, obj, context, this);\n }\n\n public override object ReadXmlValue(XmlReaderDelegator xmlReader, XmlObjectSerializerReadContext context)\n {\n if (_isScriptObject)\n {\n throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.Format(SR.UnexpectedContractType, DataContract.GetClrTypeFullName(this.GetType()), DataContract.GetClrTypeFullName(UnderlyingType))));\n }\n xmlReader.Read();\n object o = XmlFormatReaderDelegate(xmlReader, context, MemberNames, MemberNamespaces);\n xmlReader.ReadEndElement();\n return o;\n }\n\n /// \n /// Review - calculates whether this class requires MemberAccessPermission for deserialization.\n /// since this information is used to determine whether to give the generated code access\n /// permissions to private members, any changes to the logic should be reviewed.\n /// \n internal bool RequiresMemberAccessForRead(SecurityException securityException, string[] serializationAssemblyPatterns)\n {\n EnsureMethodsImported();\n if (!IsTypeVisible(UnderlyingType, serializationAssemblyPatterns))\n {\n if (securityException != null)\n {\n throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(\n new SecurityException(SR.Format(\n SR.PartialTrustDataContractTypeNotPublic,\n DataContract.GetClrTypeFullName(UnderlyingType)),\n securityException));\n }\n return true;\n }\n if (this.BaseContract != null && this.BaseContract.RequiresMemberAccessForRead(securityException, serializationAssemblyPatterns))\n return true;\n\n if (ConstructorRequiresMemberAccess(GetNonAttributedTypeConstructor(), serializationAssemblyPatterns))\n {\n if (Globals.TypeOfScriptObject_IsAssignableFrom(UnderlyingType))\n {\n return true;\n }\n if (securityException != null)\n {\n throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(\n new SecurityException(SR.Format(\n SR.PartialTrustNonAttributedSerializableTypeNoPublicConstructor,\n DataContract.GetClrTypeFullName(UnderlyingType)),\n securityException));\n }\n return true;\n }\n\n if (MethodRequiresMemberAccess(this.OnDeserializing, serializationAssemblyPatterns))\n {\n if (securityException != null)\n {\n throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(\n new SecurityException(SR.Format(\n SR.PartialTrustDataContractOnDeserializingNotPublic,\n DataContract.GetClrTypeFullName(UnderlyingType),\n this.OnDeserializing.Name),\n securityException));\n }\n return true;\n }\n\n if (MethodRequiresMemberAccess(this.OnDeserialized, serializationAssemblyPatterns))\n {\n if (securityException != null)\n {\n throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(\n new SecurityException(SR.Format(\n SR.PartialTrustDataContractOnDeserializedNotPublic,\n DataContract.GetClrTypeFullName(UnderlyingType),\n this.OnDeserialized.Name),\n securityException));\n }\n return true;\n }\n\n if (this.Members != null)\n {\n for (int i = 0; i < this.Members.Count; i++)\n {\n if (this.Members[i].RequiresMemberAccessForSet(serializationAssemblyPatterns))\n {\n if (securityException != null)\n {\n if (this.Members[i].MemberInfo is FieldInfo)\n {\n throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(\n new SecurityException(SR.Format(\n SR.PartialTrustDataContractFieldSetNotPublic,\n DataContract.GetClrTypeFullName(UnderlyingType),\n this.Members[i].MemberInfo.Name),\n securityException));\n }\n else\n {\n throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(\n new SecurityException(SR.Format(\n SR.PartialTrustDataContractPropertySetNotPublic,\n DataContract.GetClrTypeFullName(UnderlyingType),\n this.Members[i].MemberInfo.Name),\n securityException));\n }\n }\n return true;\n }\n }\n }\n\n return false;\n }\n\n /// \n /// Review - calculates whether this class requires MemberAccessPermission for serialization.\n /// since this information is used to determine whether to give the generated code access\n /// permissions to private members, any changes to the logic should be reviewed.\n /// \n internal bool RequiresMemberAccessForWrite(SecurityException securityException, string[] serializationAssemblyPatterns)\n {\n EnsureMethodsImported();\n\n if (!IsTypeVisible(UnderlyingType, serializationAssemblyPatterns))\n {\n if (securityException != null)\n {\n throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(\n new SecurityException(SR.Format(\n SR.PartialTrustDataContractTypeNotPublic,\n DataContract.GetClrTypeFullName(UnderlyingType)),\n securityException));\n }\n return true;\n }\n\n if (this.BaseContract != null && this.BaseContract.RequiresMemberAccessForWrite(securityException, serializationAssemblyPatterns))\n return true;\n\n if (MethodRequiresMemberAccess(this.OnSerializing, serializationAssemblyPatterns))\n {\n if (securityException != null)\n {\n throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(\n new SecurityException(SR.Format(\n SR.PartialTrustDataContractOnSerializingNotPublic,\n DataContract.GetClrTypeFullName(this.UnderlyingType),\n this.OnSerializing.Name),\n securityException));\n }\n return true;\n }\n\n if (MethodRequiresMemberAccess(this.OnSerialized, serializationAssemblyPatterns))\n {\n if (securityException != null)\n {\n throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(\n new SecurityException(SR.Format(\n SR.PartialTrustDataContractOnSerializedNotPublic,\n DataContract.GetClrTypeFullName(UnderlyingType),\n this.OnSerialized.Name),\n securityException));\n }\n return true;\n }\n\n if (this.Members != null)\n {\n for (int i = 0; i < this.Members.Count; i++)\n {\n if (this.Members[i].RequiresMemberAccessForGet(serializationAssemblyPatterns))\n {\n if (securityException != null)\n {\n if (this.Members[i].MemberInfo is FieldInfo)\n {\n throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(\n new SecurityException(SR.Format(\n SR.PartialTrustDataContractFieldGetNotPublic,\n DataContract.GetClrTypeFullName(UnderlyingType),\n this.Members[i].MemberInfo.Name),\n securityException));\n }\n else\n {\n throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(\n new SecurityException(SR.Format(\n SR.PartialTrustDataContractPropertyGetNotPublic,\n DataContract.GetClrTypeFullName(UnderlyingType),\n this.Members[i].MemberInfo.Name),\n securityException));\n }\n }\n return true;\n }\n }\n }\n\n return false;\n }\n [SecurityCritical]\n\n /// \n /// Critical - holds all state used for (de)serializing classes.\n /// since the data is cached statically, we lock down access to it.\n /// \n private class ClassDataContractCriticalHelper : DataContract.DataContractCriticalHelper\n {\n private ClassDataContract _baseContract;\n private List _members;\n private MethodInfo _onSerializing, _onSerialized;\n private MethodInfo _onDeserializing, _onDeserialized;\n#if !NET_NATIVE\n private DataContractDictionary _knownDataContracts;\n private bool _isKnownTypeAttributeChecked;\n#endif\n private bool _isMethodChecked;\n /// \n /// in serialization/deserialization we base the decision whether to Demand SerializationFormatter permission on this value and hasDataContract\n /// \n private bool _isNonAttributedType;\n\n /// \n /// in serialization/deserialization we base the decision whether to Demand SerializationFormatter permission on this value and isNonAttributedType\n /// \n private bool _hasDataContract;\n#if NET_NATIVE\n private bool _hasExtensionData;\n#endif\n private bool _isScriptObject;\n\n private XmlDictionaryString[] _childElementNamespaces;\n private XmlFormatClassReaderDelegate _xmlFormatReaderDelegate;\n private XmlFormatClassWriterDelegate _xmlFormatWriterDelegate;\n\n public XmlDictionaryString[] ContractNamespaces;\n public XmlDictionaryString[] MemberNames;\n public XmlDictionaryString[] MemberNamespaces;\n\n internal ClassDataContractCriticalHelper() : base()\n {\n }\n\n internal ClassDataContractCriticalHelper(Type type) : base(type)\n {\n XmlQualifiedName stableName = GetStableNameAndSetHasDataContract(type);\n if (type == Globals.TypeOfDBNull)\n {\n this.StableName = stableName;\n _members = new List();\n XmlDictionary dictionary = new XmlDictionary(2);\n this.Name = dictionary.Add(StableName.Name);\n this.Namespace = dictionary.Add(StableName.Namespace);\n this.ContractNamespaces = this.MemberNames = this.MemberNamespaces = Array.Empty();\n EnsureMethodsImported();\n return;\n }\n Type baseType = type.GetTypeInfo().BaseType;\n SetIsNonAttributedType(type);\n SetKeyValuePairAdapterFlags(type);\n this.IsValueType = type.GetTypeInfo().IsValueType;\n if (baseType != null && baseType != Globals.TypeOfObject && baseType != Globals.TypeOfValueType && baseType != Globals.TypeOfUri)\n {\n DataContract baseContract = DataContract.GetDataContract(baseType);\n if (baseContract is CollectionDataContract)\n this.BaseContract = ((CollectionDataContract)baseContract).SharedTypeContract as ClassDataContract;\n else\n this.BaseContract = baseContract as ClassDataContract;\n if (this.BaseContract != null && this.BaseContract.IsNonAttributedType && !_isNonAttributedType)\n {\n throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError\n (new InvalidDataContractException(SR.Format(SR.AttributedTypesCannotInheritFromNonAttributedSerializableTypes,\n DataContract.GetClrTypeFullName(type), DataContract.GetClrTypeFullName(baseType))));\n }\n }\n else\n this.BaseContract = null;\n {\n this.StableName = stableName;\n ImportDataMembers();\n XmlDictionary dictionary = new XmlDictionary(2 + Members.Count);\n Name = dictionary.Add(StableName.Name);\n Namespace = dictionary.Add(StableName.Namespace);\n\n int baseMemberCount = 0;\n int baseContractCount = 0;\n if (BaseContract == null)\n {\n MemberNames = new XmlDictionaryString[Members.Count];\n MemberNamespaces = new XmlDictionaryString[Members.Count];\n ContractNamespaces = new XmlDictionaryString[1];\n }\n else\n {\n baseMemberCount = BaseContract.MemberNames.Length;\n MemberNames = new XmlDictionaryString[Members.Count + baseMemberCount];\n Array.Copy(BaseContract.MemberNames, 0, MemberNames, 0, baseMemberCount);\n MemberNamespaces = new XmlDictionaryString[Members.Count + baseMemberCount];\n Array.Copy(BaseContract.MemberNamespaces, 0, MemberNamespaces, 0, baseMemberCount);\n baseContractCount = BaseContract.ContractNamespaces.Length;\n ContractNamespaces = new XmlDictionaryString[1 + baseContractCount];\n Array.Copy(BaseContract.ContractNamespaces, 0, ContractNamespaces, 0, baseContractCount);\n }\n ContractNamespaces[baseContractCount] = Namespace;\n for (int i = 0; i < Members.Count; i++)\n {\n MemberNames[i + baseMemberCount] = dictionary.Add(Members[i].Name);\n MemberNamespaces[i + baseMemberCount] = Namespace;\n }\n }\n EnsureMethodsImported();\n _isScriptObject = this.IsNonAttributedType &&\n Globals.TypeOfScriptObject_IsAssignableFrom(this.UnderlyingType);\n }\n\n internal ClassDataContractCriticalHelper(Type type, XmlDictionaryString ns, string[] memberNames) : base(type)\n {\n this.StableName = new XmlQualifiedName(GetStableNameAndSetHasDataContract(type).Name, ns.Value);\n ImportDataMembers();\n XmlDictionary dictionary = new XmlDictionary(1 + Members.Count);\n Name = dictionary.Add(StableName.Name);\n Namespace = ns;\n ContractNamespaces = new XmlDictionaryString[] { Namespace };\n MemberNames = new XmlDictionaryString[Members.Count];\n MemberNamespaces = new XmlDictionaryString[Members.Count];\n for (int i = 0; i < Members.Count; i++)\n {\n Members[i].Name = memberNames[i];\n MemberNames[i] = dictionary.Add(Members[i].Name);\n MemberNamespaces[i] = Namespace;\n }\n EnsureMethodsImported();\n }\n\n private void EnsureIsReferenceImported(Type type)\n {\n DataContractAttribute dataContractAttribute;\n bool isReference = false;\n bool hasDataContractAttribute = TryGetDCAttribute(type, out dataContractAttribute);\n\n if (BaseContract != null)\n {\n if (hasDataContractAttribute && dataContractAttribute.IsReferenceSetExplicitly)\n {\n bool baseIsReference = this.BaseContract.IsReference;\n if ((baseIsReference && !dataContractAttribute.IsReference) ||\n (!baseIsReference && dataContractAttribute.IsReference))\n {\n DataContract.ThrowInvalidDataContractException(\n SR.Format(SR.InconsistentIsReference,\n DataContract.GetClrTypeFullName(type),\n dataContractAttribute.IsReference,\n DataContract.GetClrTypeFullName(this.BaseContract.UnderlyingType),\n this.BaseContract.IsReference),\n type);\n }\n else\n {\n isReference = dataContractAttribute.IsReference;\n }\n }\n else\n {\n isReference = this.BaseContract.IsReference;\n }\n }\n else if (hasDataContractAttribute)\n {\n if (dataContractAttribute.IsReference)\n isReference = dataContractAttribute.IsReference;\n }\n\n if (isReference && type.GetTypeInfo().IsValueType)\n {\n DataContract.ThrowInvalidDataContractException(\n SR.Format(SR.ValueTypeCannotHaveIsReference,\n DataContract.GetClrTypeFullName(type),\n true,\n false),\n type);\n return;\n }\n\n this.IsReference = isReference;\n }\n\n private void ImportDataMembers()\n {\n Type type = this.UnderlyingType;\n EnsureIsReferenceImported(type);\n List tempMembers = new List();\n Dictionary memberNamesTable = new Dictionary();\n\n MemberInfo[] memberInfos;\n\n bool isPodSerializable = !_isNonAttributedType || IsKnownSerializableType(type);\n\n if (!isPodSerializable)\n {\n memberInfos = type.GetMembers(BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Public);\n }\n else\n {\n memberInfos = type.GetMembers(BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);\n }\n\n for (int i = 0; i < memberInfos.Length; i++)\n {\n MemberInfo member = memberInfos[i];\n if (HasDataContract)\n {\n object[] memberAttributes = member.GetCustomAttributes(typeof(DataMemberAttribute), false).ToArray();\n if (memberAttributes != null && memberAttributes.Length > 0)\n {\n if (memberAttributes.Length > 1)\n ThrowInvalidDataContractException(SR.Format(SR.TooManyDataMembers, DataContract.GetClrTypeFullName(member.DeclaringType), member.Name));\n\n DataMember memberContract = new DataMember(member);\n\n if (member is PropertyInfo)\n {\n PropertyInfo property = (PropertyInfo)member;\n\n MethodInfo getMethod = property.GetMethod;\n if (getMethod != null && IsMethodOverriding(getMethod))\n continue;\n MethodInfo setMethod = property.SetMethod;\n if (setMethod != null && IsMethodOverriding(setMethod))\n continue;\n if (getMethod == null)\n ThrowInvalidDataContractException(SR.Format(SR.NoGetMethodForProperty, property.DeclaringType, property.Name));\n if (setMethod == null)\n {\n if (!SetIfGetOnlyCollection(memberContract))\n {\n ThrowInvalidDataContractException(SR.Format(SR.NoSetMethodForProperty, property.DeclaringType, property.Name));\n }\n }\n if (getMethod.GetParameters().Length > 0)\n ThrowInvalidDataContractException(SR.Format(SR.IndexedPropertyCannotBeSerialized, property.DeclaringType, property.Name));\n }\n else if (!(member is FieldInfo))\n ThrowInvalidDataContractException(SR.Format(SR.InvalidMember, DataContract.GetClrTypeFullName(type), member.Name));\n\n DataMemberAttribute memberAttribute = (DataMemberAttribute)memberAttributes[0];\n if (memberAttribute.IsNameSetExplicitly)\n {\n if (memberAttribute.Name == null || memberAttribute.Name.Length == 0)\n ThrowInvalidDataContractException(SR.Format(SR.InvalidDataMemberName, member.Name, DataContract.GetClrTypeFullName(type)));\n memberContract.Name = memberAttribute.Name;\n }\n else\n memberContract.Name = member.Name;\n\n memberContract.Name = DataContract.EncodeLocalName(memberContract.Name);\n memberContract.IsNullable = DataContract.IsTypeNullable(memberContract.MemberType);\n memberContract.IsRequired = memberAttribute.IsRequired;\n if (memberAttribute.IsRequired && this.IsReference)\n {\n ThrowInvalidDataContractException(\n SR.Format(SR.IsRequiredDataMemberOnIsReferenceDataContractType,\n DataContract.GetClrTypeFullName(member.DeclaringType),\n member.Name, true), type);\n }\n memberContract.EmitDefaultValue = memberAttribute.EmitDefaultValue;\n memberContract.Order = memberAttribute.Order;\n CheckAndAddMember(tempMembers, memberContract, memberNamesTable);\n }\n }\n else if (!isPodSerializable)\n {\n FieldInfo field = member as FieldInfo;\n PropertyInfo property = member as PropertyInfo;\n if ((field == null && property == null) || (field != null && field.IsInitOnly))\n continue;\n\n object[] memberAttributes = member.GetCustomAttributes(typeof(IgnoreDataMemberAttribute), false).ToArray();\n if (memberAttributes != null && memberAttributes.Length > 0)\n {\n if (memberAttributes.Length > 1)\n ThrowInvalidDataContractException(SR.Format(SR.TooManyIgnoreDataMemberAttributes, DataContract.GetClrTypeFullName(member.DeclaringType), member.Name));\n else\n continue;\n }\n DataMember memberContract = new DataMember(member);\n if (property != null)\n {\n MethodInfo getMethod = property.GetMethod;\n if (getMethod == null || IsMethodOverriding(getMethod) || getMethod.GetParameters().Length > 0)\n continue;\n\n MethodInfo setMethod = property.SetMethod;\n if (setMethod == null)\n {\n if (!SetIfGetOnlyCollection(memberContract))\n continue;\n }\n else\n {\n if (!setMethod.IsPublic || IsMethodOverriding(setMethod))\n continue;\n }\n }\n\n memberContract.Name = DataContract.EncodeLocalName(member.Name);\n memberContract.IsNullable = DataContract.IsTypeNullable(memberContract.MemberType);\n CheckAndAddMember(tempMembers, memberContract, memberNamesTable);\n }\n else\n {\n // [Serializible] and [NonSerialized] are deprecated on FxCore\n // Try to mimic the behavior by allowing certain known types to go through\n // POD types are fine also\n\n FieldInfo field = member as FieldInfo;\n if (CanSerializeMember(field))\n {\n DataMember memberContract = new DataMember(member);\n\n memberContract.Name = DataContract.EncodeLocalName(member.Name);\n object[] optionalFields = null;\n if (optionalFields == null || optionalFields.Length == 0)\n {\n if (this.IsReference)\n {\n ThrowInvalidDataContractException(\n SR.Format(SR.NonOptionalFieldMemberOnIsReferenceSerializableType,\n DataContract.GetClrTypeFullName(member.DeclaringType),\n member.Name, true), type);\n }\n memberContract.IsRequired = true;\n }\n memberContract.IsNullable = DataContract.IsTypeNullable(memberContract.MemberType);\n CheckAndAddMember(tempMembers, memberContract, memberNamesTable);\n }\n }\n }\n if (tempMembers.Count > 1)\n tempMembers.Sort(DataMemberComparer.Singleton);\n\n SetIfMembersHaveConflict(tempMembers);\n\n Interlocked.MemoryBarrier();\n _members = tempMembers;\n }\n\n private static bool CanSerializeMember(FieldInfo field)\n {\n return field != null;\n }\n\n private bool SetIfGetOnlyCollection(DataMember memberContract)\n {\n //OK to call IsCollection here since the use of surrogated collection types is not supported in get-only scenarios\n if (CollectionDataContract.IsCollection(memberContract.MemberType, false /*isConstructorRequired*/) && !memberContract.MemberType.GetTypeInfo().IsValueType)\n {\n memberContract.IsGetOnlyCollection = true;\n return true;\n }\n return false;\n }\n\n private void SetIfMembersHaveConflict(List members)\n {\n if (BaseContract == null)\n return;\n\n int baseTypeIndex = 0;\n List membersInHierarchy = new List();\n foreach (DataMember member in members)\n {\n membersInHierarchy.Add(new Member(member, this.StableName.Namespace, baseTypeIndex));\n }\n ClassDataContract currContract = BaseContract;\n while (currContract != null)\n {\n baseTypeIndex++;\n foreach (DataMember member in currContract.Members)\n {\n membersInHierarchy.Add(new Member(member, currContract.StableName.Namespace, baseTypeIndex));\n }\n currContract = currContract.BaseContract;\n }\n\n IComparer comparer = DataMemberConflictComparer.Singleton;\n membersInHierarchy.Sort(comparer);\n\n for (int i = 0; i < membersInHierarchy.Count - 1; i++)\n {\n int startIndex = i;\n int endIndex = i;\n bool hasConflictingType = false;\n while (endIndex < membersInHierarchy.Count - 1\n && String.CompareOrdinal(membersInHierarchy[endIndex].member.Name, membersInHierarchy[endIndex + 1].member.Name) == 0\n && String.CompareOrdinal(membersInHierarchy[endIndex].ns, membersInHierarchy[endIndex + 1].ns) == 0)\n {\n membersInHierarchy[endIndex].member.ConflictingMember = membersInHierarchy[endIndex + 1].member;\n if (!hasConflictingType)\n {\n if (membersInHierarchy[endIndex + 1].member.HasConflictingNameAndType)\n {\n hasConflictingType = true;\n }\n else\n {\n hasConflictingType = (membersInHierarchy[endIndex].member.MemberType != membersInHierarchy[endIndex + 1].member.MemberType);\n }\n }\n endIndex++;\n }\n\n if (hasConflictingType)\n {\n for (int j = startIndex; j <= endIndex; j++)\n {\n membersInHierarchy[j].member.HasConflictingNameAndType = true;\n }\n }\n\n i = endIndex + 1;\n }\n }\n\n /// \n /// Critical - sets the critical hasDataContract field\n /// Safe - uses a trusted critical API (DataContract.GetStableName) to calculate the value\n /// does not accept the value from the caller\n /// \n //CSD16748\n //[SecuritySafeCritical]\n private XmlQualifiedName GetStableNameAndSetHasDataContract(Type type)\n {\n return DataContract.GetStableName(type, out _hasDataContract);\n }\n\n /// \n /// RequiresReview - marked SRR because callers may need to depend on isNonAttributedType for a security decision\n /// isNonAttributedType must be calculated correctly\n /// SetIsNonAttributedType should not be called before GetStableNameAndSetHasDataContract since it \n /// is dependent on the correct calculation of hasDataContract\n /// Safe - does not let caller influence isNonAttributedType calculation; no harm in leaking value\n /// \n private void SetIsNonAttributedType(Type type)\n {\n _isNonAttributedType = !_hasDataContract && IsNonAttributedTypeValidForSerialization(type);\n }\n\n private static bool IsMethodOverriding(MethodInfo method)\n {\n return method.IsVirtual && ((method.Attributes & MethodAttributes.NewSlot) == 0);\n }\n\n internal void EnsureMethodsImported()\n {\n if (!_isMethodChecked && UnderlyingType != null)\n {\n lock (this)\n {\n if (!_isMethodChecked)\n {\n Type type = this.UnderlyingType;\n MethodInfo[] methods = type.GetMethods(BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);\n for (int i = 0; i < methods.Length; i++)\n {\n MethodInfo method = methods[i];\n Type prevAttributeType = null;\n ParameterInfo[] parameters = method.GetParameters();\n //THese attributes are cut from mscorlib.\n if (IsValidCallback(method, parameters, Globals.TypeOfOnSerializingAttribute, _onSerializing, ref prevAttributeType))\n _onSerializing = method;\n if (IsValidCallback(method, parameters, Globals.TypeOfOnSerializedAttribute, _onSerialized, ref prevAttributeType))\n _onSerialized = method;\n if (IsValidCallback(method, parameters, Globals.TypeOfOnDeserializingAttribute, _onDeserializing, ref prevAttributeType))\n _onDeserializing = method;\n if (IsValidCallback(method, parameters, Globals.TypeOfOnDeserializedAttribute, _onDeserialized, ref prevAttributeType))\n _onDeserialized = method;\n }\n Interlocked.MemoryBarrier();\n _isMethodChecked = true;\n }\n }\n }\n }\n\n\n private static bool IsValidCallback(MethodInfo method, ParameterInfo[] parameters, Type attributeType, MethodInfo currentCallback, ref Type prevAttributeType)\n {\n if (method.IsDefined(attributeType, false))\n {\n if (currentCallback != null)\n DataContract.ThrowInvalidDataContractException(SR.Format(SR.DuplicateCallback, method, currentCallback, DataContract.GetClrTypeFullName(method.DeclaringType), attributeType), method.DeclaringType);\n else if (prevAttributeType != null)\n DataContract.ThrowInvalidDataContractException(SR.Format(SR.DuplicateAttribute, prevAttributeType, attributeType, DataContract.GetClrTypeFullName(method.DeclaringType), method), method.DeclaringType);\n else if (method.IsVirtual)\n DataContract.ThrowInvalidDataContractException(SR.Format(SR.CallbacksCannotBeVirtualMethods, method, DataContract.GetClrTypeFullName(method.DeclaringType), attributeType), method.DeclaringType);\n else\n {\n if (method.ReturnType != Globals.TypeOfVoid)\n DataContract.ThrowInvalidDataContractException(SR.Format(SR.CallbackMustReturnVoid, DataContract.GetClrTypeFullName(method.DeclaringType), method), method.DeclaringType);\n if (parameters == null || parameters.Length != 1 || parameters[0].ParameterType != Globals.TypeOfStreamingContext)\n DataContract.ThrowInvalidDataContractException(SR.Format(SR.CallbackParameterInvalid, DataContract.GetClrTypeFullName(method.DeclaringType), method, Globals.TypeOfStreamingContext), method.DeclaringType);\n\n prevAttributeType = attributeType;\n }\n return true;\n }\n return false;\n }\n\n internal ClassDataContract BaseContract\n {\n get { return _baseContract; }\n set\n {\n _baseContract = value;\n if (_baseContract != null && IsValueType)\n ThrowInvalidDataContractException(SR.Format(SR.ValueTypeCannotHaveBaseType, StableName.Name, StableName.Namespace, _baseContract.StableName.Name, _baseContract.StableName.Namespace));\n }\n }\n\n internal List Members\n {\n get { return _members; }\n }\n\n internal MethodInfo OnSerializing\n {\n get\n {\n EnsureMethodsImported();\n return _onSerializing;\n }\n }\n\n internal MethodInfo OnSerialized\n {\n get\n {\n EnsureMethodsImported();\n return _onSerialized;\n }\n }\n\n internal MethodInfo OnDeserializing\n {\n get\n {\n EnsureMethodsImported();\n return _onDeserializing;\n }\n }\n\n internal MethodInfo OnDeserialized\n {\n get\n {\n EnsureMethodsImported();\n return _onDeserialized;\n }\n }\n\n#if !NET_NATIVE\n internal override DataContractDictionary KnownDataContracts\n {\n [SecurityCritical]\n get\n {\n if (!_isKnownTypeAttributeChecked && UnderlyingType != null)\n {\n lock (this)\n {\n if (!_isKnownTypeAttributeChecked)\n {\n _knownDataContracts = DataContract.ImportKnownTypeAttributes(this.UnderlyingType);\n Interlocked.MemoryBarrier();\n _isKnownTypeAttributeChecked = true;\n }\n }\n }\n return _knownDataContracts;\n }\n [SecurityCritical]\n set\n { _knownDataContracts = value; }\n }\n#endif\n\n internal bool HasDataContract\n {\n get { return _hasDataContract; }\n#if NET_NATIVE\n set { _hasDataContract = value; }\n#endif\n }\n#if NET_NATIVE\n internal bool HasExtensionData\n {\n get { return _hasExtensionData; }\n set { _hasExtensionData = value; }\n }\n#endif\n\n internal bool IsNonAttributedType\n {\n get { return _isNonAttributedType; }\n }\n\n private void SetKeyValuePairAdapterFlags(Type type)\n {\n if (type.GetTypeInfo().IsGenericType && type.GetGenericTypeDefinition() == Globals.TypeOfKeyValuePairAdapter)\n {\n _isKeyValuePairAdapter = true;\n _keyValuePairGenericArguments = type.GetGenericArguments();\n _keyValuePairCtorInfo = type.GetConstructor(Globals.ScanAllMembers, new Type[] { Globals.TypeOfKeyValuePair.MakeGenericType(_keyValuePairGenericArguments) });\n _getKeyValuePairMethodInfo = type.GetMethod(\"GetKeyValuePair\", Globals.ScanAllMembers);\n }\n }\n\n private bool _isKeyValuePairAdapter;\n private Type[] _keyValuePairGenericArguments;\n private ConstructorInfo _keyValuePairCtorInfo;\n private MethodInfo _getKeyValuePairMethodInfo;\n\n internal bool IsKeyValuePairAdapter\n {\n get { return _isKeyValuePairAdapter; }\n }\n\n internal bool IsScriptObject\n {\n get { return _isScriptObject; }\n }\n\n internal Type[] KeyValuePairGenericArguments\n {\n get { return _keyValuePairGenericArguments; }\n }\n\n internal ConstructorInfo KeyValuePairAdapterConstructorInfo\n {\n get { return _keyValuePairCtorInfo; }\n }\n\n internal MethodInfo GetKeyValuePairMethodInfo\n {\n get { return _getKeyValuePairMethodInfo; }\n }\n\n internal ConstructorInfo GetNonAttributedTypeConstructor()\n {\n if (!this.IsNonAttributedType)\n return null;\n\n Type type = UnderlyingType;\n\n if (type.GetTypeInfo().IsValueType)\n return null;\n\n ConstructorInfo ctor = type.GetConstructor(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public, Array.Empty());\n if (ctor == null)\n throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.Format(SR.NonAttributedSerializableTypesMustHaveDefaultConstructor, DataContract.GetClrTypeFullName(type))));\n\n return ctor;\n }\n\n internal XmlFormatClassWriterDelegate XmlFormatWriterDelegate\n {\n get { return _xmlFormatWriterDelegate; }\n set { _xmlFormatWriterDelegate = value; }\n }\n\n internal XmlFormatClassReaderDelegate XmlFormatReaderDelegate\n {\n get { return _xmlFormatReaderDelegate; }\n set { _xmlFormatReaderDelegate = value; }\n }\n\n public XmlDictionaryString[] ChildElementNamespaces\n {\n get { return _childElementNamespaces; }\n set { _childElementNamespaces = value; }\n }\n\n\n internal struct Member\n {\n internal Member(DataMember member, string ns, int baseTypeIndex)\n {\n this.member = member;\n this.ns = ns;\n this.baseTypeIndex = baseTypeIndex;\n }\n internal DataMember member;\n internal string ns;\n internal int baseTypeIndex;\n }\n\n internal class DataMemberConflictComparer : IComparer\n {\n [SecuritySafeCritical]\n public int Compare(Member x, Member y)\n {\n int nsCompare = String.CompareOrdinal(x.ns, y.ns);\n if (nsCompare != 0)\n return nsCompare;\n\n int nameCompare = String.CompareOrdinal(x.member.Name, y.member.Name);\n if (nameCompare != 0)\n return nameCompare;\n\n return x.baseTypeIndex - y.baseTypeIndex;\n }\n\n internal static DataMemberConflictComparer Singleton = new DataMemberConflictComparer();\n }\n\n#if NET_NATIVE\n internal ClassDataContractCriticalHelper Clone()\n {\n ClassDataContractCriticalHelper clonedHelper = new ClassDataContractCriticalHelper(this.UnderlyingType);\n\n clonedHelper._baseContract = this._baseContract;\n clonedHelper._childElementNamespaces = this._childElementNamespaces;\n clonedHelper.ContractNamespaces = this.ContractNamespaces;\n clonedHelper._hasDataContract = this._hasDataContract;\n clonedHelper._isMethodChecked = this._isMethodChecked;\n clonedHelper._isNonAttributedType = this._isNonAttributedType;\n clonedHelper.IsReference = this.IsReference;\n clonedHelper.IsValueType = this.IsValueType;\n clonedHelper.MemberNames = this.MemberNames;\n clonedHelper.MemberNamespaces = this.MemberNamespaces;\n clonedHelper._members = this._members;\n clonedHelper.Name = this.Name;\n clonedHelper.Namespace = this.Namespace;\n clonedHelper._onDeserialized = this._onDeserialized;\n clonedHelper._onDeserializing = this._onDeserializing;\n clonedHelper._onSerialized = this._onSerialized;\n clonedHelper._onSerializing = this._onSerializing;\n clonedHelper.StableName = this.StableName;\n clonedHelper.TopLevelElementName = this.TopLevelElementName;\n clonedHelper.TopLevelElementNamespace = this.TopLevelElementNamespace;\n clonedHelper._xmlFormatReaderDelegate = this._xmlFormatReaderDelegate;\n clonedHelper._xmlFormatWriterDelegate = this._xmlFormatWriterDelegate;\n\n return clonedHelper;\n }\n#endif\n }\n\n\n internal class DataMemberComparer : IComparer\n {\n public int Compare(DataMember x, DataMember y)\n {\n int orderCompare = x.Order - y.Order;\n if (orderCompare != 0)\n return orderCompare;\n\n return String.CompareOrdinal(x.Name, y.Name);\n }\n\n internal static DataMemberComparer Singleton = new DataMemberComparer();\n }\n\n#if !NET_NATIVE\n /// \n /// Get object type for Xml/JsonFormmatReaderGenerator\n /// \n internal Type ObjectType\n {\n get\n {\n Type type = UnderlyingType;\n if (type.GetTypeInfo().IsValueType && !IsNonAttributedType)\n {\n type = Globals.TypeOfValueType;\n }\n return type;\n }\n }\n#endif\n\n#if NET_NATIVE\n internal ClassDataContract Clone()\n {\n ClassDataContract clonedDc = new ClassDataContract(this.UnderlyingType);\n clonedDc._helper = _helper.Clone();\n clonedDc.ContractNamespaces = this.ContractNamespaces;\n clonedDc.ChildElementNamespaces = this.ChildElementNamespaces;\n clonedDc.MemberNames = this.MemberNames;\n clonedDc.MemberNamespaces = this.MemberNamespaces;\n clonedDc.XmlFormatWriterDelegate = this.XmlFormatWriterDelegate;\n clonedDc.XmlFormatReaderDelegate = this.XmlFormatReaderDelegate;\n return clonedDc;\n }\n\n internal void UpdateNamespaceAndMembers(Type type, XmlDictionaryString ns, string[] memberNames)\n {\n this.StableName = new XmlQualifiedName(GetStableName(type).Name, ns.Value);\n this.Namespace = ns;\n XmlDictionary dictionary = new XmlDictionary(1 + memberNames.Length);\n this.Name = dictionary.Add(StableName.Name);\n this.Namespace = ns;\n this.ContractNamespaces = new XmlDictionaryString[] { ns };\n this.MemberNames = new XmlDictionaryString[memberNames.Length];\n this.MemberNamespaces = new XmlDictionaryString[memberNames.Length];\n for (int i = 0; i < memberNames.Length; i++)\n {\n this.MemberNames[i] = dictionary.Add(memberNames[i]);\n this.MemberNamespaces[i] = ns;\n }\n }\n#endif\n }\n}\n"},"gt":{"kind":"string","value":""}}},{"rowIdx":98461,"cells":{"context":{"kind":"string","value":"\n/* ====================================================================\n Licensed to the Apache Software Foundation (ASF) Under one or more\n contributor license agreements. See the NOTICE file distributed with\n this work for Additional information regarding copyright ownership.\n The ASF licenses this file to You Under the Apache License, Version 2.0\n (the \"License\"); you may not use this file except in compliance with\n the License. You may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\n Unless required by applicable law or agreed to in writing, software\n distributed Under the License is distributed on an \"AS Is\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations Under the License.\n==================================================================== */\n\n\nnamespace NPOI.HSSF.Record.Chart\n{\n using System;\n using System.Text;\n using NPOI.Util;\n\n /**\n * The font basis record stores various font metrics.\n * NOTE: This source is automatically generated please do not modify this file. Either subclass or\n * Remove the record in src/records/definitions.\n\n * @author Glen Stampoultzis (glens at apache.org)\n */\n internal class FontBasisRecord\n : StandardRecord\n {\n public const short sid = 0x1060;\n private short field_1_xBasis;\n private short field_2_yBasis;\n private short field_3_heightBasis;\n private short field_4_scale;\n private short field_5_indexToFontTable;\n\n\n public FontBasisRecord()\n {\n\n }\n\n /**\n * Constructs a FontBasis record and Sets its fields appropriately.\n *\n * @param in the RecordInputstream to Read the record from\n */\n\n public FontBasisRecord(RecordInputStream in1)\n {\n\n field_1_xBasis = in1.ReadShort();\n field_2_yBasis = in1.ReadShort();\n field_3_heightBasis = in1.ReadShort();\n field_4_scale = in1.ReadShort();\n field_5_indexToFontTable = in1.ReadShort();\n }\n\n public override String ToString()\n {\n StringBuilder buffer = new StringBuilder();\n\n buffer.Append(\"[FBI]\\n\");\n buffer.Append(\" .xBasis = \")\n .Append(\"0x\").Append(HexDump.ToHex(XBasis))\n .Append(\" (\").Append(XBasis).Append(\" )\");\n buffer.Append(Environment.NewLine);\n buffer.Append(\" .yBasis = \")\n .Append(\"0x\").Append(HexDump.ToHex(YBasis))\n .Append(\" (\").Append(YBasis).Append(\" )\");\n buffer.Append(Environment.NewLine);\n buffer.Append(\" .heightBasis = \")\n .Append(\"0x\").Append(HexDump.ToHex(HeightBasis))\n .Append(\" (\").Append(HeightBasis).Append(\" )\");\n buffer.Append(Environment.NewLine);\n buffer.Append(\" .scale = \")\n .Append(\"0x\").Append(HexDump.ToHex(Scale))\n .Append(\" (\").Append(Scale).Append(\" )\");\n buffer.Append(Environment.NewLine);\n buffer.Append(\" .indexToFontTable = \")\n .Append(\"0x\").Append(HexDump.ToHex(IndexToFontTable))\n .Append(\" (\").Append(IndexToFontTable).Append(\" )\");\n buffer.Append(Environment.NewLine);\n\n buffer.Append(\"[/FBI]\\n\");\n return buffer.ToString();\n }\n\n public override void Serialize(ILittleEndianOutput out1)\n {\n out1.WriteShort(field_1_xBasis);\n out1.WriteShort(field_2_yBasis);\n out1.WriteShort(field_3_heightBasis);\n out1.WriteShort(field_4_scale);\n out1.WriteShort(field_5_indexToFontTable);\n }\n\n /**\n * Size of record (exluding 4 byte header)\n */\n protected override int DataSize\n {\n get { return 2 + 2 + 2 + 2 + 2; }\n }\n\n public override short Sid\n {\n get { return sid; }\n }\n\n public override Object Clone()\n {\n FontBasisRecord rec = new FontBasisRecord();\n\n rec.field_1_xBasis = field_1_xBasis;\n rec.field_2_yBasis = field_2_yBasis;\n rec.field_3_heightBasis = field_3_heightBasis;\n rec.field_4_scale = field_4_scale;\n rec.field_5_indexToFontTable = field_5_indexToFontTable;\n return rec;\n }\n\n\n\n\n /**\n * Get the x Basis field for the FontBasis record.\n */\n public short XBasis\n {\n get\n {\n return field_1_xBasis;\n }\n set \n {\n field_1_xBasis = value;\n }\n }\n\n /**\n * Get the y Basis field for the FontBasis record.\n */\n public short YBasis\n {\n get\n {\n return field_2_yBasis;\n }\n set \n {\n field_2_yBasis = value;\n }\n }\n\n /**\n * Get the height basis field for the FontBasis record.\n */\n public short HeightBasis\n {\n get\n {\n return field_3_heightBasis;\n }\n set \n {\n this.field_3_heightBasis = value;\n }\n }\n\n /**\n * Get the scale field for the FontBasis record.\n */\n public short Scale\n {\n get\n {\n return field_4_scale;\n }\n set \n {\n field_4_scale = value;\n }\n }\n\n /**\n * Get the index to font table field for the FontBasis record.\n */\n public short IndexToFontTable\n {\n get\n {\n return field_5_indexToFontTable;\n }\n set \n {\n this.field_5_indexToFontTable = value;\n }\n }\n\n\n }\n\n}\n"},"gt":{"kind":"string","value":""}}},{"rowIdx":98462,"cells":{"context":{"kind":"string","value":"using System;\nusing System.Linq;\nusing System.Collections;\nusing System.Xml;\nusing Umbraco.Core;\nusing Umbraco.Core.Cache;\nusing Umbraco.Core.Configuration;\nusing Umbraco.Core.IO;\nusing Umbraco.Core.Logging;\nusing Umbraco.Core.Strings;\nusing umbraco.DataLayer;\nusing System.Text.RegularExpressions;\nusing System.IO;\nusing System.Collections.Generic;\nusing umbraco.cms.businesslogic.cache;\nusing umbraco.BusinessLogic;\nusing umbraco.cms.businesslogic.web;\n\nnamespace umbraco.cms.businesslogic.template\n{\n /// \n /// Summary description for Template.\n /// \n //[Obsolete(\"Obsolete, This class will eventually be phased out - Use Umbraco.Core.Models.Template\", false)]\n public class Template : CMSNode\n {\n \n #region Private members\n\n private string _OutputContentType;\n private string _design;\n private string _alias;\n private string _oldAlias;\n private int _mastertemplate;\n private bool _hasChildrenInitialized = false;\n private bool _hasChildren;\n\n #endregion\n\n #region Static members\n\n public static readonly string UmbracoMasterTemplate = SystemDirectories.Umbraco + \"/masterpages/default.master\";\n private static Hashtable _templateAliases = new Hashtable();\n private static volatile bool _templateAliasesInitialized = false;\n private static readonly object TemplateLoaderLocker = new object();\n private static readonly Guid ObjectType = new Guid(Constants.ObjectTypes.Template);\n\t\tprivate static readonly char[] NewLineChars = Environment.NewLine.ToCharArray();\n\n #endregion\n\n\t\t[Obsolete(\"Use TemplateFilePath instead\")]\n public string MasterPageFile\n {\n get { return TemplateFilePath; }\n }\n\n\t\t/// \n\t\t/// Returns the file path for the current template\n\t\t/// \n\t public string TemplateFilePath\n\t {\n\t\t get\n\t\t {\n\t\t\t\tswitch (DetermineRenderingEngine(this))\n\t\t\t\t{\n\t\t\t\t\tcase RenderingEngine.Mvc:\n\t\t\t\t\t\treturn ViewHelper.GetFilePath(this);\n\t\t\t\t\tcase RenderingEngine.WebForms:\n\t\t\t\t\t\treturn MasterPageHelper.GetFilePath(this);\n\t\t\t\t\tdefault:\n\t\t\t\t\t\tthrow new ArgumentOutOfRangeException();\n\t\t\t\t}\t \n\t\t }\n\t }\n\n public static Hashtable TemplateAliases\n {\n get { return _templateAliases; }\n set { _templateAliases = value; }\n }\n\n #region Constructors\n public Template(int id) : base(id) { }\n\n public Template(Guid id) : base(id) { }\n #endregion\n\n /// \n /// Used to persist object changes to the database. In Version3.0 it's just a stub for future compatibility\n /// \n public override void Save()\n {\n SaveEventArgs e = new SaveEventArgs();\n FireBeforeSave(e);\n\n if (!e.Cancel)\n {\n base.Save();\n FireAfterSave(e);\n }\n }\n\n public string GetRawText()\n {\n return base.Text;\n }\n\n public override string Text\n {\n get\n {\n string tempText = base.Text;\n if (!tempText.StartsWith(\"#\"))\n return tempText;\n else\n {\n language.Language lang = language.Language.GetByCultureCode(System.Threading.Thread.CurrentThread.CurrentCulture.Name);\n if (lang != null)\n {\n if (Dictionary.DictionaryItem.hasKey(tempText.Substring(1, tempText.Length - 1)))\n {\n Dictionary.DictionaryItem di = new Dictionary.DictionaryItem(tempText.Substring(1, tempText.Length - 1));\n if (di != null)\n return di.Value(lang.id);\n }\n }\n\n return \"[\" + tempText + \"]\";\n }\n }\n set\n {\n FlushCache();\n base.Text = value;\n }\n }\n\n public string OutputContentType\n {\n get { return _OutputContentType; }\n set { _OutputContentType = value; }\n }\n\n protected override void setupNode()\n {\n base.setupNode();\n\n IRecordsReader dr = SqlHelper.ExecuteReader(\"Select alias,design,master from cmsTemplate where nodeId = \" + this.Id);\n bool hasRows = dr.Read();\n if (hasRows)\n {\n _alias = dr.GetString(\"alias\");\n _design = dr.GetString(\"design\");\n //set the master template to zero if it's null\n _mastertemplate = dr.IsNull(\"master\") ? 0 : dr.GetInt(\"master\");\n }\n dr.Close();\n\n\t\t\tif (UmbracoConfig.For.UmbracoSettings().Templates.DefaultRenderingEngine == RenderingEngine.Mvc && ViewHelper.ViewExists(this))\n _design = ViewHelper.GetFileContents(this);\n else\n _design = MasterPageHelper.GetFileContents(this);\n\n }\n\t\t\n public new string Path\n {\n get\n {\n List path = new List();\n Template working = this;\n while (working != null)\n {\n path.Add(working.Id);\n try\n {\n if (working.MasterTemplate != 0)\n {\n working = new Template(working.MasterTemplate);\n }\n else\n {\n working = null;\n }\n }\n catch (ArgumentException)\n {\n working = null;\n }\n }\n path.Add(-1);\n path.Reverse();\n string sPath = string.Join(\",\", path.ConvertAll(item => item.ToString()).ToArray());\n return sPath;\n }\n set\n {\n base.Path = value;\n }\n }\n\n public string Alias\n {\n get { return _alias; }\n set\n {\n FlushCache();\n _oldAlias = _alias;\n _alias = value.ToCleanString(CleanStringType.UnderscoreAlias);\n\n SqlHelper.ExecuteNonQuery(\"Update cmsTemplate set alias = @alias where NodeId = \" + this.Id, SqlHelper.CreateParameter(\"@alias\", _alias));\n _templateAliasesInitialized = false;\n\n InitTemplateAliases();\n }\n\n }\n\n public bool HasMasterTemplate\n {\n get { return (_mastertemplate > 0); }\n }\n\n\n public override bool HasChildren\n {\n get\n {\n if (!_hasChildrenInitialized)\n {\n _hasChildren = SqlHelper.ExecuteScalar(\"select count(NodeId) as tmp from cmsTemplate where master = \" + Id) > 0;\n }\n return _hasChildren;\n }\n set\n {\n _hasChildrenInitialized = true;\n _hasChildren = value;\n }\n }\n\n public int MasterTemplate\n {\n get { return _mastertemplate; }\n set\n {\n FlushCache();\n _mastertemplate = value;\n\n //set to null if it's zero\n object masterVal = value;\n if (value == 0) masterVal = DBNull.Value;\n\n SqlHelper.ExecuteNonQuery(\"Update cmsTemplate set master = @master where NodeId = @nodeId\",\n SqlHelper.CreateParameter(\"@master\", masterVal),\n SqlHelper.CreateParameter(\"@nodeId\", this.Id));\n }\n }\n\n public string Design\n {\n get { return _design; }\n set\n {\n FlushCache();\n\n _design = value.Trim(NewLineChars);\n\n //we only switch to MVC View editing if the template has a view file, and MVC editing is enabled\n if (UmbracoConfig.For.UmbracoSettings().Templates.DefaultRenderingEngine == RenderingEngine.Mvc && !MasterPageHelper.IsMasterPageSyntax(_design))\n\t\t\t\t{\n\t\t\t\t\tMasterPageHelper.RemoveMasterPageFile(this.Alias);\n\t\t\t\t\tMasterPageHelper.RemoveMasterPageFile(_oldAlias);\n\t\t\t\t\t_design = ViewHelper.UpdateViewFile(this, _oldAlias);\n\t\t\t\t}\n\t\t\t\telse if (UmbracoConfig.For.UmbracoSettings().Templates.UseAspNetMasterPages)\n\t\t\t\t{\n\t\t\t\t\tViewHelper.RemoveViewFile(this.Alias);\n\t\t\t\t\tViewHelper.RemoveViewFile(_oldAlias);\n\t\t\t\t\t_design = MasterPageHelper.UpdateMasterPageFile(this, _oldAlias);\n\t\t\t\t}\n \n\n SqlHelper.ExecuteNonQuery(\"Update cmsTemplate set design = @design where NodeId = @id\",\n SqlHelper.CreateParameter(\"@design\", _design),\n SqlHelper.CreateParameter(\"@id\", Id));\n }\n }\n\n public XmlNode ToXml(XmlDocument doc)\n {\n XmlNode template = doc.CreateElement(\"Template\");\n template.AppendChild(xmlHelper.addTextNode(doc, \"Name\", base.Text));\n template.AppendChild(xmlHelper.addTextNode(doc, \"Alias\", this.Alias));\n\n if (this.MasterTemplate != 0)\n {\n template.AppendChild(xmlHelper.addTextNode(doc, \"Master\", new Template(this.MasterTemplate).Alias));\n }\n\n template.AppendChild(xmlHelper.addCDataNode(doc, \"Design\", this.Design));\n\n return template;\n }\n\n /// \n /// Removes any references to this templates from child templates, documenttypes and documents\n /// \n public void RemoveAllReferences()\n {\n if (HasChildren)\n {\n foreach (Template t in Template.GetAllAsList().FindAll(delegate(Template t) { return t.MasterTemplate == this.Id; }))\n {\n t.MasterTemplate = 0;\n }\n }\n\n RemoveFromDocumentTypes();\n\n // remove from documents\n Document.RemoveTemplateFromDocument(this.Id);\n }\n\n public void RemoveFromDocumentTypes()\n {\n foreach (DocumentType dt in DocumentType.GetAllAsList().Where(x => x.allowedTemplates.Select(t => t.Id).Contains(this.Id)))\n {\n dt.RemoveTemplate(this.Id);\n dt.Save();\n }\n }\n\n public IEnumerable GetDocumentTypes()\n {\n return DocumentType.GetAllAsList().Where(x => x.allowedTemplates.Select(t => t.Id).Contains(this.Id));\n }\n\n\t /// \n\t /// This checks what the default rendering engine is set in config but then also ensures that there isn't already \n\t /// a template that exists in the opposite rendering engine's template folder, then returns the appropriate \n\t /// rendering engine to use.\n\t /// \n\t /// \n\t /// If a template body is specified we'll check if it contains master page markup, if it does we'll auto assume its webforms \n\t /// \n\t /// \n\t /// The reason this is required is because for example, if you have a master page file already existing under ~/masterpages/Blah.aspx\n\t /// and then you go to create a template in the tree called Blah and the default rendering engine is MVC, it will create a Blah.cshtml \n\t /// empty template in ~/Views. This means every page that is using Blah will go to MVC and render an empty page. \n\t /// This is mostly related to installing packages since packages install file templates to the file system and then create the \n\t /// templates in business logic. Without this, it could cause the wrong rendering engine to be used for a package.\n\t /// \n\t private static RenderingEngine DetermineRenderingEngine(Template t, string design = null)\n\t\t{\n var engine = UmbracoConfig.For.UmbracoSettings().Templates.DefaultRenderingEngine;\n\n\t\t\tif (!design.IsNullOrWhiteSpace() && MasterPageHelper.IsMasterPageSyntax(design))\n\t\t\t{\n\t\t\t\t//there is a design but its definitely a webforms design\n\t\t\t\treturn RenderingEngine.WebForms;\n\t\t\t}\n\n\t\t\tswitch (engine)\n\t\t\t{\n\t\t\t\tcase RenderingEngine.Mvc:\n\t\t\t\t\t//check if there's a view in ~/masterpages\n\t\t\t\t\tif (MasterPageHelper.MasterPageExists(t) && !ViewHelper.ViewExists(t))\n\t\t\t\t\t{\n\t\t\t\t\t\t//change this to webforms since there's already a file there for this template alias\n\t\t\t\t\t\tengine = RenderingEngine.WebForms;\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\tcase RenderingEngine.WebForms:\n\t\t\t\t\t//check if there's a view in ~/views\n\t\t\t\t\tif (ViewHelper.ViewExists(t) && !MasterPageHelper.MasterPageExists(t))\n\t\t\t\t\t{\n\t\t\t\t\t\t//change this to mvc since there's already a file there for this template alias\n\t\t\t\t\t\tengine = RenderingEngine.Mvc;\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t}\n\t\t\treturn engine;\n\t\t}\n\n public static Template MakeNew(string Name, BusinessLogic.User u, Template master)\n {\n return MakeNew(Name, u, master, null);\n }\n \n private static Template MakeNew(string name, BusinessLogic.User u, string design)\n {\n return MakeNew(name, u, null, design);\n }\n\n public static Template MakeNew(string name, BusinessLogic.User u)\n {\n return MakeNew(name, u, design: null);\n }\n\n private static Template MakeNew(string name, BusinessLogic.User u, Template master, string design)\n {\n // CMSNode MakeNew(int parentId, Guid objectType, int userId, int level, string text, Guid uniqueID)\n var node = MakeNew(-1, ObjectType, u.Id, 1, name, Guid.NewGuid());\n\n //ensure unique alias \n name = name.ToCleanString(CleanStringType.UnderscoreAlias);\n if (GetByAlias(name) != null)\n name = EnsureUniqueAlias(name, 1);\n //name = name.Replace(\"/\", \".\").Replace(\"\\\\\", \"\"); //why? ToSafeAlias() already removes those chars\n\n if (name.Length > 100)\n name = name.Substring(0, 95); // + \"...\"; // no, these are invalid alias chars\n \n SqlHelper.ExecuteNonQuery(\"INSERT INTO cmsTemplate (NodeId, Alias, design, master) VALUES (@nodeId, @alias, @design, @master)\",\n SqlHelper.CreateParameter(\"@nodeId\", node.Id),\n SqlHelper.CreateParameter(\"@alias\", name),\n SqlHelper.CreateParameter(\"@design\", ' '),\n SqlHelper.CreateParameter(\"@master\", DBNull.Value));\n\n var template = new Template(node.Id);\n if (master != null)\n template.MasterTemplate = master.Id;\n\n\t\t\tswitch (DetermineRenderingEngine(template, design))\n\t\t\t{\n\t\t\t\tcase RenderingEngine.Mvc:\n\t\t\t\t\tViewHelper.CreateViewFile(template);\n\t\t\t\t\tbreak;\n\t\t\t\tcase RenderingEngine.WebForms:\n\t\t\t\t\tMasterPageHelper.CreateMasterPage(template);\n\t\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\t//if a design is supplied ensure it is updated.\n\t\t\tif (design.IsNullOrWhiteSpace() == false)\n\t\t\t{\n\t\t\t\ttemplate.ImportDesign(design);\n\t\t\t}\n\n var e = new NewEventArgs();\n template.OnNew(e);\n\n return template;\n }\n\n private static string EnsureUniqueAlias(string alias, int attempts)\n {\n if (GetByAlias(alias + attempts.ToString()) == null)\n return alias + attempts.ToString();\n else\n {\n attempts++;\n return EnsureUniqueAlias(alias, attempts);\n }\n }\n\n public static Template GetByAlias(string Alias)\n {\n return GetByAlias(Alias, false);\n }\n\n public static Template GetByAlias(string Alias, bool useCache)\n {\n\t\t\tif (!useCache)\n\t\t\t{\n\t\t\t\ttry\n\t\t\t\t{\n\t\t\t\t\treturn new Template(SqlHelper.ExecuteScalar(\"select nodeId from cmsTemplate where alias = @alias\", SqlHelper.CreateParameter(\"@alias\", Alias)));\n\t\t\t\t}\n\t\t\t\tcatch\n\t\t\t\t{\n\t\t\t\t\treturn null;\n\t\t\t\t}\t\n\t\t\t}\t\t\t\n\n\t\t\t//return from cache instead\n\t var id = GetTemplateIdFromAlias(Alias);\n\t\t\treturn id == 0 ? null : GetTemplate(id);\n }\n\n [Obsolete(\"Obsolete, please use GetAllAsList() method instead\", true)]\n public static Template[] getAll()\n {\n return GetAllAsList().ToArray();\n }\n\n public static List