code stringlengths 1 2.01M | repo_name stringlengths 3 62 | path stringlengths 1 267 | language stringclasses 231
values | license stringclasses 13
values | size int64 1 2.01M |
|---|---|---|---|---|---|
start pnunit-agent agent.conf
pnunit-launcher test.conf | zyyin2005-lokad | Resource/Tool/NUnit/runpnunit.bat | Batchfile | bsd | 55 |
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:msxsl="urn:schemas-microsoft-com:xslt">
<!-- saved from url=(0022)http://www.ncover.org/ -->
<!-- created by Yves Lorphelin, largely inspired by the nunitsumary.xsl (see nantcontrib.sourceforge.net)-->
<xsl:template match="coverage">
<html>
<head>
<title>NCover Code Coverage Report</title>
<style>
BODY {
font: small verdana, arial, helvetica;
color:#000000;
}
P {
line-height:1.5em;
margin-top:0.5em; margin-bottom:1.0em;
}
H1 {
MARGIN: 0px 0px 5px;
FONT: bold larger arial, verdana, helvetica;
}
H2 {
MARGIN-TOP: 1em; MARGIN-BOTTOM: 0.5em;
FONT: larger verdana,arial,helvetica
}
H3 {
MARGIN-BOTTOM: 0.5em; FONT: bold 13px verdana,arial,helvetica
}
H4 {
MARGIN-BOTTOM: 0.5em; FONT: bold 100% verdana,arial,helvetica
}
H5 {
MARGIN-BOTTOM: 0.5em; FONT: bold 100% verdana,arial,helvetica
}
H6 {
MARGIN-BOTTOM: 0.5em; FONT: bold 100% verdana,arial,helvetica
}
.notVisited { background:red; }
.excluded { background: skyblue; }
.visited { background: #90ee90; }
.title { font-size: 12px; font-weight: bold; }
.assembly { font-size: normal; font-weight: bold; font-size: 11px}
.class {font-size:normal; cursor: hand; color: #444444; font-size: 11px}
.module { color: navy; font-size: 12px; }
.method {cursor: hand; color: ; font-size: 10px; font-weight: bold; }
.subtitle { color: black; font-size: 10px; font-weight: bold; }
.hdrcell {font-size:9px; background-color: #DDEEFF; }
.datacell {font-size:9px; background-color: #FFFFEE; text-align: right; }
.hldatacell {font-size:9px; background-color: #FFCCCC; text-align: right; }
.exdatacell {font-size:9px; background-color: #DDEEFF; text-align: right; }
.detailPercent { font-size: 9px; font-weight: bold; padding-top: 1px; padding-bottom: 1px; padding-left: 3px; padding-right: 3px;}
</style>
<script language="JavaScript"><![CDATA[
function toggle (field)
{ field.style.display = (field.style.display == "block") ? "none" : "block"; }
function SwitchAll(how)
{ var len = document.all.length-1;
for(i=0;i!=len;i++) {
var block = document.all[i];
if (block != null && block.id != '')
{ block.style.display=how;}
}
}
function ExpandAll()
{SwitchAll('block');}
function CollapseAll()
{SwitchAll('none');}
]]></script>
</head>
<body>
<a name="#top"></a>
<xsl:call-template name="header" />
<xsl:call-template name="ModuleSummary" />
<xsl:call-template name="module" />
<xsl:call-template name="footer" />
<script language="JavaScript">CollapseAll();</script>
</body>
</html>
</xsl:template>
<xsl:template name="module">
<xsl:for-each select="//module">
<xsl:sort select="@assembly" />
<xsl:variable name="module" select="./@assembly" />
<div class="assembly">
<a name="#{generate-id($module)}">Module
<xsl:value-of select="$module" />
</a>
</div>
<xsl:for-each select="./method[not(./@class = preceding-sibling::method/@class)]">
<xsl:sort select="@class" />
<xsl:sort select="@name" />
<xsl:call-template name="ClassSummary">
<xsl:with-param name="module" select="$module" />
<xsl:with-param name="class" select="./@class" />
</xsl:call-template>
</xsl:for-each>
</xsl:for-each>
<xsl:variable name="totalMod" select="count(./method/seqpnt[@excluded='false'])" />
<xsl:variable name="notvisitedMod" select="count( ./method/seqpnt[ @visitcount='0'][@excluded='false'] ) div $totalMod * 100 " />
<xsl:variable name="visitedMod" select="count(./method/seqpnt[not(@visitcount='0')] ) div $totalMod * 100" />
</xsl:template>
<xsl:template name="Methods">
<xsl:param name="module" />
<xsl:param name="class" />
<xsl:for-each select="//method[(@class = $class) and (parent::module/@assembly=$module)]">
<xsl:sort select="@name" />
<xsl:variable name="total" select="count(./seqpnt[@excluded='false'])" />
<xsl:variable name="notvisited" select="count(./seqpnt[@visitcount='0'][@excluded='false'] ) " />
<xsl:variable name="visited" select="count(./seqpnt[not(@visitcount='0')])" />
<xsl:variable name="methid" select="generate-id(.)" />
<table cellpadding="3" cellspacing="0" width="90%">
<tr>
<td width="45%" class='method'>
<xsl:attribute name="onclick">javascript:toggle(
<xsl:value-of select="$methid" />)
</xsl:attribute>
<xsl:value-of select="@name" />
</td>
<td width="55%">
<xsl:call-template name="detailPercent">
<xsl:with-param name="visited" select="$visited" />
<xsl:with-param name="notVisited" select="$notvisited" />
<xsl:with-param name="total" select="$total" />
</xsl:call-template>
</td>
</tr>
</table>
<xsl:call-template name="seqpnt">
<xsl:with-param name="module" select="$module" />
<xsl:with-param name="class" select="$class" />
<xsl:with-param name="id" select="$methid" />
</xsl:call-template>
</xsl:for-each>
</xsl:template>
<xsl:template name="seqpnt">
<xsl:param name="module" />
<xsl:param name="class" />
<xsl:param name="id" />
<table cellpadding="3" cellspacing="0" border='1' width="90%" bordercolor="black" style="display: block;">
<xsl:attribute name="id">
<xsl:value-of select="$id" />
</xsl:attribute>
<tr>
<td class="hdrcell">Visits</td>
<td class="hdrcell">Line</td>
<td class="hdrcell">End</td>
<td class="hdrcell">Column</td>
<td class="hdrcell">End</td>
<td class="hdrcell">Document</td>
</tr>
<xsl:for-each select="./seqpnt">
<xsl:sort select="@line" />
<tr>
<td class="datacell">
<xsl:attribute name="class">
<xsl:choose>
<xsl:when test="@excluded = 'true'">exdatacell</xsl:when>
<xsl:when test="@visitcount = 0">hldatacell</xsl:when>
<xsl:otherwise>datacell</xsl:otherwise>
</xsl:choose>
</xsl:attribute>
<xsl:choose>
<xsl:when test="@excluded = 'true'">---</xsl:when>
<xsl:otherwise><xsl:value-of select="@visitcount" /></xsl:otherwise>
</xsl:choose>
</td>
<td class="datacell">
<xsl:value-of select="@line" />
</td>
<td class="datacell">
<xsl:value-of select="@endline" />
</td>
<td class="datacell">
<xsl:value-of select="@column" />
</td>
<td class="datacell">
<xsl:value-of select="@endcolumn" />
</td>
<td class="datacell">
<xsl:value-of select="@document" />
</td>
</tr>
</xsl:for-each>
</table>
</xsl:template>
<!-- Class Summary -->
<xsl:template name="ClassSummary">
<xsl:param name="module" />
<xsl:param name="class" />
<xsl:variable name="total" select="count(//seqpnt[(parent::method/parent::module/@assembly=$module) and (parent::method/@class=$class) and (@excluded='false') ])" />
<xsl:variable name="notvisited" select="count(//seqpnt[(parent::method/parent::module/@assembly=$module)and (parent::method/@class=$class) and (@visitcount='0') and (@excluded='false')] )" />
<xsl:variable name="visited" select="count(//seqpnt[(parent::method/parent::module/@assembly=$module) and (parent::method/@class=$class) and (not(@visitcount='0'))] )" />
<xsl:variable name="newid" select="concat (generate-id(), 'class')" />
<table width='90%'>
<tr>
<td width="40%" class="class">
<xsl:attribute name="onclick">javascript:toggle(
<xsl:value-of select="$newid" />)
</xsl:attribute>
<xsl:value-of select="$class" />
</td>
<td width="60%">
<xsl:call-template name="detailPercent">
<xsl:with-param name="visited" select="$visited" />
<xsl:with-param name="notVisited" select="$notvisited" />
<xsl:with-param name="total" select="$total" />
</xsl:call-template>
</td>
</tr>
<tr>
<table style="display: block;" width="100%">
<tr>
<td>
<xsl:attribute name="id">
<xsl:value-of select="$newid" />
</xsl:attribute>
<xsl:call-template name="Methods">
<xsl:with-param name="module" select="$module" />
<xsl:with-param name="class" select="$class" />
</xsl:call-template>
</td>
</tr>
</table>
</tr>
</table>
<hr size="1" width='90%' align='left' style=" border-bottom: 1px dotted #999;" />
</xsl:template>
<xsl:template name="ClassSummaryDetail">
<xsl:param name="module" />
<xsl:variable name="total" select="count(./method/seqpnt[ @excluded='false' ])" />
<xsl:variable name="notVisited" select="count( ./method/seqpnt[ @visitcount='0'][ @excluded='false' ] )" />
<xsl:variable name="visited" select="count(./method/seqpnt[not(@visitcount='0')] )" />
<td width="35%">
<div class="assembly">
<a href="#{generate-id($module)}">
<xsl:value-of select="$module" />
</a>
</div>
</td>
<td width="65%">
<xsl:call-template name="detailPercent">
<xsl:with-param name="visited" select="$visited" />
<xsl:with-param name="notVisited" select="$notVisited" />
<xsl:with-param name="total" select="$total" />
</xsl:call-template>
</td>
</xsl:template>
<!-- Modules Summary -->
<xsl:template name="ModuleSummary">
<H2>Modules summary</H2>
<xsl:for-each select="//module">
<xsl:sort select="@assembly" />
<table width='90%'>
<tr>
<xsl:call-template name="ModuleSummaryDetail">
<xsl:with-param name="module" select="./@assembly" />
</xsl:call-template>
</tr>
</table>
</xsl:for-each>
<hr size="1" />
</xsl:template>
<xsl:template name="ModuleSummaryDetail">
<xsl:param name="module" />
<xsl:variable name="total" select="count(./method/seqpnt[@excluded='false'])" />
<xsl:variable name="notVisited" select="count( ./method/seqpnt[ @visitcount='0' ][ @excluded='false' ] )" />
<xsl:variable name="visited" select="count(./method/seqpnt[not(@visitcount='0')] )" />
<td width="30%">
<div class="assembly">
<a href="#{generate-id($module)}">
<xsl:value-of select="$module" />
</a>
</div>
</td>
<td width="70%">
<xsl:call-template name="detailPercent">
<xsl:with-param name="visited" select="$visited" />
<xsl:with-param name="notVisited" select="$notVisited" />
<xsl:with-param name="total" select="$total" />
</xsl:call-template>
</td>
</xsl:template>
<!-- General Header -->
<xsl:template name="header">
<h1>
<b>NCover</b> Code Coverage Report
</h1>
<table>
<tr>
<td class="class">
<a onClick="ExpandAll();">Expand</a>
</td>
<td> | </td>
<td class="class">
<a onClick="CollapseAll();">Collapse</a>
</td>
</tr>
</table>
<hr size="1" />
</xsl:template>
<xsl:template name="footer">
<hr size="1" />
<a class="detailPercent" href="#{top}">Top</a>
</xsl:template>
<!-- draw % table-->
<xsl:template name="detailPercent">
<xsl:param name="visited" />
<xsl:param name="notVisited" />
<xsl:param name="total" />
<table width="100%" class="detailPercent">
<tr>
<xsl:if test="($notVisited=0) and ($visited=0)">
<td class="excluded" width="100%">Excluded</td>
</xsl:if>
<xsl:if test="not($notVisited=0)">
<td class="notVisited">
<xsl:attribute name="width">
<xsl:value-of select="concat($notVisited div $total * 100,'%')" />
</xsl:attribute>
<xsl:value-of select="concat (format-number($notVisited div $total * 100,'#.##'),'%')" />
</td>
</xsl:if>
<xsl:if test="not ($visited=0)">
<td class="visited">
<xsl:attribute name="width">
<xsl:value-of select="concat($visited div $total * 100,'%')" />
</xsl:attribute>
<xsl:value-of select="concat (format-number($visited div $total * 100,'#.##'), '%')" />
</td>
</xsl:if>
</tr>
</table>
</xsl:template>
</xsl:stylesheet> | zyyin2005-lokad | Resource/Tool/NCover/Coverage.xsl | XSLT | bsd | 12,625 |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
<!-- $Id: NCoverFAQ.html 247 2007-04-26 15:17:46Z peterwald $ -->
<title></title>
<meta content="Microsoft Visual Studio .NET 7.1" name="GENERATOR">
<meta content="http://schemas.microsoft.com/intellisense/ie5" name="vs_targetSchema">
<style> body { font-size: 10pt; font-family: Verdana; }
p.title { font-size: 20pt; font-weight: bold; }
.subtitle { color: maroon; }
p.question { font-weight: bold; }
pre { font-size: 10pt; font-family: Courier; }
pre.usage { background-color: #F0F0F0; }
.quote { background-color: #F0F0F0; margin-left: 36pt;}
.method { color: maroon; font-size: 10pt; font-weight: bold; }
.hdrcell { background-color: #DDEEFF; font-size: 10pt; }
.datacell { background-color: #FFFFEE; text-align: right; font-size: 10pt; }
.hldatacell { background-color: #FFCCCC; text-align: right; font-size: 10pt; }
.box { border: 1px solid; padding: 10px; }
</style>
</head>
<body>
<P class="title">NCover FAQ</P>
<P>If you have questions that this document does not address, contact <A href="mailto:peter@waldschmidt.com">
Peter Waldschmidt</A> or try the <A href="http://ncover.org/">NCover Forums</A>.</P>
<P class="question">1. What is code coverage analysis?</P>
<P class="answer">A code coverage analyzer monitors your code at runtime and
records information about which lines of code were executed. NCover shows each
sequence point in your application along with the number of times that point
was executed. Sequence points are generated by the compiler and stored in the
debug information (.pdb) files. A sequence point basically corresponds to a
single program statement (often a line of code) in your high-level language.</P>
<P class="question">2. Why would I want to do code coverage analysis?</P>
<P class="answer">Unit test suites are often used as a quality tool during the
development process to keep the codebase stable as it changes and expands.
Tools such as <A href="http://nunit.org/">NUnit</A> are often used to run and
report on the test suites. However, when implementing unit testing in your
build process, you have no way of knowing how much of your code the unit tests
are actually testing. This is where code coverage comes in. You can run NUnit
within NCover and use the code coverage report to determine which code was not
tested by that particular test suite.</P>
<P class="question">3. What versions of the CLR does NCover support?</P>
<P class="answer">
NCover 1.5.x requires the .NET framework version 2.0.50727 to be installed; however,
the application being profiled can be written against any shipping version of the
framework. NCover
has been tested profiling coverage of .NET 2.0, .NET 1.1 and .NET 1.0 applications.</P>
<P class="question">4. Which version of NCover should I install?</p>
<P class="answer">
If you have the .NET 2.0 framework installed on your machine then you should use
the latest NCover version available. NCover as of version 1.5 can profile .NET 2.0, 1.1 and 1.0 applications.</p>
<p class="answer">
For development teams who do not have the .NET framework 2.0 installed but do have
the .NET framework version 1.1.4322, you can
try NCover 1.3.3. Note however that this version is no longer supported as
it has a number of known issues and limitations.</p>
<P class="question">5. What is the command line syntax for NCover?</P>
<P class="answer">Here is the usage info from the NCover command line (for NCover versions from 1.5.6
only):</P>
<pre class="usage">NCover.Console [<command line> [<command args>]]
[//svc <service name>]
[//iis]
[//a <assembly list>]
[//w <working directory>]
[//ea <exclusion list>]
[//reg]
[//x <xml output file>]
[//s [<settings file>]] [//r [<settings file>]]
[//v] [//q]
[//l <log file>]
//svc For profiling windows services
//iis For profiling web applications
//a List of assemblies to profile separated by semi-colons i.e. "MyAssembly1;MyAssembly2". Do not include paths or suffixes.
//w Working directory for profiled application
//ea List of attributes marking classes or methods to exclude from coverage
//reg Register profiler temporarily for user. (helps with xcopy deployment)
//x Specify coverage output file. (default: coverage.xml).
//pm Specify name of process to profile (i.e. myapp.exe)
//s Save settings to a file (defaults: NCover.Settings)
//r Use settings file, overriding other settings (default: NCover.Settings)
//l Specify profiler log file (default: coverage.log).
//q No logging (quiet)
//v Enable verbose logging (show instrumented code)
</pre>
<UL>
<LI><command line> - This argument specifies the command-line of the .NET application
you want to analyze.
Any command line arguments not starting with // will be passed
through to that application. NCover will profile the running application until it has exited. See below for examples.<li>//svc - This option is an alternative to the <command line>
for profiling windows services, which cannot be run directly as executables. NCover
will start the service (stopping it first if already running) and profile coverage
until the windows service is stopped.</li>
<li>//iis - This option is an alternative to the <command line> for profiling
web applications. NCover will start the IISAdmin and W3C
services (stopping first if currently running) and profile coverage until the IISAdmin
service is stopped.<br />
</li>
<li>//a - This command-line argument specifies the assemblies that you want to analyze.
NCover can only analyze assemblies that have .pdb files included with them. If
you do not specify the //a argument, NCover will attempt to analyze every loaded
assembly that has debug information available. Note that the assembly name arguments are
the module name within the assembly, not the physical file name. e.g. "MyAssembly"
rather than "MyAssembly.dll".<li>//w - If the application being profiled requires the
working directory to be set to something other than the current directory you are
executing the command line from then you can override it with this argument.</li>
<li>//ea - You can choose to exclude classes and methods
from coverage statistics by defining .NET attribute(s) and applying it to the affected
code. When using this argument you must specify the full type namespace of these
attribute(s) separated by semi-colons. See below for an example.<br />
</li>
<li>//reg - NCover requires a COM registration of the CoverLib.dll assembly containing
the profiler, which is performed automatically by the default .msi installation.
If you require an xcopy style deployment of NCover like many other .NET tools, then
you can use this argument which will temporarily register the profiler while performing
coverage. This feature was added in NCover 1.5.6.</li>
<li>//x - The output of NCover is an xml file (example below). Use this argument to
specify an alternate filename to "coverage.xml" in the current directory.<br />
</li>
<li>//pm - This setting tells NCover to ignore processes that don't have the specified process module name.
This is the name of the executable (i.e. myapp.exe). This setting is useful in cases, where your NCover
command spawns a series of child processes. Using this setting will help NCover determine which process to profile.
</li>
<li>//s - You may find it more convenient to use a settings file rather than specifying
a long list of command line arguments for running NCover. If you get the NCover
command line working as you would like it and then use the //s argument it will
save the required arguments as an xml file that can then be used by the //r argument
below.</li>
<li>//r - For use when you have used //s to construct an NCover settings file containing
your command line arguments. e.g. "ncover.console.exe //r NCover.Settings"<br />
</li>
<li>//l - The coverage log file can provide an insight if the desired coverage output
is not obtained. Useful information you may find to assist you includes which assemblies
were loaded by NCover, their file paths and which of those it found the .pdb build
symbols for. Use this argument to specify an alternative log file name or location
to coverage.log in the current directory.</li>
<li>//q - Suppresses writing the coverage.log file.</li>
<li>//v - This command-line argument makes the profiler emit all the original IL and
modified IL instructions to the coverage log. This is useful for debugging
purposes. Beware that this can make your coverage log file very large!
</li>
</UL>
<P class="question">6. Does NCover required a special compilation step for my code?</P>
<P class="answer">No. Some code coverage tools change your source code and force
you to recompile it into a special build. NCover is designed to work
on shipping code. NCover uses the .NET Framework profiling API to monitor
your code. It does require build symbols, but can be run on release code
without any modifications.</P>
<P class="question">7. How does NCover work?</P>
<P class="answer">NCover uses the .NET Framework profiler API to monitor an
application's execution. When a method is loaded by the CLR, NCover retrieves
the IL and replaces it with instrumented IL code. NCover does not change
your original IL code, it simply inserts new code to update a visit
counter at each sequence point. Upon
request, (usually after the .NET process has shut down) the profiler outputs statistics
to the coverage file.
</P>
<P class="question">
8. What is the output of NCover?</P>
<P class="answer">NCover generally writes out three files after analysis
completes.
<ul>
<li>
Coverage.log - This file is a log of the events and messages from the profiler
during the analysis process. Most of the time, error messages are recorded in
this log. If you enable verbose logging, the coverage log will contain
disassembly of the original and instrumented IL code. Verbose logging is not recommended for
normal use.<li>
Coverage.xml - This file is the analysis output of NCover. You can see an
example of the output below.
<LI>
Coverage.xsl - This file is a simple XML transformation that makes the XML
output easily readable.
</LI>
</ul>
<span class="subtitle">Example XML output</span>
<div class="box"><pre><method class="NCoverTest.ClassLoaded" name="HasDeadCode">
<seqpnt document="C:\Dev\Utilities\ncover\NCoverTest\NCoverTest.cs"
column="13" line="48" endcolumn="58" endline="48" visitcount="1" />
<seqpnt document="C:\Dev\Utilities\ncover\NCoverTest\NCoverTest.cs"
column="13" line="49" endcolumn="22" endline="49" visitcount="1" />
<seqpnt document="C:\Dev\Utilities\ncover\NCoverTest\NCoverTest.cs"
column="17" line="50" endcolumn="24" endline="50" visitcount="1" />
<seqpnt document="C:\Dev\Utilities\ncover\NCoverTest\NCoverTest.cs"
column="13" line="51" endcolumn="48" endline="51" visitcount="0" />
<seqpnt document="C:\Dev\Utilities\ncover\NCoverTest\NCoverTest.cs"
column="9" line="52" endcolumn="10" endline="52" visitcount="0" />
</method></pre>
</div>
<p></p>
<span class="subtitle">Example transformed output</span>
<div class="box">
<DIV class="method">NCoverTest.ClassLoaded.HasDeadCode</DIV>
<TABLE id="Table1" borderColor="black" cellSpacing="0" cellPadding="3" border="1">
<TBODY>
<TR>
<TD class="hdrcell">Visit Count</TD>
<TD class="hdrcell">Line</TD>
<TD class="hdrcell">Column</TD>
<TD class="hdrcell">End Line</TD>
<TD class="hdrcell">End Column</TD>
<TD class="hdrcell">Document</TD>
</TR>
<TR>
<TD class="datacell">1</TD>
<TD class="datacell">48</TD>
<TD class="datacell">13</TD>
<TD class="datacell">48</TD>
<TD class="datacell">58</TD>
<TD class="datacell">C:\Dev\Utilities\ncover\NCoverTest\NCoverTest.cs</TD>
</TR>
<TR>
<TD class="datacell">1</TD>
<TD class="datacell">49</TD>
<TD class="datacell">13</TD>
<TD class="datacell">49</TD>
<TD class="datacell">22</TD>
<TD class="datacell">C:\Dev\Utilities\ncover\NCoverTest\NCoverTest.cs</TD>
</TR>
<TR>
<TD class="datacell">1</TD>
<TD class="datacell">50</TD>
<TD class="datacell">17</TD>
<TD class="datacell">50</TD>
<TD class="datacell">24</TD>
<TD class="datacell">C:\Dev\Utilities\ncover\NCoverTest\NCoverTest.cs</TD>
</TR>
<TR>
<TD class="hldatacell">0</TD>
<TD class="datacell">51</TD>
<TD class="datacell">13</TD>
<TD class="datacell">51</TD>
<TD class="datacell">48</TD>
<TD class="datacell">C:\Dev\Utilities\ncover\NCoverTest\NCoverTest.cs</TD>
</TR>
<TR>
<TD class="hldatacell">0</TD>
<TD class="datacell">52</TD>
<TD class="datacell">9</TD>
<TD class="datacell">52</TD>
<TD class="datacell">10</TD>
<TD class="datacell">C:\Dev\Utilities\ncover\NCoverTest\NCoverTest.cs</TD>
</TR>
</TBODY>
</TABLE>
</div>
<P>Suggested usages of the coverage.xml output are to display it in the <a href="http://ncoverexplorer.org/">
NCoverExplorer</a> gui with the source
code highlighted, to generate html reports, or to include it in your continuous build server reports such as CruiseControl.Net.
For more information on these options see below in the FAQ.</P>
<P></P>
<P class="question">
9. How do I use coverage exclusions?</P>
<p>
First you should define an attribute to markup your excluded code with. You will
likely want to put this in a common assembly to make it reusable, or indeed within
a "CommonAssemblyInfo.cs" that you include in all your application assemblies.</p>
<P></P>
<pre class="usage">namespace MyNamespace {
class CoverageExcludeAttribute : System.Attribute { }
}</pre>
<p>
Apply the attribute to the C# classes and/or methods you wish to mark as excluded
from code coverage statistics:</p>
<P></P>
<pre class="usage"> [CoverageExclude]
private void SomeMethodToExclude() {} </pre>
<p>
Finally, ensure you pass the full qualified attribute information in the NCover command line:</p>
<P></P>
<pre class="usage"> NCover.Console MyApplication.exe //ea MyNamespace.CoverageExcludeAttribute </pre>
<p>
Note that if you are using the <a href="http://testdriven.net/">TestDriven.Net</a>
VS.Net add-in to "Test with Coverage" it will automatically
pass through "//ea CoverageExcludeAttribute"
which you should define without a namespace like above. For further information refer to this
<a href="http://weblogs.asp.net/nunitaddin/archive/2006/10/04/CoverageExclude.aspx">
blog entry</a>.</p>
<P class="question">
10. Examples</P>
<p>
Coverage while running a simple executable until it exits:</p>
<P></P>
<pre class="usage"> NCover.Console MyApplication.exe</pre>
<p>
Coverage while running all the unit tests in an assembly using NUnit, profiling
all loaded assemblies with .pdb build symbols:</p>
<P></P>
<pre class="usage"> NCover.Console nunit-console.exe MyApplication.Tests.dll</pre>
<p>
Coverage of only a subset of loaded assemblies while running unit tests:</p>
<P></P>
<pre class="usage"> NCover.Console nunit-console.exe MyApplication.Tests.dll //a MyApplication.Core;MyApplication.Utilities</pre>
<p>
Coverage of a windows service. Stop the service to generate the coverage output:</p>
<P></P>
<pre class="usage"> NCover.Console //svc MyServiceName</pre>
<p>
Coverage of an ASP.Net application. Stop the IIS service to generate the coverage
output:</p>
<P></P>
<pre class="usage"> NCover.Console //iis</pre>
<P class="question">
11. Where can I get help or support?</P>
<P class="answer">
Your best approach is to browse the <a href="http://ncover.org/site/forums/default.aspx">
NCover forums</a> as well as the <a href="http://ncover.org/SITE/blogs/default.aspx">
blog</a> by the author Peter Waldschmidt. If you cannot find a similar issue
mentioned feel free to post your query and perhaps someone can help.</P>
<P class="question">
12. How do I "xcopy deploy" NCover like my other build tools?</P>
<P class="answer">
Many developers prefer to have their build tools such as NUnit, NAnt etc stored
in source control in a Tools folder along with the source code. This ensures that
a new developer can obtain and build the application without having to install additional
tools on their own machines.</P>
<p>
NCover can also be deployed in this fashion. However the one gotcha with NCover
versus other tools is that the profiler within CoverLib.dll must be COM registered
on the local machine before you execute it. Prior to NCover 1.5.6 this was usually
achieved as part of your build script, which would call regsvr32 with the path to
the CoverLib.dll in your Tools folder. Alternatively the <ncover> NAnt and
MSBuild tasks described below will do this for you. As of NCover 1.5.6 you can also
use the //reg option in the command line arguments which will temporarily register
the profiler. Note that the //reg option will not work for IIS or Windows Service
profiling unless you are running NCover under the same Windows login account as
the IIS worker process, or your Windows Service.</p>
<P class="question">
13. How do I see my source code highlighted with the coverage results?</P>
<P class="answer">
<a href="http://ncoverexplorer.org/">NCoverExplorer</a> is a gui and console-based
.NET application developed by <a href="http://www.kiwidude.com/blog/">Grant Drake</a>. NCoverExplorer
parses the coverage.xml files output from NCover and displays the results integrated
with your source code. It also includes a number of additional features to merge,
filter, sort and generate html reports. The console version is
designed to be used as part of an automated build process. The support forums for
NCoverExplorer are located with the NCover ones at <a href="http://ncover.org">http://ncover.org/</a>.<strong> </strong></P>
<P class="question">
14. How do I run NCover from within the Visual Studio.Net IDE?</P>
<P class="answer">
The <a href="http://testdriven.net/">TestDriven.Net</a> add-in by <a href="http://weblogs.asp.net/nunitaddin/">
Jamie Cansdale</a> offers a right-click capability within the IDE to execute
your unit tests with code coverage. The results of the NCover code coverage are
displayed with the bundled NCoverExplorer gui for analysis and reporting.</P>
<P class="question">
15. How do I run NCover from a NAnt or MSBuild task?</P>
<P class="answer">
You can use an <exec> task with <a href="http://nant.sourceforge.net/">NAnt</a>
or an <Exec> task with MSBuild. Alternatively you may want to use the custom
<ncover> task for NAnt or <NCover> task for MSBuild developed by Grant
Drake for a more developer friendly syntax. The source code, compiled assemblies
and documentation are located in the NCoverExplorer.Extras.zip available from <a
href="http://ncoverexplorer.org/">http://ncoverexplorer.org/</a>.</P>
<P class="question">
16. How do I include NCover output in my CruiseControl.Net build reports?</P>
<P class="answer">
<a href="http://ccnet.thoughtworks.com/">CruiseControl.Net</a> is a continuous integration
build server which offers web-based reporting of the outputs of a build such as
unit test results and code coverage reporting. The default CruiseControl.Net installation
includes a basic stylesheet which works in combination with the standard coverage.xml
formatted output. So all you need to do is include the execution of NCover as part
of your build, then add a CruiseControl.Net merge file publisher task to integrate
the coverage.xml results into the build output.</P>
<p class="answer">
An improvement on the above to display more attractive and powerful reports as well
as minimize the build log size is to use NCoverExplorer. The NCoverExplorer.Console.exe
is designed to produce a more concise xml report summary that is combined with an
alternate xsl stylesheet for CruiseControl.Net. You can find more information and
screenshots in this <a href="http://www.kiwidude.com/blog/2006/04/ncoverexplorer-v133.html">
blog entry</a> - all the necessary tasks, examples and documentation are located
within NCoverExplorer.Extras.zip available from <a href="http://ncoverexplorer.org/">
http://ncoverexplorer.org/</a>. </p>
<P class="question">
17. How do I merge multiple NCover coverage.xml results?</P>
<P class="answer">
You can can use NCoverExplorer to merge the results of multiple coverage runs. For
more information refer to this <a href="http://www.kiwidude.com/blog/2006/10/ncoverexplorer-merging-ncover-reports.html">
blog entry</a>.</P>
<P class="question">
18. Troubleshooting: Why is my coverage.xml file empty?</P>
<ul>
<li>If using the command-line, did you COM register CoverLib.dll (or use the //reg option
from NCover 1.5.6)?</li>
<li>Did you generate build symbol files (.pdbs) for the profiled application?</li>
<li>If using the //a option, did you correctly list just the assembly names without
paths or .dll suffixes?</li>
</ul>
<P class="question">
19. Troubleshooting: I have coverage.xml output but my XYZ assembly is not included in it?</P>
<ul>
<li>NCover will only profile loaded assemblies - did your code execution path while
under coverage force that assembly to be loaded (e.g. by loading a type or calling
a method in that assembly)? </li>
<li>Did you generate build symbol files (.pdb files) for the missing assembly? </li>
<li>If using the //a option, did you correctly list the assembly names including the
one that is missing?</li>
<li>Can you see information about the assembly being loaded within the coverage.log?
Is the correct assembly being loaded (check the path) - if you have a version in
the GAC it may possibly prevent the .pdb file from being loaded.</li><li>If using the NCoverExplorer gui, have you got a coverage exclusion defined which
is hiding it from the display?</li>
</ul>
<P class="question">
20. Troubleshooting: After running NCover my coverage.log says "Failed to load symbols for module XYZ"?</P>
<ul>
<li>This message means that no .pdb build symbol file was found for that assembly so
it cannot be profiled for code coverage. If that assembly is part of the .NET framework
for instance like System.Data.dll, then this is an expected message and should not
cause concern. </li><li>If however the assembly belongs to your application, did you generate the
build symbol files (.pdb files) for it? </li>
</ul>
<P class="question">
21. Troubleshooting: I get a "Profiled process terminated. Profiler connection not
established" message?</P>
<ul>
<li>If using the command-line, did you COM register CoverLib.dll (or use the //reg option
from NCover 1.5.6)?</li><li>Are you running Windows XP 64-bit? You may want to take a look at
<a href="http://ncover.org/SITE/forums/thread/43.aspx">this thread</a></li></ul>
<P class="question">
22. Troubleshooting: My coverage exclusions are not working?</P>
<ul>
<li>Have you put the full namespace type name to the exclusion including the Attribute suffix in the //ea argument? See the "How
do I use coverage exclusions?" question above.</li></ul>
</body>
</html>
| zyyin2005-lokad | Resource/Tool/NCover/NCoverFAQ.html | HTML | bsd | 28,820 |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>NCoverExplorer Release Notes</title>
<meta content="Microsoft Visual Studio .NET 7.1" name="GENERATOR" />
<meta content="http://schemas.microsoft.com/intellisense/ie5" name="vs_targetSchema" />
<style type="text/css">
body { font-size: 10pt; font-family: Verdana; }
p.title { font-size: 20pt; font-weight: bold; }
.subtitle { color: maroon; }
p.question { font-weight: bold; }
pre { font-size: 10pt; font-family: Courier; }
pre.usage { background-color: #F0F0F0; }
.quote { background-color: #F0F0F0; margin-left: 36pt;}
.method { color: maroon; font-size: 10pt; font-weight: bold; }
.hdrcell { background-color: #DDEEFF; font-size: 10pt; }
.datacell { background-color: #FFFFEE; text-align: right; font-size: 10pt; }
.hldatacell { background-color: #FFCCCC; text-align: right; font-size: 10pt; }
.box { border: 1px solid; padding: 10px; }
.treeviewBlack { color: black; }
.treeviewGrey { color: grey; }
.treeviewRed { color: red; }
.treeviewBlue { color: blue; }
.sourceBlue { background-color: #E0EDFD; color: black; }
.sourceRed { background-color: #E6B0A5; color: black; }
</style>
</head>
<body>
<p class="title">NCoverExplorer Release Notes</p>
<p>The latest version of this document is located <a href="http://www.kiwidude.com/dotnet/NCoverExplorerReleaseNotes.html">here</a>.
<br/>For the latest NCoverExplorer news and updates, visit my <a href="http://www.kiwidude.com/blog/">blog</a>.</p>
<hr/>
<p class="question">v1.4.0 - Sep 16th 2007</p>
<p class="answer">The following new features were introduced:</p>
<ul>
<li>
Major rewrite of the underlying object design for future maintainability. Should improve treeview
performance for .NET 2.0 users (and load performance for all users) as well as make it easier to
add new features.
</li>
<li>
Changes to the project setting file format and location, both as used by the NCoverExplorer gui
and the NCoverExplorer.Console.exe application. If you use the /c argument supplying a configuration
file to NCoverExplorer then you must modify your project file format. See ConsoleExample.config
for details (replace the outer tag to be called ConsoleSetting).
</li>
<li>
Replaced ICSharpCode text editor with Actipro which offers far superior features, more attractive
appearance and provides a more flexible licensing model for the future of NCoverExplorer.
</li>
<li>
A new attribute added into the coverage report xml of "totalSeqPoints" which includes the
total of any excluded sequence points at that level. In response to a feature request in
<a href="http://ncover.org/SITE/forums/thread/697.aspx">this</a> NCover forum thread to allow
people to report how much code was excluded from coverage.
</li>
<li>
Add a copy command to the right-click menu for the source code area.
</li>
<li>
Add a print preview command to the File menu.
</li>
<li>
Add support for profiling a specific process module to the Run NCover dialog.
</li>
<li>
Add a /fc (failCombinedMinimum) option to NCoverExplorer.Console.exe for emulating the
original behaviour of failing based on total coverage to supplement the /f option which
fails if an individual module is below the coverage threshold.
</li>
</ul>
<p class="answer">The following minor changes were made:</p>
<ul>
<li>
Rewrite the options dialog to use a VS.Net style property pages approach.
</li>
<li>
Exclusions tab in Options dialog - delete key is now a shortcut to removing an exclusion.
</li>
<li>
Reorder the file menu slightly so Run NCover is separated.
</li>
<li>
Source code window now has a splitter bar.
</li>
<li>
Command line generated for NCover 1.5.7+ in NCover Runner dialog includes the //reg
option if choosing to register coverlib.dll.
</li>
<li>
Statistics pane auto-sizes the last column to fill the width of the listview.
</li>
<li>
Coverage exclusions now support '?' and more complex wildcard expressions such
as Test.*.Something*.
</li>
</ul>
<p class="answer">The following bug fixes were made:</p>
<ul>
<li>
Line number foreground colour not displayed correctly in options dialog tab.
</li>
<li>
Directory not created if not existing when writing output report.
</li>
<li>
Corrected typo in full name of parameter when using /quiet option with NCoverExplorer.Console.
</li>
<li>
Reduce GDI usage by editor control.
Rnsure Actipro renderer is correctly utilised.
Turn off text margins in NCover run dialog for editor.
Ensure C++ code has whole line highlighted even though no sequence point values.
(Build 1.4.0.6)
</li>
</ul>
<hr/>
<p class="question">v1.3.6 - Apr 5th 2007</p>
<p class="answer">Bundled with TestDriven.Net from build 2.5.2078.</p>
<p class="answer">The following new features were introduced:</p>
<ul>
<li>
Added a Find dialog (ctrl+F) to quickly navigate to a class. Wildcards are supported.
</li>
<li>
Added a /q or /quiet option to NCoverExplorer.Console.exe to minimise the output.
</li>
</ul>
<p class="answer">The following minor changes were made:</p>
<ul>
<li>
Failing if less than a threshold now applies to any assembly not meeting the threshold
rather than comparing against the total coverage across all assemblies.
</li>
<li>
Add some examples to the NCoverExplorer.Console.exe output for the /help or /? (or no arguments).
</li>
<li>
Pressing ESC on the NCover Runner dialog will now close it.
</li>
<li>
Implement a workaround for poor treeview performance under .NET 2.0.
</li>
<li>
Rather than displaying validation errors automatically "fix" paths with matching trailing
slashes in the Change Source Path dialog.
</li>
<li>
Writing of coverage files should now match the schema for the relevant NCover version.
Later NCover versions like 1.5.7 have enhanced the schema, so the results of a merge or
save from NCoverExplorer should offer a comparative schema in the result.
</li>
<li>
Add a message indicating the return code to the output.
</li>
</ul>
<p class="answer">The following bug fixes were made:</p>
<ul>
<li>
NCover 1.5.5/6 produce duplicate sequence points. To workaround this fix Jamie Cansdale implemented
a change for me to the way the methods are identified uniquely. The longer term fix is NCover version 1.5.7
- this should keep things usable until that is released.
</li>
<li>
Another issue up to at least NCover 1.5.7 is that non-instrumented code does not have the sequence
points optimised. When merging multiple coverage files NCoverExplorer was incorrectly merging the noops with
valid instrumented sequence points, resulting in lower coverage information.
</li>
<li>
If CoverageReport.xsl stylesheet already exists in destination output folder for an xml report
and is marked as read-only then the replace would fail.
</li>
<li>
Drag/drop of coverage.xml files would add to the wrong end of the MRU menu once the maximum
number of items is reached.
</li>
<li>
If multiple classes in the same file then selecting a class node was not navigating to that
class in the source code tab. It will now jump to the first unvisited sequence point, or if
there are none of those the first sequence point in the class.
</li>
<li>
Wildcards for coverage exclusions were only working if placed at the ends, not in the middle
e.g. *.Tests or Testing.* would work, but xxx.*.yyy would not.
</li>
<li>
Prevent some of the nasty GDI errors in CommandBars code from disrupting the GUI. Longer
term will utilise another framework.
</li>
<li>
Replacing paths by typing them in had MaxLength set to 50 so impossible to edit long paths
in the Change Source Path dialog.
</li>
<li>
Merging property nodes under a parent in the tree has a dependency on the ordering of the coverage output
to ensure they appear properly.
</li>
<li>
When restoring form position from persisted values, ensure it appears on a visible screen,
catering for the user changing their display settings between sessions.
</li>
<li>
Ensure stylesheet cannot be copied over the top of itself.
</li>
<li>
Supplying a file pattern with no matches to NCoverExplorer.Console.exe was throwing an "Index was
outside the bounds of the array" exception.
</li>
<li>
Multiple coverage exclusion attributes not supplied correctly to NCover (build 26).
</li>
<li>
Check to make sure node is assigned to a TreeView before getting handle to set text (build 32).
</li>
<li>
Sort sequence point nodes when loading and handle merge case of multiple non-instrumented
sequence points becoming a single sequence point. (build 36).
</li>
</ul>
<hr/>
<p class="question">v1.3.5 - Oct 23rd 2006</p>
<p class="answer">Bundled with TestDriven.Net from build 2.0.1921.</p>
<p class="answer">The following new features were introduced:</p>
<ul>
<li>
Added ability to run NCover from within NCoverExplorer (all versions). User Ctrl+N or
entries on File menu/toolbar to bring up configuration dialog. After successful
execution, the resultant coverage file is displayed in NCoverExplorer.
</li>
<li>
Added ability to generate MSBuild, NAnt and command-line scripts for running NCover
from within NCoverExplorer. See the NCover dialog above.
</li>
<li>
Added new function coverage viewing options and module/class coverage report.
Indicates the percentage of functions covered rather than the sequence points within each.
Supported by a new "satisfactory function threshold" and function % sorting options.
</li>
<li>
Background colours can now be customised for coverage nodes in the tree.
</li>
<li>
Reports will now have the current filtering applied, not just the sorting settings.
</li>
<li>
Reports using NCoverExplorer.Console can now have filtering and sorting applied. Use the
/sort: and /filter: command line arguments, or specify in a .config file (see example.config),
or use the sort/filter arguments to the NAnt/MSBuild tasks.
</li>
<li>
Sorting and filtering options applied are now persisted and reapplied to the next coverage
xml file loaded, both in this and future sessions.
</li>
<li>
Added ability to filter out all nodes exceeding coverage threshold.
</li>
<li>
Revamp to the NAnt/MSBuild tasks. Renamed assemblies and namespaces. Included new attribute of
"AssembliesList" as an alternative to the "Assemblies" group element to allow direct
specification of a list as you would on the command line. The "Version" attribute is now optional
- the task determines it from the NCover assembly instead if not specified. Tasks will automatically
register NCover coverlib.dll using the HKCU entry in the registry - no need for regsvr32 any more!
NCoverExplorer task now writes it's config file to temp folder for passing to the executable.
</li>
<li>
Added documentation for the NAnt and MSBuild tasks. This is included both in the NCoverExplorer.Extras.zip
file, as well as being available online for the custom <a href="http://www.kiwidude.com/dotnet/doc/NCoverExplorer.MSBuildTasks/index.html">MSBuild Task Help</a>
and <a href="http://www.kiwidude.com/dotnet/doc/NCoverExplorer.NAntTasks/index.html">NAnt Task Help</a>.
Links also available off the Help menu for NCoverExplorer.
</li>
<li>
Added a schema file ConsoleConfig.xsd to the distribution for people wanting to know the exact syntax
options for creating .config files to pass to NCoverExplorer.Console using the /config switch.
</li>
<li>
Added regular expression support to the coverage exclusions dialog for people wanting more complex queries.
</li>
</ul>
<p class="answer">The following minor changes were made:</p>
<ul>
<li>
<span style="color:red">Configuration file change - the ModuleThresholds section in .config files passed to NCoverExplorer.Console now
uses propercase attribute names to be consistent with the rest of the configuration file.
i.e. "ModuleName" instead of "moduleName", and "SatisfactoryCoverage" instead of "satisfactoryCoverage".</span> You must update
your NAnt/MSBuild tasks for NCoverExplorer if you use these. If you instead use the <exec> task with a .config
file then you should update the case of the entries in this file. This only affects people who have setup coverage exclusions
at the module level for reporting purposes.
</li>
<li>
If source code is out of date compared to the coverage results, the user is prompted with
the change source path dialog.
</li>
<li>
If the user chooses a new source code location, the tab is now automatically opened for
that location rather than requiring the user to click on the tree node again.
</li>
<li>
Added Help->NCoverExplorer Forum menu option to link to the NCover website. Also included
forum link information on the exception dialog.
</li>
<li>
Added a toolbar button for turning off filtering.
</li>
<li>
<span style="color:red">Keyboard shortcut change - Changed the keyboard shortcuts for next/previous unvisited class (ALT+UP/DOWN) and
next/previous unvisited line in class (ALT+LEFT/RIGHT).</span>
</li>
<li>
Remember which tab was last opened in the NCoverExplorer options dialog during an NCoverExplorer session.
</li>
<li>
Replaced references to "transparent.gif" with "shim.gif" in the NCoverExplorerSummary.xsl. The "shim.gif"
file is a transparent 1x1 gif already distributed with CC.Net.
</li>
<li>
Coverage exclusions for assemblies are now case insensitive.
</li>
<li>
There are no longer two default coverage exclusions added of "*.Tests" and "*.My*" for first time users.
Intended for demo purposes only but stayed in until now. New users can manually add them if they desire them.
</li>
</ul>
<p class="answer">The following bug fixes were made:</p>
<ul>
<li>
Overloaded constructors with class level variable declarations were being merged into a single
constructor in the coverage results as they had the same "start line" of the variable. Now uses
end line as part of the identifying key for each method.
</li>
<li>
Memory leak from opening and closing tabs displaying source code.
</li>
<li>
.Net 2.0 performance is pretty dire due to crap Microsoft changes to the TreeView control.
Change to default to .Net 1.1 in NCoverExplorer.exe.config and wrap updates to the tree
in BeginUpdate/EndUpdate.
</li>
<li>
Parsing Java code would blow up if an accessor had the same name as a nested class (illegal in C#).
</li>
<li>
Bugfix in NCover task where multiple assemblies were specified for NCover 1.5.4, which requires
separate <assembly> nodes.
</li>
<li>
Bugfix in trying to restore selected node text after refreshing file could raise
null reference exception.
</li>
<li>
Bugfix so that module names specified in module thresholds when using NCoverExplorer.Console
are no longer case sensitive for matching.
</li>
<li>
Added support for NCover 1.5.5 - the //q bug is fixed in NCover. Also changed parsing code so that modules
with a blank assembly name (through using TestDriven.Net) are ignored from the coverage.
</li>
<li>
Bugfix for merge functionality for NCover.Console when wildcards were used with relative paths.
</li>
<li>
Bugfix for naming of xml/html arguments for NCover.Console with relative file paths.
</li>
<li>
Bugfix for drag/drop broken while making the memory usage optimisations during the 1.3.5 beta release.
</li>
<li>
Print button was enabled when no source code displayed resulting in exception.
</li>
</ul>
<hr/>
<p class="question">v1.3.4 - Jul 10th 2006</p>
<p class="answer">Bundled with TestDriven.Net from build 2.0.1702.</p>
<p class="answer">The following new features were introduced:</p>
<ul>
<li>
Added toolbar buttons which support moving to the next and previous unvisited code
within a class or namespace. Shortcut keys of N and P for next/previous unvisited line in the
current class (or mouse forward/back buttons). Use Ctrl+N and Ctrl+P to navigate to the
next/previous partially or unvisited class within the namespace (or Ctrl+forward/back mouse buttons).
</li>
<li>
NCoverExplorer.Console.exe now supports saving the merged results of the coverage xml file(s) with
a /s[ave] option. The NCoverExplorer NAnt and MSBuild tasks have also been enhanced to support this
with an optional "mergeFileName" attribute.
</li>
<li>
NCoverExplorer.Console.exe now supports wildcards for coverage xml filename(s).
</li>
<li>
NCoverExplorer.Console.exe now supports module level coverage thresholds, rather than just a project
coverage threshold. This feature allows finer tolerance for both output on the reports and to fail
a build. Specifying the module thresholds is done either through a .config file (see ConsoleExample.config)
or through parameters in the NAnt/MSBuild tasks.
</li>
<li>
Added a new summary report showing class coverage per namespace per module.
</li>
<li>
Enhanced the NCoverExplorerSummary.xsl to display summaries of each module.
</li>
<li>
Clicking on a class with non-existent source code displays a dialog allowing the user to specify an alternate
folder. For use when the source code location indicated within the coverage.xml file(s) loaded differs from
that on the local machine now (e.g. a different drive letter or folder path).
</li>
</ul>
<p class="answer">The following minor changes were made:</p>
<ul>
<li>
NCoverExplorer release is compiled against .Net 1.1 rather than .Net 1.0 due to a dependency on the
FolderBrowserDialog not available in .Net 1.0.
</li>
<li>
Coverage file stylesheet modified to show coverage column and NCoverExplorer version information with
numerous other cosmetic enhancements.
</li>
<li>
Enrich error environment information to include .Net framework version and operating system.
</li>
<li>
Classes without a namespace are now shown under a namespace node of "-" like in Reflector.
</li>
</ul>
<p class="answer">The following bug fixes were made:</p>
<ul>
<li>
Warnings about mismatches when merging xml files are no longer issued. NCover seems to inconsistently
produce xml file coverage of methods which caused some users problems when merging.
</li>
<li>
Nested classes without a namespace specified would cause the coverage.xml file to fail to load.
</li>
<li>
Parsing overloaded properties (overloads of this[]) would not show the separate overloads in the tree
and have incorrect coverage stats.
</li>
<li>
Fix memory leaks for when source code tabs are closed.
</li>
<li>
Minimum coverage threshold for NCoverExplorer.Console would sometimes be incorrect due to rounding.
</li>
<li>
Changed NCoverExplorerSummary.xsl to format to 1dp rather than rounding to 0.
</li>
<li>
Sorting by filename for a method then clicking on class node threw exception.
</li>
<li>
VB.Net source code keywords not highlighted with the correct ICSharpCode template.
</li>
</ul>
<hr/>
<p class="question">v1.3.3 - Apr 4th 2006</p>
<p class="answer">Bundled with TestDriven.Net from build 2.0.1578.</p>
<p class="answer">The following new features were introduced:</p>
<ul>
<li>
Added NCoverExplorer.Console.exe for utilising NCoverExplorer features with automated
coverage builds and NAnt tasks. By default will load up all the specified coverage file(s), apply
any coverage exclusion(s) specified in the NCoverExplorer configuration and display total
coverage statistics in the console output. If all items processed successfully returns an exit code of 0,
if an exception occurs returns an exit code of 2.
</li>
<li>
Added /m:xx (or /minCoverage:xx) argument to NCoverExplorer.Console.exe. When used in conjunction with
/f (or /failMinimum) an exit code of 3 is returned if the min coverage is not reached. Can act
as a trigger for failing an automated build such as with CruiseControl.Net.
</li>
<li>
Added module & namespace summary xml report generation to NCoverExplorer (both the GUI and Console versions).
In the GUI, this is available via the "View->Reports" menu. The three reports that are offered currently are:
<br/> - Module Summary (Coverage totals for the project and per module);
<br/> - Namespace Summary (Coverage totals for the project and per namespace);
<br/> - Module Namespace Summary (Coverage totals for the project, per module and per namespace);
</li>
<li>
Reports can be generated in xml or html format. Native html may be useful for directly attaching to e-mails.
If xml format is chosen a "CoverageReport.xsl" stylesheet is copied from the NCoverExplorer installation
folder to the report directory and linked to the xml file similar to coverage.xml/coverage.xsl by NCover.
</li>
<li>
Reports can contain an "excluded nodes" footer section. This lists at the topmost level all of the items
excluded from coverage at the time the report was run.
</li>
<li>
Added "View->Filter" main menu and context menus, offering the ability to filter out nodes. Filtered
nodes are simply moved under a new "Filtered" tree node and do not alter the coverage statistics
(unlike excluded nodes which are effectively removed from the tree). Filters offered are either to
hide all 100% covered nodes, or hide all unvisited (0%) nodes.
</li>
<li>
Added "Include in Results" context menu option for when clicking on either the "Excluded" bin or one
of it's immediate child nodes. Offers a way to "undo" an exclusion without reloading the file.
</li>
<li>
Added "View->Summary Statistics" menu option (shortcut F3) to show dialog of totals of files, classes, members,
NCLOC (non-commented lines of code) and sequence points. Statistics do not include excluded nodes
(but will include filtered nodes).
</li>
<li>
Created NAnt and MSBuild tasks for execution of NCoverExplorer.Console as an alternative to the <exec> task.
These tasks offer a more developer friendly alternative such as <fileset> for coverage files and creating a
.config file on the fly based on specified parameters such as <exclusions> within the .build/.proj file.
</li>
<li>
Replaced menus with a lightly tweaked variant of Lutz Roeder's excellent CommandBar code to give a more modern
look and assign icons on the menus.
</li>
<li>
Added a toolbar. If not wanted the toolbar can be hidden using the "View->Show Toolbar" menu option.
</li>
</ul>
<p class="answer">The following minor changes were made:</p>
<ul>
<li>
Options dialog shortcut changed to F2.
</li>
<li>
Excluding a node will now select the node after by default rather than the one previous.
</li>
</ul>
<p class="answer">The following bug fixes were made:</p>
<ul>
<li>
Fix bug where delete key shortcut was active on the root coverage file node, causing an exception to be thrown.
</li>
<li>
Path was being truncated from the module name when saved.
</li>
<li>
Fix bug where changing theme without coverage file loaded caused error.
</li>
</ul>
<hr/>
<p class="question">v1.3.2 - Mar 14th 2006</p>
<p class="answer">Bundled with TestDriven.Net from build 2.0.1545.</p>
<p class="answer">The following new features were introduced:</p>
<ul>
<li>
Added support for merging multiple coverage files. This can be triggered through a variety of ways:
<br/> - Selecting multiple test classes/fixtures/projects in TestDriven.Net;
<br/> - Passing multiple files in the command line arguments;
<br/> - Selecting multiple files in the Open dialog;
<br/> - Using a new "File->Merge..." menu option;
<br/> - Drag/dropping onto the NCoverExplorer application.
</li>
<li>
Added tabs for each source code file you open to explore coverage on. If you click on a partial class
then tabs will be opened for each of the source code files making up the class.
</li>
<li>
Added the ability to exclude assemblies, namespaces or classes from the coverage results by a wildcard capable
case-sensitive match on the name. By default NCoverExplorer includes two exclusions:
<br/> - Exclude all assemblies with the name ending in ".Tests".
<br/> - Exclude all namespaces with the name containing ".My" (for VB.Net exclusions).
</li>
<li>
Added support for the NCover 1.5.4 "excluded" attribute which can be found in the coverage.xml files when
the appropriate NCover command-line attributes are used. Note that TestDriven.Net still does not as yet
support this attribute so you need to use the NCover.Console command line for this feature - for more information see
<a href=http://ncover.org/SITE/blogs/ncover_blog/archive/2006/01/29/103.aspx>here</a>. NCoverExplorer
will not include nodes marked as 'excluded' by NCover in it's totals but will still display them in the tree.
</li>
<li>
Added an "Excluded" child bin node containing all nodes that have been excluded by the options dialog, by NCover
attributes or by the "Exclude From Results" context menu option (see next point).
</li>
<li>
Replaced the "Remove from Results" context menu feature with "Exclude from Results" (shortcut of the DEL key).
Achieves a similar result of removing nodes from coverage calculations, however the nodes are "moved" to the
Excluded bin rather than being deleted from the tree.
</li>
<li>
Added a custom "theme" capability along with further colour and font customisation options for the coverage tree,
statistics and source code panes. A number of predefined "themes" are supplied and users can add their own.
Users can switch between themes either in the Options dialog or via the "View->Themes" menu.
</li>
<li>
Added a new "View->Coverage" menu which has sub-options related to "Sequence Point Coverage" and
"Function Coverage", assigned shortcut keys ctrl+(1-4):
<br/> - Choosing one of the "Sequence Point" variants will display the tree nodes with differing naming
combinations of coverage percentage and # unvisited sequence points.
<br/> - Choosing "Function Coverage" will alter the coverage tree display so that only methods/classes that were
invoked are highlighted. Method nodes show the number of visits to that method. Class, namespace and module nodes
show the maximum visit count by any of their children.
</li>
<li>
Added a "View->Sort By" menu option and context menu on the tree, with sub-options for "Name" (default),
"Class name/line number", "Coverage %" (ascending/descending), "Uncovered Sequence Points" (ascending/descending)
and "Visit Counts" (ascending/descending).
Assigned shortcut keys of ctrl+shift+(1-8). Note that reloading the coverage file will remove the current sort
and default back to by "Name".
</li>
<li>
Added "Save" and "Save As" options to the File menu. These give you the option of overwriting/creating a
new coverage.xml file with the current values loaded in NCoverExplorer. Any coverage exclusions/removed
nodes will not appear in the saved coverage file. Note that the methods are written in the same order as
the sort order specified above.
</li>
<li>
Added an "Explore Coverage Folder" menu option to the file menu.
</li>
<li>
Added an "Expand All" context menu option on the tree (shortcut ctrl+L).
</li>
<li>
Enhanced the statistics pane. When a class node is selected you will now see additional columns of
coverage %, unvisited sequence points and sequence points. When clicking on a method node you will
now see the filename.
</li>
<li>
Implemented "smart expansion" in the tree. If when you expand a node there is only one child node
then that node will also be expanded and so on. Increases speed of tree navigation particularly
if using a style of "Nested" namespaces with deep hierarchies.
</li>
<li>
Display class file name in tab page header bar when a method node is clicked on. Tooltip shows the path.
</li>
</ul>
<p class="answer">The following minor changes were made:</p>
<ul>
<li>
Optimised when reloads of the coverage file so it is now only required if you change a coverage exclusion
or the tree grouping/nesting styles in the options dialog. Makes for a snappier UI.
</li>
<li>
Added a "Close" menu option to remove any loaded coverage file(s) from display.
</li>
<li>
Moved all the "Recent Files" into a submenu to tidy up the File menu.
</li>
<li>
Pressing Tab/shift-tab while focus is in the TextEditor pane of source code will now
move focus out of the TextEditor.
</li>
<li>
If a source code file contains multiple classes (not nested), then only the highlighting relevant
to that particular class will be displayed in the editor window as each class tree node is clicked.
</li>
<li>
Excluding the My namespace is now done through the Exclusions feature.
</li>
<li>
Options dialog can be displayed using the F4 shortcut key.
</li>
<li>
Removed last remnants of "non VS.Net standard colors" from the C# ICSharpCode TextEditor template.
</li>
<li>
Make the GUI naming consistent to correctly reference "sequence points" rather than "lines" and "unvisited"
rather than "uncovered".
</li>
<li>
Removed "Edit in VS.Net" from the View menu.
</li>
<li>
Changed NCoverExplorer main form icon to one that includes 32x32 sizes so Alt-Tab switching looks
better than upscaled 16x16 icon.
</li>
<li>
User is now prompted to remove a non-existent coverage file from the "Recent" files list rather than
automatically being removed.
</li>
</ul>
<p class="answer">The following bug fixes were made:</p>
<ul>
<li>
Serializing the configuration settings was not flushing the stream - resulting sometimes in a blank settings file
preventing people from loading NCoverExplorer. Will now revert to default settings if an error occurs.
</li>
<li>
Displaying a source code file that has been modified to have less lines of code than at the time of the coverage run
will now display a user friendly message box.
</li>
<li>
Compensation made for NCover not reporting column information when profiling C++ code. NCoverExplorer will now
highlight the entire line rather than throwing an error.
</li>
<li>
In some circumstances properties were not highlighted consistently due to a bug in the property node expansion.
</li>
<li>
Coverage greater than 99.5% will no longer be rounded up to 100% in the display. It is instead shown as ">99.5%".
</li>
<li>
Extremely high visit counts will no longer overflow the visit count.
</li>
<li>
Statistics pane for a class will now always consistently show the property nodes grouped, rather than only
after the class node has been expanded in the tree.
</li>
<li>
Recent file menu would display incorrectly for files numbered from 10 onwards truncating first character.
</li>
<li>
Release notes & FAQ were always directed to website rather than local versions when NCoverExplorer was started
from TestDriven.Net.
</li>
</ul>
<hr/>
<p class="question">v1.3.1 - Feb 15th 2006</p>
<p class="answer">Bundled with TestDriven.Net from build 2.0.1435.</p>
<p class="answer">The following new features were introduced:</p>
<ul>
<li>
Namespaces are now "flattened" by default in the tree. This looks like the ClassView
browser in VS.Net 2005 (or Lutz Roeder's Reflector). You can retain the nested look by changing it in the View->Options dialog.
</li>
<li>
If you use the original "nested" namespace style (like the VS.Net 2003 class browser), then inner namespaces will now be
listed at the top of each branch with the classes listed underneath which is less confusing to navigate.
</li>
<li>
Option to exclude the "My" namespace for VB.Net projects (for use with with BCL 2.0 & NCover 1.5.x).
</li>
<li>
Right-click menu option on coverage tree (shortcut ctrl+R) to "Remove From Results" that selected node
and all it's children. Will force the coverage values to be recalculated. Intended for use where
you have undesired assemblies, namespaces, classes or methods included in the report that are skewing your
coverage results and you want them removed.
</li>
<li>
Option to specify a satisfactory coverage threshold as a number of lines instead/as well as a percentage.
If either of the conditions are met the node is coloured differently (provided the coverage is not zero).
</li>
<li>
Colours can now be customised for both the source code highlighting and the nodes in the tree.
</li>
<li>
Collapse all nodes context menu option on the coverage tree control (shortcut ctrl-A). Equivalent to reloading
the coverage file (but would preserve any changes you have made such as removing nodes).
</li>
<li>
By default the NCoverExplorer now attempts to restore your currently selected node/caret position after
reloading a coverage.xml file (either F5 or by execution of another "Test With Coverage" command in TestDriven.Net).
You can turn off this behaviour in the View->Options dialog.
</li>
<li>
Statistics pane is now sortable by method name (default), visit count and line number.
</li>
<li>
Statistics pane now summarises all the methods and their visit counts when a class node is clicked.
Can be used as a basic form of method invocation counting for a fairly rudimentary level of profiling.
The colouring used is the same as that of the tree to visually assist in identifying methods invoked.
</li>
</ul>
<p class="answer">The following minor changes were made:</p>
<ul>
<li>
Restructured the Options dialog to have a tabbed interface.
</li>
<li>
Renamed the "Show Visit Pane" menu option to "Show Statistics".
</li>
<li>
The statistics pane now includes the method name. Widths of the columns are remembered each time you close NCoverExplorer.
</li>
<li>
Statistics pane now has icons and colouring to match those of the associated nodes in the coverage tree.
</li>
<li>
Inner nested classes now nested internally in the tree under the parent class, sorted to the top.
</li>
<li>
Added FAQ, Release Notes and Blog website to the Help menu.
</li>
</ul>
<p class="answer">The following bug fixes were made:</p>
<ul>
<li>
Source code files now loading with "Encoding.Default" rather than previous default of UTF-8.
</li>
<li>
Coverage highlighting not working correctly on multiple line statements.
</li>
<li>
Now handles partial classes and yield statements correctly.
</li>
</ul>
<hr/>
<p class="question">v1.3 - Feb 6th 2006</p>
<p class="answer">Bundled with TestDriven.Net from build 2.0.1373d.</p>
<p class="answer">The following new features were introduced:</p>
<ul>
<li>
Launching from VS.Net using TestDriven.Net will now re-use the NCoverExplorer instance
opened from a previous "Test with... Coverage" click. Each VS.Net instance has it's own
instance of NCoverExplorer.
</li>
<li>
Added "Edit in VS.Net" functionality (keyboard shortcut ctrl+ E) for classes and methods.
Will navigate to source code in your IDE at same point where your cursor resides in NCoverExplorer.
Replaces and enhances previous "Open File" right-click option which has been removed.
</li>
<li>
Added "Expand Covered" functionality (keyboard shortcut ctrl + Q) - recurses through the child
nodes of the current node and expands all those with partial or complete coverage. Useful when
using in conjunction with TestDriven.Net for isolated unit testing.
</li>
<li>
Added "coverage file" node at the top of the tree showing total coverage across all modules/namespaces.
</li>
<li>
Group by module option (default) to assist with navigating coverage for large solutions.
</li>
<li>
Configuration information for NCoverExplorer now written to Local Settings rather than registry.
</li>
<li>
Increase default number of "recent files" to 10, with ability to alter in the Options dialog.
</li>
<li>
Reload of the current coverage file now has a shortcut key of F5.
</li>
<li>
Display the path to the currently loaded coverage file in the title bar.
</li>
</ul>
<p class="answer">The following minor changes were made:</p>
<ul>
<li>
Performance enhancements to improve loading times further for large files.
</li>
<li>
Static constructors now renamed from "cctor" to ".cctor" so as to be sorted at the top.
</li>
<li>
Running NCoverExplorer for first time ever will use a better starting form position.
</li>
<li>
Removed configuration option for "nesting properties" - default remains the same of "true".
</li>
<li>
Source code refactoring into separate assemblies to facilitate unit testing.
</li>
</ul>
<hr/>
<p class="question">v1.2 - Feb 1st 2006</p>
<p class="answer">First public release, bundled with TestDriven.Net from build 2.0.1341d.</p>
<p class="answer">The following new features were introduced:</p>
<ul>
<li>
Block style highlighting option for both visited and unvisited code.
</li>
<li>
Satisfactory coverage threshold.
</li>
<li>
Nesting of properties as nodes are expanded.
</li>
<li>
Further speed improvements for initial file parsing.
</li>
</ul>
<hr/>
<p class="question">v1.1 - Jan 1st 2006</p>
<p class="answer">Speed improvements.</p>
<hr/>
<p class="question">v1.0 - Dec 17th 2005</p>
<p class="answer">First version created.</p>
</body>
</html>
| zyyin2005-lokad | Resource/Tool/NCoverExplorer/NCoverExplorerReleaseNotes.html | HTML | bsd | 41,251 |
#region (c)2009 Lokad - New BSD license
// Company: http://www.lokad.com
// This code is released under the terms of the new BSD licence
#endregion
using System.Reflection;
using System.Runtime.InteropServices;
using System.Security;
[assembly : AssemblyCompany("Lokad")]
[assembly : AssemblyProduct("Lokad.Cloud")]
[assembly : AssemblyCulture("")]
[assembly : ComVisible(false)]
// .NET 2.0 security model
[assembly: SecurityRules(SecurityRuleSet.Level1)]
///<summary>
/// Assembly information class that is shared between all projects
///</summary>
internal static class GlobalAssemblyInfo
{
// copied from the Lokad.Client 'GlobalAssemblyInfo.cs'
internal const string PublicKey =
"00240000048000009400000006020000002400005253413100040000010001009df7" +
"e75ec7a084a12820d571ea9184386b479eb6e8dbf365106519bda8fc437cbf8e" +
"fb3ce06212ac89e61cd0caa534537575c638a189caa4ac7b831474ceca5a" +
"cf5018f2d4b41499044ce90e4f67bb0e8da4121882399b13aabaa6ff" +
"46b4c24d5ec6141104028e1b5199e2ba1e35ad95bd50c1cf6ec5" +
"c4e7b97c1d29c976e793";
} | zyyin2005-lokad | Source/GlobalAssemblyInfo.cs | C# | bsd | 1,097 |
#region Copyright (c) Lokad 2009
// This code is released under the terms of the new BSD licence.
// URL: http://www.lokad.com/
#endregion
using Lokad.Cloud.ServiceFabric.Runtime;
using Microsoft.WindowsAzure.ServiceRuntime;
namespace Lokad.Cloud
{
/// <summary>Entry point of Lokad.Cloud.</summary>
public class WorkerRole : RoleEntryPoint
{
readonly ServiceFabricHost _serviceFabricHost;
public WorkerRole()
{
_serviceFabricHost = new ServiceFabricHost();
}
/// <summary>
/// Called by Windows Azure to initialize the role instance.
/// </summary>
/// <returns>
/// True if initialization succeeds, False if it fails. The default implementation returns True.
/// </returns>
/// <remarks>
/// <para>Any exception that occurs within the OnStart method is an unhandled exception.</para>
/// </remarks>
public override bool OnStart()
{
_serviceFabricHost.StartRuntime();
return true;
}
/// <summary>
/// Called by Windows Azure when the role instance is to be stopped.
/// </summary>
/// <remarks>
/// <para>
/// Override the OnStop method to implement any code your role requires to
/// shut down in an orderly fashion.
/// </para>
/// <para>
/// This method must return within certain period of time. If it does not,
/// Windows Azure will stop the role instance.
/// </para>
/// <para>
/// A web role can include shutdown sequence code in the ASP.NET
/// Application_End method instead of the OnStop method. Application_End is
/// called before the Stopping event is raised or the OnStop method is called.
/// </para>
/// <para>
/// Any exception that occurs within the OnStop method is an unhandled
/// exception.
/// </para>
/// </remarks>
public override void OnStop()
{
_serviceFabricHost.ShutdownRuntime();
}
/// <summary>
/// Called by Windows Azure after the role instance has been initialized. This
/// method serves as the main thread of execution for your role.
/// </summary>
/// <remarks>
/// <para>The role recycles when the Run method returns.</para>
/// <para>Any exception that occurs within the Run method is an unhandled exception.</para>
/// </remarks>
public override void Run()
{
_serviceFabricHost.Run();
}
}
}
| zyyin2005-lokad | Source/Lokad.Cloud.WorkerRole/WorkerRole.cs | C# | bsd | 2,343 |
#region Copyright (c) Lokad 2009
// This code is released under the terms of the new BSD licence.
// URL: http://www.lokad.com/
#endregion
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Lokad.Cloud.WorkerRole")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyCopyright("Copyright © Lokad 2009")]
[assembly: AssemblyTrademark("")]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("6d6757ec-a849-4cb5-bdbb-17707b7129a5")]
| zyyin2005-lokad | Source/Lokad.Cloud.WorkerRole/Properties/AssemblyInfo.cs | C# | bsd | 773 |
@{
Layout = "~/Views/Shared/_Layout.cshtml";
} | zyyin2005-lokad | Source/Lokad.Cloud.Console.WebRole/Views/_ViewStart.cshtml | HTML+Razor | bsd | 52 |
@model Lokad.Cloud.Console.WebRole.Models.Services.ServicesModel
@{ ViewBag.Title = "Lokad.Cloud Administration Console - Services"; }
<h1>Service Manager</h1>
<p>All initialized cloud services are listed below. Enable or disable a service by clicking its status icon.</p>
@if (Model.QueueServices.Any()) {
<h2>Queue Services</h2>
<table class="table">
@foreach (var item in Model.QueueServices) {
<tr>
<td>@Html.StartStopIconButton(item.IsStarted, item.ServiceName)</td>
<td><b>@item.ServiceName</b><br />
<small>Messages: @item.Definition.MessageTypeName</small><br />
<small>Queue: @item.Definition.QueueName</small></td>
</tr>
}
</table>
}
@if (Model.ScheduledServices.Any()) {
<h2>Scheduled Services</h2>
<table class="table">
@foreach (var item in Model.ScheduledServices) {
<tr>
<td>@Html.StartStopIconButton(item.IsStarted, item.ServiceName)</td>
<td>@item.ServiceName</td>
</tr>
}
</table>
}
@if (Model.CloudServices.Any()) {
<h2>Other Services</h2>
<table class="table">
@foreach (var item in Model.CloudServices) {
<tr>
<td>@Html.StartStopIconButton(item.IsStarted, item.ServiceName)</td>
<td>@item.ServiceName</td>
</tr>
}
</table>
}
@if (Model.UnavailableServices.Any()) {
<h2>Unavailable Services</h2>
<table class="table">
@foreach (var item in Model.UnavailableServices) {
<tr>
<td>@Html.StartStopIconButton(item.IsStarted, item.ServiceName)</td>
<td>@item.ServiceName</td>
</tr>
}
</table>
}
<script type="text/javascript">
function statusToClass(status) {
if (status) return '@IconMap.StartStopOf(true)';
else return '@IconMap.StartStopOf(false)';
}
$(document).ready(function () {
$('.icon-button').click(function () {
$('#AjaxLoading').show();
me = $(this);
enable = me.hasClass(statusToClass(false));
me.removeClass(statusToClass(!enable));
me.addClass('@IconMap.Loading');
$.ajax({
url: '@ViewBag.TenantPath/Status/' + me.attr('id'),
type: 'PUT',
dataType: 'json',
data: { isStarted: enable },
cache: false,
success: function (data) {
element = $('span[id=' + data.serviceName + ']');
element.removeClass('@IconMap.Loading');
element.addClass(statusToClass(data.isStarted));
$('#AjaxLoading').hide();
}
});
});
});
</script>
| zyyin2005-lokad | Source/Lokad.Cloud.Console.WebRole/Views/Services/ByHostedService.cshtml | HTML+Razor | bsd | 2,375 |
@model Lokad.Cloud.Console.WebRole.Models.Assemblies.AssembliesModel
@{ ViewBag.Title = "Lokad.Cloud Administration Console - Assemblies"; }
<h1>Assembly Manager</h1>
<p>Content of the assembly archive:</p>
@if (Model.ApplicationAssemblies.HasValue) {
<table class="table">
<tr>
<th>Assembly</th>
<th>Version</th>
<th>Created</th>
<th>Size</th>
<th>Symbols</th>
</tr>
@foreach (var item in Model.ApplicationAssemblies.Value)
{
<tr>
<td>@Html.OkCancelIcon(item.IsValid) @item.AssemblyName</td>
<td>@item.Version.ToString()</td>
<td>@String.Format("{0:g}", item.DateTime)</td>
<td>@String.Format("{0} KB", item.SizeBytes / 1024)</td>
<td>@Html.OkCancelIcon(item.HasSymbols) @(item.HasSymbols ? "Available" : "None")</td>
</tr>
}
</table>
} else {
<div class="warning">No Cloud Application Package was found</div>
}
<h2>Replace assembly package</h2>
<p>Upload a stand-alone .Net assembly (*.dll) or a Zip archive containing multiple assemblies. Matching symbol files (*.pdb) are supported but optional. The current assembly package will be deleted.</p>
@using (Html.BeginForm("UploadPackage", "Assemblies", new { hostedServiceName = ViewBag.Navigation.CurrentHostedServiceName }, FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<p><input type="file" name="package" accept="application/octet-stream, application/zip" /><br /><input type="submit" value="Upload" /></p>
}
| zyyin2005-lokad | Source/Lokad.Cloud.Console.WebRole/Views/Assemblies/ByHostedService.cshtml | HTML+Razor | bsd | 1,458 |
@{ ViewBag.Title = "Lokad.Cloud Administration Console - Login"; }
<h2>Login</h2>
@if (ViewBag.Message != null) {
<div style="border: solid 1px red">@ViewBag.Message</div>
}
<p>You must log in before entering the Administration Console: </p>
<form action="Authenticate?ReturnUrl=@Html.Raw(HttpUtility.UrlEncode(Request.QueryString["ReturnUrl"]))" method="post">
<label for="openid_identifier">OpenID: </label>
<input id="openid_identifier" name="openid_identifier" size="40" />
<input type="submit" value="Login" />
</form>
<script type="text/javascript">
$(document).ready(function () {
$("#openid_identifier").focus();
});
</script>
| zyyin2005-lokad | Source/Lokad.Cloud.Console.WebRole/Views/Account/Login.cshtml | HTML+Razor | bsd | 667 |
@model Lokad.Cloud.Console.WebRole.Models.Scheduler.SchedulerModel
@{ ViewBag.Title = "Lokad.Cloud Administration Console - Scheduler"; }
<h1>Scheduler</h1>
<p>Manage scheduled execution of your services.</p>
<table class="table">
<tr>
<th>Name</th>
<th>Last Run</th>
<th>Period</th>
<th>Scope</th>
<th>Lease</th>
</tr>
@foreach (var item in Model.Schedules) {
<tr>
<td>@item.ServiceName</td>
<td>@(item.WorkerScoped ? "untracked" : Lokad.FormatUtil.TimeOffsetUtc(item.LastExecuted.UtcDateTime))</td>
<td>@item.TriggerInterval</td>
<td>@(item.WorkerScoped ? "Worker" : "Cloud")</td>
<td>@PresentationHelpers.PrettyFormatLease(item)</td>
</tr>
}
</table>
| zyyin2005-lokad | Source/Lokad.Cloud.Console.WebRole/Views/Scheduler/ByHostedService.cshtml | HTML+Razor | bsd | 722 |
@model Lokad.Cloud.Console.WebRole.Models.Logs.LogsModel
@{ ViewBag.Title = "Lokad.Cloud Administration Console - Logs"; }
@section Header {
<script src="http://ajax.aspnetcdn.com/ajax/jquery.templates/beta1/jquery.tmpl.min.js" type="text/javascript"></script>
<link href="@Url.Content("~/Content/ui.slider.extras.css")" rel="stylesheet" type="text/css" />
<script src="@Url.Content("~/Scripts/selectToUISlider.jQuery.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/knockout-1.1.2.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/knockout.mapping.js")" type="text/javascript"></script>
}
<h1>Logs</h1>
<p>Use the slider below to choose the threshold level for filtering out less important log entries.</p>
<fieldset>
<select name="loglevel" id="loglevel">
<option value="Debug">Debug</option>
<option value="Info" selected="selected">Info</option>
<option value="Warn">Warning</option>
<option value="Error">Error</option>
<option value="Fatal">Fatal</option>
</select>
</fieldset>
<div class="loadMore" data-bind='visible: NewerAvailable, click: loadNewerEntries'>New Entries Available</div>
<div data-bind='template: { name: "logGroupTemplate", foreach: Groups }'></div>
<br />
<p data-bind="visible: Groups().length == 0">No log entries satisfy the chosen log level threshold. Use the level selector above to choose a different level.</p>
<script type="text/html" id="logGroupTemplate">
<h2>${Title}</h2>
<table class="table" id="datatable">
<thead>
<tr>
<th width="60">Time</th>
<th width="20"></th>
<th width="100%">Message</th>
</tr>
</thead>
<tbody data-bind='template: {name: "logEntryTemplate", foreach: Entries}'></tbody>
</table>
<div class="loadMore" data-bind='visible: OlderAvailable, click: function() { loadOlderEntries($data) }'>More Available</div>
</script>
<script type="text/html" id="logEntryTemplate">
<tr>
<td>${Time}</td>
<td><span class="icon-LogLevels icon-LogLevels-${Level}"></span></td>
<td>
${Message}<br />
<div data-bind="visible: Error">
<b>Exception Details and Stack:</b> (<a href="#" data-bind="click: function() { toggleShowDetails($data) }">Show/Hide</a>)<br />
<pre data-bind="visible: ShowDetails">${Error}</pre>
</div>
</td>
</tr>
</script>
<script type="text/javascript">
// inline to save a separate request
var viewModel = ko.mapping.fromJSON(@Html.Enquote(new System.Web.Script.Serialization.JavaScriptSerializer().Serialize(Model)));
var updateMask = false;
var ajaxQueue = $({});
$.ajaxQueue = function(ajaxOpts) {
var oldComplete = ajaxOpts.complete;
ajaxQueue.queue(function(next) {
ajaxOpts.complete = function() {
if(oldComplete) { oldComplete.apply(this, arguments); }
next();
};
$.ajax(ajaxOpts);
});
};
toggleShowDetails = function(entry) {
entry.ShowDetails(!entry.ShowDetails());
};
loadOlderEntries = function(group) {
group.OlderAvailable(false);
var groupIndex = viewModel.Groups.indexOf(group);
var newerThanToken = groupIndex == (viewModel.Groups().length - 1) ? undefined : viewModel.Groups()[groupIndex + 1].NewestToken();
$.ajaxQueue({
url: '@ViewBag.TenantPath/Entries',
dataType: 'json',
data: { threshold: $('select#loglevel').val(), skip: group.Entries().length, count: 50, olderThanToken: group.OldestToken(), newerThanToken: newerThanToken },
cache: false,
success: function (data) {
$.each(data.Groups, function (i, g) { viewModel.Groups.push(ko.mapping.fromJS(g)); });
sortGroups();
joinGroups();
}
});
};
loadNewerEntries = function() {
viewModel.NewerAvailable(false);
$.ajaxQueue({
url: '@ViewBag.TenantPath/Entries',
dataType: 'json',
data: { threshold: $('select#loglevel').val(), count: 50, newerThanToken: viewModel.NewestToken() },
cache: false,
success: function (data) {
viewModel.NewerAvailable(false);
viewModel.NewestToken(data.NewestToken);
while(group = data.Groups.pop()) { viewModel.Groups.unshift(ko.mapping.fromJS(group)); }
joinGroups();
}
});
}
sortGroups = function() {
viewModel.Groups.sort(function (l,r) {
if(l.Key() != r.Key()) {
return l.Key() < r.Key() ? 1 : -1
}
if(l.NewestToken() != r.NewestToken()) {
return l.NewestToken() < r.NewestToken() ? 1 : -1
}
return 0;
});
}
joinGroups = function() {
var groups = viewModel.Groups();
for(index=groups.length-2; index >= 0; index--) {
var upper = groups[index];
var lower = groups[index+1];
if ((upper.Key() == lower.Key()) && !upper.OlderAvailable()) {
$.each(lower.Entries(), function (i,e) { upper.Entries.push(e); });
upper.OlderAvailable(lower.OlderAvailable());
upper.OldestToken(lower.OldestToken());
viewModel.Groups.remove(lower);
}
}
}
$(document).ready(function() {
ko.applyBindings(viewModel);
$('#AjaxLoading')
.bind("ajaxStart", function() { $(this).show(); updateMask = true; })
.bind("ajaxStop", function() { $(this).hide(); updateMask = false; })
$('select#loglevel').selectToUISlider({ labels: 5, sliderOptions: { change: function() {
$.ajaxQueue({
url: '@ViewBag.TenantPath/Entries',
dataType: 'json',
data: { threshold: $('select#loglevel').val() },
cache: false,
success: function (data) {
ko.mapping.updateFromJS(viewModel, data);
}
});
}}}).hide();
setInterval(function () {
if (updateMask || viewModel.NewerAvailable()) { return; }
$.ajaxQueue({
url: '@ViewBag.TenantPath/HasNewerEntries',
dataType: 'json',
data: { threshold: $('select#loglevel').val(), newerThanToken: viewModel.NewestToken() },
cache: false,
success: function (data) {
viewModel.NewerAvailable(data.HasMore);
}
});
}, 30000);
});
</script>
| zyyin2005-lokad | Source/Lokad.Cloud.Console.WebRole/Views/Logs/ByHostedService.cshtml | HTML+Razor | bsd | 5,971 |
@model Lokad.Cloud.Console.WebRole.Models.Overview.DeploymentModel
@{ ViewBag.Title = "Lokad.Cloud Administration Console - Overview"; }
<h1>Lokad.Cloud Hosted Service Overview</h1>
<p>Details for the @Model.HostedService.ServiceLabel Hosted Service.</p>
<table class="table">
<tr>
<th style="text-align: right;">Name (Subdomain):</th>
<td><b>@Model.HostedService.ServiceName</b></td>
</tr>
<tr>
<th style="text-align: right;">Label:</th>
<td><b>@Model.HostedService.ServiceLabel</b></td>
</tr>
@if (!String.IsNullOrEmpty(Model.HostedService.Description)) {
<tr>
<th style="text-align: right;">Description:</th>
<td><em>@Model.HostedService.Description</em></td>
</tr>
}
<tr>
<th style="text-align: right;">Storage Account:</th>
<td><code>@Model.HostedService.StorageAccountName</code>, with key <code>@Model.HostedService.StorageAccountKeyPrefix...</code></td>
</tr>
</table>
<h2>Azure Deployments</h2>
<p>The following deployments have been discovered in the @Model.HostedService.ServiceLabel Hosted Service.</p>
<table class="table">
@foreach (var deployment in Model.HostedService.Deployments) {
<tr>
<td>
@Html.OkCancelIcon(deployment.IsRunning) <b>@deployment.Slot</b><br />
<br />
@if(deployment.IsTransitioning) { <b>UPDATING</b> }
else if(!deployment.IsRunning) { <b>SUSPENDED</b> }
</td>
<td>
@deployment.DeploymentLabel<br />
<br />
<b>@deployment.InstanceCount Worker Instances</b><br/><br />
@if (deployment.IsRunning) {
using (Html.BeginForm("InstanceCount", "Overview")) {
@Html.Hidden("slot", deployment.Slot)
<div class="warning">Update to @Html.TextBox("instanceCount", deployment.InstanceCount, new { style = "width:25px;" }) Worker Instances: <input type="submit" value="Request" /></div>
}
}
else if(deployment.IsTransitioning) { <div class="warning">An Azure deployment update is currently in progress.</div> }
else if(!deployment.IsRunning) { <div class="warning">The Azure deployment is suspended.</div> }
</td>
</tr>
}
</table>
| zyyin2005-lokad | Source/Lokad.Cloud.Console.WebRole/Views/Overview/ByHostedService.cshtml | HTML+Razor | bsd | 2,088 |
@model Lokad.Cloud.Console.WebRole.Models.Overview.OverviewModel
@{ ViewBag.Title = "Lokad.Cloud Administration Console - Overview"; }
<h1>Lokad.Cloud Hosted Services Overview</h1>
<p>The following Lokad.Cloud Hosted Services have been discovered in your Windows Azure subscription.</p>
@foreach (var item in Model.HostedServices) {
<table class="table">
<tr>
<th style="width: 180px;"><b>@item.ServiceName</b></th>
<th style="width: 500px;"><b>@item.ServiceLabel</b></th>
</tr>
@if (!String.IsNullOrEmpty(item.Description)) {
<tr>
<td colspan="2"><em>@item.Description</em></td>
</tr>
}
<tr>
<td style="text-align: right;">Storage Account:</td>
<td><code>@item.StorageAccountName</code>, with key <code>@item.StorageAccountKeyPrefix...</code></td>
</tr>
<tr>
<td style="text-align: right;">Deployments:</td>
<td>
@foreach (var deployment in item.Deployments) {
@: @Html.OkCancelIcon(deployment.IsRunning) @deployment.Slot @if (deployment.IsTransitioning) { <b>UPDATING</b> } with <b>@deployment.InstanceCount Worker Instances</b>: <em>@deployment.DeploymentLabel</em><br/>
}
</td>
</tr>
</table>
<p> </p>
}
| zyyin2005-lokad | Source/Lokad.Cloud.Console.WebRole/Views/Overview/Index.cshtml | HTML+Razor | bsd | 1,189 |
@model Lokad.Cloud.Console.WebRole.Models.Config.ConfigModel
@{ ViewBag.Title = "Lokad.Cloud Administration Console - Config"; }
<h1>Dependency Injection Configuration</h1>
<p>Optional XML application configuration to customize dependency injection for cloud services using an autofac configuration section.</p>
@using (Html.BeginForm("Configuration", "Config")) {
@Html.TextAreaFor(m => m.Configuration, 20, 80, null)
<input type="submit" value="Save" />
}
| zyyin2005-lokad | Source/Lokad.Cloud.Console.WebRole/Views/Config/ByHostedService.cshtml | HTML+Razor | bsd | 475 |
@using Lokad.Cloud.Console.WebRole.Models.Shared
<!DOCTYPE html>
<html>
<head>
<title>@ViewBag.Title</title>
<link href="@Url.Content("~/Content/Lokad.css")" rel="stylesheet" type="text/css" />
<link href="@Url.Content("~/Content/jquery-ui-1.7.1.custom.css")" rel="stylesheet" type="text/css" />
<script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.4.4.min.js" type="text/javascript"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.ui/1.8.7/jquery-ui.min.js" type="text/javascript"></script>
@RenderSection("Header", required: false)
</head>
<body>
<div class="page">
<div id="HeaderDiv">
<div id="AuthBar">
@Html.Partial("AuthBarPartial")
</div>
<div id="TopBarBackground"></div>
<div id="TopBar">
<div id="Logo"><h1><a href="http://www.lokad.com/"><span class="hidden">Lokad.com</span></a></h1></div>
<div id="TopControls"></div>
</div>
<div id="TitleBar"><h2>Lokad.Cloud - Administration Console</h2></div>
@if (ViewBag.Navigation.ShowDeploymentSelector) {
<div id="SubNavBar">
@Html.Partial("DeploymentMenuPartial", (NavigationModel)ViewBag.Navigation)
</div>
}
<div id="NavBar">
@Html.Partial("NavigationMenuPartial", (NavigationModel)ViewBag.Navigation)
</div>
</div>
<div id="ContentWrapper">
<div id="ContainerDiv">
<div id="SidebarDiv">
<div id="SidebarHeaderDiv"></div>
<div id="SidebarContentDiv"></div>
<div id="SidebarFooterDiv"></div>
</div>
<div id="MainDiv">
<div id="MainHeaderDiv"></div>
<div id="Text">
@RenderBody()
</div>
<div id="MainFooterDiv"></div>
</div>
</div>
<div id="FooterDiv">
</div>
</div>
<div id="FooterWrapper">
<div id="Footer">
<div class="left">
<b>Lokad.Cloud</b>
<ul>
<li class="first"><a href="http://code.google.com/p/lokad-cloud/" class="pagelink">Project homepage</a><br />
<a href="http://code.google.com/p/lokad-cloud/issues/list" class="pagelink">Report an issue</a>
</li>
</ul>
</div>
<div class="right">
<a href="http://www.lokad.com/AboutUs.ashx" class="pagelink" title="About Us">About Us</a> |
<a href="http://www.lokad.com/ContactUs.ashx" class="pagelink" title="Contact Us">Contact Us</a> |
© 2011 Lokad<br />
<img id="AjaxLoading" src="/Content/Images/loading.gif" style="display: none;" /><br />
@if (IsSectionDefined("Timestamp")) {
@RenderSection("Timestamp")
}
else if (ViewBag.Discovery.ShowLastDiscoveryUpdate) {
@: Data shown is not older than @ViewBag.Discovery.LastDiscoveryUpdate
}
</div>
</div>
<br />
</div>
</div>
</body>
</html>
| zyyin2005-lokad | Source/Lokad.Cloud.Console.WebRole/Views/Shared/_Layout.cshtml | HTML+Razor | bsd | 2,794 |
@model Lokad.Cloud.Console.WebRole.Models.Shared.NavigationModel
<ul id="menu">
@foreach (var item in Model.HostedServiceNames) {
@Html.DeploymentMenuEntry(Model, item, item)
}
</ul>
| zyyin2005-lokad | Source/Lokad.Cloud.Console.WebRole/Views/Shared/DeploymentMenuPartial.cshtml | HTML+Razor | bsd | 196 |
@model System.Web.Mvc.HandleErrorInfo
@{ ViewBag.Title = "Error"; }
<h2>Sorry, an error occurred while processing your request.</h2>
| zyyin2005-lokad | Source/Lokad.Cloud.Console.WebRole/Views/Shared/Error.cshtml | HTML+Razor | bsd | 141 |
<ul>
@if (Request.IsAuthenticated) {
<li>Welcome <b>@HttpContext.Current.User.Identity.Name</b> @Html.ActionLink("Logout", "Logout", "Account")</li>
}
else {
<li>@Html.ActionLink("Login", "Login", "Account")</li>
}
</ul>
| zyyin2005-lokad | Source/Lokad.Cloud.Console.WebRole/Views/Shared/AuthBarPartial.cshtml | HTML+Razor | bsd | 259 |
@model Lokad.Cloud.Console.WebRole.Models.Shared.NavigationModel
<ul id="menu">
@Html.NavigationMenuEntry(Model, "Overview", "Overview")
@Html.NavigationMenuEntry(Model, "Assemblies", "Assemblies")
@Html.NavigationMenuEntry(Model, "Config", "Config")
@Html.NavigationMenuEntry(Model, "Services", "Services")
@Html.NavigationMenuEntry(Model, "Scheduler", "Scheduler")
@Html.NavigationMenuEntry(Model, "Queues", "Queues")
@Html.NavigationMenuEntry(Model, "Logs", "Logs")
</ul>
| zyyin2005-lokad | Source/Lokad.Cloud.Console.WebRole/Views/Shared/NavigationMenuPartial.cshtml | HTML+Razor | bsd | 495 |
@{ ViewBag.Title = "Lokad.Cloud Administration Console - Discovery"; }
<div class="warning">
The Lokad.Cloud Administration Console is currently discovering the Windows Azure subscription
for Lokad.Cloud deployments. This page automatically refreshes every 10 seconds.
Please wait or refresh manually.
</div>
<script type="text/javascript">
setTimeout("location.reload(true);", 10000);
</script>
| zyyin2005-lokad | Source/Lokad.Cloud.Console.WebRole/Views/Discovery/Index.cshtml | HTML+Razor | bsd | 416 |
@model Lokad.Cloud.Console.WebRole.Models.Queues.QueuesModel
@{ ViewBag.Title = "Lokad.Cloud Administration Console - Queues"; }
@section Header {
<script src="http://ajax.aspnetcdn.com/ajax/jquery.templates/beta1/jquery.tmpl.min.js" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/knockout-1.1.2.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/knockout.mapping.js")" type="text/javascript"></script>
}
<h1>Queue Workload</h1>
<p>This table reports the workload in the various queues of the account</p>
<table class="table">
<tr>
<th></th>
<th>Queue</th>
<th>Messages</th>
<th>Latency</th>
</tr>
<tbody data-bind='template: {name: "queueRowTemplate", foreach: Queues, beforeRemove: function(e) { $(e).slideUp() }, afterAdd: function(e) { $(e).hide().slideDown() } }'></tbody>
</table>
<h2>Quarantine: Failing Messages</h2>
<p>
Messages which fail repeatedly are persisted and removed from the queue in order to keep it healthy.
</p>
<div data-bind="visible: Quarantine().length == 0">
No message has been considered as failing so far.
</div>
<div data-bind="visible: Quarantine().length > 0">
The following messages have been considered as failing. Note that persisted messages may become unrestorable if their originating queue is deleted. No more than 50 messsages are shown at a time.
</div>
<div data-bind='template: { name: "quarantineTemplate", foreach: Quarantine, beforeRemove: function(e) { $(e).slideUp() }, afterAdd: function(e) { $(e).hide().slideDown() } }'></div>
<script type="text/html" id="queueRowTemplate">
<tr>
<td><button data-bind="click: function() { removeQueue($data) }">Delete</button></td>
<td><b data-bind="css: { queueNameWithMessages: MessageCount() > 0 }">${QueueName}</b>
{{each Services}}
<br/><small>Consumed by: ${TypeName}</small>
{{/each}}
</td>
<td data-bind="css: { queueMessageNumberWithMessages: MessageCount() > 0 }">${MessageCount}</td>
<td>${Latency}</td>
</tr>
</script>
<script type="text/html" id="quarantineTemplate">
<h3>Queue: ${QueueName}
<button data-bind="click: function() { restoreQuarantineQueue($data) }">Restore All</button>
<button data-bind="click: function() { removeQuarantineQueue($data) }">Delete All</button>
</h3>
<div data-bind='template: { name: "messageTemplate", foreach: Messages, beforeRemove: function(e) { $(e).slideUp() }, afterAdd: function(e) { $(e).hide().slideDown() } }'></div>
</script>
<script type="text/html" id="messageTemplate">
<div class="groupbox">
<p>Inserted ${Inserted} but quarantined ${Persisted}
<button data-bind="click: function() { restoreQuarantineMessage($data) }">Restore</button>
<button data-bind="click: function() { removeQuarantineMessage($data) }">Delete</button>
</p>
<div class="warning" data-bind="visible: !HasData">The raw data was lost, the message is not restoreable. Maybe the queue has been deleted in the meantime.</div>
<div class="warning" data-bind="visible: HasData && !HasXml">The XML representation of this message is not available, but message is still restoreable in its raw representation.</div>
<pre data-bind="visible: HasXml">${Content}</pre>
<div data-bind="visible: Reason">
Reason:
<pre>${Reason}</pre>
</div>
</div>
</script>
<script type="text/javascript">
var viewModel = ko.mapping.fromJSON(@Html.Enquote(new System.Web.Script.Serialization.JavaScriptSerializer().Serialize(Model)));
removeQueue = function(queue) {
ajaxDeleteQueue(queue);
viewModel.Queues.remove(queue);
};
removeQuarantineQueue = function(queue) {
while(message = queue.Messages.pop()) {
ajaxDeleteQuarantineMessage(message);
}
viewModel.Quarantine.remove(queue);
};
removeQuarantineMessage = function(message) {
ajaxDeleteQuarantineMessage(message);
var queue = quarantineQueueOfMessage(message);
queue.Messages.remove(message);
if (queue.Messages().length == 0) {
viewModel.Quarantine.remove(queue);
}
};
restoreQuarantineQueue = function(queue) {
while(message = queue.Messages.pop()) {
ajaxRestoreQuarantineMessage(message);
}
viewModel.Quarantine.remove(queue);
};
restoreQuarantineMessage = function(message) {
ajaxRestoreQuarantineMessage(message);
var queue = quarantineQueueOfMessage(message);
queue.Messages.remove(message);
if (queue.Messages().length == 0) {
viewModel.Quarantine.remove(queue);
}
};
quarantineQueueOfMessage = function(message) {
var queue;
$.each(viewModel.Quarantine(), function(i,q) { if (q.Messages.indexOf(message) >= 0) { queue = q; } });
return queue;
};
ajaxDeleteQueue = function(queue) {
$.ajax({
url: '@ViewBag.TenantPath/Queue/' + queue.QueueName(),
type: 'DELETE',
dataType: 'json',
cache: false,
});
};
ajaxDeleteQuarantineMessage = function(message) {
$.ajax({
url: '@ViewBag.TenantPath/QuarantinedMessage/' + message.Key(),
type: 'DELETE',
dataType: 'json',
cache: false,
});
};
ajaxRestoreQuarantineMessage = function(message) {
$.ajax({
url: '@ViewBag.TenantPath/RestoreQuarantinedMessage/' + message.Key(),
type: 'POST',
dataType: 'json',
cache: false,
});
};
$(document).ready(function () {
ko.applyBindings(viewModel);
$('#AjaxLoading')
.bind("ajaxStart", function() { $(this).show() })
.bind("ajaxStop", function() { $(this).hide() });
});
</script> | zyyin2005-lokad | Source/Lokad.Cloud.Console.WebRole/Views/Queues/ByHostedService.cshtml | HTML+Razor | bsd | 5,556 |
/*
* --------------------------------------------------------------------
* jQuery-Plugin - selectToUISlider - creates a UI slider component from a select element(s)
* by Scott Jehl, scott@filamentgroup.com
* http://www.filamentgroup.com
* reference article: http://www.filamentgroup.com/lab/update_jquery_ui_16_slider_from_a_select_element/
* demo page: http://www.filamentgroup.com/examples/slider_v2/index.html
*
* Copyright (c) 2008 Filament Group, Inc
* Dual licensed under the MIT (filamentgroup.com/examples/mit-license.txt) and GPL (filamentgroup.com/examples/gpl-license.txt) licenses.
*
* Usage Notes: please refer to our article above for documentation
*
* --------------------------------------------------------------------
*/
jQuery.fn.selectToUISlider = function(settings){
var selects = jQuery(this);
//accessible slider options
var options = jQuery.extend({
labels: 3, //number of visible labels
tooltip: true, //show tooltips, boolean
tooltipSrc: 'text',//accepts 'value' as well
labelSrc: 'value',//accepts 'value' as well ,
sliderOptions: null
}, settings);
//handle ID attrs - selects each need IDs for handles to find them
var handleIds = (function(){
var tempArr = [];
selects.each(function(){
tempArr.push('handle_'+jQuery(this).attr('id'));
});
return tempArr;
})();
//array of all option elements in select element (ignores optgroups)
var selectOptions = (function(){
var opts = [];
selects.eq(0).find('option').each(function(){
opts.push({
value: jQuery(this).attr('value'),
text: jQuery(this).text()
});
});
return opts;
})();
//array of opt groups if present
var groups = (function(){
if(selects.eq(0).find('optgroup').size()>0){
var groupedData = [];
selects.eq(0).find('optgroup').each(function(i){
groupedData[i] = {};
groupedData[i].label = jQuery(this).attr('label');
groupedData[i].options = [];
jQuery(this).find('option').each(function(){
groupedData[i].options.push({text: jQuery(this).text(), value: jQuery(this).attr('value')});
});
});
return groupedData;
}
else return null;
})();
//check if obj is array
function isArray(obj) {
return obj.constructor == Array;
}
//return tooltip text from option index
function ttText(optIndex){
return (options.tooltipSrc == 'text') ? selectOptions[optIndex].text : selectOptions[optIndex].value;
}
//plugin-generated slider options (can be overridden)
var sliderOptions = {
step: 1,
min: 0,
orientation: 'horizontal',
max: selectOptions.length-1,
range: selects.length > 1,//multiple select elements = true
slide: function(e, ui) {//slide function
var thisHandle = jQuery(ui.handle);
//handle feedback
var textval = ttText(ui.value);
thisHandle
.attr('aria-valuetext', textval)
.attr('aria-valuenow', ui.value)
.find('.ui-slider-tooltip .ttContent')
.text( textval );
//control original select menu
var currSelect = jQuery('#' + thisHandle.attr('id').split('handle_')[1]);
currSelect.find('option').eq(ui.value).attr('selected', 'selected');
},
values: (function(){
var values = [];
selects.each(function(){
values.push( jQuery(this).get(0).selectedIndex );
});
return values;
})()
};
//slider options from settings
options.sliderOptions = (settings) ? jQuery.extend(sliderOptions, settings.sliderOptions) : sliderOptions;
//select element change event
selects.bind('change keyup click', function(){
var thisIndex = jQuery(this).get(0).selectedIndex;
var thisHandle = jQuery('#handle_'+ jQuery(this).attr('id'));
var handleIndex = thisHandle.data('handleNum');
thisHandle.parents('.ui-slider:eq(0)').slider("values", handleIndex, thisIndex);
});
//create slider component div
var sliderComponent = jQuery('<div></div>');
//CREATE HANDLES
selects.each(function(i){
var hidett = '';
//associate label for ARIA
var thisLabel = jQuery('label[for=' + jQuery(this).attr('id') +']');
//labelled by aria doesn't seem to work on slider handle. Using title attr as backup
var labelText = (thisLabel.size()>0) ? 'Slider control for '+ thisLabel.text()+'' : '';
var thisLabelId = thisLabel.attr('id') || thisLabel.attr('id', 'label_'+handleIds[i]).attr('id');
if( options.tooltip == false ){hidett = ' style="display: none;"';}
jQuery('<a '+
'href="#" tabindex="0" '+
'id="'+handleIds[i]+'" '+
'class="ui-slider-handle" '+
'role="slider" '+
'aria-labelledby="'+thisLabelId+'" '+
'aria-valuemin="'+options.sliderOptions.min+'" '+
'aria-valuemax="'+options.sliderOptions.max+'" '+
'aria-valuenow="'+options.sliderOptions.values[i]+'" '+
'aria-valuetext="'+ttText(options.sliderOptions.values[i])+'" '+
'><span class="screenReaderContext">' + labelText + '</span>' +
'<span class="ui-slider-tooltip ui-widget-content ui-corner-all"'+ hidett +'><span class="ttContent"></span>'+
'<span class="ui-tooltip-pointer-down ui-widget-content"><span class="ui-tooltip-pointer-down-inner"></span></span>'+
'</span></a>')
.data('handleNum',i)
.appendTo(sliderComponent);
});
//CREATE SCALE AND TICS
//write dl if there are optgroups
if(groups) {
var inc = 0;
var scale = sliderComponent.append('<dl class="ui-slider-scale ui-helper-reset" role="presentation"></dl>').find('.ui-slider-scale:eq(0)');
jQuery(groups).each(function(h){
scale.append('<dt style="width: ' + (100 / groups.length).toFixed(2) + '%' + '; left:' + (h / (groups.length - 1) * 100).toFixed(2) + '%' + '"><span>' + this.label + '</span></dt>'); //class name becomes camelCased label
var groupOpts = this.options;
jQuery(this.options).each(function(i){
var style = (inc == selectOptions.length-1 || inc == 0) ? 'style="display: none;"' : '' ;
var labelText = (options.labelSrc == 'text') ? groupOpts[i].text : groupOpts[i].value;
scale.append('<dd style="left:' + leftVal(inc) + '"><span class="ui-slider-label">' + labelText + '</span><span class="ui-slider-tic ui-widget-content"' + style + '></span></dd>');
inc++;
});
});
}
//write ol
else {
var scale = sliderComponent.append('<ol class="ui-slider-scale ui-helper-reset" role="presentation"></ol>').find('.ui-slider-scale:eq(0)');
jQuery(selectOptions).each(function(i){
var style = (i == selectOptions.length-1 || i == 0) ? 'style="display: none;"' : '' ;
var labelText = (options.labelSrc == 'text') ? this.text : this.value;
scale.append('<li style="left:' + leftVal(i) + '"><span class="ui-slider-label"><img src="/Content/Images/' + labelText + '16.png"/></span><span class="ui-slider-tic ui-widget-content"' + style + '></span></li>');
});
}
function leftVal(i){
return (i/(selectOptions.length-1) * 100).toFixed(2) +'%';
}
//show and hide labels depending on labels pref
//show the last one if there are more than 1 specified
if(options.labels > 1) sliderComponent.find('.ui-slider-scale li:last span.ui-slider-label, .ui-slider-scale dd:last span.ui-slider-label').addClass('ui-slider-label-show');
//set increment
var increm = Math.max(1, Math.round(selectOptions.length / options.labels));
//show em based on inc
for(var j=0; j<selectOptions.length; j+=increm){
if((selectOptions.length - j) > increm){//don't show if it's too close to the end label
sliderComponent.find('.ui-slider-scale li:eq('+ j +') span.ui-slider-label, .ui-slider-scale dd:eq('+ j +') span.ui-slider-label').addClass('ui-slider-label-show');
}
}
//style the dt's
sliderComponent.find('.ui-slider-scale dt').each(function(i){
jQuery(this).css({
'left': ((100 /( groups.length))*i).toFixed(2) + '%'
});
});
//inject and return
sliderComponent
.insertAfter(jQuery(this).eq(this.length-1))
.slider(options.sliderOptions)
.attr('role','application')
.find('.ui-slider-label')
.each(function(){
jQuery(this).css('marginLeft', -jQuery(this).width()/2);
});
//update tooltip arrow inner color
sliderComponent.find('.ui-tooltip-pointer-down-inner').each(function(){
var bWidth = jQuery('.ui-tooltip-pointer-down-inner').css('borderTopWidth');
var bColor = jQuery(this).parents('.ui-slider-tooltip').css('backgroundColor')
jQuery(this).css('border-top', bWidth+' solid '+bColor);
});
var values = sliderComponent.slider('values');
if(isArray(values)){
jQuery(values).each(function(i){
sliderComponent.find('.ui-slider-tooltip .ttContent').eq(i).text( ttText(this) );
});
}
else {
sliderComponent.find('.ui-slider-tooltip .ttContent').eq(0).text( ttText(values) );
}
return this;
}
| zyyin2005-lokad | Source/Lokad.Cloud.Console.WebRole/Scripts/selectToUISlider.jQuery.js | JavaScript | bsd | 8,635 |
#region Copyright (c) Lokad 2009-2011
// This code is released under the terms of the new BSD licence.
// URL: http://www.lokad.com/
#endregion
using System.Web;
using System.Web.Mvc;
namespace Lokad.Cloud.Console.WebRole.Behavior
{
public sealed class RequireAuthorizationAttribute : AuthorizeAttribute
{
protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
{
// do not use 'filterContext.RequestContext.HttpContext.Request.Url' because of Azure port forwarding
// http://social.msdn.microsoft.com/Forums/en-US/windowsazure/thread/9142db8d-0f85-47a2-91f7-418bb5a0c675/
var request = filterContext.RequestContext.HttpContext.Request;
var returnUrl = request.Url.Scheme + @"://" + request.Headers["Host"] + request.RawUrl;
filterContext.Result = new RedirectResult("~/Account/Login?returnUrl=" + HttpUtility.UrlEncode(returnUrl));
}
}
} | zyyin2005-lokad | Source/Lokad.Cloud.Console.WebRole/Behavior/RequireAuthorization.cs | C# | bsd | 992 |
#region Copyright (c) Lokad 2009-2011
// This code is released under the terms of the new BSD licence.
// URL: http://www.lokad.com/
#endregion
using System;
using System.Linq;
namespace Lokad.Cloud.Console.WebRole.Behavior
{
public static class Users
{
public static bool IsAdministrator(string identifier)
{
return CloudConfiguration.Admins
.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries)
.Contains(identifier);
}
}
} | zyyin2005-lokad | Source/Lokad.Cloud.Console.WebRole/Behavior/Users.cs | C# | bsd | 536 |
#region Copyright (c) Lokad 2009-2011
// This code is released under the terms of the new BSD licence.
// URL: http://www.lokad.com/
#endregion
using System;
using System.Web;
using System.Web.Mvc;
using Lokad.Cloud.Console.WebRole.Framework.Discovery;
using Ninject.Modules;
using Ninject.Web.Mvc.FilterBindingSyntax;
namespace Lokad.Cloud.Console.WebRole.Behavior
{
public sealed class RequireDiscoveryFilter : IActionFilter
{
private readonly AzureDiscoveryInfo _discoveryInfo;
public RequireDiscoveryFilter(AzureDiscoveryInfo discoveryInfo)
{
_discoveryInfo = discoveryInfo;
}
public void OnActionExecuting(ActionExecutingContext filterContext)
{
if (_discoveryInfo.IsAvailable)
{
return;
}
// do not use 'filterContext.RequestContext.HttpContext.Request.Url' because of Azure port forwarding
// http://social.msdn.microsoft.com/Forums/en-US/windowsazure/thread/9142db8d-0f85-47a2-91f7-418bb5a0c675/
var scheme = filterContext.RequestContext.HttpContext.Request.Url.Scheme;
var host = filterContext.RequestContext.HttpContext.Request.Headers["Host"];
var path = filterContext.RequestContext.HttpContext.Request.RawUrl;
var returnUrl = scheme + @"://" + host + path;
filterContext.Result = new RedirectResult("~/Discovery/Index?returnUrl=" + HttpUtility.UrlEncode(returnUrl));
}
public void OnActionExecuted(ActionExecutedContext filterContext)
{
}
}
[AttributeUsage(AttributeTargets.Class)]
public sealed class RequireDiscoveryAttribute : Attribute { }
public sealed class RequireDiscoveryModule : NinjectModule
{
public override void Load()
{
this.BindFilter<RequireDiscoveryFilter>(FilterScope.Controller, 0).WhenControllerHas<RequireDiscoveryAttribute>();
}
}
} | zyyin2005-lokad | Source/Lokad.Cloud.Console.WebRole/Behavior/RequireDiscovery.cs | C# | bsd | 2,033 |
#region Copyright (c) Lokad 2009-2011
// This code is released under the terms of the new BSD licence.
// URL: http://www.lokad.com/
#endregion
using System.Web.Mvc;
using System.Web.Mvc.Html;
using Lokad.Cloud.Console.WebRole.Models.Shared;
namespace Lokad.Cloud.Console.WebRole.Helpers
{
public static class MenuHtmlExtensions
{
public static MvcHtmlString NavigationMenuEntry(this HtmlHelper htmlHelper, NavigationModel navigationModel, string text, string controller)
{
if (controller == navigationModel.CurrentController || string.IsNullOrEmpty(navigationModel.CurrentHostedServiceName))
{
return BuildMenuEntry(
controller == navigationModel.CurrentController,
htmlHelper.MenuIndexLink(text, controller));
}
return BuildMenuEntry(false, htmlHelper.MenuByHostedServiceLink(text, controller, navigationModel.CurrentHostedServiceName));
}
public static MvcHtmlString DeploymentMenuEntry(this HtmlHelper htmlHelper, NavigationModel navigationModel, string text, string hostedServiceName)
{
return BuildMenuEntry(
navigationModel.CurrentHostedServiceName == hostedServiceName,
htmlHelper.MenuByHostedServiceLink(text, navigationModel.CurrentController, hostedServiceName));
}
private static MvcHtmlString BuildMenuEntry(bool isActive, MvcHtmlString linkHtml)
{
return MvcHtmlString.Create(string.Format("<li{0}>{1}</li>", isActive ? @" class=""active""" : string.Empty, linkHtml));
}
public static MvcHtmlString MenuIndexLink(this HtmlHelper htmlHelper, string text, string controller)
{
return htmlHelper.RouteLink(text, "MenuIndex", new { controller, action = "Index" });
}
public static MvcHtmlString MenuByHostedServiceLink(this HtmlHelper htmlHelper, string text, string controller, string hostedServiceName)
{
return htmlHelper.RouteLink(text, "MenuByHostedService", new { controller, hostedServiceName, action = "ByHostedService" });
}
}
} | zyyin2005-lokad | Source/Lokad.Cloud.Console.WebRole/Helpers/MenuHtmlExtensions.cs | C# | bsd | 2,222 |
#region Copyright (c) Lokad 2009-2011
// This code is released under the terms of the new BSD licence.
// URL: http://www.lokad.com/
#endregion
using System;
using Lokad.Cloud.Management.Api10;
namespace Lokad.Cloud.Console.WebRole.Helpers
{
public static class PresentationHelpers
{
public static string PrettyFormat(this TimeSpan timeSpan)
{
// TODO: Reuse Lokad.Shared FormatUtil, once it supports this scenario (implemented but currently internal)
const int second = 1;
const int minute = 60 * second;
const int hour = 60 * minute;
const int day = 24 * hour;
const int month = 30*day;
double delta = timeSpan.TotalSeconds;
if (delta < 1) return timeSpan.Milliseconds + " ms";
if (delta < 1 * minute) return timeSpan.Seconds == 1 ? "one second" : timeSpan.Seconds + " seconds";
if (delta < 2 * minute) return "a minute";
if (delta < 50 * minute) return timeSpan.Minutes + " minutes";
if (delta < 70 * minute) return "an hour";
if (delta < 2 * hour) return (int)timeSpan.TotalMinutes + " minutes";
if (delta < 24 * hour) return timeSpan.Hours + " hours";
if (delta < 48 * hour) return (int)timeSpan.TotalHours + " hours";
if (delta < 30 * day) return timeSpan.Days + " days";
if (delta < 12 * month)
{
var months = (int)Math.Floor(timeSpan.Days / 30.0);
return months <= 1 ? "one month" : months + " months";
}
var years = (int)Math.Floor(timeSpan.Days / 365.0);
return years <= 1 ? "one year" : years + " years";
}
public static string PrettyFormatLease(CloudServiceSchedulingInfo info)
{
if (!info.LeasedSince.HasValue || !info.LeasedUntil.HasValue)
{
return "available";
}
var now = DateTimeOffset.UtcNow;
if (info.LeasedUntil.Value < now)
{
return "expired";
}
if (!info.LeasedBy.HasValue || String.IsNullOrEmpty(info.LeasedBy.Value))
{
return String.Format(
"{0} ago, expires in {1}",
now.Subtract(info.LeasedSince.Value).PrettyFormat(),
info.LeasedUntil.Value.Subtract(now).PrettyFormat());
}
return String.Format(
"by {0} {1} ago, expires in {2}",
info.LeasedBy.Value,
now.Subtract(info.LeasedSince.Value).PrettyFormat(),
info.LeasedUntil.Value.Subtract(now).PrettyFormat());
}
}
}
| zyyin2005-lokad | Source/Lokad.Cloud.Console.WebRole/Helpers/PresentationHelpers.cs | C# | bsd | 2,828 |
#region Copyright (c) Lokad 2009-2011
// This code is released under the terms of the new BSD licence.
// URL: http://www.lokad.com/
#endregion
using System.Web.Mvc;
namespace Lokad.Cloud.Console.WebRole.Helpers
{
public static class IconHtmlExtensions
{
private const string InlineImageHtml = @"<span class=""{0} {1}""></span>";
private const string InlineImageHtmlClientScript = @"<span class=""{0} {0}-' + {1} + '""></span>";
private const string InlineImageHtmlButton = @"<span id=""{2}"" class=""{0} {1} icon-button""></span>";
public static MvcHtmlString GoodBadIcon(this HtmlHelper htmlHelper, bool isGood)
{
return MvcHtmlString.Create(string.Format(InlineImageHtml, IconMap.GoodBad, IconMap.GoodBadOf(isGood)));
}
public static MvcHtmlString LogLevelIcon(this HtmlHelper htmlHelper, string logLevel)
{
return MvcHtmlString.Create(string.Format(InlineImageHtml, IconMap.LogLevels, IconMap.LogLevelsOf(logLevel)));
}
public static MvcHtmlString LogLevelIconClientScript(this HtmlHelper htmlHelper, string logLevelExpression)
{
return MvcHtmlString.Create(string.Format(InlineImageHtmlClientScript, IconMap.LogLevels, logLevelExpression));
}
public static MvcHtmlString OkCancelIcon(this HtmlHelper htmlHelper, bool isOk)
{
return MvcHtmlString.Create(string.Format(InlineImageHtml, IconMap.OkCancel, IconMap.OkCancelOf(isOk)));
}
public static MvcHtmlString PlusMinusIcon(this HtmlHelper htmlHelper, bool isPlus)
{
return MvcHtmlString.Create(string.Format(InlineImageHtml, IconMap.PlusMinus, IconMap.PlusMinusOf(isPlus)));
}
public static MvcHtmlString StartStopIcon(this HtmlHelper htmlHelper, bool isStart)
{
return MvcHtmlString.Create(string.Format(InlineImageHtml, IconMap.StartStop, IconMap.StartStopOf(isStart)));
}
public static MvcHtmlString StartStopIconButton(this HtmlHelper htmlHelper, bool isStart, string id)
{
return MvcHtmlString.Create(string.Format(InlineImageHtmlButton, IconMap.StartStop, IconMap.StartStopOf(isStart), id));
}
}
} | zyyin2005-lokad | Source/Lokad.Cloud.Console.WebRole/Helpers/IconHtmlExtensions.cs | C# | bsd | 2,305 |
#region Copyright (c) Lokad 2009-2011
// This code is released under the terms of the new BSD licence.
// URL: http://www.lokad.com/
#endregion
using Lokad.Cloud.Storage.Shared.Logging;
namespace Lokad.Cloud.Console.WebRole.Helpers
{
public static class IconMap
{
public const string Loading = "icon-loading";
public const string GoodBad = "icon-GoodBad";
public static string GoodBadOf(bool isGood)
{
return string.Concat(GoodBad, (isGood ? "-Good" : "-VeryBad"));
}
public const string LogLevels = "icon-LogLevels";
public static string LogLevelsOf(LogLevel level)
{
return string.Concat(LogLevels, "-", level.ToString());
}
public static string LogLevelsOf(string level)
{
return string.Concat(LogLevels, "-", level);
}
public const string OkCancel = "icon-OkCancel";
public static string OkCancelOf(bool isOk)
{
return string.Concat(OkCancel, (isOk ? "-Ok" : "-Cancel"));
}
public const string PlusMinus = "icon-PlusMinus";
public static string PlusMinusOf(bool isOk)
{
return string.Concat(PlusMinus, (isOk ? "-Plus" : "-Minus"));
}
public const string StartStop = "icon-StartStop";
public static string StartStopOf(StartStopState level)
{
return string.Concat(StartStop, "-", level.ToString());
}
public static string StartStopOf(bool isStart)
{
return StartStopOf(isStart ? StartStopState.Start : StartStopState.Stop);
}
}
public enum StartStopState
{
Start,
Stop,
Pause,
Standby
}
} | zyyin2005-lokad | Source/Lokad.Cloud.Console.WebRole/Helpers/IconMap.cs | C# | bsd | 1,816 |
#region Copyright (c) Lokad 2009-2011
// This code is released under the terms of the new BSD licence.
// URL: http://www.lokad.com/
#endregion
namespace Lokad.Cloud.Console.WebRole.Helpers
{
using System.Text;
using System.Web.Mvc;
public static class JavascriptHtmlExtensions
{
public static MvcHtmlString Enquote(this HtmlHelper htmlHelper, string text)
{
if (string.IsNullOrEmpty(text))
{
return MvcHtmlString.Create(@"""""");
}
var sb = new StringBuilder(text.Length + 4);
sb.Append('"');
var tokens = text.ToCharArray();
for (int i = 0; i < tokens.Length; i++)
{
char c = tokens[i];
switch(tokens[i])
{
case '\\':
case '"':
case '>':
sb.Append('\\');
sb.Append(c);
break;
case '\b':
sb.Append("\\b");
break;
case '\t':
sb.Append("\\t");
break;
case '\n':
sb.Append("\\n");
break;
case '\f':
sb.Append("\\f");
break;
case '\r':
sb.Append("\\r");
break;
default:
if (c >= ' ')
{
sb.Append(c);
}
break;
}
}
sb.Append('"');
return MvcHtmlString.Create(sb.ToString());
}
}
} | zyyin2005-lokad | Source/Lokad.Cloud.Console.WebRole/Helpers/JavascriptHtmlExtensions.cs | C# | bsd | 1,917 |
#region Copyright (c) Lokad 2009-2011
// This code is released under the terms of the new BSD licence.
// URL: http://www.lokad.com/
#endregion
using System;
using System.Linq;
using System.Text;
using System.Web;
using System.Xml;
using Lokad.Cloud.Application;
using Lokad.Cloud.Console.WebRole.Helpers;
using Lokad.Cloud.Console.WebRole.Models.Queues;
using Lokad.Cloud.Console.WebRole.Models.Services;
using Lokad.Cloud.Management;
using Lokad.Cloud.Management.Api10;
using Lokad.Cloud.Runtime;
using Lokad.Cloud.Storage;
using Lokad.Cloud.Storage.Shared;
namespace Lokad.Cloud.Console.WebRole.Framework.Services
{
public class AppDefinitionWithLiveDataProvider
{
const string FailingMessagesStoreName = "failing-messages";
private readonly RuntimeProviders _runtimeProviders;
public AppDefinitionWithLiveDataProvider(RuntimeProviders runtimeProviders)
{
_runtimeProviders = runtimeProviders;
}
public ServicesModel QueryServices()
{
var serviceManager = new CloudServices(_runtimeProviders);
var services = serviceManager.GetServices();
var inspector = new CloudApplicationInspector(_runtimeProviders);
var applicationDefinition = inspector.Inspect();
if (!applicationDefinition.HasValue)
{
return new ServicesModel
{
QueueServices = new QueueServiceModel[0],
ScheduledServices = new CloudServiceInfo[0],
CloudServices = new CloudServiceInfo[0],
UnavailableServices = new CloudServiceInfo[0]
};
}
var appDefinition = applicationDefinition.Value;
var queueServices = services.Join(
appDefinition.QueueServices,
s => s.ServiceName,
d => d.TypeName,
(s, d) => new QueueServiceModel { ServiceName = s.ServiceName, IsStarted = s.IsStarted, Definition = d }).ToArray();
var scheduledServices = services.Where(s => appDefinition.ScheduledServices.Any(ads => ads.TypeName.StartsWith(s.ServiceName))).ToArray();
var otherServices = services.Where(s => appDefinition.CloudServices.Any(ads => ads.TypeName.StartsWith(s.ServiceName))).ToArray();
var unavailableServices = services
.Where(s => !queueServices.Any(d => d.ServiceName == s.ServiceName))
.Except(scheduledServices).Except(otherServices).ToArray();
return new ServicesModel
{
QueueServices = queueServices,
ScheduledServices = scheduledServices,
CloudServices = otherServices,
UnavailableServices = unavailableServices
};
}
public QueuesModel QueryQueues()
{
var queueStorage = _runtimeProviders.QueueStorage;
var inspector = new CloudApplicationInspector(_runtimeProviders);
var applicationDefinition = inspector.Inspect();
var failingMessages = queueStorage.ListPersisted(FailingMessagesStoreName)
.Select(key => queueStorage.GetPersisted(FailingMessagesStoreName, key))
.Where(m => m.HasValue)
.Select(m => m.Value)
.OrderByDescending(m => m.PersistenceTime)
.Take(50)
.ToList();
return new QueuesModel
{
Queues = queueStorage.List(null).Select(queueName => new AzureQueue
{
QueueName = queueName,
MessageCount = queueStorage.GetApproximateCount(queueName),
Latency = queueStorage.GetApproximateLatency(queueName).Convert(ts => ts.PrettyFormat(), string.Empty),
Services = applicationDefinition.Convert(cd => cd.QueueServices.Where(d => d.QueueName == queueName).ToArray(), new QueueServiceDefinition[0])
}).ToArray(),
HasQuarantinedMessages = failingMessages.Count > 0,
Quarantine = failingMessages
.GroupBy(m => m.QueueName)
.Select(group => new AzureQuarantineQueue
{
QueueName = group.Key,
Messages = group.OrderByDescending(m => m.PersistenceTime)
.Select(m => new AzureQuarantineMessage
{
Inserted = FormatUtil.TimeOffsetUtc(m.InsertionTime.UtcDateTime),
Persisted = FormatUtil.TimeOffsetUtc(m.PersistenceTime.UtcDateTime),
Reason = HttpUtility.HtmlEncode(m.Reason),
Content = FormatQuarantinedLogEntryXmlContent(m),
Key = m.Key,
HasData = m.IsDataAvailable,
HasXml = m.DataXml.HasValue
})
.ToArray()
})
.ToArray()
};
}
static string FormatQuarantinedLogEntryXmlContent(PersistedMessage message)
{
if (!message.IsDataAvailable || !message.DataXml.HasValue)
{
return string.Empty;
}
var sb = new StringBuilder();
var settings = new XmlWriterSettings
{
Indent = true,
IndentChars = " ",
NewLineChars = Environment.NewLine,
NewLineHandling = NewLineHandling.Replace,
OmitXmlDeclaration = true
};
using (var writer = XmlWriter.Create(sb, settings))
{
message.DataXml.Value.WriteTo(writer);
writer.Flush();
}
return HttpUtility.HtmlEncode(sb.ToString());
}
}
} | zyyin2005-lokad | Source/Lokad.Cloud.Console.WebRole/Framework/Services/AppDefinitionWithLiveDataProvider.cs | C# | bsd | 6,343 |
#region Copyright (c) Lokad 2009-2011
// This code is released under the terms of the new BSD licence.
// URL: http://www.lokad.com/
#endregion
using Ninject;
using Ninject.Modules;
namespace Lokad.Cloud.Console.WebRole.Framework.Discovery
{
public class DiscoveryNinjectModule : NinjectModule
{
public override void Load()
{
Bind<AzureDiscoveryFetcher>().ToSelf().InSingletonScope();
Bind<AzureDiscoveryProvider>().ToSelf();
Bind<AzureUpdater>().ToSelf();
Bind<AzureDiscoveryInfo>()
.ToMethod(c => c.Kernel.Get<AzureDiscoveryProvider>().GetDiscoveryInfo())
.InRequestScope();
}
}
} | zyyin2005-lokad | Source/Lokad.Cloud.Console.WebRole/Framework/Discovery/DiscoveryNinjectModule.cs | C# | bsd | 739 |
#region Copyright (c) Lokad 2009-2011
// This code is released under the terms of the new BSD licence.
// URL: http://www.lokad.com/
#endregion
using System.Collections.Generic;
using System.Xml.Linq;
using Microsoft.WindowsAzure;
namespace Lokad.Cloud.Console.WebRole.Framework.Discovery
{
public class LokadCloudHostedService
{
public string ServiceName { get; set; }
public string ServiceLabel { get; set; }
public string Description { get; set; }
public List<LokadCloudDeployment> Deployments { get; set; }
public XElement Configuration { get; set; }
public CloudStorageAccount StorageAccount { get; set; }
public string StorageAccountName { get; set; }
public string StorageAccountKeyPrefix { get; set; }
}
public class LokadCloudDeployment
{
public string DeploymentName { get; set; }
public string DeploymentLabel { get; set; }
public string Status { get; set; }
public string Slot { get; set; }
public int InstanceCount { get; set; }
public bool IsRunning { get; set; }
public bool IsTransitioning { get; set; }
public XElement Configuration { get; set; }
public CloudStorageAccount StorageAccount { get; set; }
public string StorageAccountName { get; set; }
public string StorageAccountKeyPrefix { get; set; }
}
} | zyyin2005-lokad | Source/Lokad.Cloud.Console.WebRole/Framework/Discovery/LokadCloudHostedService.cs | C# | bsd | 1,445 |
#region Copyright (c) Lokad 2009-2011
// This code is released under the terms of the new BSD licence.
// URL: http://www.lokad.com/
#endregion
using System;
using System.Collections.Generic;
namespace Lokad.Cloud.Console.WebRole.Framework.Discovery
{
public class AzureDiscoveryInfo
{
public bool IsAvailable { get; set; }
public DateTimeOffset Timestamp { get; set; }
public DateTimeOffset FinishedTimestamp { get; set; }
public List<LokadCloudHostedService> LokadCloudDeployments { get; set; }
}
} | zyyin2005-lokad | Source/Lokad.Cloud.Console.WebRole/Framework/Discovery/AzureDiscoveryInfo.cs | C# | bsd | 566 |
#region Copyright (c) Lokad 2009-2011
// This code is released under the terms of the new BSD licence.
// URL: http://www.lokad.com/
#endregion
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;
using Lokad.Cloud.Management.Azure;
using Lokad.Cloud.Management.Azure.Entities;
using Lokad.Cloud.Storage;
using Microsoft.WindowsAzure;
namespace Lokad.Cloud.Console.WebRole.Framework.Discovery
{
public sealed class AzureDiscoveryFetcher
{
private readonly X509Certificate2 _certificate;
private readonly string _subscriptionId;
private readonly ManagementClient _client;
public AzureDiscoveryFetcher()
{
_subscriptionId = CloudConfiguration.SubscriptionId;
_certificate = CloudConfiguration.GetManagementCertificate();
_client = new ManagementClient(_certificate);
}
public Task<AzureDiscoveryInfo> FetchAsync()
{
return Task.Factory.StartNew(() =>
{
var started = DateTimeOffset.UtcNow;
var proxy = _client.CreateChannel();
try
{
return new AzureDiscoveryInfo
{
LokadCloudDeployments = FetchLokadCloudHostedServices(proxy)
.Select(MapHostedService).OrderBy(hs => hs.ServiceName).ToList(),
IsAvailable = true,
Timestamp = started,
FinishedTimestamp = DateTimeOffset.UtcNow
};
}
finally
{
_client.CloseChannel(proxy);
}
});
}
private IEnumerable<HostedService> FetchLokadCloudHostedServices(IAzureServiceManagement proxy)
{
return proxy
.ListHostedServices(_subscriptionId)
.AsParallel()
.Select(service => proxy.GetHostedServiceWithDetails(_subscriptionId, service.ServiceName, true))
.Where(hs => hs.Deployments.Any(d => d.RoleInstanceList.Exists(ri => ri.RoleName == "Lokad.Cloud.WorkerRole")));
}
private static LokadCloudHostedService MapHostedService(HostedService hostedService)
{
var lokadCloudDeployments = hostedService.Deployments.Select(d =>
{
var config = XElement.Parse(Base64Decode(hostedService.Deployments.First().Configuration));
var nn = config.Name.NamespaceName;
var xmlWorkerRole = config.Elements().Single(x => x.Attribute("name").Value == "Lokad.Cloud.WorkerRole");
var xmlConfigSettings = xmlWorkerRole.Element(XName.Get("ConfigurationSettings", nn));
var xmlDataConnectionString = xmlConfigSettings.Elements().Single(x => x.Attribute("name").Value == "DataConnectionString").Attribute("value").Value;
var storageAccount = CloudStorageAccount.Parse(xmlDataConnectionString);
var accountAndKey = storageAccount.Credentials as StorageCredentialsAccountAndKey;
return new LokadCloudDeployment
{
DeploymentName = d.Name,
DeploymentLabel = Base64Decode(d.Label),
Status = d.Status.ToString(),
Slot = d.DeploymentSlot.ToString(),
InstanceCount = d.RoleInstanceList.Count(ri => ri.RoleName == "Lokad.Cloud.WorkerRole"),
IsRunning = d.Status == DeploymentStatus.Running,
IsTransitioning =
d.Status != DeploymentStatus.Running && d.Status != DeploymentStatus.Suspended,
Configuration = config,
StorageAccount = storageAccount,
StorageAccountName = storageAccount.Credentials.AccountName,
StorageAccountKeyPrefix = accountAndKey != null ? accountAndKey.Credentials.ExportBase64EncodedKey().Substring(0, 4) : null,
};
}).ToList();
return new LokadCloudHostedService
{
ServiceName = hostedService.ServiceName,
ServiceLabel = Base64Decode(hostedService.HostedServiceProperties.Label),
Description = hostedService.HostedServiceProperties.Description,
Deployments = lokadCloudDeployments,
Configuration = lokadCloudDeployments[0].Configuration,
StorageAccount = lokadCloudDeployments[0].StorageAccount,
StorageAccountName = lokadCloudDeployments[0].StorageAccountName,
StorageAccountKeyPrefix = lokadCloudDeployments[0].StorageAccountKeyPrefix,
};
}
private static string Base64Decode(string value)
{
var bytes = Convert.FromBase64String(value);
return Encoding.UTF8.GetString(bytes);
}
}
} | zyyin2005-lokad | Source/Lokad.Cloud.Console.WebRole/Framework/Discovery/AzureDiscoveryFetcher.cs | C# | bsd | 5,527 |
#region Copyright (c) Lokad 2009-2011
// This code is released under the terms of the new BSD licence.
// URL: http://www.lokad.com/
#endregion
using System;
using System.Linq;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;
using Lokad.Cloud.Management.Azure;
using Lokad.Cloud.Management.Azure.InputParameters;
namespace Lokad.Cloud.Console.WebRole.Framework.Discovery
{
public sealed class AzureUpdater
{
private readonly X509Certificate2 _certificate;
private readonly string _subscriptionId;
private readonly ManagementClient _client;
private readonly AzureDiscoveryInfo _info;
public AzureUpdater(AzureDiscoveryInfo discoveryInfo)
{
_info = discoveryInfo;
_subscriptionId = CloudConfiguration.SubscriptionId;
_certificate = CloudConfiguration.GetManagementCertificate();
_client = new ManagementClient(_certificate);
}
public Task UpdateInstanceCountAsync(string hostedServiceName, string slot, int instanceCount)
{
var hostedService = _info.LokadCloudDeployments.Single(hs => hs.ServiceName == hostedServiceName);
var deployment = hostedService.Deployments.Single(d => d.Slot == slot);
var config = deployment.Configuration;
var instanceCountAttribute = config
.Descendants()
.Single(d => d.Name.LocalName == "Role" && d.Attributes().Single(a => a.Name.LocalName == "name").Value == "Lokad.Cloud.WorkerRole")
.Elements()
.Single(e => e.Name.LocalName == "Instances")
.Attributes()
.Single(a => a.Name.LocalName == "count");
// Note: The side effect on the cached discovery info is intended/by design
instanceCountAttribute.Value = instanceCount.ToString();
deployment.IsRunning = false;
deployment.IsTransitioning = true;
return Task.Factory.StartNew(() =>
{
var proxy = _client.CreateChannel();
try
{
proxy.ChangeConfiguration(_subscriptionId, hostedService.ServiceName, deployment.DeploymentName, new ChangeConfigurationInput
{
Configuration = Base64Encode(config.ToString(SaveOptions.DisableFormatting))
});
}
finally
{
_client.CloseChannel(proxy);
}
});
}
private static string Base64Encode(string value)
{
var bytes = Encoding.UTF8.GetBytes(value);
return Convert.ToBase64String(bytes);
}
}
} | zyyin2005-lokad | Source/Lokad.Cloud.Console.WebRole/Framework/Discovery/AzureUpdater.cs | C# | bsd | 2,967 |
#region Copyright (c) Lokad 2009-2011
// This code is released under the terms of the new BSD licence.
// URL: http://www.lokad.com/
#endregion
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using System.Web;
using System.Web.Caching;
namespace Lokad.Cloud.Console.WebRole.Framework.Discovery
{
public class AzureDiscoveryProvider
{
private readonly AzureDiscoveryFetcher _fetcher;
public AzureDiscoveryProvider(AzureDiscoveryFetcher fetcher)
{
_fetcher = fetcher;
}
public AzureDiscoveryInfo GetDiscoveryInfo()
{
// Hardcoded against HttpRuntime Cache for simplicity
return HttpRuntime.Cache.Get("lokadcloud-DiscoveryInfo") as AzureDiscoveryInfo
?? new AzureDiscoveryInfo
{
IsAvailable = false,
Timestamp = DateTimeOffset.UtcNow,
LokadCloudDeployments = new List<LokadCloudHostedService>()
};
}
public Task<AzureDiscoveryInfo> UpdateAsync()
{
var fetchTask = _fetcher.FetchAsync();
// Insert into HttpRuntime Cache once finished
fetchTask.ContinueWith(discoveryInfo => HttpRuntime.Cache.Insert(
"lokadcloud-DiscoveryInfo", discoveryInfo.Result,
null, DateTime.UtcNow.AddMinutes(60), Cache.NoSlidingExpiration),
TaskContinuationOptions.OnlyOnRanToCompletion);
return fetchTask;
}
public void StartAutomaticCacheUpdate(CancellationToken cancellationToken)
{
// Handler is reentrant. Doesn't make sense in practice but we don't prevent it technically.
var timer = new Timer(state => UpdateAsync(), null, TimeSpan.Zero, TimeSpan.FromMinutes(5));
cancellationToken.Register(timer.Dispose);
}
}
} | zyyin2005-lokad | Source/Lokad.Cloud.Console.WebRole/Framework/Discovery/AzureDiscoveryProvider.cs | C# | bsd | 2,036 |
#region Copyright (c) Lokad 2009-2011
// This code is released under the terms of the new BSD licence.
// URL: http://www.lokad.com/
#endregion
using System.Web.Mvc;
using Lokad.Cloud.Console.WebRole.Behavior;
using Lokad.Cloud.Console.WebRole.Controllers.ObjectModel;
using Lokad.Cloud.Console.WebRole.Framework.Discovery;
using Lokad.Cloud.Console.WebRole.Models.Config;
namespace Lokad.Cloud.Console.WebRole.Controllers
{
[RequireAuthorization, RequireDiscovery]
public sealed class ConfigController : TenantController
{
public ConfigController(AzureDiscoveryInfo discoveryInfo)
: base(discoveryInfo)
{
}
[HttpGet]
public override ActionResult ByHostedService(string hostedServiceName)
{
InitializeDeploymentTenant(hostedServiceName);
var cloudConfiguration = new Management.CloudConfiguration(Providers);
return View(new ConfigModel
{
Configuration = cloudConfiguration.GetConfigurationString()
});
}
[HttpPost]
[ValidateInput(false)] // we're expecting xml
public ActionResult Configuration(string hostedServiceName, ConfigModel model)
{
InitializeDeploymentTenant(hostedServiceName);
var cloudConfiguration = new Management.CloudConfiguration(Providers);
if (ModelState.IsValid)
{
if (string.IsNullOrWhiteSpace(model.Configuration))
{
cloudConfiguration.RemoveConfiguration();
}
else
{
cloudConfiguration.SetConfiguration(model.Configuration.Trim());
}
}
return RedirectToAction("ByHostedService");
}
}
}
| zyyin2005-lokad | Source/Lokad.Cloud.Console.WebRole/Controllers/ConfigController.cs | C# | bsd | 1,897 |
#region Copyright (c) Lokad 2009-2011
// This code is released under the terms of the new BSD licence.
// URL: http://www.lokad.com/
#endregion
using System.Linq;
using System.Web.Mvc;
using Lokad.Cloud.Console.WebRole.Framework.Discovery;
using Lokad.Cloud.Runtime;
using Lokad.Cloud.Storage;
namespace Lokad.Cloud.Console.WebRole.Controllers.ObjectModel
{
public abstract class TenantController : ApplicationController
{
protected LokadCloudHostedService HostedService { get; private set; }
protected RuntimeProviders Providers { get; private set; }
protected TenantController(AzureDiscoveryInfo discoveryInfo) : base(discoveryInfo)
{
}
protected void InitializeDeploymentTenant(string hostedServiceName)
{
CurrentHostedService = hostedServiceName;
var services = DiscoveryInfo.LokadCloudDeployments;
HostedService = services.Single(d => d.ServiceName == hostedServiceName);
Providers = CloudStorage
.ForAzureAccount(HostedService.StorageAccount)
.BuildRuntimeProviders();
}
public abstract ActionResult ByHostedService(string hostedServiceName);
public virtual ActionResult Index()
{
return RedirectToAction("ByHostedService", new { hostedServiceName = DiscoveryInfo.LokadCloudDeployments.First().ServiceName });
}
}
} | zyyin2005-lokad | Source/Lokad.Cloud.Console.WebRole/Controllers/ObjectModel/TenantController.cs | C# | bsd | 1,473 |
#region Copyright (c) Lokad 2009-2011
// This code is released under the terms of the new BSD licence.
// URL: http://www.lokad.com/
#endregion
using System;
using System.Linq;
using System.Web.Mvc;
using Lokad.Cloud.Console.WebRole.Framework.Discovery;
using Lokad.Cloud.Console.WebRole.Helpers;
using Lokad.Cloud.Console.WebRole.Models.Shared;
namespace Lokad.Cloud.Console.WebRole.Controllers.ObjectModel
{
public abstract class ApplicationController : Controller
{
private readonly NavigationModel _navigation;
private readonly DiscoveryModel _discovery;
protected AzureDiscoveryInfo DiscoveryInfo { get; private set; }
protected ApplicationController(AzureDiscoveryInfo discoveryInfo)
{
DiscoveryInfo = discoveryInfo;
ViewBag.Discovery = _discovery = new DiscoveryModel
{
IsAvailable = discoveryInfo.IsAvailable,
ShowLastDiscoveryUpdate = discoveryInfo.IsAvailable,
LastDiscoveryUpdate = (DateTimeOffset.UtcNow - discoveryInfo.Timestamp).PrettyFormat() + " (" + Math.Round((discoveryInfo.FinishedTimestamp - discoveryInfo.Timestamp).TotalSeconds,1) + "s)"
};
var controllerName = GetType().Name;
ViewBag.Navigation = _navigation = new NavigationModel
{
ShowDeploymentSelector = discoveryInfo.IsAvailable,
HostedServiceNames = discoveryInfo.LokadCloudDeployments.Select(d => d.ServiceName).ToArray(),
CurrentController = controllerName.Substring(0, controllerName.Length - 10),
ControllerAction = discoveryInfo.IsAvailable ? "ByHostedService" : "Index"
};
}
protected bool ShowWaitingForDiscoveryInsteadOfContent
{
get { return !_discovery.IsAvailable; }
set { _discovery.IsAvailable = !value; }
}
protected string CurrentHostedService
{
get { return _navigation.CurrentHostedServiceName; }
set
{
_navigation.CurrentHostedServiceName = value;
ViewBag.TenantPath = String.Format("/{0}/{1}", _navigation.CurrentController, value);
}
}
protected void HideDiscovery()
{
_navigation.ShowDeploymentSelector = false;
_navigation.ControllerAction = "Index";
_discovery.ShowLastDiscoveryUpdate = false;
}
}
} | zyyin2005-lokad | Source/Lokad.Cloud.Console.WebRole/Controllers/ObjectModel/ApplicationController.cs | C# | bsd | 2,604 |
#region Copyright (c) Lokad 2009-2011
// This code is released under the terms of the new BSD licence.
// URL: http://www.lokad.com/
#endregion
using System;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Lokad.Cloud.Console.WebRole.Behavior;
using Lokad.Cloud.Console.WebRole.Controllers.ObjectModel;
using Lokad.Cloud.Console.WebRole.Framework.Discovery;
using Lokad.Cloud.Console.WebRole.Models.Logs;
using Lokad.Cloud.Diagnostics;
namespace Lokad.Cloud.Console.WebRole.Controllers
{
using System.Collections.Generic;
[RequireAuthorization, RequireDiscovery]
public sealed class LogsController : TenantController
{
private const int InitialEntriesCount = 15;
public LogsController(AzureDiscoveryInfo discoveryInfo)
: base(discoveryInfo)
{
}
[HttpGet]
public override ActionResult ByHostedService(string hostedServiceName)
{
InitializeDeploymentTenant(hostedServiceName);
var entries = new CloudLogger(Providers.BlobStorage, string.Empty)
.GetLogsOfLevelOrHigher(Storage.Shared.Logging.LogLevel.Info)
.Take(InitialEntriesCount);
return View(LogEntriesToModel(entries.ToArray(), InitialEntriesCount));
}
[HttpGet]
public ActionResult Entries(string hostedServiceName, string threshold, int skip = 0, int count = InitialEntriesCount, string olderThanToken = null, string newerThanToken = null)
{
if(count < 1 || count > 100) throw new ArgumentOutOfRangeException("count", "Must be in range [1;100].");
InitializeDeploymentTenant(hostedServiceName);
var entries = new CloudLogger(Providers.BlobStorage, string.Empty)
.GetLogsOfLevelOrHigher(ParseLogLevel(threshold), skip);
if (!string.IsNullOrWhiteSpace(olderThanToken))
{
entries = entries.SkipWhile(entry => string.Compare(EntryToToken(entry), olderThanToken) >= 0);
}
if (!string.IsNullOrWhiteSpace(newerThanToken))
{
entries = entries.TakeWhile(entry => string.Compare(EntryToToken(entry), newerThanToken) > 0);
}
entries = entries.Take(count);
return Json(LogEntriesToModel(entries.ToArray(), count), JsonRequestBehavior.AllowGet);
}
[HttpGet]
public ActionResult HasNewerEntries(string hostedServiceName, string threshold, string newerThanToken)
{
InitializeDeploymentTenant(hostedServiceName);
var entry = new CloudLogger(Providers.BlobStorage, string.Empty)
.GetLogsOfLevelOrHigher(ParseLogLevel(threshold))
.FirstOrDefault();
if (null != entry && string.Compare(EntryToToken(entry), newerThanToken) > 0)
{
return Json(new { HasMore = true, NewestToken = EntryToToken(entry) }, JsonRequestBehavior.AllowGet);
}
return Json(new { HasMore = false }, JsonRequestBehavior.AllowGet);
}
private static LogsModel LogEntriesToModel(IList<LogEntry> entryList, int requestedCount)
{
if (entryList.Count == 0)
{
return new LogsModel { NewestToken = string.Empty, Groups = new LogGroup[0] };
}
var logsModel = new LogsModel
{
NewestToken = EntryToToken(entryList[0]),
Groups = entryList.GroupBy(EntryToGroupKey).Select(group => new LogGroup
{
Key = group.Key,
Title = group.First().DateTimeUtc.ToLongDateString(),
NewestToken = EntryToToken(group.First()),
OldestToken = EntryToToken(group.Last()),
Entries = group.Select(entry => new LogItem
{
Token = EntryToToken(entry),
Time = entry.DateTimeUtc.ToString("HH:mm:ss"),
Level = entry.Level,
Message = HttpUtility.HtmlEncode(entry.Message),
Error = HttpUtility.HtmlEncode(entry.Error ?? string.Empty)
}).ToArray()
}).ToArray()
};
if (entryList.Count == requestedCount)
{
logsModel.Groups.Last().OlderAvailable = true;
}
return logsModel;
}
static Storage.Shared.Logging.LogLevel ParseLogLevel(string str)
{
switch (str.ToLowerInvariant())
{
case "debug":
return Storage.Shared.Logging.LogLevel.Debug;
case "info":
return Storage.Shared.Logging.LogLevel.Info;
case "warn":
return Storage.Shared.Logging.LogLevel.Warn;
case "error":
return Storage.Shared.Logging.LogLevel.Error;
case "fatal":
return Storage.Shared.Logging.LogLevel.Fatal;
}
throw new ArgumentOutOfRangeException();
}
static string EntryToToken(LogEntry entry)
{
return entry.DateTimeUtc.ToString("yyyyMMddHHmmssffff");
}
static int EntryToGroupKey(LogEntry entry)
{
var date = entry.DateTimeUtc.Date;
return (date.Year * 100 + date.Month) * 100 + date.Day;
}
}
}
| zyyin2005-lokad | Source/Lokad.Cloud.Console.WebRole/Controllers/LogsController.cs | C# | bsd | 5,840 |
#region Copyright (c) Lokad 2009-2011
// This code is released under the terms of the new BSD licence.
// URL: http://www.lokad.com/
#endregion
using System.Web.Mvc;
using Lokad.Cloud.Console.WebRole.Behavior;
using Lokad.Cloud.Console.WebRole.Controllers.ObjectModel;
using Lokad.Cloud.Console.WebRole.Framework.Discovery;
using Lokad.Cloud.Console.WebRole.Models.Scheduler;
using Lokad.Cloud.Management;
namespace Lokad.Cloud.Console.WebRole.Controllers
{
[RequireAuthorization, RequireDiscovery]
public sealed class SchedulerController : TenantController
{
public SchedulerController(AzureDiscoveryInfo discoveryInfo)
: base(discoveryInfo)
{
}
[HttpGet]
public override ActionResult ByHostedService(string hostedServiceName)
{
InitializeDeploymentTenant(hostedServiceName);
var cloudServiceScheduling = new CloudServiceScheduling(Providers);
return View(new SchedulerModel
{
Schedules = cloudServiceScheduling.GetSchedules().ToArray()
});
}
}
}
| zyyin2005-lokad | Source/Lokad.Cloud.Console.WebRole/Controllers/SchedulerController.cs | C# | bsd | 1,162 |
#region Copyright (c) Lokad 2009-2011
// This code is released under the terms of the new BSD licence.
// URL: http://www.lokad.com/
#endregion
using System.Web.Mvc;
using Lokad.Cloud.Console.WebRole.Behavior;
using Lokad.Cloud.Console.WebRole.Controllers.ObjectModel;
using Lokad.Cloud.Console.WebRole.Framework.Discovery;
using Lokad.Cloud.Console.WebRole.Framework.Services;
using Lokad.Cloud.Management;
namespace Lokad.Cloud.Console.WebRole.Controllers
{
[RequireAuthorization, RequireDiscovery]
public sealed class ServicesController : TenantController
{
public ServicesController(AzureDiscoveryInfo discoveryInfo)
: base(discoveryInfo)
{
}
[HttpGet]
public override ActionResult ByHostedService(string hostedServiceName)
{
InitializeDeploymentTenant(hostedServiceName);
var provider = new AppDefinitionWithLiveDataProvider(Providers);
return View(provider.QueryServices());
}
[HttpPut]
public ActionResult Status(string hostedServiceName, string id, bool isStarted)
{
InitializeDeploymentTenant(hostedServiceName);
var cloudServices = new CloudServices(Providers);
if (isStarted)
{
cloudServices.EnableService(id);
}
else
{
cloudServices.DisableService(id);
}
return Json(new
{
serviceName = id,
isStarted,
});
}
}
}
| zyyin2005-lokad | Source/Lokad.Cloud.Console.WebRole/Controllers/ServicesController.cs | C# | bsd | 1,650 |
#region Copyright (c) Lokad 2009-2011
// This code is released under the terms of the new BSD licence.
// URL: http://www.lokad.com/
#endregion
using System.Web.Mvc;
using Lokad.Cloud.Console.WebRole.Behavior;
using Lokad.Cloud.Console.WebRole.Controllers.ObjectModel;
using Lokad.Cloud.Console.WebRole.Framework.Discovery;
using Lokad.Cloud.Console.WebRole.Framework.Services;
namespace Lokad.Cloud.Console.WebRole.Controllers
{
[RequireAuthorization, RequireDiscovery]
public sealed class QueuesController : TenantController
{
const string FailingMessagesStoreName = "failing-messages";
public QueuesController(AzureDiscoveryInfo discoveryInfo)
: base(discoveryInfo)
{
}
[HttpGet]
public override ActionResult ByHostedService(string hostedServiceName)
{
InitializeDeploymentTenant(hostedServiceName);
var provider = new AppDefinitionWithLiveDataProvider(Providers);
return View(provider.QueryQueues());
}
[HttpDelete]
public EmptyResult Queue(string hostedServiceName, string id)
{
InitializeDeploymentTenant(hostedServiceName);
Providers.QueueStorage.DeleteQueue(id);
return null;
}
[HttpDelete]
public EmptyResult QuarantinedMessage(string hostedServiceName, string id)
{
InitializeDeploymentTenant(hostedServiceName);
Providers.QueueStorage.DeletePersisted(FailingMessagesStoreName, id);
return null;
}
[HttpPost]
public EmptyResult RestoreQuarantinedMessage(string hostedServiceName, string id)
{
InitializeDeploymentTenant(hostedServiceName);
Providers.QueueStorage.RestorePersisted(FailingMessagesStoreName, id);
return null;
}
}
}
| zyyin2005-lokad | Source/Lokad.Cloud.Console.WebRole/Controllers/QueuesController.cs | C# | bsd | 1,940 |
#region Copyright (c) Lokad 2009-2011
// This code is released under the terms of the new BSD licence.
// URL: http://www.lokad.com/
#endregion
using System.Web.Mvc;
using Lokad.Cloud.Console.WebRole.Behavior;
using Lokad.Cloud.Console.WebRole.Controllers.ObjectModel;
using Lokad.Cloud.Console.WebRole.Framework.Discovery;
using Lokad.Cloud.Console.WebRole.Models.Overview;
namespace Lokad.Cloud.Console.WebRole.Controllers
{
[RequireAuthorization, RequireDiscovery]
public sealed class OverviewController : TenantController
{
private readonly AzureUpdater _updater;
public OverviewController(AzureDiscoveryInfo discoveryInfo, AzureUpdater updater)
: base(discoveryInfo)
{
_updater = updater;
}
[HttpGet]
public override ActionResult Index()
{
return View(new OverviewModel
{
HostedServices = DiscoveryInfo.LokadCloudDeployments.ToArray()
});
}
[HttpGet]
public override ActionResult ByHostedService(string hostedServiceName)
{
InitializeDeploymentTenant(hostedServiceName);
return View(new DeploymentModel
{
HostedService = HostedService
});
}
[HttpPost]
public ActionResult InstanceCount(string hostedServiceName, string slot, int instanceCount)
{
InitializeDeploymentTenant(hostedServiceName);
_updater.UpdateInstanceCountAsync(hostedServiceName, slot, instanceCount).Wait();
return RedirectToAction("ByHostedService");
}
}
}
| zyyin2005-lokad | Source/Lokad.Cloud.Console.WebRole/Controllers/OverviewController.cs | C# | bsd | 1,741 |
#region Copyright (c) Lokad 2009-2011
// This code is released under the terms of the new BSD licence.
// URL: http://www.lokad.com/
#endregion
using System.Web.Mvc;
using Lokad.Cloud.Console.WebRole.Behavior;
using Lokad.Cloud.Console.WebRole.Controllers.ObjectModel;
using Lokad.Cloud.Console.WebRole.Framework.Discovery;
namespace Lokad.Cloud.Console.WebRole.Controllers
{
[RequireAuthorization]
public sealed class DiscoveryController : ApplicationController
{
public DiscoveryController(AzureDiscoveryInfo discoveryInfo)
: base(discoveryInfo)
{
}
[HttpGet]
public ActionResult Index(string returnUrl)
{
if (DiscoveryInfo.IsAvailable)
{
if (!string.IsNullOrEmpty(returnUrl))
{
return Redirect(returnUrl);
}
return RedirectToAction("Index", "Overview");
}
ShowWaitingForDiscoveryInsteadOfContent = true;
HideDiscovery();
return View();
}
[HttpGet]
public ActionResult Status()
{
return Json(new
{
isAvailable = DiscoveryInfo.IsAvailable
});
}
}
}
| zyyin2005-lokad | Source/Lokad.Cloud.Console.WebRole/Controllers/DiscoveryController.cs | C# | bsd | 1,361 |
#region Copyright (c) Lokad 2009-2011
// This code is released under the terms of the new BSD licence.
// URL: http://www.lokad.com/
#endregion
using System.IO;
using System.Web;
using System.Web.Mvc;
using Lokad.Cloud.Application;
using Lokad.Cloud.Console.WebRole.Behavior;
using Lokad.Cloud.Console.WebRole.Controllers.ObjectModel;
using Lokad.Cloud.Console.WebRole.Framework.Discovery;
using Lokad.Cloud.Console.WebRole.Models.Assemblies;
namespace Lokad.Cloud.Console.WebRole.Controllers
{
[RequireAuthorization, RequireDiscovery]
public sealed class AssembliesController : TenantController
{
public AssembliesController(AzureDiscoveryInfo discoveryInfo)
: base(discoveryInfo)
{
}
[HttpGet]
public override ActionResult ByHostedService(string hostedServiceName)
{
InitializeDeploymentTenant(hostedServiceName);
var cloudAssemblies = new Management.CloudAssemblies(Providers);
var appDefinition = cloudAssemblies.GetApplicationDefinition();
return View(new AssembliesModel
{
ApplicationAssemblies = appDefinition.HasValue ?
appDefinition.Value.Assemblies : new CloudApplicationAssemblyInfo[0]
});
}
[HttpPost]
public ActionResult UploadPackage(string hostedServiceName, HttpPostedFileBase package)
{
InitializeDeploymentTenant(hostedServiceName);
var cloudAssemblies = new Management.CloudAssemblies(Providers);
byte[] bytes;
using (var reader = new BinaryReader(package.InputStream))
{
bytes = reader.ReadBytes(package.ContentLength);
}
switch ((Path.GetExtension(package.FileName) ?? string.Empty).ToLowerInvariant())
{
case ".dll":
cloudAssemblies.UploadAssemblyDll(bytes, package.FileName);
break;
default:
cloudAssemblies.UploadAssemblyZipContainer(bytes);
break;
}
return RedirectToAction("ByHostedService");
}
}
}
| zyyin2005-lokad | Source/Lokad.Cloud.Console.WebRole/Controllers/AssembliesController.cs | C# | bsd | 2,291 |
#region Copyright (c) Lokad 2009-2011
// This code is released under the terms of the new BSD licence.
// URL: http://www.lokad.com/
#endregion
using System.Web.Mvc;
using System.Web.Security;
using DotNetOpenAuth.Messaging;
using DotNetOpenAuth.OpenId;
using DotNetOpenAuth.OpenId.RelyingParty;
using Lokad.Cloud.Console.WebRole.Behavior;
using Lokad.Cloud.Console.WebRole.Controllers.ObjectModel;
using Lokad.Cloud.Console.WebRole.Framework.Discovery;
namespace Lokad.Cloud.Console.WebRole.Controllers
{
public sealed class AccountController : ApplicationController
{
private static readonly OpenIdRelyingParty OpenId = new OpenIdRelyingParty();
public AccountController(AzureDiscoveryInfo discoveryInfo)
: base(discoveryInfo)
{
ShowWaitingForDiscoveryInsteadOfContent = false;
HideDiscovery();
}
public ActionResult Login()
{
return View();
}
public ActionResult Authenticate(string returnUrl)
{
var response = OpenId.GetResponse();
if (response == null)
{
// Stage 2: user submitting Identifier
Identifier id;
if (Identifier.TryParse(Request.Form["openid_identifier"], out id))
{
try
{
OpenId.CreateRequest(Request.Form["openid_identifier"]).RedirectToProvider();
}
catch (ProtocolException)
{
ViewBag.Message = "No such endpoint can be found.";
return View("Login");
}
}
else
{
ViewBag.Message = "Invalid identifier.";
return View("Login");
}
}
else
{
// HACK: Filtering users based on their registrations
if (!Users.IsAdministrator(response.ClaimedIdentifier))
{
ViewBag.Message = "This user does not have access rights.";
return View("Login");
}
// Stage 3: OpenID Provider sending assertion response
switch (response.Status)
{
case AuthenticationStatus.Authenticated:
Session["FriendlyIdentifier"] = response.FriendlyIdentifierForDisplay;
FormsAuthentication.SetAuthCookie(response.ClaimedIdentifier, false);
if (!string.IsNullOrEmpty(returnUrl))
{
return Redirect(returnUrl);
}
else
{
return RedirectToAction("Index", "Overview");
}
case AuthenticationStatus.Canceled:
ViewBag.Message = "Canceled at provider";
return View("Login");
case AuthenticationStatus.Failed:
ViewBag.Message = response.Exception.Message;
return View("Login");
}
}
return new EmptyResult();
}
public ActionResult Logout()
{
FormsAuthentication.SignOut();
return RedirectToAction("Index", "Overview");
}
}
}
| zyyin2005-lokad | Source/Lokad.Cloud.Console.WebRole/Controllers/AccountController.cs | C# | bsd | 3,616 |
#region Copyright (c) Lokad 2009-2011
// This code is released under the terms of the new BSD licence.
// URL: http://www.lokad.com/
#endregion
using Lokad.Cloud.Management.Api10;
using Lokad.Cloud.Application;
namespace Lokad.Cloud.Console.WebRole.Models.Services
{
public class ServicesModel
{
public QueueServiceModel[] QueueServices { get; set; }
public CloudServiceInfo[] ScheduledServices { get; set; }
public CloudServiceInfo[] CloudServices { get; set; }
public CloudServiceInfo[] UnavailableServices { get; set; }
}
public class QueueServiceModel
{
public string ServiceName { get; set; }
public bool IsStarted { get; set; }
public QueueServiceDefinition Definition { get; set; }
}
} | zyyin2005-lokad | Source/Lokad.Cloud.Console.WebRole/Models/Services/ServicesModel.cs | C# | bsd | 802 |
#region Copyright (c) Lokad 2009-2011
// This code is released under the terms of the new BSD licence.
// URL: http://www.lokad.com/
#endregion
using Lokad.Cloud.Application;
using Lokad.Cloud.Storage;
namespace Lokad.Cloud.Console.WebRole.Models.Assemblies
{
public class AssembliesModel
{
public Maybe<CloudApplicationAssemblyInfo[]> ApplicationAssemblies { get; set; }
}
} | zyyin2005-lokad | Source/Lokad.Cloud.Console.WebRole/Models/Assemblies/AssembliesModel.cs | C# | bsd | 414 |
#region Copyright (c) Lokad 2009-2011
// This code is released under the terms of the new BSD licence.
// URL: http://www.lokad.com/
#endregion
using Lokad.Cloud.Management.Api10;
namespace Lokad.Cloud.Console.WebRole.Models.Scheduler
{
public class SchedulerModel
{
public CloudServiceSchedulingInfo[] Schedules { get; set; }
}
} | zyyin2005-lokad | Source/Lokad.Cloud.Console.WebRole/Models/Scheduler/SchedulerModel.cs | C# | bsd | 368 |
#region Copyright (c) Lokad 2009-2011
// This code is released under the terms of the new BSD licence.
// URL: http://www.lokad.com/
#endregion
namespace Lokad.Cloud.Console.WebRole.Models.Logs
{
public class LogsModel
{
public string NewestToken { get; set; }
public bool NewerAvailable { get; set; }
public LogGroup[] Groups { get; set; }
}
public class LogGroup
{
public int Key { get; set; }
public string Title { get; set; }
public string NewestToken { get; set; }
public string OldestToken { get; set; }
public bool OlderAvailable { get; set; }
public LogItem[] Entries { get; set; }
}
public class LogItem
{
public string Token { get; set; }
public string Time { get; set; }
public string Level { get; set; }
public string Message { get; set; }
public string Error { get; set; }
public bool ShowDetails { get; set; }
}
} | zyyin2005-lokad | Source/Lokad.Cloud.Console.WebRole/Models/Logs/LogsModel.cs | C# | bsd | 1,022 |
#region Copyright (c) Lokad 2009-2011
// This code is released under the terms of the new BSD licence.
// URL: http://www.lokad.com/
#endregion
using Lokad.Cloud.Console.WebRole.Framework.Discovery;
namespace Lokad.Cloud.Console.WebRole.Models.Overview
{
public class DeploymentModel
{
public LokadCloudHostedService HostedService { get; set; }
}
} | zyyin2005-lokad | Source/Lokad.Cloud.Console.WebRole/Models/Overview/DeploymentModel.cs | C# | bsd | 386 |
#region Copyright (c) Lokad 2009-2011
// This code is released under the terms of the new BSD licence.
// URL: http://www.lokad.com/
#endregion
using Lokad.Cloud.Console.WebRole.Framework.Discovery;
namespace Lokad.Cloud.Console.WebRole.Models.Overview
{
public class OverviewModel
{
public LokadCloudHostedService[] HostedServices { get; set; }
}
} | zyyin2005-lokad | Source/Lokad.Cloud.Console.WebRole/Models/Overview/OverviewModel.cs | C# | bsd | 387 |
#region Copyright (c) Lokad 2009-2011
// This code is released under the terms of the new BSD licence.
// URL: http://www.lokad.com/
#endregion
namespace Lokad.Cloud.Console.WebRole.Models.Config
{
public class ConfigModel
{
public string Configuration { get; set; }
}
} | zyyin2005-lokad | Source/Lokad.Cloud.Console.WebRole/Models/Config/ConfigModel.cs | C# | bsd | 305 |
#region Copyright (c) Lokad 2009-2011
// This code is released under the terms of the new BSD licence.
// URL: http://www.lokad.com/
#endregion
namespace Lokad.Cloud.Console.WebRole.Models.Shared
{
public class DiscoveryModel
{
public bool IsAvailable { get; set; }
public bool ShowLastDiscoveryUpdate { get; set; }
public string LastDiscoveryUpdate { get; set; }
}
} | zyyin2005-lokad | Source/Lokad.Cloud.Console.WebRole/Models/Shared/DiscoveryModel.cs | C# | bsd | 422 |
#region Copyright (c) Lokad 2009-2011
// This code is released under the terms of the new BSD licence.
// URL: http://www.lokad.com/
#endregion
namespace Lokad.Cloud.Console.WebRole.Models.Shared
{
public class NavigationModel
{
public string CurrentController { get; set; }
public string ControllerAction { get; set; }
public bool ShowDeploymentSelector { get; set; }
public string CurrentHostedServiceName { get; set; }
public string[] HostedServiceNames { get; set; }
}
} | zyyin2005-lokad | Source/Lokad.Cloud.Console.WebRole/Models/Shared/NavigationModel.cs | C# | bsd | 547 |
#region Copyright (c) Lokad 2009-2011
// This code is released under the terms of the new BSD licence.
// URL: http://www.lokad.com/
#endregion
using Lokad.Cloud.Application;
namespace Lokad.Cloud.Console.WebRole.Models.Queues
{
public class QueuesModel
{
public AzureQueue[] Queues { get; set; }
public AzureQuarantineQueue[] Quarantine { get; set; }
public bool HasQuarantinedMessages { get; set; }
}
public class AzureQueue
{
public string QueueName { get; set; }
public int MessageCount { get; set; }
public string Latency { get; set; }
public QueueServiceDefinition[] Services { get; set; }
}
public class AzureQuarantineQueue
{
public string QueueName { get; set; }
public AzureQuarantineMessage[] Messages { get; set; }
}
public class AzureQuarantineMessage
{
public string Inserted { get; set; }
public string Persisted { get; set; }
public string Reason { get; set; }
public string Content { get; set; }
public string Key { get; set; }
public bool HasData { get; set; }
public bool HasXml { get; set; }
}
} | zyyin2005-lokad | Source/Lokad.Cloud.Console.WebRole/Models/Queues/QueuesModel.cs | C# | bsd | 1,239 |
<%@ Application Codebehind="Global.asax.cs" Inherits="Lokad.Cloud.Console.WebRole.MvcApplication" Language="C#" %>
| zyyin2005-lokad | Source/Lokad.Cloud.Console.WebRole/Global.asax | ASP.NET | bsd | 119 |
using System.Reflection;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Lokad.Cloud.Console.WebRole")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Microsoft")]
[assembly: AssemblyProduct("Lokad.Cloud.Console.WebRole")]
[assembly: AssemblyCopyright("Copyright © Microsoft 2010")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("3302cbdf-398b-44de-bc2b-f4a3c604b05a")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Revision and Build Numbers
// by using the '*' as shown below:
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| zyyin2005-lokad | Source/Lokad.Cloud.Console.WebRole/Properties/AssemblyInfo.cs | C# | bsd | 1,403 |
#region Copyright (c) Lokad 2009-2011
// This code is released under the terms of the new BSD licence.
// URL: http://www.lokad.com/
#endregion
using System.Configuration;
using System.Security.Cryptography.X509Certificates;
using Microsoft.WindowsAzure.ServiceRuntime;
namespace Lokad.Cloud.Console.WebRole
{
public class CloudConfiguration
{
public static string Admins
{
get { return GetSetting("Admins"); }
}
public static string SubscriptionId
{
get { return GetSetting("SubscriptionId"); }
}
public static X509Certificate2 GetManagementCertificate()
{
var thumbprint = GetSetting("ManagementCertificateThumbprint");
var store = new X509Store(StoreName.My, StoreLocation.CurrentUser);
store.Open(OpenFlags.ReadOnly);
try
{
return store.Certificates.Find(X509FindType.FindByThumbprint, thumbprint, false)[0];
}
finally
{
store.Close();
}
}
private static string GetSetting(string name)
{
return RoleEnvironment.IsAvailable
? RoleEnvironment.GetConfigurationSettingValue(name)
: ConfigurationManager.AppSettings[name];
}
}
} | zyyin2005-lokad | Source/Lokad.Cloud.Console.WebRole/CloudConfiguration.cs | C# | bsd | 1,410 |
/*NEW SLIDER STYLES FOR SCALE, ETC*/
/* slider widget */
.ui-slider {
text-decoration: none !important;
}
.ui-slider .ui-slider-handle {
overflow: visible !important;
}
.ui-slider .ui-slider-tooltip {
display: none;
}
.ui-slider .screenReaderContext {
position: absolute;
width: 0;
height: 0;
overflow: hidden;
left: -999999999px;
}
.ui-slider .ui-state-active .ui-slider-tooltip, .ui-slider .ui-state-focus .ui-slider-tooltip, .ui-slider .ui-state-hover .ui-slider-tooltip {
display: block;
position: absolute;
bottom: 2.5em;
text-align: center;
padding: .3em .2em .4em;
font-size: .9em;
width: 8em;
margin-left: -3.7em;
}
.ui-slider .ui-slider-tooltip .ui-tooltip-pointer-down, .ui-slider .ui-slider-tooltip .ui-tooltip-pointer-down-inner {
position: absolute;
display: block;
width:0;
height:0;
border-bottom-width: 0;
background: none;
}
.ui-slider .ui-slider-tooltip .ui-tooltip-pointer-down {
border-left: 7px dashed transparent;
border-right: 7px dashed transparent;
border-top-width: 8px;
bottom: -8px;
right: auto;
left: 50%;
margin-left: -7px;
}
.ui-slider .ui-slider-tooltip .ui-tooltip-pointer-down-inner {
border-left: 6px dashed transparent;
border-right: 6px dashed transparent;
border-top: 7px solid #fff;
bottom: auto;
top: -9px;
left: -6px;
}
.ui-slider a {
text-decoration: none;
}
.ui-slider ol, .ui-slider li, .ui-slider dl, .ui-slider dd, .ui-slider dt {
list-style: none;
margin: 0;
padding: 0;
}
.ui-slider ol, .ui-slider dl {
position: relative;
top: 1.3em;
width: 100%;
}
.ui-slider dt {
top: 1.5em;
position: absolute;
padding-top: .2em;
text-align: center;
border-bottom: 1px dotted #ddd;
height: .7em;
color: #999;
}
.ui-slider dt span {
background: #fff;
padding: 0 .5em;
}
.ui-slider li, .ui-slider dd {
position: absolute;
overflow: visible;
color: #666;
}
.ui-slider span.ui-slider-label {
position: absolute;
}
.ui-slider li span.ui-slider-label, .ui-slider dd span.ui-slider-label {
display: none;
}
.ui-slider li span.ui-slider-label-show, .ui-slider dd span.ui-slider-label-show {
display: block;
}
.ui-slider span.ui-slider-tic {
position: absolute;
left: 0;
height: .8em;
top: -1.3em;
}
.ui-slider li span.ui-widget-content, .ui-slider dd span.ui-widget-content {
border-right: 0;
border-left-width: 1px;
border-left-style: solid;
border-top: 0;
border-bottom: 0;
}
.ui-slider .first .ui-slider-tic, .ui-slider .last .ui-slider-tic {
display: none;
}
| zyyin2005-lokad | Source/Lokad.Cloud.Console.WebRole/Content/ui.slider.extras.css | CSS | bsd | 2,466 |
/*----------------------------------------------------------
The base color for this template is #5c87b2. If you'd like
to use a different color start by replacing all instances of
#5c87b2 with your new color.
----------------------------------------------------------*/
body
{
background-color: #5c87b2;
font-size: 75%;
font-family: Verdana, Tahoma, Arial, "Helvetica Neue", Helvetica, Sans-Serif;
margin: 0;
padding: 0;
color: #696969;
}
a:link
{
color: #034af3;
text-decoration: underline;
}
a:visited
{
color: #505abc;
}
a:hover
{
color: #1d60ff;
text-decoration: none;
}
a:active
{
color: #12eb87;
}
p, ul
{
margin-bottom: 20px;
line-height: 1.6em;
}
/* HEADINGS
----------------------------------------------------------*/
h1, h2, h3, h4, h5, h6
{
font-size: 1.5em;
color: #000;
}
h1
{
font-size: 2em;
padding-bottom: 0;
margin-bottom: 0;
}
h2
{
padding: 0 0 10px 0;
}
h3
{
font-size: 1.2em;
}
h4
{
font-size: 1.1em;
}
h5, h6
{
font-size: 1em;
}
/* this rule styles <h2> tags that are the
first child of the left and right table columns */
.rightColumn > h1, .rightColumn > h2, .leftColumn > h1, .leftColumn > h2
{
margin-top: 0;
}
/* PRIMARY LAYOUT ELEMENTS
----------------------------------------------------------*/
/* you can specify a greater or lesser percentage for the
page width. Or, you can specify an exact pixel width. */
.page
{
width: 90%;
margin-left: auto;
margin-right: auto;
}
#header
{
position: relative;
margin-bottom: 0px;
color: #000;
padding: 0;
}
#header h1
{
font-weight: bold;
padding: 5px 0;
margin: 0;
color: #fff;
border: none;
line-height: 2em;
font-size: 32px !important;
}
#main
{
padding: 30px 30px 15px 30px;
background-color: #fff;
margin-bottom: 30px;
_height: 1px; /* only IE6 applies CSS properties starting with an underscore */
}
#footer
{
color: #999;
padding: 10px 0;
text-align: center;
line-height: normal;
margin: 0;
font-size: .9em;
}
/* TAB MENU
----------------------------------------------------------*/
ul#menu
{
border-bottom: 1px #5C87B2 solid;
padding: 0 0 2px;
position: relative;
margin: 0;
text-align: right;
}
ul#menu li
{
display: inline;
list-style: none;
}
ul#menu li#greeting
{
padding: 10px 20px;
font-weight: bold;
text-decoration: none;
line-height: 2.8em;
color: #fff;
}
ul#menu li a
{
padding: 10px 20px;
font-weight: bold;
text-decoration: none;
line-height: 2.8em;
background-color: #e8eef4;
color: #034af3;
}
ul#menu li a:hover
{
background-color: #fff;
text-decoration: none;
}
ul#menu li a:active
{
background-color: #a6e2a6;
text-decoration: none;
}
ul#menu li.selected a
{
background-color: #fff;
color: #000;
}
/* FORM LAYOUT ELEMENTS
----------------------------------------------------------*/
fieldset
{
border:1px solid #ddd;
padding:0 1.4em 1.4em 1.4em;
margin:0 0 1.5em 0;
}
legend
{
font-size:1.2em;
font-weight: bold;
}
textarea
{
min-height: 75px;
}
input[type="text"]
{
width: 200px;
border: 1px solid #CCC;
}
input[type="password"]
{
width: 200px;
border: 1px solid #CCC;
}
/* TABLE
----------------------------------------------------------*/
table
{
border: solid 1px #e8eef4;
border-collapse: collapse;
}
table td
{
padding: 5px;
border: solid 1px #e8eef4;
}
table th
{
padding: 6px 5px;
text-align: left;
background-color: #e8eef4;
border: solid 1px #e8eef4;
}
/* MISC
----------------------------------------------------------*/
.clear
{
clear: both;
}
.error
{
color:Red;
}
#menucontainer
{
margin-top:40px;
}
div#title
{
display:block;
float:left;
text-align:left;
}
#logindisplay
{
font-size:1.1em;
display:block;
text-align:right;
margin:10px;
color:White;
}
#logindisplay a:link
{
color: white;
text-decoration: underline;
}
#logindisplay a:visited
{
color: white;
text-decoration: underline;
}
#logindisplay a:hover
{
color: white;
text-decoration: none;
}
/* Styles for validation helpers
-----------------------------------------------------------*/
.field-validation-error
{
color: #ff0000;
}
.field-validation-valid
{
display: none;
}
.input-validation-error
{
border: 1px solid #ff0000;
background-color: #ffeeee;
}
.validation-summary-errors
{
font-weight: bold;
color: #ff0000;
}
.validation-summary-valid
{
display: none;
}
/* Styles for editor and display helpers
----------------------------------------------------------*/
.display-label,
.editor-label
{
margin: 1em 0 0 0;
}
.display-field,
.editor-field
{
margin:0.5em 0 0 0;
}
.text-box
{
width: 30em;
}
.text-box.multi-line
{
height: 6.5em;
}
.tri-state
{
width: 6em;
}
| zyyin2005-lokad | Source/Lokad.Cloud.Console.WebRole/Content/Site.css | CSS | bsd | 5,324 |
/* Copyright (c) Lokad 2009 - All rights reserved */
/* When updating this file do not forget about Lokad.App overrides at the bottom */
body { padding: 0; margin: 0; font-family: "Trebuchet MS", Arial, Helvetica, sans-serif; font-size: 62.5%; color: #565656; background: #2B2B2B; }
table, img, div, form{ padding:0; margin:0; border:none; }
p { font-family: "Trebuchet MS", Arial, Helvetica, sans-serif; color: #555555; padding: 0; margin: 0; }
h1, h2, h3, h4 { font-family: Arial, Helvetica, sans-serif; font-size: 24px; color: #686868; padding: 0; margin: 0 0 10px 0; font-weight: normal; }
h2 { font-size: 16px; padding: 0px; margin: 0px; font-weight: bold; padding-bottom: 2px; margin-bottom: 0.3em; padding-top: 2px; margin-top: 1em; }
h3 { font-size: 14px; padding: 0px; margin: 0px; font-weight: bold; padding-bottom: 2px; margin-bottom: 0.3em; padding-top: 2px; margin-top: 1em; }
h4 { padding: 0px; margin: 0px; font-weight: normal; font-style: italic; padding-bottom: 2px; margin-bottom: 0.3em; padding-top: 2px; margin-top: 1em; }
ul, ol { font-size:1em; margin: 0px; padding-top: 0px; padding-bottom: 0px; padding-left: 28px; padding-right: 8px; }
li { margin: 2px 0px 0px 0px; padding: 0px; }
a:active{outline: none;}
.hidden{ display:none; }
.resulterror, .resulterror * { color: #FF0000; }
.resultok, .resultok * { color: #009900; }
input, label { font-family: Verdana, Arial, Helvetica, sans-serif; font-size: 12px; color: #000000; padding: 2px; margin: 4px; }
button { color: #000000; padding: 1px; margin: 0px; }
select { font-family: Verdana, Arial, Helvetica, sans-serif; font-size: 12px; color: #000000; margin: 0px; }
input.tab { background-color: #DDDDDD; border: solid 3px #DDDDDD; color: #000000; font-size: 11px; width: auto; overflow: visible; padding: 0px; }
input.tabselected { background-color: #214C9A; border: solid 3px #214C9A; color: #FFFFFF; font-size: 11px; width: auto; overflow: visible; font-weight: bold; padding: 0px; }
#TabDiv { border-bottom: solid 6px #214C9A; margin-bottom: 10px; }
/* Contains the date picks in the Edit.aspx page */
#DatePickDiv { font-size: 11px; border: solid 1px #999999; background-color: #FFFFFF; padding: 2px; }
a.datepicklink { display: block; }
/* Small text */
p.small, small { font-size: 11px; }
/* Big text */
p.big, big { font-size: 15px; }
/* Description/legend for images */
p.imagedescription { font-size: 11px; font-style: italic; margin-top: 4px; }
/* General purpose links */
a, a:link, a:active { color: #C7180F; text-decoration: underline; }
a:hover { color: #E80C00; text-decoration: underline; }
a:visited { color: #660000; text-decoration: underline; }
/* Link to an external URL */
a.externallink { background-image: url(Images/ExternalLink.gif); background-position: right; background-repeat: no-repeat; padding-right: 14px; }
/* Link to an internal file */
a.internallink {}
/* Link to a Wiki page */
a.pagelink {}
/* Link to unknown/inexistent pages */
a.unknownlink, a.unknownlink:link, a.unknownlink:active { color: #990000; text-decoration: none; }
a.unknownlink:hover { color: #D9671E; text-decoration: underline; }
/* Email Link */
a.emaillink {}
h1.pagetitle { font-size: 22px; margin-bottom: 2px; }
a.editsectionlink { float: right; font-size: 11px; margin: 4px 0px 0px 0px; }
/* Class for general purpose images (contained in Wiki pages) */
img.image { border: solid 1px #F5F5F5; }
/* Class of the formatting Buttons in Edit.aspx */
img.format { border: solid 1px; padding: 2px; }
/* Div used for clearing floats */
.clear { clear: both; height:1px; line-height:1px; font-size:1px; overflow: hidden;}
/* Div containing images alighed to the left */
div.imageleft { border: 1px solid #E0DAC8; background-color: #FFFFFF; padding: 4px; margin-left: 0px; margin-right: 8px; margin-top: 4px; margin-bottom: 4px; float: left; }
/* Div containing images alighed to the right */
div.imageright { border: 1px solid #E0DAC8; background-color: #FFFFFF; padding: 4px; margin-left: 8px; margin-right: 0px; margin-top: 4px; margin-bottom: 4px; float: right; }
/* Table containing images not aligned */
table.imageauto { border: 1px solid #E0DAC8; background-color: #FFFFFF; padding: 4px; margin: 4px 4px 4px 0px; }
/* Div acting like a box */
div.box { border: 1px solid #CCCCCC; background-color: #F9F9F9; display: block; padding: 7px; margin: 0em 0em 1em 0em; }
div.groupbox { border: 1px solid #CCCCCC; background-color: #FCF9F0; padding: 7px; margin: 0em 0em 1em 0em; }
div.warning { border: solid 1px #FFCF10; background-color: #FEF693; display: inline-block; padding: 7px; margin: 0em 0em 1em 0em; }
code, pre { font-family: Consolas, Courier New, Monospace; color: #000000; padding: 0px; margin: 0px; }
pre { border: dashed 1px #999999; background-color: #FFFFF0; margin: 0px 0px 10px 0px; padding: 7px; overflow: auto; font-size: small; }
/* Contains the Header */
#HeaderDiv { width:100%; float:left; background: #F2EDD9 url(Images/bg_body.gif) repeat-x; }
#AuthBar{ width: 780px; margin:0 auto; height:13px; padding:4px 0 4px 0; }
#AuthBar ul{ list-style: none; float:right; padding:0; margin:0;}
#AuthBar li{ display: block; padding:0; margin:0 0 0 9px; float:left; background-repeat: no-repeat; }
#AuthBar a:hover{ font-weight: bold; }
#TopBarBackground{ position:absolute; left:0; top:21px; width:50%; height:51px; background-color: #F2EDD9; }
#TopBar{ position:relative; width: 780px; margin:0 auto; height:51px; }
#Logo{ position:absolute; top:0; left: 0; width:390px; height:51px; background-image: url(Images/bg_logo.gif); background-color: #FBF7EC; background-position: left; background-repeat: no-repeat; }
#Logo h1{ padding: 0 157px 0 0; display:block; width:223px; height:51px; overflow: hidden; background: url(Images/logo.gif) no-repeat; margin: 0; }
#TopControls{ position:absolute; top: 0; right: 0; width: 390px; height: 51px; margin:0 auto; background-color: #FBF7EC; }
#LogoLine{ }
.logo{ position:absolute; left:0; top:21px; width:50%; height:51px; background-image: url(Images/bg_logo.png); background-color: #F2EDD9; background-position: left; background-repeat: no-repeat; }
.logo a{ display:block; width:223px; height:51px; }
.logo h1{ padding: 0 157px 0 0; float:right; display:block; width:223px; height:51px; overflow: hidden; background: url(Images/logo.gif) no-repeat; margin: 0; }
#LogoBar{ width: 780px; height: 51px; margin:0 auto; }
#LogoBar div.btn{ font-size:1.1em; font-weight:bold; padding: 0 9px 0 0; float: right; margin: 13px 0 0 0px; display: block; height: 30px; background-image: url(Images/bt_btntop_right.gif); background-position: right; background-repeat: no-repeat; background-color: #FCBC5D; font-family: Arial, Helvetica, sans-serif; }
#LogoBar div.btn a{ color: #A11603; text-decoration: none; padding-top:5px; display:block; height:18px; overflow: hidden; float: left; }
#LogoBar div.btn a:hover{ color: #E81D00; text-decoration: none; cursor: pointer; }
#LogoBar div.btn span{ float:left; display:block; height:30px; padding:0 0 0 27px; background-image: url(Images/bt_btntop_left.gif); background-position: left; background-repeat: no-repeat; }
.searchbox{position:relative; float: right; width:139px; height:30px; margin:13px 0 0 5px; background-image: url(Images/bg_searchbox.gif); background-repeat: no-repeat; }
#TxtSearchBox { font-size: 11px; width: 100px; margin:5px 0 0 22px; padding: 1px 3px 1px 3px; height: 12px; background:none; border: none; color: #912711; }
#TitleBar{ margin:0 auto; width:780px; height: 60px; overflow: hidden; background: #AB1B11; }
#TitleBar h2{ height:104px; overflow: hidden; display: block; margin:0 auto; padding: 18px 0 0 0; color: #E6AA94; font-family: "Trebuchet MS", Arial, Helvetica, sans-serif; font-size: 1.8em; font-weight:normal; }
#NavBar{ text-align:center; width: 780px; height:30px; margin:0 auto; }
#NavBar ul{ list-style: none; padding:0; margin:0; font-size:1.3em; }
#NavBar li{ height: 30px; float: left; padding: 0; margin: 0 0 0 1px; background: #E25333 url(Images/bg_nav.gif) repeat-x bottom; }
#NavBar li.active{ background: #FAFAFA url(Images/bg_nav_active.gif) repeat-x; }
#NavBar li.home{ padding:0 3px; }
#NavBar a{ color: white; margin: 0; text-decoration: none; display: block; padding: 6px 0 0 0; width: 85px; text-align: center; font-weight: bold; font-family: "Trebuchet MS", Arial, Helvetica, sans-serif; }
#NavBar li.active a{ color: #AB0B00; }
#NavBar a:hover{ position: relative; top: -1px; }
#SubNavBar{ text-align:center; width: 780px; height:20px; margin: 0 auto 1px auto;}
#SubNavBar ul{ list-style: none; padding: 0 0 0 0px; margin: 0; font-size:1.3em; }
#SubNavBar li{ height: 20px; float: left; padding: 0; margin: 0 0 0 1px; background: #E25333 url(Images/bg_nav.gif) repeat-x bottom; }
#SubNavBar li.active{ background: #FAFAFA url(Images/bg_nav_active.gif) repeat-x; }
#SubNavBar li.home{ padding:0 3px; }
#SubNavBar a{ color: white; margin: 0; text-decoration: none; display: block; padding: 1px 6px 0 6px; width: auto; text-align: center; font-weight: bold; font-family: "Trebuchet MS", Arial, Helvetica, sans-serif; }
#SubNavBar li.active a{ color: #AB0B00; }
#SubNavBar a:hover{ position: relative; top: -1px; }
/* Contains the SidebarDiv and the MainDiv */
#ContentWrapper{ width:100%; padding: 0 0 50px 0; float:left; background: White url(Images/bg_content.gif) repeat-x; }
#ContainerDiv { width: 780px; padding: 0; margin: 0 auto; }
/* Contains the Sidebar */
#SidebarDiv { display:none; }
#SidebarContentDiv{}
#Side{ float:right; font-size:1.2em; width: 180px; margin: 0; padding: 36px 0 0px 40px; background: url(Images/bg_SidebarDiv.gif) no-repeat 0 6px; /* min-height: 460px; */ position: relative; }
#Side h3{ font-size: 1.38em; text-transform: uppercase; color: #727272; font-family: "Trebuchet MS"; font-weight: bold; }
#GetStarted ul{ list-style: none; padding: 0; margin: 1em 0 1.5em 0; font-size: 1.1em; }
#GetStarted li{ display: block; margin:0 0 8px 0; background-repeat: no-repeat; padding:0;}
#GetStarted li a{ display: block; height: 30px; width: 128px; padding: 9px 0 0 52px; background: url(Images/start_tour.gif); overflow: hidden; color: #545454; text-decoration: none; }
#GetStarted li.tour a{ background: url(Images/start_tour.gif); }
#GetStarted li.try a{ background: url(Images/start_trylokad.gif); }
#GetStarted li.download a{ background: url(Images/start_download.gif); }
#GetStarted li.save a{ background: url(Images/start_save.gif); }
#GetStarted li.ecommerce a{ background: url(Images/industry_ecommerce.gif); }
#GetStarted li.retail a{ background: url(Images/industry_retail.gif); }
#GetStarted li.manufacturing a{ background: url(Images/industry_manufacturing.gif); }
#GetStarted li.call a{ background: url(Images/industry_call.gif); }
#GetStarted li a:hover{ text-decoration: underline; background-position: 0 -39px; }
#GetStarted li.active a{ color: #cc0000; background-position: 0 -78px; }
#GetStarted li.active a:hover{ background-position: 0 -78px; }
#Side .fromprice{ width:180px; margin: 0 0 1.5em 0; padding:0; height: 59px; background: #A5C7EB url(Images/from_price.gif); }
#Side .fromprice a{ display:block; text-decoration:none; width:110px; padding:21px 60px 0 10px; height: 25px; color: White; font-size: 1.2em; font-weight:bold; overflow: hidden; }
#Side .fromprice a:hover{ text-decoration: underline; }
#Side .news ul{ list-style:none; font-weight: bold; font-size:0.9em; color: #DE4338; margin:0.8em 0 20px 0; padding:0; font-family: Arial, Helvetica, sans-serif; }
#Side .news li{ margin:0 0 10px 0; }
#Side .news a{ font-style: normal; font-family: "Trebuchet MS", Arial, Helvetica, sans-serif; line-height:1.4em; font-size: 1.2em; font-weight: normal; text-decoration: none; color: #515151; }
#Side .news a:hover{ text-decoration: underline; }
/* Contains the contents of a Page */
#MainDiv { float:left; width:780px; margin: 0; padding:0;}
#Text { float:left; width:780px; line-height:1.4em; margin: 0; padding:40px 0 0 0; font-size:1.4em; }
#Text .large{ font-size: 1.17em; color: #777777; }
#Text .frontlist{ margin:10px 0 15px 0; }
#Text .frontlist ul{ list-style:none; margin:0; padding:3px 0 0 20px; }
#Text .frontlist li{ padding:0 0 0 30px; margin:0 0 6px 0; background-image: url(Images/ico_frontlist.gif); background-position: left; background-repeat: no-repeat;}
ul.listorange{ padding: 0 0 0 18px; }
ul.listorange li{ list-style: url(Images/bullet_orange.gif); }
ul.listred li{ list-style: url(Images/bullet_red.gif); }
ul.listred li.empty{ list-style: none none; }
/* 2-columns 'table' */
.col2{ float:left; width:100%; list-style: none; margin: 0; padding: 0; background: url(Images/bg_col2.gif) repeat-y 255px 0; }
.col2 li.left{ list-style: none; margin: 0; padding: 0; width: 250px; padding: 0 15px 0 0; }
.col2 li.right{ list-style: none; margin: 0; padding: 0; width: 250px; padding: 0 0 0 15px; }
.col2 li li{ list-style: disc; }
/* decorated list */
ul.tick{ margin: 0; padding: 0; }
ul.tick li{ list-style: none; margin: 0 0 5px 0; padding: 0 0 0 20px; background: url(Images/bullet_tick.gif) no-repeat 0 4px; }
/* LSSC page */
h1.lssc{ background: url(Images/icon_ssc.gif) no-repeat left; line-height: 33px; padding: 0 0 0 40px; }
/* screenshots */
.screenshot{ float: left; margin: 0 60px 15px 0; padding: 2px; border: 1px solid #e1e1e1; position: relative; }
.screenshot img{ float: left; width:131px; }
.screenshot a{ position: absolute; text-indent: -5000px; bottom: 0; left: 0; width: 135px; height: 95px; background: url(Images/icon_zoom.gif) no-repeat bottom right; }
.rightscreenshot{ margin: 0 0 15px 0; }
/* Contains the Page Header (title, last modify, etc.) */
#PageTop{ display: none; }
#PageHeaderDiv { display:none;}
#PageInternalHeaderDiv { }
#PageInternalFooterDiv { }
/* Contains the Footer */
#FooterWrapper{ width:100%; margin: 0; padding: 18px 0 0px 0; border-top: 13px solid #E6E6E6; background-color: #2B2B2B; color: #D5D5D5; clear: both; position: relative; }
#Footer{ width:780px; margin:0 auto; padding:0; line-height:1.6em; font-size:1.1em; font-family: "MS Sans Serif", Geneva, sans-serif; }
#Footer .left{ float: left; width: 530px; padding-bottom:30px; }
#Footer .right{ float: right; width: 225px; text-align: right; }
#Footer .right a{ text-decoration: none; color:#dddddd; }
#Footer .left a{ color: #8A8A8A; text-decoration: none;}
#Footer a:hover{ color:#EEEEEE; border-bottom:1px solid #CCCCCC; }
#Footer .left ul{ list-style: none; padding: 0; margin: 0; }
#Footer .left li{ display:block; float:left; border-left: 1px solid #222222; border-right: 1px solid #414141; padding: 0 14px 0 14px; }
#Footer .left li.first{ border-left:none; padding-left:0;}
#Footer .left li.last{ border-right:none; padding-right:0; }
#Footer .admin{ float: right; width: 225px; text-align: right; color: #666666; margin: 0; padding: 0; }
#Footer .admin a{ text-decoration: none; color:#666666; }
#AjaxLoading { display: none; margin-top: 5px; margin-right: -7px; }
/* Contains the link to the page editing form (Edit.aspx) and history */
#EditHistoryLinkDiv { float: right; font-size: 11px; padding-top: 4px; padding-bottom: 4px; }
#EditLink, #HistoryLink, #ViewCodeLink, #DiscussLink, #BackLink, #PostReplyLink { margin-left: 4px; padding: 2px; border: solid 1px #999999; display: none; }
#EditLink:hover, #HistoryLink:hover, #ViewCodeLink:hover, #DiscussLink:hover, #BackLink:hover, #PostReplyLink:hover { border: solid 1px #214C9A; text-decoration: none; background-color: #FFFFEE; }
/* Class of the P containing the Edit Link */
p.editlink { font-size: 11px; }
.editsectionlink{ font-size: 8px; /* display:none; */ }
/* Shown when a page is Locked */
#PageLockedDiv { float: left; width: 12px; height: 12px; margin-right: 4px; background-image: url(Images/Lock.png); background-repeat: no-repeat; background-position: center; text-indent: -3000px; position: relative; }
/* Shown when a page is Public */
#PagePublicDiv { float: left; width: 12px; height: 12px; margin-right: 4px; background-image: url(Images/Public.png); background-repeat: no-repeat; background-position: center; text-indent: -3000px; position: relative; }
#PageInfoDiv { font-size: 11px; }
#BreadcrumbsDiv { font-size: 11px; margin-top: 2px; padding-bottom: 1px; border-bottom: solid 1px #F0F0F0; border-top: solid 1px #F0F0F0; /*background-color: #FFFEDF;*/ overflow: hidden; }
/* Contains the link to the Page RSS */
#RssLinkDiv { float: right; position: relative; }
/* The link to the Page RSS */
#RssLink { background-image: url(Images/RSS.png); background-repeat: no-repeat; text-indent: -2500px; display: block; height: 13px; width: 24px; }
#PrintLinkDiv { float: right; position: relative; }
#PrintLink { background-image: url(Images/Print.png); background-repeat: no-repeat; text-indent: -2500px; display: block; margin-left: 4px; height: 16px; width: 16px; }
/* Contains the Page Content */
#PageContentDiv { margin: 0; }
/* Contains the page preview in the Edit.aspx page */
#PreviewDiv {}
/* Contains the special tags in the Edit.aspx page */
#SpecialTagsDiv { font-size: 11px; border: solid 1px #999999; background-color: #FFFFFF; padding: 0px; }
a.specialtaglink { display: block; }
#PageListDiv { font-size: 11px; border: solid 1px #999999; background-color: #FFFFFF; padding: 0px; }
#FileListDiv { font-size: 11px; border: solid 1px #999999; background-color: #FFFFFF; padding: 4px; }
a.pagelistlink { display: block; }
#SnippetListDiv { font-size: 11px; border: solid 1px #999999; background-color: #FFFFFF; padding: 0px; }
a.snippetlistlink { display: block; }
/* Contains the anchors in the Edit.aspx page */
#AnchorsDiv { font-size: 11px; border: solid 1px #999999; background-color: #FFFFFF; padding: 0px; }
a.anchorlink { display: block; }
/* Contains the anchors in the Edit.aspx page */
#ImagesDiv { font-size: 11px; border: solid 1px #999999; background-color: #FFFFFF; padding: 0px; }
a.imagelink { display: block; }
#SpecialTagsDiv *, #AnchorsDiv *, #ImagesDiv *, #PageListDiv *, #SnippetListDiv * { padding: 2px; }
#SpecialTagsDiv a:hover, #AnchorsDiv a:hover, #ImagesDiv a:hover, #PageListDiv a:hover, #SnippetListDiv a:hover { color: #FFFFFF; background-color: #214C9A; text-decoration: none; }
/* Contains the Special characters in the Edit.aspx page */
#SpecialCharsDiv { margin-top: 8px; border: solid 1px #888888; padding: 4px; }
.queueNameWithMessages { color: #AB0B00; }
.queueMessageNumberWithMessages { font-weight: bold; font-size:1.5em; color: #AB0B00; }
#FormatUl { margin: 0px; padding: 0px; }
#FormatUl li { display: inline; list-style-image: none; margin: 0px; padding: 0px; }
/* Formatting Button in Edit.aspx */
a.formatlink { background-position: center; background-repeat: no-repeat; width: 20px; height: 20px; border: solid 1px #214C9A; text-indent: -2000px; margin-right: 2px; float: left; }
/* Formatting Button in Edit.aspx */
a.formatlink:hover { text-decoration: none; border: solid 1px #D9671E; }
#BoldLink { background-image: url(Images/Bold.png); }
#ItalicLink { background-image: url(Images/Italic.png); }
#UnderlineLink { background-image: url(Images/Underline.png); }
#StrikeLink { background-image: url(Images/Strike.png); }
#H1Link { background-image: url(Images/H1.png); }
#H2Link { background-image: url(Images/H2.png); }
#H3Link { background-image: url(Images/H3.png); }
#H4Link { background-image: url(Images/H4.png); }
#SubLink { background-image: url(Images/Sub.png); }
#SupLink { background-image: url(Images/Sup.png); }
#PageListLink { background-image: url(Images/PageLink.png); }
#FileLink { background-image: url(Images/File.png); }
#LinkLink { background-image: url(Images/Link.png); }
#ImageLink { background-image: url(Images/Image.png); }
#AnchorLink { background-image: url(Images/Anchor.png); }
#CodeLink { background-image: url(Images/Code.png); }
#PreLink { background-image: url(Images/Pre.png); }
#BoxLink { background-image: url(Images/Box.png); }
#BrLink { background-image: url(Images/BR.png); }
#SnippetListLink { background-image: url(Images/Snippet.png); }
#SpecialTagsLink { background-image: url(Images/SpecialTags.png); }
#NoWikiLink { background-image: url(Images/NoWiki.png); }
#CommentLink { background-image: url(Images/Comment.png); }
#EscapeLink { background-image: url(Images/Escape.png); }
#PageListTable { width: 90%; margin: 0px 10px 0px 10px; }
#PageListHeader { background-color: #DDDDDD; }
.pagelistcelleven { border-bottom: solid 1px #CCCCCC; }
.pagelistcellodd { border-bottom: solid 1px #CCCCCC; background-color: #F4F4F4; }
#PageTreeP { margin: 0px 0px 0px 10px; padding: 0px 0px 0px 6px; border-left: 4px solid #CCCCCC; }
#FileListTable { width: 98%; margin: 0px; }
#FileListHeader { background-color: #DDDDDD; }
.filelistcelleven { border-bottom: solid 1px #CCCCCC; }
.filelistcellodd { border-bottom: solid 1px #CCCCCC; background-color: #F4F4F4; }
#RevisionListTable { width: 98%; margin: 0px; }
#RevisionListHeader { background-color: #DDDDDD; }
.revisionlistcelleven { border-bottom: solid 1px #CCCCCC; }
.revisionlistcellodd { border-bottom: solid 1px #CCCCCC; background-color: #F4F4F4; }
#PreviewDivExternal { }
#PreviewDiv { padding: 10px; border: solid 4px #CCCCCC; }
blockquote { border-left: solid 8px #DDDDDD; margin-left: 16px; padding: 0px 0px 2px 6px; }
div.messagecontainer { margin: 0px 0px 0px 16px; }
div.rootmessagecontainer { border-top: solid 4px #214C9A; }
div.messageheader { font-size: 10px; background-color: #F0F0F0; padding: 2px; }
span.messagesubject { font-weight: bold; font-size: 12px;}
div.messagebody { border-bottom: solid 1px #F0F0F0; border-left: solid 1px #F0F0F0; border-right: solid 1px #F0F0F0; margin: 0px 0px 6px 0px; padding: 4px;}
div.reply { float: right; margin: 6px 10px 0px 0px; font-size: 11px; font-weight: bold;}
a.reply { background-image: url(Images/MessageReply.png); background-repeat: no-repeat; background-position: left center; padding: 0px 0px 0px 12px;}
a.edit { background-image: url(Images/MessageEdit.png); background-repeat: no-repeat; background-position: left center; padding: 0px 0px 0px 13px; margin-left: 16px; }
a.delete { background-image: url(Images/MessageDelete.png); background-repeat: no-repeat; background-position: left center; padding: 0px 0px 0px 10px; margin-left: 16px; }
#ConcurrentEditingDiv { padding: 6px; background-color: #FEF693; border: solid 1px #FFCF10; }
span.signature { font-style: italic; }
#TocContainer { border: solid 1px #CCCCCC; display: table-cell; padding: 7px; border-collapse: collapse; background-color: #F9F9F9; }
#AttachmentsDiv { margin-top: 6px; padding: 4px; border: solid 1px #559955; background-color: #D6EED2; }
a.attachment { padding-left: 14px; background-image: url(Images/Attachment.png); background-repeat: no-repeat; background-position: left center; }
#RedirectionInfoDiv { font-size: 11px; padding-left: 10px; padding-top: 4px; color: #999999; }
#RedirectionDiv { margin-bottom: 16px; padding-left: 24px; margin-left: 10px; font-size: 14px; background-image: url(Images/Redirect.png); background-repeat: no-repeat; background-position: left center; }
/* JsFileTree control begin */
div.subtreediv { margin: 0px 0px 0px 10px; }
a.subdirlink { background-image: url(../../Images/Dir.png); background-repeat: no-repeat; background-position: left center; padding: 0px 0px 0px 18px; }
a.filelink { background-image: url(../../Images/File.png); background-repeat: no-repeat; background-position: left center; padding: 0px 0px 0px 18px; }
/* JsFileTree control end */
/* JsImageBrowser control begin */
#ImageBrowserDiv { background-color: #FFFFFF; border: solid 1px #999999; width: 616px; }
#MainContainerDiv { overflow: auto; height: 286px; }
div.container { float: left; width: 96px; height: 126px; background-color: #FFFFFF; margin: 4px; }
#UpLevelLink, #UpLevelLink:hover { display: block; width: 96px; height: 96px; vertical-align: bottom; text-align: center; text-decoration: none; }
a.dirlink, a.dirlink:hover { display: block; width: 96px; height: 96px; vertical-align: bottom; text-align: center; text-decoration: none; }
a.itemlink, a.itemlink:hover { display: block; width: 96px; height: 116px; vertical-align: bottom; text-align: center; text-decoration: none; }
span.itemtext { color: #000000; background-color: #FFFFFF; padding: 0px; width: 96px; height: 96px; vertical-align: bottom; font-size: 10px; }
#ImagePreviewDiv { float: right; width: 256px; height: 268px; border: solid 1px #CCCCCC; margin: 4px; padding: 4px; text-align: center; vertical-align: middle; background-color: #FFFFFF; }
#PreviewImg { height: 248px; vertical-align: middle; }
img.thumb { border: solid 1px #CCCCCC; }
#ImageDescriptionSpan { font-size: 11px; font-style: italic; }
/* JsImageBrowser control end */
.table
{
border: 1px solid #FCD396;
border-spacing: 0px;
border-collapse: collapse;
empty-cells: show;
}
.table th{ border-style: solid; border-width: 0 0 1px 1px; border-color: #FCE7C5; padding: 4px 10px 4px 4px; margin: 0; background-color: #FCF0DA; text-align: left; vertical-align: top; }
.table td{ border-style: solid; border-width: 0 0 1px 1px; border-color: #FCE7C5; padding: 4px 10px 4px 4px; margin: 0; background-color: #FCF9F0; text-align: left; vertical-align: top; }
.table pre { width: 600px; }
.tableseparator td{ background-color: #FFFFFF; border-width: 0 0 1px 0; }
.loadMore { border: solid 1px #FFCF10; background-color: #FEF693; display: inline-block; padding: 0.2em 0em 0.2em 0em; margin: 1em 0em 1em 0em; text-align: center; width: 780px; cursor: pointer; }
.updatedText{ text-align: right; font-style: italic; font-size: 0.8em; padding: 2em 0 0 0; }
/*.table th{ background-color: #FCF9F0; color: #312104; }
.table td{ background-color: #FCF9F0; }*/
.small { font-size: 0.85em; }
/* NEW FRONTPAGE */
.linelist{ padding:0; margin:7px 0 36px 0; float:left; width:100%; list-style:none; }
.linelist li{ float: left; padding: 0 30px 0 30px; width:125px; background-image: url(Images/ico_frontlist.gif); background-position: left top; background-repeat: no-repeat; color: #535353; }
#Side .btndownload{ cursor: pointer; position:relative; width: 180px; margin: 0 0 1.5em 0; height: 59px; background: #A5C7EB url(Images/bg_download.gif); }
#Side .btndownload a{ padding: 16px 22px 0 0; height: 43px; width:158px; display:block; text-align: right; color: white; letter-spacing:2px; font: bold 1.2em Arial, Helvetica, sans-serif; text-decoration: none; }
#Side .btndownload a:hover{ text-decoration: underline;}
#Side .btndownload span{ position:absolute; right:22px; top: 29px; color:white; display: block; font: bold 10px Arial, Helvetica, sans-serif; }
#Text .right{ float:right; }
#Text .left{ float:left; }
#Text img.left{ margin: 5px 15px 5px 0; }
#Text img.right{ margin: 5px 0 5px 15px; }
.textjustify{ text-align: justify; }
.textleft{ text-align: left; }
.textright{ text-align: right; }
.textcenter{ text-align: center; }
#Text .actions{ list-style:none; padding:0; margin:10px 0 15px 0; font-size:1.4em; }
#Text .actions li{ display:inline; }
#Text .actions li.arrow{ padding: 0 0 0 10px; margin: 0 0 0 6px; background: url(Images/ico_arrow.gif) no-repeat left; }
/* ------------------------------------------------- */
/* Local Overrides specific to the Lokad application */
/* Bigger Logo */
.logo a{ width:332px; }
.logo h1{ padding: 0 48px 0 0; width:332px; overflow: hidden; background:url(Images/bg_logo.png) no-repeat; }
.logo h1.Test { background:url(Images/logo_test.gif) no-repeat;}
#Visual { background-image: url(Images/bg_slogan.gif); }
/* Help styles */
#HelpHeader { width:100%; float:left; border-bottom: solid #F2EDD9 2px; background-color:White;}
#HelpLogo { background-image: url(Images/lokad-help.gif);background-repeat: no-repeat; height:51px; }
#HelpWrapper { line-height:1.4em; margin: 0; font-size:1.4em; background-color:White; padding-left:10px;padding-right:10px; padding-top:15px;}
#HelpWrapper h1 {padding-bottom: 2px; margin-bottom: 8px;}
#HelpWrapper h2 { margin-top: 20px;}
.CloseHelp {float: right; }
/* Main style overrides */
#TopControls div.btn { margin-left:5px;}
#Text p { padding: 0 0 1em 0; width:750px}
div.box { width:530px; }
div.warning { max-width:530px; }
span.warning { color: #ff0000; }
.statusenabled { font-weight: bold; }
.statusdisabled { color: #FF0000; }
/* Used for Lokad.skin */
.DefaultGrid
{
border-collapse: collapse;
border: solid 1px #BBBBBB;
}
.Centered
{
margin: 0em auto 1em auto;
}
fieldset { border:0; margin: 0em 4em 1em 4em; height: 2.5em;}
select {margin-right: 1em; float: left;}
.icon-GoodBad { display: inline-block; width: 16px; height: 16px; background-image: url(Icons/GoodBad16.png); background-repeat: no-repeat; vertical-align: middle; margin-right: 0.5em; }
.icon-GoodBad-Good { background-position: 0px 0px; }
.icon-GoodBad-Bad { background-position: -16px 0px; }
.icon-GoodBad-VeryBad { background-position: -32px 0px; }
.icon-LogLevels { display: block; width: 16px; height: 16px; background-image: url(Icons/LogLevels16.png); background-repeat: no-repeat; float: left; vertical-align: middle; margin-right: 0.5em; }
.icon-LogLevels-Debug { background-position: 0px 0px; }
.icon-LogLevels-Info { background-position: -16px 0px; }
.icon-LogLevels-Warn { background-position: -32px 0px; }
.icon-LogLevels-Error { background-position: -48px 0px; }
.icon-LogLevels-Fatal { background-position: -64px 0px; }
.icon-OkCancel { display: block; width: 16px; height: 16px; background-image: url(Icons/OkCancel16.png); background-repeat: no-repeat; float: left; vertical-align: middle; margin-right: 0.5em; }
.icon-OkCancel-Ok { background-position: 0px 0px; }
.icon-OkCancel-Cancel { background-position: -16px 0px; }
.icon-PlusMinus { display: block; width: 16px; height: 16px; background-image: url(Icons/PlusMinus16.png); background-repeat: no-repeat; float: left; vertical-align: middle; margin-right: 0.5em; }
.icon-PlusMinus-Plus { background-position: 0px 0px; }
.icon-PlusMinus-Minus { background-position: -16px 0px; }
.icon-StartStop { display: block; width: 16px; height: 16px; background-image: url(Icons/StartStop16.png); background-repeat: no-repeat; float: left; vertical-align: middle; margin-right: 0.5em; }
.icon-StartStop-Start { background-position: 0px 0px; }
.icon-StartStop-Stop { background-position: -16px 0px; }
.icon-StartStop-Pause { background-position: -32px 0px; }
.icon-StartStop-Standby { background-position: -48px 0px; }
.icon-button { cursor: pointer; }
.icon-loading { background-image: url(Icons/Loading16.png); background-position: 0px 0px; }
| zyyin2005-lokad | Source/Lokad.Cloud.Console.WebRole/Content/Lokad.css | CSS | bsd | 31,857 |
using System.Reflection;
using System.Threading;
using System.Web.Mvc;
using System.Web.Routing;
using Lokad.Cloud.Console.WebRole.Framework.Discovery;
using Ninject;
using Ninject.Web.Mvc;
namespace Lokad.Cloud.Console.WebRole
{
public class MvcApplication : NinjectHttpApplication
{
private CancellationTokenSource _discoveryCancellation;
private static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new HandleErrorAttribute());
}
private static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.IgnoreRoute("Content/{*pathInfo}");
routes.MapRoute("Overview", "", new { controller = "Overview", action = "Index" });
routes.MapRoute("Account", "Account/{action}/{id}", new { controller = "Account", action = "Index", id = UrlParameter.Optional });
routes.MapRoute("Discovery", "Discovery/{action}/{id}", new { controller = "Discovery", action = "Index", id = UrlParameter.Optional });
routes.MapRoute("ByHostedService", "{controller}/{hostedServiceName}/{action}/{id}", new { action = "ByHostedService", id = UrlParameter.Optional });
routes.MapRoute("Default", "{controller}/{action}/{id}", new { controller = "Overview", action = "Index", id = UrlParameter.Optional });
routes.MapRoute("MenuIndex", "{controller}/{action}", new { controller = "Overview", action = "Index" });
routes.MapRoute("MenuByHostedService", "{controller}/{hostedServiceName}/{action}", new { controller = "Overview", action = "ByHostedService" });
}
protected override IKernel CreateKernel()
{
var kernel = new StandardKernel();
kernel.Load(Assembly.GetExecutingAssembly());
return kernel;
}
protected override void OnApplicationStarted()
{
base.OnApplicationStarted();
AreaRegistration.RegisterAllAreas();
RegisterGlobalFilters(GlobalFilters.Filters);
RegisterRoutes(RouteTable.Routes);
_discoveryCancellation = new CancellationTokenSource();
var discovery = (AzureDiscoveryProvider)DependencyResolver.Current.GetService(typeof(AzureDiscoveryProvider));
discovery.StartAutomaticCacheUpdate(_discoveryCancellation.Token);
}
protected override void OnApplicationStopped()
{
if (_discoveryCancellation != null)
{
_discoveryCancellation.Cancel();
_discoveryCancellation = null;
}
base.OnApplicationStopped();
}
}
} | zyyin2005-lokad | Source/Lokad.Cloud.Console.WebRole/Global.asax.cs | C# | bsd | 2,809 |
#region Copyright (c) Lokad 2010-2011
// This code is released under the terms of the new BSD licence.
// URL: http://www.lokad.com/
#endregion
using System;
using System.ComponentModel;
using System.Net;
using Lokad.Cloud.Storage.Shared;
using Microsoft.WindowsAzure;
using Microsoft.WindowsAzure.StorageClient;
namespace Lokad.Cloud.Storage
{
public static class CloudStorage
{
public static CloudStorageBuilder ForAzureAccount(CloudStorageAccount storageAccount)
{
return new AzureCloudStorageBuilder(storageAccount);
}
public static CloudStorageBuilder ForAzureConnectionString(string connectionString)
{
CloudStorageAccount storageAccount;
if (!CloudStorageAccount.TryParse(connectionString, out storageAccount))
{
throw new InvalidOperationException("Failed to get valid connection string");
}
return new AzureCloudStorageBuilder(storageAccount);
}
public static CloudStorageBuilder ForAzureAccountAndKey(string accountName, string key, bool useHttps = true)
{
return new AzureCloudStorageBuilder(new CloudStorageAccount(new StorageCredentialsAccountAndKey(accountName, key), useHttps));
}
public static CloudStorageBuilder ForDevelopmentStorage()
{
return new AzureCloudStorageBuilder(CloudStorageAccount.DevelopmentStorageAccount);
}
public static CloudStorageBuilder ForInMemoryStorage()
{
return new InMemoryStorageBuilder();
}
[EditorBrowsable(EditorBrowsableState.Never)]
public abstract class CloudStorageBuilder
{
/// <remarks>Can not be null</remarks>
protected IDataSerializer DataSerializer { get; private set; }
/// <remarks>Can be null if not needed</remarks>
protected Shared.Logging.ILog Log { get; private set; }
/// <remarks>Can be null if not needed</remarks>
protected IRuntimeFinalizer RuntimeFinalizer { get; private set; }
protected CloudStorageBuilder()
{
// defaults
DataSerializer = new CloudFormatter();
}
/// <summary>
/// Replace the default data serializer with a custom implementation
/// </summary>
public CloudStorageBuilder WithDataSerializer(IDataSerializer dataSerializer)
{
DataSerializer = dataSerializer;
return this;
}
/// <summary>
/// Optionally provide a log provider.
/// </summary>
public CloudStorageBuilder WithLog(Shared.Logging.ILog log)
{
Log = log;
return this;
}
/// <summary>
/// Optionally provide a runtime finalizer.
/// </summary>
public CloudStorageBuilder WithRuntimeFinalizer(IRuntimeFinalizer runtimeFinalizer)
{
RuntimeFinalizer = runtimeFinalizer;
return this;
}
public abstract IBlobStorageProvider BuildBlobStorage();
public abstract ITableStorageProvider BuildTableStorage();
public abstract IQueueStorageProvider BuildQueueStorage();
public CloudStorageProviders BuildStorageProviders()
{
return new CloudStorageProviders(
BuildBlobStorage(),
BuildQueueStorage(),
BuildTableStorage(),
RuntimeFinalizer,
Log);
}
}
}
internal sealed class InMemoryStorageBuilder : CloudStorage.CloudStorageBuilder
{
public override IBlobStorageProvider BuildBlobStorage()
{
return new InMemory.MemoryBlobStorageProvider
{
DataSerializer = DataSerializer
};
}
public override ITableStorageProvider BuildTableStorage()
{
return new InMemory.MemoryTableStorageProvider
{
DataSerializer = DataSerializer
};
}
public override IQueueStorageProvider BuildQueueStorage()
{
return new InMemory.MemoryQueueStorageProvider
{
DataSerializer = DataSerializer
};
}
}
internal sealed class AzureCloudStorageBuilder : CloudStorage.CloudStorageBuilder
{
private readonly CloudStorageAccount _storageAccount;
internal AzureCloudStorageBuilder(CloudStorageAccount storageAccount)
{
_storageAccount = storageAccount;
// http://blogs.msdn.com/b/windowsazurestorage/archive/2010/06/25/nagle-s-algorithm-is-not-friendly-towards-small-requests.aspx
ServicePointManager.FindServicePoint(storageAccount.TableEndpoint).UseNagleAlgorithm = false;
ServicePointManager.FindServicePoint(storageAccount.QueueEndpoint).UseNagleAlgorithm = false;
}
public override IBlobStorageProvider BuildBlobStorage()
{
return new Azure.BlobStorageProvider(
BlobClient(),
DataSerializer,
Log);
}
public override ITableStorageProvider BuildTableStorage()
{
return new Azure.TableStorageProvider(
TableClient(),
DataSerializer);
}
public override IQueueStorageProvider BuildQueueStorage()
{
return new Azure.QueueStorageProvider(
QueueClient(),
BuildBlobStorage(),
DataSerializer,
RuntimeFinalizer,
Log);
}
CloudBlobClient BlobClient()
{
var blobClient = _storageAccount.CreateCloudBlobClient();
blobClient.RetryPolicy = BuildDefaultRetry();
return blobClient;
}
CloudTableClient TableClient()
{
var tableClient = _storageAccount.CreateCloudTableClient();
tableClient.RetryPolicy = BuildDefaultRetry();
return tableClient;
}
CloudQueueClient QueueClient()
{
var queueClient = _storageAccount.CreateCloudQueueClient();
queueClient.RetryPolicy = BuildDefaultRetry();
return queueClient;
}
static RetryPolicy BuildDefaultRetry()
{
// [abdullin]: in short this gives us MinBackOff + 2^(10)*Rand.(~0.5.Seconds())
// at the last retry. Reflect the method for more details
var deltaBackoff = TimeSpan.FromSeconds(0.5);
return RetryPolicies.RetryExponential(10, deltaBackoff);
}
}
}
| zyyin2005-lokad | Source/Lokad.Cloud.Storage/CloudStorage.cs | C# | bsd | 7,094 |
#region Copyright (c) Lokad 2009
// This code is released under the terms of the new BSD licence.
// URL: http://www.lokad.com/
#endregion
using System.IO;
using System.Xml.Linq;
using Lokad.Cloud.Storage.Shared;
namespace Lokad.Cloud.Storage
{
/// <summary>
/// Optional extension for custom formatters supporting an
/// intermediate xml representation for inspection and recovery.
/// </summary>
/// <remarks>
/// This extension can be implemented even when the serializer
/// is not xml based but in a format that can be transformed
/// to xml easily in a robust way (i.e. more robust than
/// deserializing to a full object). Note that formatters
/// should be registered in IoC as IBinaryFormatter, not by
/// this extension interface.
/// </remarks>
public interface IIntermediateDataSerializer : IDataSerializer
{
/// <summary>Unpack and transform an object from a stream to xml.</summary>
XElement UnpackXml(Stream source);
/// <summary>Transform and repack an object from xml to a stream.</summary>
void RepackXml(XElement data, Stream destination);
}
} | zyyin2005-lokad | Source/Lokad.Cloud.Storage/IIntermediateDataSerializer.cs | C# | bsd | 1,191 |
#region Copyright (c) Lokad 2009-2011
// This code is released under the terms of the new BSD licence.
// URL: http://www.lokad.com/
#endregion
using System;
using System.Collections.Generic;
using System.Data.Services.Client;
using System.Linq;
using Lokad.Cloud.Storage.Azure;
using Lokad.Cloud.Storage.Shared;
namespace Lokad.Cloud.Storage.InMemory
{
/// <summary>Mock in-memory TableStorage Provider.</summary>
/// <remarks>
/// All the methods of <see cref="MemoryTableStorageProvider"/> are thread-safe.
/// </remarks>
public class MemoryTableStorageProvider : ITableStorageProvider
{
/// <summary>In memory table storage : entries per table (designed for simplicity instead of performance)</summary>
readonly Dictionary<string, List<MockTableEntry>> _tables;
/// <summary>Formatter as requiered to handle FatEntities.</summary>
internal IDataSerializer DataSerializer { get; set; }
/// <summary>naive global lock to make methods thread-safe.</summary>
readonly object _syncRoot;
int _nextETag;
/// <summary>
/// Constructor for <see cref="MemoryTableStorageProvider"/>.
/// </summary>
public MemoryTableStorageProvider()
{
_tables = new Dictionary<string, List<MockTableEntry>>();
_syncRoot = new object();
DataSerializer = new CloudFormatter();
}
/// <see cref="ITableStorageProvider.CreateTable"/>
public bool CreateTable(string tableName)
{
lock (_syncRoot)
{
if (_tables.ContainsKey(tableName))
{
//If the table already exists: return false.
return false;
}
//create table return true.
_tables.Add(tableName, new List<MockTableEntry>());
return true;
}
}
/// <see cref="ITableStorageProvider.DeleteTable"/>
public bool DeleteTable(string tableName)
{
lock (_syncRoot)
{
if (_tables.ContainsKey(tableName))
{
//If the table exists remove it.
_tables.Remove(tableName);
return true;
}
//Can not remove an unexisting table.
return false;
}
}
/// <see cref="ITableStorageProvider.GetTables"/>
public IEnumerable<string> GetTables()
{
lock (_syncRoot)
{
return _tables.Keys;
}
}
/// <see cref="ITableStorageProvider.Get{T}(string)"/>
IEnumerable<CloudEntity<T>> GetInternal<T>(string tableName, Func<MockTableEntry,bool> predicate)
{
lock (_syncRoot)
{
if (!_tables.ContainsKey(tableName))
{
return new List<CloudEntity<T>>();
}
return from entry in _tables[tableName]
where predicate(entry)
select entry.ToCloudEntity<T>(DataSerializer);
}
}
/// <see cref="ITableStorageProvider.Get{T}(string)"/>
public IEnumerable<CloudEntity<T>> Get<T>(string tableName)
{
return GetInternal<T>(tableName, entry => true);
}
/// <see cref="ITableStorageProvider.Get{T}(string,string)"/>
public IEnumerable<CloudEntity<T>> Get<T>(string tableName, string partitionKey)
{
return GetInternal<T>(tableName, entry => entry.PartitionKey == partitionKey);
}
/// <see cref="ITableStorageProvider.Get{T}(string,string,string,string)"/>
public IEnumerable<CloudEntity<T>> Get<T>(string tableName, string partitionKey, string startRowKey, string endRowKey)
{
var isInRange = string.IsNullOrEmpty(endRowKey)
? (Func<string, bool>)(rowKey => string.Compare(startRowKey, rowKey) <= 0)
: (rowKey => string.Compare(startRowKey, rowKey) <= 0 && string.Compare(rowKey, endRowKey) < 0);
return GetInternal<T>(tableName, entry => entry.PartitionKey == partitionKey && isInRange(entry.RowKey))
.OrderBy(entity => entity.RowKey);
}
/// <see cref="ITableStorageProvider.Get{T}(string,string,System.Collections.Generic.IEnumerable{string})"/>
public IEnumerable<CloudEntity<T>> Get<T>(string tableName, string partitionKey, IEnumerable<string> rowKeys)
{
var keys = new HashSet<string>(rowKeys);
return GetInternal<T>(tableName, entry => entry.PartitionKey == partitionKey && keys.Contains(entry.RowKey));
}
/// <see cref="ITableStorageProvider.Insert{T}"/>
public void Insert<T>(string tableName, IEnumerable<CloudEntity<T>> entities)
{
lock (_syncRoot)
{
List<MockTableEntry> entries;
if (!_tables.TryGetValue(tableName, out entries))
{
_tables.Add(tableName, entries = new List<MockTableEntry>());
}
// verify valid data BEFORE inserting them
if (entities.Join(entries, u => ToId(u), ToId, (u, v) => true).Any())
{
throw new DataServiceRequestException("INSERT: key conflict.");
}
if (entities.GroupBy(e => ToId(e)).Any(id => id.Count() != 1))
{
throw new DataServiceRequestException("INSERT: duplicate keys.");
}
// ok, we can insert safely now
foreach (var entity in entities)
{
var etag = (_nextETag++).ToString();
entity.ETag = etag;
entries.Add(new MockTableEntry
{
PartitionKey = entity.PartitionKey,
RowKey = entity.RowKey,
ETag = etag,
Value = FatEntity.Convert(entity, DataSerializer)
});
}
}
}
/// <see cref="ITableStorageProvider.Update{T}"/>
public void Update<T>(string tableName, IEnumerable<CloudEntity<T>> entities, bool force)
{
lock (_syncRoot)
{
List<MockTableEntry> entries;
if (!_tables.TryGetValue(tableName, out entries))
{
throw new DataServiceRequestException("UPDATE: table not found.");
}
// verify valid data BEFORE updating them
if (entities.GroupJoin(entries, u => ToId(u), ToId, (u, vs) => vs.Count(entry => force || u.ETag == null || entry.ETag == u.ETag)).Any(c => c != 1))
{
throw new DataServiceRequestException("UPDATE: key not found or etag conflict.");
}
if (entities.GroupBy(e => ToId(e)).Any(id => id.Count() != 1))
{
throw new DataServiceRequestException("UPDATE: duplicate keys.");
}
// ok, we can update safely now
foreach (var entity in entities)
{
var etag = (_nextETag++).ToString();
entity.ETag = etag;
var index = entries.FindIndex(entry => entry.PartitionKey == entity.PartitionKey && entry.RowKey == entity.RowKey);
entries[index] = new MockTableEntry
{
PartitionKey = entity.PartitionKey,
RowKey = entity.RowKey,
ETag = etag,
Value = FatEntity.Convert(entity, DataSerializer)
};
}
}
}
/// <see cref="ITableStorageProvider.Update{T}"/>
public void Upsert<T>(string tableName, IEnumerable<CloudEntity<T>> entities)
{
lock (_syncRoot)
{
// deleting all existing entities
foreach (var g in entities.GroupBy(e => e.PartitionKey))
{
Delete<T>(tableName, g.Key, g.Select(e => e.RowKey));
}
// inserting all entities
Insert(tableName, entities);
}
}
/// <see cref="ITableStorageProvider.Delete{T}"/>
public void Delete<T>(string tableName, string partitionKey, IEnumerable<string> rowKeys)
{
lock (_syncRoot)
{
List<MockTableEntry> entries;
if (!_tables.TryGetValue(tableName, out entries))
{
return;
}
var keys = new HashSet<string>(rowKeys);
entries.RemoveAll(entry => entry.PartitionKey == partitionKey && keys.Contains(entry.RowKey));
}
}
/// <see cref="ITableStorageProvider.Delete{T}"/>
public void Delete<T>(string tableName, IEnumerable<CloudEntity<T>> entities, bool force)
{
lock (_syncRoot)
{
List<MockTableEntry> entries;
if (!_tables.TryGetValue(tableName, out entries))
{
return;
}
var entityList = entities.ToList();
// verify valid data BEFORE deleting them
if (entityList.Join(entries, u => ToId(u), ToId, (u, v) => force || u.ETag == null || u.ETag == v.ETag).Any(c => !c))
{
throw new DataServiceRequestException("DELETE: etag conflict.");
}
// ok, we can delete safely now
entries.RemoveAll(entry => entityList.Any(entity => entity.PartitionKey == entry.PartitionKey && entity.RowKey == entry.RowKey));
}
}
static System.Tuple<string, string> ToId<T>(CloudEntity<T> entity)
{
return System.Tuple.Create(entity.PartitionKey, entity.RowKey);
}
static System.Tuple<string, string> ToId(MockTableEntry entry)
{
return System.Tuple.Create(entry.PartitionKey, entry.RowKey);
}
class MockTableEntry
{
public string PartitionKey { get; set; }
public string RowKey { get; set; }
public string ETag { get; set; }
public FatEntity Value { get; set; }
public CloudEntity<T> ToCloudEntity<T>(IDataSerializer serializer)
{
return FatEntity.Convert<T>(Value, serializer, ETag);
}
}
}
}
| zyyin2005-lokad | Source/Lokad.Cloud.Storage/InMemory/MemoryTableStorageProvider.cs | C# | bsd | 11,195 |
#region Copyright (c) Lokad 2009-2011
// This code is released under the terms of the new BSD licence.
// URL: http://www.lokad.com/
#endregion
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Xml.Linq;
using Lokad.Cloud.Storage.Shared;
namespace Lokad.Cloud.Storage.InMemory
{
/// <summary>Mock in-memory Blob Storage.</summary>
/// <remarks>
/// All the methods of <see cref="MemoryBlobStorageProvider"/> are thread-safe.
/// Note that the blob lease implementation is simplified such that leases do not time out.
/// </remarks>
public class MemoryBlobStorageProvider : IBlobStorageProvider
{
/// <summary> Containers Property.</summary>
Dictionary<string, MockContainer> Containers { get { return _containers;} }
readonly Dictionary<string, MockContainer> _containers;
/// <summary>naive global lock to make methods thread-safe.</summary>
readonly object _syncRoot;
internal IDataSerializer DataSerializer { get; set; }
/// <remarks></remarks>
public MemoryBlobStorageProvider()
{
_containers = new Dictionary<string, MockContainer>();
_syncRoot = new object();
DataSerializer = new CloudFormatter();
}
public IEnumerable<string> ListContainers(string prefix = null)
{
lock (_syncRoot)
{
if (String.IsNullOrEmpty(prefix))
{
return Containers.Keys;
}
return Containers.Keys.Where(key => key.StartsWith(prefix));
}
}
public bool CreateContainerIfNotExist(string containerName)
{
lock (_syncRoot)
{
if (!BlobStorageExtensions.IsContainerNameValid(containerName))
{
throw new NotSupportedException("the containerName is not compliant with azure constraints on container names");
}
if (Containers.Keys.Contains(containerName))
{
return false;
}
Containers.Add(containerName, new MockContainer());
return true;
}
}
public bool DeleteContainerIfExist(string containerName)
{
lock (_syncRoot)
{
if (!Containers.Keys.Contains(containerName))
{
return false;
}
Containers.Remove(containerName);
return true;
}
}
public IEnumerable<string> ListBlobNames(string containerName, string blobNamePrefix = null)
{
lock (_syncRoot)
{
if (!Containers.Keys.Contains(containerName))
{
return Enumerable.Empty<string>();
}
var names = Containers[containerName].BlobNames;
return String.IsNullOrEmpty(blobNamePrefix) ? names : names.Where(name => name.StartsWith(blobNamePrefix));
}
}
public IEnumerable<T> ListBlobs<T>(string containerName, string blobNamePrefix = null, int skip = 0)
{
var names = ListBlobNames(containerName, blobNamePrefix);
if (skip > 0)
{
names = names.Skip(skip);
}
return names.Select(name => GetBlob<T>(containerName, name))
.Where(blob => blob.HasValue)
.Select(blob => blob.Value);
}
public bool DeleteBlobIfExist(string containerName, string blobName)
{
lock (_syncRoot)
{
if (!Containers.Keys.Contains(containerName) || !Containers[containerName].BlobNames.Contains(blobName))
{
return false;
}
Containers[containerName].RemoveBlob(blobName);
return true;
}
}
public void DeleteAllBlobs(string containerName, string blobNamePrefix = null)
{
foreach (var blobName in ListBlobNames(containerName, blobNamePrefix))
{
DeleteBlobIfExist(containerName, blobName);
}
}
public Maybe<T> GetBlob<T>(string containerName, string blobName)
{
string ignoredEtag;
return GetBlob<T>(containerName, blobName, out ignoredEtag);
}
public Maybe<T> GetBlob<T>(string containerName, string blobName, out string etag)
{
return GetBlob(containerName, blobName, typeof(T), out etag)
.Convert(o => o is T ? (T)o : Maybe<T>.Empty, Maybe<T>.Empty);
}
public Maybe<object> GetBlob(string containerName, string blobName, Type type, out string etag)
{
lock (_syncRoot)
{
if (!Containers.ContainsKey(containerName)
|| !Containers[containerName].BlobNames.Contains(blobName))
{
etag = null;
return Maybe<object>.Empty;
}
etag = Containers[containerName].BlobsEtag[blobName];
return Containers[containerName].GetBlob(blobName);
}
}
public Maybe<XElement> GetBlobXml(string containerName, string blobName, out string etag)
{
etag = null;
var formatter = DataSerializer as IIntermediateDataSerializer;
if (formatter == null)
{
return Maybe<XElement>.Empty;
}
object data;
lock (_syncRoot)
{
if (!Containers.ContainsKey(containerName)
|| !Containers[containerName].BlobNames.Contains(blobName))
{
return Maybe<XElement>.Empty;
}
etag = Containers[containerName].BlobsEtag[blobName];
data = Containers[containerName].GetBlob(blobName);
}
using (var stream = new MemoryStream())
{
formatter.Serialize(data, stream);
stream.Position = 0;
return formatter.UnpackXml(stream);
}
}
public Maybe<T>[] GetBlobRange<T>(string containerName, string[] blobNames, out string[] etags)
{
// Copy-paste from BlobStorageProvider.cs
var tempResult = blobNames.Select(blobName =>
{
string etag;
var blob = GetBlob<T>(containerName, blobName, out etag);
return new System.Tuple<Maybe<T>, string>(blob, etag);
}).ToArray();
etags = new string[blobNames.Length];
var result = new Maybe<T>[blobNames.Length];
for (int i = 0; i < tempResult.Length; i++)
{
result[i] = tempResult[i].Item1;
etags[i] = tempResult[i].Item2;
}
return result;
}
public Maybe<T> GetBlobIfModified<T>(string containerName, string blobName, string oldEtag, out string newEtag)
{
lock (_syncRoot)
{
string currentEtag = GetBlobEtag(containerName, blobName);
if (currentEtag == oldEtag)
{
newEtag = null;
return Maybe<T>.Empty;
}
newEtag = currentEtag;
return GetBlob<T>(containerName, blobName);
}
}
public string GetBlobEtag(string containerName, string blobName)
{
lock (_syncRoot)
{
return (Containers.ContainsKey(containerName) && Containers[containerName].BlobNames.Contains(blobName))
? Containers[containerName].BlobsEtag[blobName]
: null;
}
}
public void PutBlob<T>(string containerName, string blobName, T item)
{
PutBlob(containerName, blobName, item, true);
}
public bool PutBlob<T>(string containerName, string blobName, T item, bool overwrite)
{
string ignored;
return PutBlob(containerName, blobName, item, overwrite, out ignored);
}
public bool PutBlob<T>(string containerName, string blobName, T item, bool overwrite, out string etag)
{
return PutBlob(containerName, blobName, item, typeof(T), overwrite, out etag);
}
public bool PutBlob<T>(string containerName, string blobName, T item, string expectedEtag)
{
string ignored;
return PutBlob(containerName, blobName, item, typeof (T), true, expectedEtag, out ignored);
}
public bool PutBlob(string containerName, string blobName, object item, Type type, bool overwrite, out string etag)
{
return PutBlob(containerName, blobName, item, type, overwrite, null, out etag);
}
public bool PutBlob(string containerName, string blobName, object item, Type type, bool overwrite, string expectedEtag, out string etag)
{
lock(_syncRoot)
{
etag = null;
if(Containers.ContainsKey(containerName))
{
if(Containers[containerName].BlobNames.Contains(blobName))
{
if(!overwrite || expectedEtag != null && expectedEtag != Containers[containerName].BlobsEtag[blobName])
{
return false;
}
using (var stream = new MemoryStream())
{
DataSerializer.Serialize(item, stream);
}
Containers[containerName].SetBlob(blobName, item);
etag = Containers[containerName].BlobsEtag[blobName];
return true;
}
Containers[containerName].AddBlob(blobName, item);
etag = Containers[containerName].BlobsEtag[blobName];
return true;
}
if (!BlobStorageExtensions.IsContainerNameValid(containerName))
{
throw new NotSupportedException("the containerName is not compliant with azure constraints on container names");
}
Containers.Add(containerName, new MockContainer());
using (var stream = new MemoryStream())
{
DataSerializer.Serialize(item, stream);
}
Containers[containerName].AddBlob(blobName, item);
etag = Containers[containerName].BlobsEtag[blobName];
return true;
}
}
public Maybe<T> UpdateBlobIfExist<T>(string containerName, string blobName, Func<T, T> update)
{
return UpsertBlobOrSkip(containerName, blobName, () => Maybe<T>.Empty, t => update(t));
}
public Maybe<T> UpdateBlobIfExistOrSkip<T>(string containerName, string blobName, Func<T, Maybe<T>> update)
{
return UpsertBlobOrSkip(containerName, blobName, () => Maybe<T>.Empty, update);
}
public Maybe<T> UpdateBlobIfExistOrDelete<T>(string containerName, string blobName, Func<T, Maybe<T>> update)
{
var result = UpsertBlobOrSkip(containerName, blobName, () => Maybe<T>.Empty, update);
if (!result.HasValue)
{
DeleteBlobIfExist(containerName, blobName);
}
return result;
}
public T UpsertBlob<T>(string containerName, string blobName, Func<T> insert, Func<T, T> update)
{
return UpsertBlobOrSkip<T>(containerName, blobName, () => insert(), t => update(t)).Value;
}
public Maybe<T> UpsertBlobOrSkip<T>(
string containerName, string blobName, Func<Maybe<T>> insert, Func<T, Maybe<T>> update)
{
lock (_syncRoot)
{
Maybe<T> input;
if (Containers.ContainsKey(containerName))
{
if (Containers[containerName].BlobNames.Contains(blobName))
{
var blobData = Containers[containerName].GetBlob(blobName);
input = blobData == null ? Maybe<T>.Empty : (T)blobData;
}
else
{
input = Maybe<T>.Empty;
}
}
else
{
Containers.Add(containerName, new MockContainer());
input = Maybe<T>.Empty;
}
var output = input.HasValue ? update(input.Value) : insert();
if (output.HasValue)
{
Containers[containerName].SetBlob(blobName, output.Value);
}
return output;
}
}
public Maybe<T> UpsertBlobOrDelete<T>(
string containerName, string blobName, Func<Maybe<T>> insert, Func<T, Maybe<T>> update)
{
var result = UpsertBlobOrSkip(containerName, blobName, insert, update);
if (!result.HasValue)
{
DeleteBlobIfExist(containerName, blobName);
}
return result;
}
class MockContainer
{
readonly Dictionary<string, object> _blobSet;
readonly Dictionary<string, string> _blobsEtag;
readonly Dictionary<string, string> _blobsLeases;
public string[] BlobNames { get { return _blobSet.Keys.ToArray(); } }
public Dictionary<string, string> BlobsEtag { get { return _blobsEtag; } }
public Dictionary<string, string> BlobsLeases { get { return _blobsLeases; } }
public MockContainer()
{
_blobSet = new Dictionary<string, object>();
_blobsEtag = new Dictionary<string, string>();
_blobsLeases = new Dictionary<string, string>();
}
public void SetBlob(string blobName, object item)
{
_blobSet[blobName] = item;
_blobsEtag[blobName] = Guid.NewGuid().ToString();
}
public object GetBlob(string blobName)
{
return _blobSet[blobName];
}
public void AddBlob(string blobName, object item)
{
_blobSet.Add(blobName, item);
_blobsEtag.Add(blobName, Guid.NewGuid().ToString());
}
public void RemoveBlob(string blobName)
{
_blobSet.Remove(blobName);
_blobsEtag.Remove(blobName);
_blobsLeases.Remove(blobName);
}
}
public Result<string> TryAcquireLease(string containerName, string blobName)
{
lock (_syncRoot)
{
if (!Containers[containerName].BlobsLeases.ContainsKey(blobName))
{
var leaseId = Guid.NewGuid().ToString("N");
Containers[containerName].BlobsLeases[blobName] = leaseId;
return Result.CreateSuccess(leaseId);
}
return Result<string>.CreateError("Conflict");
}
}
public bool TryReleaseLease(string containerName, string blobName, string leaseId)
{
lock (_syncRoot)
{
string actualLeaseId;
if (Containers[containerName].BlobsLeases.TryGetValue(blobName, out actualLeaseId) && actualLeaseId == leaseId)
{
Containers[containerName].BlobsLeases.Remove(blobName);
return true;
}
return false;
}
}
public bool TryRenewLease(string containerName, string blobName, string leaseId)
{
lock (_syncRoot)
{
string actualLeaseId;
return Containers[containerName].BlobsLeases.TryGetValue(blobName, out actualLeaseId)
&& actualLeaseId == leaseId;
}
}
}
}
| zyyin2005-lokad | Source/Lokad.Cloud.Storage/InMemory/MemoryBlobStorageProvider.cs | C# | bsd | 17,108 |
#region Copyright (c) Lokad 2009-2011
// This code is released under the terms of the new BSD licence.
// URL: http://www.lokad.com/
#endregion
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Lokad.Cloud.Storage.Shared;
using Tu = System.Tuple<string, object, System.Collections.Generic.List<byte[]>>;
namespace Lokad.Cloud.Storage.InMemory
{
/// <summary>Mock in-memory Queue Storage.</summary>
public class MemoryQueueStorageProvider : IQueueStorageProvider
{
/// <summary>Root used to synchronize accesses to <c>_inprocess</c>.</summary>
private readonly object _sync = new object();
private readonly Dictionary<string, Queue<byte[]>> _queues;
private readonly Dictionary<object, Tu> _inProcessMessages;
private readonly HashSet<System.Tuple<string, string, string, byte[]>> _persistedMessages;
internal IDataSerializer DataSerializer { get; set; }
/// <summary>Default constructor.</summary>
public MemoryQueueStorageProvider()
{
_queues = new Dictionary<string, Queue<byte[]>>();
_inProcessMessages = new Dictionary<object, Tu>();
_persistedMessages = new HashSet<System.Tuple<string, string, string, byte[]>>();
DataSerializer = new CloudFormatter();
}
public IEnumerable<string> List(string prefix)
{
return _queues.Keys.Where(e => e.StartsWith(prefix));
}
public IEnumerable<T> Get<T>(string queueName, int count, TimeSpan visibilityTimeout, int maxProcessingTrials)
{
lock (_sync)
{
var items = new List<T>(count);
for (int i = 0; i < count; i++)
{
if (_queues.ContainsKey(queueName) && _queues[queueName].Any())
{
var messageBytes = _queues[queueName].Dequeue();
object message;
using (var stream = new MemoryStream(messageBytes))
{
message = DataSerializer.Deserialize(stream, typeof (T));
}
Tu inProcess;
if (!_inProcessMessages.TryGetValue(message, out inProcess))
{
inProcess = new Tu(queueName, message, new List<byte[]>());
_inProcessMessages.Add(message, inProcess);
}
inProcess.Item3.Add(messageBytes);
items.Add((T)message);
}
}
return items;
}
}
public void Put<T>(string queueName, T message)
{
lock (_sync)
{
byte[] messageBytes;
using (var stream = new MemoryStream())
{
DataSerializer.Serialize(message, stream);
messageBytes = stream.ToArray();
}
if (!_queues.ContainsKey(queueName))
{
_queues.Add(queueName, new Queue<byte[]>());
}
_queues[queueName].Enqueue(messageBytes);
}
}
public void PutRange<T>(string queueName, IEnumerable<T> messages)
{
lock (_sync)
{
foreach(var message in messages)
{
Put(queueName, message);
}
}
}
public void Clear(string queueName)
{
lock (_sync)
{
_queues[queueName].Clear();
var toDelete = _inProcessMessages.Where(pair => pair.Value.Item1 == queueName).ToList();
foreach(var pair in toDelete)
{
_inProcessMessages.Remove(pair.Key);
}
}
}
public bool Delete<T>(T message)
{
lock (_sync)
{
Tu inProcess;
if (!_inProcessMessages.TryGetValue(message, out inProcess))
{
return false;
}
inProcess.Item3.RemoveAt(0);
if (inProcess.Item3.Count == 0)
{
_inProcessMessages.Remove(inProcess.Item2);
}
return true;
}
}
public int DeleteRange<T>(IEnumerable<T> messages)
{
lock (_sync)
{
return messages.Where(Delete).Count();
}
}
public bool Abandon<T>(T message)
{
lock (_sync)
{
Tu inProcess;
if (!_inProcessMessages.TryGetValue(message, out inProcess))
{
return false;
}
// Add back to queue
if (!_queues.ContainsKey(inProcess.Item1))
{
_queues.Add(inProcess.Item1, new Queue<byte[]>());
}
_queues[inProcess.Item1].Enqueue(inProcess.Item3[0]);
// Remove from invisible queue
inProcess.Item3.RemoveAt(0);
if (inProcess.Item3.Count == 0)
{
_inProcessMessages.Remove(inProcess.Item2);
}
return true;
}
}
public int AbandonRange<T>(IEnumerable<T> messages)
{
lock (_sync)
{
return messages.Count(Abandon);
}
}
public bool ResumeLater<T>(T message)
{
// same as abandon as the InMemory provider applies no poison detection
return Abandon(message);
}
public int ResumeLaterRange<T>(IEnumerable<T> messages)
{
// same as abandon as the InMemory provider applies no poison detection
return AbandonRange(messages);
}
public void Persist<T>(T message, string storeName, string reason)
{
lock (_sync)
{
Tu inProcess;
if (!_inProcessMessages.TryGetValue(message, out inProcess))
{
return;
}
// persist
var key = Guid.NewGuid().ToString("N");
_persistedMessages.Add(System.Tuple.Create(storeName, key, inProcess.Item1, inProcess.Item3[0]));
// Remove from invisible queue
inProcess.Item3.RemoveAt(0);
if (inProcess.Item3.Count == 0)
{
_inProcessMessages.Remove(inProcess.Item2);
}
}
}
public void PersistRange<T>(IEnumerable<T> messages, string storeName, string reason)
{
lock (_sync)
{
foreach(var message in messages)
{
Persist(message, storeName, reason);
}
}
}
public IEnumerable<string> ListPersisted(string storeName)
{
lock (_sync)
{
return _persistedMessages
.Where(x => x.Item1 == storeName)
.Select(x => x.Item2)
.ToArray();
}
}
public Maybe<PersistedMessage> GetPersisted(string storeName, string key)
{
var intermediateDataSerializer = DataSerializer as IIntermediateDataSerializer;
var xmlProvider = intermediateDataSerializer != null
? new Maybe<IIntermediateDataSerializer>(intermediateDataSerializer)
: Maybe<IIntermediateDataSerializer>.Empty;
lock (_sync)
{
var tuple = _persistedMessages.FirstOrDefault(x => x.Item1 == storeName && x.Item2 == key);
if(null != tuple)
{
return new PersistedMessage
{
QueueName = tuple.Item3,
StoreName = tuple.Item1,
Key = tuple.Item2,
IsDataAvailable = true,
DataXml = xmlProvider.Convert(s => s.UnpackXml(new MemoryStream(tuple.Item4)))
};
}
return Maybe<PersistedMessage>.Empty;
}
}
public void DeletePersisted(string storeName, string key)
{
lock (_sync)
{
_persistedMessages.RemoveWhere(x => x.Item1 == storeName && x.Item2 == key);
}
}
public void RestorePersisted(string storeName, string key)
{
lock (_sync)
{
var item = _persistedMessages.First(x => x.Item1 == storeName && x.Item2 == key);
_persistedMessages.Remove(item);
if (!_queues.ContainsKey(item.Item3))
{
_queues.Add(item.Item3, new Queue<byte[]>());
}
_queues[item.Item3].Enqueue(item.Item4);
}
}
public bool DeleteQueue(string queueName)
{
lock (_sync)
{
if (!_queues.ContainsKey(queueName))
{
return false;
}
_queues.Remove(queueName);
var toDelete = _inProcessMessages.Where(pair => pair.Value.Item1 == queueName).ToList();
foreach (var pair in toDelete)
{
_inProcessMessages.Remove(pair.Key);
}
return true;
}
}
public int GetApproximateCount(string queueName)
{
lock (_sync)
{
Queue<byte[]> queue;
return _queues.TryGetValue(queueName, out queue)
? queue.Count : 0;
}
}
public Maybe<TimeSpan> GetApproximateLatency(string queueName)
{
return Maybe<TimeSpan>.Empty;
}
}
}
| zyyin2005-lokad | Source/Lokad.Cloud.Storage/InMemory/MemoryQueueStorageProvider.cs | C# | bsd | 10,697 |
#region Copyright (c) Lokad 2010-2011
// This code is released under the terms of the new BSD licence.
// URL: http://www.lokad.com/
#endregion
using System;
using System.IO;
using System.Runtime.Serialization;
using System.Xml.Linq;
using Lokad.Cloud.Storage.Shared;
namespace Lokad.Cloud.Storage
{
internal static class DataSerializerExtensions
{
public static Result<T, Exception> TryDeserializeAs<T>(this IDataSerializer serializer, Stream source)
{
var position = source.Position;
try
{
var result = serializer.Deserialize(source, typeof(T));
if (result == null)
{
return Result<T, Exception>.CreateError(new SerializationException("Serializer returned null"));
}
if (!(result is T))
{
return Result<T, Exception>.CreateError(new InvalidCastException(
String.Format("Source was expected to be of type {0} but was of type {1}.",
typeof (T).Name,
result.GetType().Name)));
}
return Result<T, Exception>.CreateSuccess((T)result);
}
catch (Exception e)
{
return Result<T, Exception>.CreateError(e);
}
finally
{
source.Position = position;
}
}
public static Result<object, Exception> TryDeserialize(this IDataSerializer serializer, Stream source, Type type)
{
var position = source.Position;
try
{
var result = serializer.Deserialize(source, type);
if (result == null)
{
return Result<object, Exception>.CreateError(new SerializationException("Serializer returned null"));
}
var actualType = result.GetType();
if (!type.IsAssignableFrom(actualType))
{
return Result<object, Exception>.CreateError(new InvalidCastException(
String.Format("Source was expected to be of type {0} but was of type {1}.",
type.Name,
actualType.Name)));
}
return Result<object, Exception>.CreateSuccess(result);
}
catch (Exception e)
{
return Result<object, Exception>.CreateError(e);
}
finally
{
source.Position = position;
}
}
public static Result<T, Exception> TryDeserializeAs<T>(this IDataSerializer serializer, byte[] source)
{
using (var stream = new MemoryStream(source))
{
return TryDeserializeAs<T>(serializer, stream);
}
}
public static Result<XElement, Exception> TryUnpackXml(this IIntermediateDataSerializer serializer, Stream source)
{
var position = source.Position;
try
{
var result = serializer.UnpackXml(source);
if (result == null)
{
return Result<XElement, Exception>.CreateError(new SerializationException("Serializer returned null"));
}
return Result<XElement, Exception>.CreateSuccess(result);
}
catch (Exception e)
{
return Result<XElement, Exception>.CreateError(e);
}
finally
{
source.Position = position;
}
}
}
}
| zyyin2005-lokad | Source/Lokad.Cloud.Storage/DataSerializerExtensions.cs | C# | bsd | 3,868 |
#region Copyright (c) Lokad 2009-2011
// This code is released under the terms of the new BSD licence.
// URL: http://www.lokad.com/
#endregion
using System;
using System.IO.Compression;
using System.Reflection;
using System.Runtime.Serialization;
using System.IO;
using System.Linq;
using System.Xml;
using System.Xml.Linq;
namespace Lokad.Cloud.Storage
{
/// <summary>
/// Formatter based on <c>DataContractSerializer</c> and <c>NetDataContractSerializer</c>.
/// The formatter targets storage of persistent or transient data in the cloud storage.
/// </summary>
/// <remarks>
/// If a <c>DataContract</c> attribute is present, then the <c>DataContractSerializer</c>
/// is favored. If not, then the <c>NetDataContractSerializer</c> is used instead.
/// This class is not <b>thread-safe</b>.
/// </remarks>
public class CloudFormatter : IIntermediateDataSerializer
{
XmlObjectSerializer GetXmlSerializer(Type type)
{
// 'false' == do not inherit the attribute
if (GetAttributes<DataContractAttribute>(type, false).Length > 0)
{
return new DataContractSerializer(type);
}
return new NetDataContractSerializer();
}
public void Serialize(object instance, Stream destination)
{
var serializer = GetXmlSerializer(instance.GetType());
using(var compressed = Compress(destination, true))
using(var writer = XmlDictionaryWriter.CreateBinaryWriter(compressed, null, null, false))
{
serializer.WriteObject(writer, instance);
}
}
public object Deserialize(Stream source, Type type)
{
var serializer = GetXmlSerializer(type);
using(var decompressed = Decompress(source, true))
using(var reader = XmlDictionaryReader.CreateBinaryReader(decompressed, XmlDictionaryReaderQuotas.Max))
{
return serializer.ReadObject(reader);
}
}
public XElement UnpackXml(Stream source)
{
using(var decompressed = Decompress(source, true))
using (var reader = XmlDictionaryReader.CreateBinaryReader(decompressed, XmlDictionaryReaderQuotas.Max))
{
return XElement.Load(reader);
}
}
public void RepackXml(XElement data, Stream destination)
{
using(var compressed = Compress(destination, true))
using(var writer = XmlDictionaryWriter.CreateBinaryWriter(compressed, null, null, false))
{
data.Save(writer);
writer.Flush();
compressed.Flush();
}
}
static GZipStream Compress(Stream stream, bool leaveOpen)
{
return new GZipStream(stream, CompressionMode.Compress, leaveOpen);
}
static GZipStream Decompress(Stream stream, bool leaveOpen)
{
return new GZipStream(stream, CompressionMode.Decompress, leaveOpen);
}
///<summary>Retrieve attributes from the type.</summary>
///<param name="target">Type to perform operation upon</param>
///<param name="inherit"><see cref="MemberInfo.GetCustomAttributes(Type,bool)"/></param>
///<typeparam name="T">Attribute to use</typeparam>
///<returns>Empty array of <typeparamref name="T"/> if there are no attributes</returns>
static T[] GetAttributes<T>(ICustomAttributeProvider target, bool inherit) where T : Attribute
{
if (target.IsDefined(typeof(T), inherit))
{
return target
.GetCustomAttributes(typeof(T), inherit)
.Select(a => (T)a).ToArray();
}
return new T[0];
}
}
} | zyyin2005-lokad | Source/Lokad.Cloud.Storage/CloudFormatter.cs | C# | bsd | 3,994 |
#region Copyright (c) Lokad 2010
// This code is released under the terms of the new BSD licence.
// URL: http://www.lokad.com/
#endregion
using System;
namespace Lokad.Cloud
{
/// <summary>Collects objects that absolutely need to be disposed
/// before the runtime gets shut down.</summary>
/// <remarks>
/// There is no garanty that registered objects will actually be disposed.
/// When a VM is shutdown, a small grace period (30s) is offered to clean-up
/// resources before the OS itself is aborted. The runtime finalizer
/// should be kept for very critical clean-ups to be performed during the
/// grace period.
///
/// Typically, the runtime finalizer is used to abandon in-process queue
/// messages and lease on blobs. Any extra object that you register here
/// is likely to negatively impact more prioritary clean-ups. Use with care.
///
/// Implementations must be thread-safe.
/// </remarks>
public interface IRuntimeFinalizer
{
/// <summary>Register a object for high priority finalization if runtime is terminating.</summary>
/// <remarks>The method is idempotent, once an object is registered,
/// registering the object again has no effect.</remarks>
void Register(IDisposable obj);
/// <summary>Unregister a object from high priority finalization.</summary>
/// <remarks>The method is idempotent, once an object is unregistered,
/// unregistering the object again has no effect.</remarks>
void Unregister(IDisposable obj);
/// <summary>
/// Finalize high-priority resources hold by the runtime. This method
/// should only be called ONCE upon runtime finalization.
/// </summary>
void FinalizeRuntime();
}
} | zyyin2005-lokad | Source/Lokad.Cloud.Storage/IRuntimeFinalizer.cs | C# | bsd | 1,851 |
#region Copyright (c) Lokad 2009-2011
// This code is released under the terms of the new BSD licence.
// URL: http://www.lokad.com/
#endregion
namespace Lokad.Cloud.Storage
{
public class CloudStorageProviders
{
/// <summary>Abstracts the Blob Storage.</summary>
public IBlobStorageProvider BlobStorage { get; private set; }
/// <summary>Abstracts the Queue Storage.</summary>
public IQueueStorageProvider QueueStorage { get; private set; }
/// <summary>Abstracts the Table Storage.</summary>
public ITableStorageProvider TableStorage { get; private set; }
/// <summary>Abstracts the finalizer (used for fast resource release
/// in case of runtime shutdown).</summary>
public IRuntimeFinalizer RuntimeFinalizer { get; private set; }
public Shared.Logging.ILog Log { get; private set; }
/// <summary>IoC constructor.</summary>
public CloudStorageProviders(
IBlobStorageProvider blobStorage,
IQueueStorageProvider queueStorage,
ITableStorageProvider tableStorage,
IRuntimeFinalizer runtimeFinalizer,
Shared.Logging.ILog log)
{
BlobStorage = blobStorage;
QueueStorage = queueStorage;
TableStorage = tableStorage;
RuntimeFinalizer = runtimeFinalizer;
Log = log;
}
/// <summary>Copy constructor.</summary>
protected CloudStorageProviders(
CloudStorageProviders copyFrom)
{
BlobStorage = copyFrom.BlobStorage;
QueueStorage = copyFrom.QueueStorage;
TableStorage = copyFrom.TableStorage;
RuntimeFinalizer = copyFrom.RuntimeFinalizer;
Log = copyFrom.Log;
}
}
}
| zyyin2005-lokad | Source/Lokad.Cloud.Storage/CloudStorageProviders.cs | C# | bsd | 1,863 |
#region Copyright (c) Lokad 2009-2010
// This code is released under the terms of the new BSD licence.
// URL: http://www.lokad.com/
#endregion
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Lokad.Cloud.Storage")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyCopyright("Copyright © Lokad 2010")]
[assembly: AssemblyTrademark("")]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("f1c9ee22-a41c-47ce-8d7e-bcacd3954986")]
[assembly: InternalsVisibleTo("Lokad.Cloud.Framework.Test")] | zyyin2005-lokad | Source/Lokad.Cloud.Storage/Properties/AssemblyInfo.cs | C# | bsd | 839 |
#region Copyright (c) Lokad 2009-2010
// This code is released under the terms of the new BSD licence.
// URL: http://www.lokad.com/
#endregion
using System;
using System.Runtime.Serialization;
namespace Lokad.Cloud.Storage
{
/// <summary>
/// Base class for strongly typed hierarchical references to blobs of a
/// strongly typed content.
/// </summary>
/// <typeparam name="T">Type contained in the blob.</typeparam>
/// <remarks>
/// The type <c>T</c> is handy to strengthen the
/// <see cref="StorageExtensions"/>.
/// </remarks>
[Serializable, DataContract]
public abstract class BlobName<T> : UntypedBlobName
{
}
} | zyyin2005-lokad | Source/Lokad.Cloud.Storage/Blobs/BlobName.cs | C# | bsd | 701 |
#region Copyright (c) Lokad 2009-2011
// This code is released under the terms of the new BSD licence.
// URL: http://www.lokad.com/
#endregion
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
// ReSharper disable UnusedMember.Global
// ReSharper disable UnusedMethodReturnValue.Global
namespace Lokad.Cloud.Storage
{
/// <summary>Helpers for the <see cref="IBlobStorageProvider"/>.</summary>
public static class BlobStorageExtensions
{
/// <summary>
/// List the blob names of all blobs matching the provided blob name prefix.
/// </summary>
/// <remarks>
/// <para>This method is sideeffect-free, except for infrastructure effects like thread pool usage.</para>
/// </remarks>
public static IEnumerable<T> ListBlobNames<T>(this IBlobStorageProvider provider, T blobNamePrefix) where T : UntypedBlobName
{
return provider.ListBlobNames(blobNamePrefix.ContainerName, blobNamePrefix.ToString())
.Select(UntypedBlobName.Parse<T>);
}
/// <summary>
/// List and get all blobs matching the provided blob name prefix.
/// </summary>
/// <remarks>
/// <para>This method is sideeffect-free, except for infrastructure effects like thread pool usage.</para>
/// </remarks>
public static IEnumerable<T> ListBlobs<T>(this IBlobStorageProvider provider, BlobName<T> blobNamePrefix, int skip = 0)
{
return provider.ListBlobs<T>(blobNamePrefix.ContainerName, blobNamePrefix.ToString(), skip);
}
/// <summary>
/// Deletes a blob if it exists.
/// </summary>
/// <remarks>
/// <para>This method is idempotent.</para>
/// </remarks>
public static bool DeleteBlobIfExist<T>(this IBlobStorageProvider provider, BlobName<T> fullName)
{
return provider.DeleteBlobIfExist(fullName.ContainerName, fullName.ToString());
}
/// <summary>
/// Delete all blobs matching the provided blob name prefix.
/// </summary>
/// <remarks>
/// <para>This method is idempotent.</para>
/// </remarks>
public static void DeleteAllBlobs(this IBlobStorageProvider provider, UntypedBlobName blobNamePrefix)
{
provider.DeleteAllBlobs(blobNamePrefix.ContainerName, blobNamePrefix.ToString());
}
public static Maybe<T> GetBlob<T>(this IBlobStorageProvider provider, BlobName<T> name)
{
return provider.GetBlob<T>(name.ContainerName, name.ToString());
}
public static Maybe<T> GetBlob<T>(this IBlobStorageProvider provider, BlobName<T> name, out string etag)
{
return provider.GetBlob<T>(name.ContainerName, name.ToString(), out etag);
}
public static string GetBlobEtag<T>(this IBlobStorageProvider provider, BlobName<T> name)
{
return provider.GetBlobEtag(name.ContainerName, name.ToString());
}
public static void PutBlob<T>(this IBlobStorageProvider provider, BlobName<T> name, T item)
{
provider.PutBlob(name.ContainerName, name.ToString(), item);
}
public static bool PutBlob<T>(this IBlobStorageProvider provider, BlobName<T> name, T item, bool overwrite)
{
return provider.PutBlob(name.ContainerName, name.ToString(), item, overwrite);
}
/// <summary>Push the blob only if etag is matching the etag of the blob in BlobStorage</summary>
public static bool PutBlob<T>(this IBlobStorageProvider provider, BlobName<T> name, T item, string etag)
{
return provider.PutBlob(name.ContainerName, name.ToString(), item, etag);
}
/// <summary>
/// Updates a blob if it already exists.
/// </summary>
/// <remarks>
/// <para>
/// The provided lambdas can be executed multiple times in case of
/// concurrency-related retrials, so be careful with side-effects
/// (like incrementing a counter in them).
/// </para>
/// <para>This method is idempotent if and only if the provided lambdas are idempotent.</para>
/// </remarks>
/// <returns>The value returned by the lambda, or empty if the blob did not exist.</returns>
public static Maybe<T> UpdateBlobIfExist<T>(this IBlobStorageProvider provider, BlobName<T> name, Func<T, T> update)
{
return provider.UpsertBlobOrSkip(name.ContainerName, name.ToString(), () => Maybe<T>.Empty, t => update(t));
}
/// <summary>
/// Updates a blob if it already exists.
/// If the insert or update lambdas return empty, the blob will not be changed.
/// </summary>
/// <remarks>
/// <para>
/// The provided lambdas can be executed multiple times in case of
/// concurrency-related retrials, so be careful with side-effects
/// (like incrementing a counter in them).
/// </para>
/// <para>This method is idempotent if and only if the provided lambdas are idempotent.</para>
/// </remarks>
/// <returns>The value returned by the lambda, or empty if the blob did not exist or no change was applied.</returns>
public static Maybe<T> UpdateBlobIfExistOrSkip<T>(
this IBlobStorageProvider provider, BlobName<T> name, Func<T, Maybe<T>> update)
{
return provider.UpsertBlobOrSkip(name.ContainerName, name.ToString(), () => Maybe<T>.Empty, update);
}
/// <summary>
/// Updates a blob if it already exists.
/// If the insert or update lambdas return empty, the blob will be deleted.
/// </summary>
/// <remarks>
/// <para>
/// The provided lambdas can be executed multiple times in case of
/// concurrency-related retrials, so be careful with side-effects
/// (like incrementing a counter in them).
/// </para>
/// <para>This method is idempotent if and only if the provided lambdas are idempotent.</para>
/// </remarks>
/// <returns>The value returned by the lambda, or empty if the blob did not exist or was deleted.</returns>
public static Maybe<T> UpdateBlobIfExistOrDelete<T>(
this IBlobStorageProvider provider, BlobName<T> name, Func<T, Maybe<T>> update)
{
return provider.UpdateBlobIfExistOrDelete(name.ContainerName, name.ToString(), update);
}
/// <summary>
/// Inserts or updates a blob depending on whether it already exists or not.
/// </summary>
/// <remarks>
/// <para>
/// The provided lambdas can be executed multiple times in case of
/// concurrency-related retrials, so be careful with side-effects
/// (like incrementing a counter in them).
/// </para>
/// <para>
/// This method is idempotent if and only if the provided lambdas are idempotent
/// and if the object returned by the insert lambda is an invariant to the update lambda
/// (if the second condition is not met, it is idempotent after the first successful call).
/// </para>
/// </remarks>
/// <returns>The value returned by the lambda.</returns>
public static T UpsertBlob<T>(this IBlobStorageProvider provider, BlobName<T> name, Func<T> insert, Func<T, T> update)
{
return provider.UpsertBlobOrSkip<T>(name.ContainerName, name.ToString(), () => insert(), t => update(t)).Value;
}
/// <summary>
/// Inserts or updates a blob depending on whether it already exists or not.
/// If the insert or update lambdas return empty, the blob will not be changed.
/// </summary>
/// <remarks>
/// <para>
/// The provided lambdas can be executed multiple times in case of
/// concurrency-related retrials, so be careful with side-effects
/// (like incrementing a counter in them).
/// </para>
/// <para>
/// This method is idempotent if and only if the provided lambdas are idempotent
/// and if the object returned by the insert lambda is an invariant to the update lambda
/// (if the second condition is not met, it is idempotent after the first successful call).
/// </para>
/// </remarks>
/// <returns>The value returned by the lambda. If empty, then no change was applied.</returns>
public static Maybe<T> UpsertBlobOrSkip<T>(this IBlobStorageProvider provider,
BlobName<T> name, Func<Maybe<T>> insert, Func<T, Maybe<T>> update)
{
return provider.UpsertBlobOrSkip(name.ContainerName, name.ToString(), insert, update);
}
/// <summary>
/// Inserts or updates a blob depending on whether it already exists or not.
/// If the insert or update lambdas return empty, the blob will be deleted (if it exists).
/// </summary>
/// <remarks>
/// <para>
/// The provided lambdas can be executed multiple times in case of
/// concurrency-related retrials, so be careful with side-effects
/// (like incrementing a counter in them).
/// </para>
/// <para>
/// This method is idempotent if and only if the provided lambdas are idempotent
/// and if the object returned by the insert lambda is an invariant to the update lambda
/// (if the second condition is not met, it is idempotent after the first successful call).
/// </para>
/// </remarks>
/// <returns>The value returned by the lambda. If empty, then the blob has been deleted.</returns>
public static Maybe<T> UpsertBlobOrDelete<T>(
this IBlobStorageProvider provider, BlobName<T> name, Func<Maybe<T>> insert, Func<T, Maybe<T>> update)
{
return provider.UpsertBlobOrDelete(name.ContainerName, name.ToString(), insert, update);
}
/// <summary>Checks that containerName is a valid DNS name, as requested by Azure</summary>
public static bool IsContainerNameValid(string containerName)
{
return (Regex.IsMatch(containerName, @"(^([a-z]|\d))((-([a-z]|\d)|([a-z]|\d))+)$")
&& (3 <= containerName.Length) && (containerName.Length <= 63));
}
}
}
| zyyin2005-lokad | Source/Lokad.Cloud.Storage/Blobs/BlobStorageExtensions.cs | C# | bsd | 10,748 |
#region Copyright (c) Lokad 2009-2011
// This code is released under the terms of the new BSD licence.
// URL: http://www.lokad.com/
#endregion
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Reflection;
using System.Runtime.Serialization;
using System.Text;
namespace Lokad.Cloud.Storage
{
/// <summary>
/// Base class for untyped hierarchical blob names. Implementations should
/// not inherit <see cref="UntypedBlobName"/>c> but <see cref="BlobName{T}"/> instead.
/// </summary>
[Serializable, DataContract]
public abstract class UntypedBlobName
{
class InheritanceComparer : IComparer<Type>
{
public int Compare(Type x, Type y)
{
if (x.Equals(y)) return 0;
return x.IsSubclassOf(y) ? 1 : -1;
}
}
/// <summary>Sortable pattern for date times.</summary>
/// <remarks>Hyphens can be eventually used to refine further the iteration.</remarks>
public const string DateFormatInBlobName = "yyyy-MM-dd-HH-mm-ss";
static readonly Dictionary<Type, Func<string, object>> Parsers = new Dictionary<Type, Func<string, object>>();
static readonly Dictionary<Type, Func<object, string>> Printers = new Dictionary<Type, Func<object, string>>();
/// <summary>Name of the container (to be used as a short-hand while
/// operating with the <see cref="IBlobStorageProvider"/>).</summary>
/// <remarks>Do not introduce an extra field for the property as
/// it would be incorporated in the blob name. Instead, just
/// return a constant string.</remarks>
public abstract string ContainerName { get; }
static UntypedBlobName()
{
// adding overrides
// Guid: does not have default converter
Printers.Add(typeof(Guid), o => ((Guid)o).ToString("N"));
Parsers.Add(typeof(Guid), s => new Guid(s));
// DateTime: sortable ascending;
// NOTE: not time zone safe, users have to deal with that temselves
Printers.Add(typeof(DateTime),
o => ((DateTime)o).ToString(DateFormatInBlobName, CultureInfo.InvariantCulture));
Parsers.Add(typeof(DateTime),
s => DateTime.ParseExact(s, DateFormatInBlobName, CultureInfo.InvariantCulture));
// DateTimeOffset: sortable ascending;
// time zone safe, but always returned with UTC/zero offset (comparisons can deal with that)
Printers.Add(typeof(DateTimeOffset),
o => ((DateTimeOffset)o).UtcDateTime.ToString(DateFormatInBlobName, CultureInfo.InvariantCulture));
Parsers.Add(typeof(DateTimeOffset),
s => new DateTimeOffset(DateTime.SpecifyKind(DateTime.ParseExact(s, DateFormatInBlobName, CultureInfo.InvariantCulture), DateTimeKind.Utc)));
}
public override string ToString()
{
// Invoke a Static Generic Method using Reflection
// because type is programmatically defined
var method = typeof(UntypedBlobName).GetMethod("Print", BindingFlags.Static | BindingFlags.Public);
// Binding the method info to generic arguments
method = method.MakeGenericMethod(new[] { GetType() });
// Invoking the method and passing parameters
// The null parameter is the object to call the method from. Since the method is static, pass null.
return (string)method.Invoke(null, new object[] { this });
}
static object InternalParse(string value, Type type)
{
var func = GetValue(Parsers, type, s => Convert.ChangeType(s, type));
return func(value);
}
static string InternalPrint(object value, Type type)
{
var func = GetValue(Printers, type, o => o.ToString());
return func(value);
}
/// <summary>Returns <paramref name="defaultValue"/> if the given <paramref name="key"/>
/// is not present within the dictionary.</summary>
/// <typeparam name="TKey">The type of the key.</typeparam>
/// <typeparam name="TValue">The type of the value.</typeparam>
/// <param name="self">The dictionary.</param>
/// <param name="key">The key to look for.</param>
/// <param name="defaultValue">The default value.</param>
/// <returns>value matching <paramref name="key"/> or <paramref name="defaultValue"/> if none is found</returns>
static TValue GetValue<TKey, TValue>(IDictionary<TKey, TValue> self, TKey key, TValue defaultValue)
{
TValue value;
if (self.TryGetValue(key, out value))
{
return value;
}
return defaultValue;
}
class ConverterTypeCache<T>
{
static readonly MemberInfo[] Members; // either 'FieldInfo' or 'PropertyInfo'
static readonly bool[] TreatDefaultAsNull;
const string Delimeter = "/";
static readonly ConstructorInfo FirstCtor;
static ConverterTypeCache()
{
// HACK: optimize this to IL code, if needed
// NB: this approach could be used to generate F# style objects!
Members =
(typeof(T).GetFields().Select(f => (MemberInfo)f).Union(typeof(T).GetProperties()))
.Where(f => f.GetCustomAttributes(typeof(RankAttribute), true).Any())
// ordering always respect inheritance
.GroupBy(f => f.DeclaringType)
.OrderBy(g => g.Key, new InheritanceComparer())
.Select(g =>
g.OrderBy(f => ((RankAttribute)f.GetCustomAttributes(typeof(RankAttribute), true).First()).Index))
.SelectMany(f => f)
.ToArray();
TreatDefaultAsNull = Members.Select(m =>
((RankAttribute) (m.GetCustomAttributes(typeof (RankAttribute), true).First())).TreatDefaultAsNull).ToArray();
FirstCtor = typeof(T).GetConstructors(
BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance).First();
}
public static string Print(T instance)
{
var sb = new StringBuilder();
for (int i = 0; i < Members.Length; i++)
{
var info = Members[i];
var fieldInfo = info as FieldInfo;
var propInfo = info as PropertyInfo;
var memberType = (null != fieldInfo) ? fieldInfo.FieldType : propInfo.PropertyType;
var value = (null != fieldInfo) ? fieldInfo.GetValue(instance) : propInfo.GetValue(instance, new object[0]);
if(null == value || (TreatDefaultAsNull[i] && IsDefaultValue(value, memberType)))
{
// Delimiter has to be appended here to avoid enumerating
// too many blog (names being prefix of each other).
//
// For example, without delimiter, the prefix 'foo/123' whould enumerate both
// foo/123/bar
// foo/1234/bar
//
// Then, we should not append a delimiter if prefix is entirely empty
// because it would not properly enumerate all blobs (semantic associated with
// empty prefix).
if (i > 0) sb.Append(Delimeter);
break;
}
var s = InternalPrint(value, memberType);
if (i > 0) sb.Append(Delimeter);
sb.Append(s);
}
return sb.ToString();
}
private static bool IsDefaultValue(object value, Type type)
{
if (type == typeof(string))
{
return String.IsNullOrEmpty((string)value);
}
if (type.IsValueType)
{
return Activator.CreateInstance(type).Equals(value);
}
return value == null;
}
public static T Parse(string value)
{
if (string.IsNullOrEmpty(value))
{
throw new ArgumentNullException("value");
}
var split = value.Split(new[] { Delimeter }, StringSplitOptions.RemoveEmptyEntries);
// In order to support parsing blob names also to blob name supper classes
// in case of inheritance, we simply ignore supplementary items in the name
if (split.Length < Members.Length)
{
throw new ArgumentException("Number of items in the string is invalid. Are you missing something?", "value");
}
var parameters = new object[Members.Length];
for (int i = 0; i < parameters.Length; i++)
{
var memberType = Members[i] is FieldInfo
? ((FieldInfo) Members[i]).FieldType
: ((PropertyInfo) Members[i]).PropertyType;
parameters[i] = InternalParse(split[i], memberType);
}
// Initialization through reflection (no assumption on constructors)
var name = (T)FormatterServices.GetUninitializedObject(typeof (T));
for (int i = 0; i < Members.Length; i++)
{
if (Members[i] is FieldInfo)
{
((FieldInfo)Members[i]).SetValue(name, parameters[i]);
}
else
{
((PropertyInfo)Members[i]).SetValue(name, parameters[i], new object[0]);
}
}
return name;
}
}
/// <summary>Do not use directly, call <see cref="ToString"/> instead.</summary>
public static string Print<T>(T instance) where T : UntypedBlobName
{
return ConverterTypeCache<T>.Print(instance);
}
/// <summary>Parse a hierarchical blob name.</summary>
public static T Parse<T>(string value) where T : UntypedBlobName
{
return ConverterTypeCache<T>.Parse(value);
}
/// <summary>Returns the <see cref="ContainerName"/> value without
/// having an instance at hand.</summary>
public static string GetContainerName<T>() where T : UntypedBlobName
{
// HACK: that's a heavy way of getting the thing done
return ((T)FormatterServices.GetUninitializedObject(typeof(T))).ContainerName;
}
}
} | zyyin2005-lokad | Source/Lokad.Cloud.Storage/Blobs/UntypedBlobName.cs | C# | bsd | 11,396 |
#region Copyright (c) Lokad 2009-2011
// This code is released under the terms of the new BSD licence.
// URL: http://www.lokad.com/
#endregion
using System;
using System.Runtime.Serialization;
namespace Lokad.Cloud.Storage
{
/// <summary>
/// Reference to a unique blob with a fixed limited lifespan.
/// </summary>
/// <remarks>
/// Used in conjunction with the Gargage Collector service. Use as
/// base class for custom temporary blobs with additional attributes, or use
/// the method
/// <see cref="GetNew(System.DateTimeOffset)"/> to instantiate a new instance
/// directly linked to the garbage collected container.
/// </remarks>
/// <typeparam name="T">Type referred by the blob name.</typeparam>
[Serializable, DataContract]
public class TemporaryBlobName<T> : BlobName<T>
{
public const string DefaultContainerName = "lokad-cloud-temporary";
/// <summary>
/// Returns the garbage collected container.
/// </summary>
public sealed override string ContainerName
{
get { return DefaultContainerName; }
}
[Rank(0), DataMember] public readonly DateTimeOffset Expiration;
[Rank(1), DataMember] public readonly string Suffix;
/// <summary>
/// Explicit constructor.
/// </summary>
/// <param name="expiration">
/// Date that triggers the garbage collection.
/// </param>
/// <param name="suffix">
/// Static suffix (typically used to avoid overlaps between temporary blob name
/// inheritor). If the provided suffix is <c>null</c>then the
/// default prefix <c>GetType().FullName</c> is used instead.
/// </param>
protected TemporaryBlobName(DateTimeOffset expiration, string suffix)
{
Expiration = expiration;
Suffix = suffix ?? GetType().FullName;
}
/// <summary>
/// Gets a full name to a temporary blob.
/// </summary>
public static TemporaryBlobName<T> GetNew(DateTimeOffset expiration)
{
return new TemporaryBlobName<T>(expiration, Guid.NewGuid().ToString("N"));
}
/// <summary>
/// Gets a full name to a temporary blob.
/// </summary>
public static TemporaryBlobName<T> GetNew(DateTimeOffset expiration, string prefix)
{
// hyphen used on purpose, not to interfere with parsing later on.
return new TemporaryBlobName<T>(expiration, prefix + "-" + Guid.NewGuid().ToString("N"));
}
}
} | zyyin2005-lokad | Source/Lokad.Cloud.Storage/Blobs/TemporaryBlobName.cs | C# | bsd | 2,690 |
#region Copyright (c) Lokad 2009-2011
// This code is released under the terms of the new BSD licence.
// URL: http://www.lokad.com/
#endregion
using System;
using System.Collections.Generic;
using System.Xml.Linq;
namespace Lokad.Cloud.Storage
{
/// <summary>Abstraction for the Blob Storage.</summary>
/// <remarks>
/// This provider represents a <em>logical</em> blob storage, not the actual
/// Blob Storage. In particular, this provider deals with overflowing buffers
/// that need to be split in smaller chunks to be uploaded.
/// </remarks>
public interface IBlobStorageProvider
{
/// <summary>
/// List the names of all containers, matching the optional prefix if provided.
/// </summary>
IEnumerable<string> ListContainers(string containerNamePrefix = null);
/// <summary>Creates a new blob container.</summary>
/// <returns><c>true</c> if the container was actually created and <c>false</c> if
/// the container already exists.</returns>
/// <remarks>This operation is idempotent.</remarks>
bool CreateContainerIfNotExist(string containerName);
/// <summary>Delete a container.</summary>
/// <returns><c>true</c> if the container has actually been deleted.</returns>
/// <remarks>This operation is idempotent.</remarks>
bool DeleteContainerIfExist(string containerName);
/// <summary>
/// List the blob names of all blobs matching both the provided container name and the optional blob name prefix.
/// </summary>
/// <remarks>
/// <para>This method is sideeffect-free, except for infrastructure effects like thread pool usage.</para>
/// </remarks>
IEnumerable<string> ListBlobNames(string containerName, string blobNamePrefix = null);
/// <summary>
/// List and get all blobs matching both the provided container name and the optional blob name prefix.
/// </summary>
/// <remarks>
/// <para>This method is sideeffect-free, except for infrastructure effects like thread pool usage.</para>
/// </remarks>
IEnumerable<T> ListBlobs<T>(string containerName, string blobNamePrefix = null, int skip = 0);
/// <summary>
/// Deletes a blob if it exists.
/// </summary>
/// <remarks>
/// <para>This method is idempotent.</para>
/// </remarks>
bool DeleteBlobIfExist(string containerName, string blobName);
/// <summary>
/// Delete all blobs matching the provided blob name prefix.
/// </summary>
/// <remarks>
/// <para>This method is idempotent.</para>
/// </remarks>
void DeleteAllBlobs(string containerName, string blobNamePrefix = null);
/// <summary>Gets a blob.</summary>
/// <returns>
/// If there is no such blob, the returned object
/// has its property HasValue set to <c>false</c>.
/// </returns>
Maybe<T> GetBlob<T>(string containerName, string blobName);
/// <summary>Gets a blob.</summary>
/// <typeparam name="T">Blob type.</typeparam>
/// <param name="containerName">Name of the container.</param>
/// <param name="blobName">Name of the blob.</param>
/// <param name="etag">Identifier assigned by the storage to the blob
/// that can be used to distinguish be successive version of the blob
/// (useful to check for blob update).</param>
/// <returns>
/// If there is no such blob, the returned object
/// has its property HasValue set to <c>false</c>.
/// </returns>
Maybe<T> GetBlob<T>(string containerName, string blobName, out string etag);
/// <summary>Gets a blob.</summary>
/// <param name="containerName">Name of the container.</param>
/// <param name="blobName">Name of the blob.</param>
/// <param name="type">The type of the blob.</param>
/// <param name="etag">Identifier assigned by the storage to the blob
/// that can be used to distinguish be successive version of the blob
/// (useful to check for blob update).</param>
/// <returns>
/// If there is no such blob, the returned object
/// has its property HasValue set to <c>false</c>.
/// </returns>
/// <remarks>This method should only be used when the caller does not know the type of the
/// object stored in the blob at compile time, but it can only be determined at run time.
/// In all other cases, you should use the generic overloads of the method.</remarks>
Maybe<object> GetBlob(string containerName, string blobName, Type type, out string etag);
/// <summary>
/// Gets a blob in intermediate XML representation for inspection and recovery,
/// if supported by the serialization formatter.
/// </summary>
/// <param name="containerName">Name of the container.</param>
/// <param name="blobName">Name of the blob.</param>
/// <param name="etag">Identifier assigned by the storage to the blob
/// that can be used to distinguish be successive version of the blob
/// (useful to check for blob update).</param>
/// <returns>
/// If there is no such blob or the formatter supports no XML representation,
/// the returned object has its property HasValue set to <c>false</c>.
/// </returns>
Maybe<XElement> GetBlobXml(string containerName, string blobName, out string etag);
/// <summary>
/// Gets a range of blobs.
/// </summary>
/// <typeparam name="T">Blob type.</typeparam>
/// <param name="containerName">Name of the container.</param>
/// <param name="blobNames">Names of the blobs.</param>
/// <param name="etags">Etag identifiers for all returned blobs.</param>
/// <returns>For each requested blob, an element in the array is returned in the same order.
/// If a specific blob was not found, the corresponding <b>etags</b> array element is <c>null</c>.</returns>
Maybe<T>[] GetBlobRange<T>(string containerName, string[] blobNames, out string[] etags);
/// <summary>Gets a blob only if the etag has changed meantime.</summary>
/// <typeparam name="T">Type of the blob.</typeparam>
/// <param name="containerName">Name of the container.</param>
/// <param name="blobName">Name of the blob.</param>
/// <param name="oldEtag">Old etag value. If this value is <c>null</c>, the blob will always
/// be retrieved (except if the blob does not exist anymore).</param>
/// <param name="newEtag">New etag value. Will be <c>null</c> if the blob no more exist,
/// otherwise will be set to the current etag value of the blob.</param>
/// <returns>
/// If the blob has not been modified or if there is no such blob,
/// then the returned object has its property HasValue set to <c>false</c>.
/// </returns>
Maybe<T> GetBlobIfModified<T>(string containerName, string blobName, string oldEtag, out string newEtag);
/// <summary>
/// Gets the current etag of the blob, or <c>null</c> if the blob does not exists.
/// </summary>
string GetBlobEtag(string containerName, string blobName);
/// <summary>Puts a blob (overwrite if the blob already exists).</summary>
/// <remarks>Creates the container if it does not exist beforehand.</remarks>
void PutBlob<T>(string containerName, string blobName, T item);
/// <summary>Puts a blob and optionally overwrite.</summary>
/// <remarks>Creates the container if it does not exist beforehand.</remarks>
/// <returns><c>true</c> if the blob has been put and <c>false</c> if the blob already
/// exists but could not be overwritten.</returns>
bool PutBlob<T>(string containerName, string blobName, T item, bool overwrite);
/// <summary>Puts a blob and optionally overwrite.</summary>
/// <param name="containerName">Name of the container.</param>
/// <param name="blobName">Name of the blob.</param>
/// <param name="item">Item to be put.</param>
/// <param name="overwrite">Indicates whether existing blob should be overwritten
/// if it exists.</param>
/// <param name="etag">New etag (identifier used to track for blob change) if
/// the blob is written, or <c>null</c> if no blob is written.</param>
/// <remarks>Creates the container if it does not exist beforehand.</remarks>
/// <returns><c>true</c> if the blob has been put and <c>false</c> if the blob already
/// exists but could not be overwritten.</returns>
bool PutBlob<T>(string containerName, string blobName, T item, bool overwrite, out string etag);
/// <summary>Puts a blob only if etag given in argument is matching blob's etag in blobStorage.</summary>
/// <param name="containerName">Name of the container.</param>
/// <param name="blobName">Name of the blob.</param>
/// <param name="item">Item to be put.</param>
/// <param name="expectedEtag">etag that should be matched inside BlobStorage.</param>
/// <remarks>Creates the container if it does not exist beforehand.</remarks>
/// <returns><c>true</c> if the blob has been put and <c>false</c> if the blob already
/// exists but version were not matching.</returns>
bool PutBlob<T>(string containerName, string blobName, T item, string expectedEtag);
/// <summary>Puts a blob and optionally overwrite.</summary>
/// <param name="containerName">Name of the container.</param>
/// <param name="blobName">Name of the blob.</param>
/// <param name="item">Item to be put.</param>
/// <param name="type">The type of the blob.</param>
/// <param name="overwrite">Indicates whether existing blob should be overwritten
/// if it exists.</param>
/// <param name="etag">New etag (identifier used to track for blob change) if
/// the blob is written, or <c>null</c> if no blob is written.</param>
/// <remarks>Creates the container if it does not exist beforehand.</remarks>
/// <returns><c>true</c> if the blob has been put and <c>false</c> if the blob already
/// exists but could not be overwritten.</returns>
/// <remarks>This method should only be used when the caller does not know the type of the
/// object stored in the blob at compile time, but it can only be determined at run time.
/// In all other cases, you should use the generic overloads of the method.</remarks>
bool PutBlob(string containerName, string blobName, object item, Type type, bool overwrite, out string etag);
/// <summary>
/// Updates a blob if it already exists.
/// </summary>
/// <remarks>
/// <para>
/// The provided lambdas can be executed multiple times in case of
/// concurrency-related retrials, so be careful with side-effects
/// (like incrementing a counter in them).
/// </para>
/// <para>This method is idempotent if and only if the provided lambdas are idempotent.</para>
/// </remarks>
/// <returns>The value returned by the lambda, or empty if the blob did not exist.</returns>
Maybe<T> UpdateBlobIfExist<T>(string containerName, string blobName, Func<T, T> update);
/// <summary>
/// Updates a blob if it already exists.
/// If the insert or update lambdas return empty, the blob will not be changed.
/// </summary>
/// <remarks>
/// <para>
/// The provided lambdas can be executed multiple times in case of
/// concurrency-related retrials, so be careful with side-effects
/// (like incrementing a counter in them).
/// </para>
/// <para>This method is idempotent if and only if the provided lambdas are idempotent.</para>
/// </remarks>
/// <returns>The value returned by the lambda, or empty if the blob did not exist or no change was applied.</returns>
Maybe<T> UpdateBlobIfExistOrSkip<T>(string containerName, string blobName, Func<T, Maybe<T>> update);
/// <summary>
/// Updates a blob if it already exists.
/// If the insert or update lambdas return empty, the blob will be deleted.
/// </summary>
/// <remarks>
/// <para>
/// The provided lambdas can be executed multiple times in case of
/// concurrency-related retrials, so be careful with side-effects
/// (like incrementing a counter in them).
/// </para>
/// <para>This method is idempotent if and only if the provided lambdas are idempotent.</para>
/// </remarks>
/// <returns>The value returned by the lambda, or empty if the blob did not exist or was deleted.</returns>
Maybe<T> UpdateBlobIfExistOrDelete<T>(string containerName, string blobName, Func<T, Maybe<T>> update);
/// <summary>
/// Inserts or updates a blob depending on whether it already exists or not.
/// </summary>
/// <remarks>
/// <para>
/// The provided lambdas can be executed multiple times in case of
/// concurrency-related retrials, so be careful with side-effects
/// (like incrementing a counter in them).
/// </para>
/// <para>
/// This method is idempotent if and only if the provided lambdas are idempotent
/// and if the object returned by the insert lambda is an invariant to the update lambda
/// (if the second condition is not met, it is idempotent after the first successful call).
/// </para>
/// </remarks>
/// <returns>The value returned by the lambda.</returns>
T UpsertBlob<T>(string containerName, string blobName, Func<T> insert, Func<T, T> update);
/// <summary>
/// Inserts or updates a blob depending on whether it already exists or not.
/// If the insert or update lambdas return empty, the blob will not be changed.
/// </summary>
/// <remarks>
/// <para>
/// The provided lambdas can be executed multiple times in case of
/// concurrency-related retrials, so be careful with side-effects
/// (like incrementing a counter in them).
/// </para>
/// <para>
/// This method is idempotent if and only if the provided lambdas are idempotent
/// and if the object returned by the insert lambda is an invariant to the update lambda
/// (if the second condition is not met, it is idempotent after the first successful call).
/// </para>
/// </remarks>
/// <returns>The value returned by the lambda. If empty, then no change was applied.</returns>
Maybe<T> UpsertBlobOrSkip<T>(string containerName, string blobName, Func<Maybe<T>> insert, Func<T, Maybe<T>> update);
/// <summary>
/// Inserts or updates a blob depending on whether it already exists or not.
/// If the insert or update lambdas return empty, the blob will be deleted (if it exists).
/// </summary>
/// <remarks>
/// <para>
/// The provided lambdas can be executed multiple times in case of
/// concurrency-related retrials, so be careful with side-effects
/// (like incrementing a counter in them).
/// </para>
/// <para>
/// This method is idempotent if and only if the provided lambdas are idempotent
/// and if the object returned by the insert lambda is an invariant to the update lambda
/// (if the second condition is not met, it is idempotent after the first successful call).
/// </para>
/// </remarks>
/// <returns>The value returned by the lambda. If empty, then the blob has been deleted.</returns>
Maybe<T> UpsertBlobOrDelete<T>(string containerName, string blobName, Func<Maybe<T>> insert, Func<T, Maybe<T>> update);
/// <summary>Requests a new lease on the blob and returns its new lease ID</summary>
Result<string> TryAcquireLease(string containerName, string blobName);
/// <summary>Releases the lease of the blob if the provided lease ID matches.</summary>
bool TryReleaseLease(string containerName, string blobName, string leaseId);
/// <summary>Renews the lease of the blob if the provided lease ID matches.</summary>
bool TryRenewLease(string containerName, string blobName, string leaseId);
}
} | zyyin2005-lokad | Source/Lokad.Cloud.Storage/Blobs/IBlobStorageProvider.cs | C# | bsd | 17,142 |
#region Copyright (c) Lokad 2009-2011
// This code is released under the terms of the new BSD licence.
// URL: http://www.lokad.com/
#endregion
using System;
namespace Lokad.Cloud.Storage
{
/// <summary>Used to specify the field position in the blob name.</summary>
/// <remarks>The name (chosen as the abbreviation of "field position")
/// is made compact not to make client code too verbose.</remarks>
public class RankAttribute : Attribute
{
public readonly int Index;
/// <summary>Indicates whether the default value (for value types)
/// should be treated as 'null'. Not relevant for class types.
/// </summary>
public readonly bool TreatDefaultAsNull;
/// <summary>Position v</summary>
public RankAttribute(int index)
{
Index = index;
}
/// <summary>Position v, and default behavior.</summary>
public RankAttribute(int index, bool treatDefaultAsNull)
{
Index = index;
TreatDefaultAsNull = treatDefaultAsNull;
}
}
} | zyyin2005-lokad | Source/Lokad.Cloud.Storage/Blobs/RankAttribute.cs | C# | bsd | 1,126 |
#region Copyright (c) Lokad 2010
// This code is released under the terms of the new BSD licence.
// URL: http://www.lokad.com/
#endregion
using System;
namespace Lokad.Cloud.Storage
{
/// <summary>Entity to be stored by the <see cref="ITableStorageProvider"/>.</summary>
/// <typeparam name="T">Type of the value carried by the entity.</typeparam>
/// <remarks>Once serialized the <c>CloudEntity.Value</c> should weight less
/// than 720KB to be compatible with Table Storage limitations on entities.</remarks>
public class CloudEntity<T>
{
/// <summary>Indexed system property.</summary>
public string RowKey { get; set; }
/// <summary>Indexed system property.</summary>
public string PartitionKey { get; set; }
/// <summary>Flag indicating last update. Populated by the Table Storage.</summary>
public DateTime Timestamp { get; set; }
/// <summary>ETag. Indicates changes. Populated by the Table Storage.</summary>
public string ETag { get; set; }
/// <summary>Value carried by the entity.</summary>
public T Value { get; set; }
}
} | zyyin2005-lokad | Source/Lokad.Cloud.Storage/Tables/CloudEntity.cs | C# | bsd | 1,182 |
#region Copyright (c) Lokad 2010-2011
// This code is released under the terms of the new BSD licence.
// URL: http://www.lokad.com/
#endregion
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
namespace Lokad.Cloud.Storage
{
/// <summary>Strong-typed utility wrapper for the <see cref="ITableStorageProvider"/>.</summary>
/// <remarks>
/// The purpose of the <c>CloudTable{T}</c> is to provide a strong-typed access to the
/// table storage in the client code. Indeed, the row table storage provider typically
/// let you (potentially) mix different types into a single table.
/// </remarks>
public class CloudTable<T>
{
readonly ITableStorageProvider _provider;
readonly string _tableName;
/// <summary>Name of the underlying table.</summary>
public string Name
{
get { return _tableName; }
}
/// <remarks></remarks>
public CloudTable(ITableStorageProvider provider, string tableName)
{
// validating against the Windows Azure rule for table names.
if (!Regex.Match(tableName, "^[A-Za-z][A-Za-z0-9]{2,62}").Success)
{
throw new ArgumentException("Table name is incorrect", "tableName");
}
_provider = provider;
_tableName = tableName;
}
/// <seealso cref="ITableStorageProvider.Get{T}(string, string)"/>
public Maybe<CloudEntity<T>> Get(string partitionName, string rowKey)
{
var entity = _provider.Get<T>(_tableName, partitionName, new[] {rowKey}).FirstOrDefault();
return null != entity ? new Maybe<CloudEntity<T>>(entity) : Maybe<CloudEntity<T>>.Empty;
}
/// <seealso cref="ITableStorageProvider.Get{T}(string)"/>
public IEnumerable<CloudEntity<T>> Get()
{
return _provider.Get<T>(_tableName);
}
/// <seealso cref="ITableStorageProvider.Get{T}(string, string)"/>
public IEnumerable<CloudEntity<T>> Get(string partitionKey)
{
return _provider.Get<T>(_tableName, partitionKey);
}
/// <seealso cref="ITableStorageProvider.Get{T}(string, string, string, string)"/>
public IEnumerable<CloudEntity<T>> Get(string partitionKey, string startRowKey, string endRowKey)
{
return _provider.Get<T>(_tableName, partitionKey, startRowKey, endRowKey);
}
/// <seealso cref="ITableStorageProvider.Get{T}(string, string, IEnumerable{string})"/>
public IEnumerable<CloudEntity<T>> Get(string partitionKey, IEnumerable<string> rowKeys)
{
return _provider.Get<T>(_tableName, partitionKey, rowKeys);
}
/// <seealso cref="ITableStorageProvider.Insert{T}(string, IEnumerable{CloudEntity{T}})"/>
public void Insert(IEnumerable<CloudEntity<T>> entities)
{
_provider.Insert(_tableName, entities);
}
/// <seealso cref="ITableStorageProvider.Insert{T}(string, IEnumerable{CloudEntity{T}})"/>
public void Insert(CloudEntity<T> entity)
{
_provider.Insert(_tableName, new []{entity});
}
/// <seealso cref="ITableStorageProvider.Update{T}(string, IEnumerable{CloudEntity{T}})"/>
public void Update(IEnumerable<CloudEntity<T>> entities)
{
_provider.Update(_tableName, entities);
}
/// <seealso cref="ITableStorageProvider.Update{T}(string, IEnumerable{CloudEntity{T}})"/>
public void Update(CloudEntity<T> entity)
{
_provider.Update(_tableName, new [] {entity});
}
/// <seealso cref="ITableStorageProvider.Upsert{T}(string, IEnumerable{CloudEntity{T}})"/>
public void Upsert(IEnumerable<CloudEntity<T>> entities)
{
_provider.Upsert(_tableName, entities);
}
/// <seealso cref="ITableStorageProvider.Upsert{T}(string, IEnumerable{CloudEntity{T}})"/>
public void Upsert(CloudEntity<T> entity)
{
_provider.Upsert(_tableName, new [] {entity});
}
/// <seealso cref="ITableStorageProvider.Delete{T}(string, string, IEnumerable{string})"/>
public void Delete(string partitionKey, IEnumerable<string> rowKeys)
{
_provider.Delete<T>(_tableName, partitionKey, rowKeys);
}
/// <seealso cref="ITableStorageProvider.Delete{T}(string, string, IEnumerable{string})"/>
public void Delete(string partitionKey, string rowKey)
{
_provider.Delete<T>(_tableName, partitionKey, new []{rowKey});
}
}
} | zyyin2005-lokad | Source/Lokad.Cloud.Storage/Tables/CloudTable.cs | C# | bsd | 4,844 |
#region Copyright (c) Lokad 2009-2010
// This code is released under the terms of the new BSD licence.
// URL: http://www.lokad.com/
#endregion
using System;
using System.Collections.Generic;
using System.Linq;
// ReSharper disable UnusedMember.Global
// ReSharper disable UnusedMethodReturnValue.Global
namespace Lokad.Cloud.Storage
{
/// <summary>Helper extensions methods for storage providers.</summary>
public static class TableStorageExtensions
{
/// <summary>Gets the specified cloud entity if it exists.</summary>
/// <typeparam name="T"></typeparam>
public static Maybe<CloudEntity<T>> Get<T>(this ITableStorageProvider provider, string tableName, string partitionName, string rowKey)
{
var entity = provider.Get<T>(tableName, partitionName, new[] {rowKey}).FirstOrDefault();
return null != entity ? new Maybe<CloudEntity<T>>(entity) : Maybe<CloudEntity<T>>.Empty;
}
/// <summary>Gets a strong typed wrapper around the table storage provider.</summary>
public static CloudTable<T> GetTable<T>(this ITableStorageProvider provider, string tableName)
{
return new CloudTable<T>(provider, tableName);
}
/// <summary>Updates a collection of existing entities into the table storage.</summary>
/// <remarks>
/// <para>The call is expected to fail on the first non-existing entity.
/// Results are not garanteed if one or several entities do not exist already.
/// </para>
/// <para>The call is also expected to fail if one or several entities have
/// changed remotely in the meantime. Use the overloaded method with the additional
/// force parameter to change this behavior if needed.
/// </para>
/// <para>There is no upper limit on the number of entities provided through
/// the enumeration. The implementations are expected to lazily iterates
/// and to create batch requests as the move forward.
/// </para>
/// <para>Idempotence of the implementation is required.</para>
/// </remarks>
/// <exception cref="InvalidOperationException"> thrown if the table does not exist
/// or an non-existing entity has been encountered.</exception>
public static void Update<T>(this ITableStorageProvider provider, string tableName, IEnumerable<CloudEntity<T>> entities)
{
provider.Update(tableName, entities, false);
}
/// <summary>Deletes a collection of entities.</summary>
/// <remarks>
/// <para>
/// The implementation is expected to lazily iterate through all row keys
/// and send batch deletion request to the underlying storage.</para>
/// <para>Idempotence of the method is required.</para>
/// <para>The method should not fail if the table does not exist.</para>
/// <para>The call is expected to fail if one or several entities have
/// changed remotely in the meantime. Use the overloaded method with the additional
/// force parameter to change this behavior if needed.
/// </para>
/// </remarks>
public static void Delete<T>(this ITableStorageProvider provider, string tableName, IEnumerable<CloudEntity<T>> entities)
{
provider.Delete(tableName, entities, false);
}
}
}
| zyyin2005-lokad | Source/Lokad.Cloud.Storage/Tables/TableStorageExtensions.cs | C# | bsd | 3,493 |
#region Copyright (c) Lokad 2010
// This code is released under the terms of the new BSD licence.
// URL: http://www.lokad.com/
#endregion
using System;
using System.Collections.Generic;
namespace Lokad.Cloud.Storage
{
/// <summary>Abstraction for the Table Storage.</summary>
/// <remarks>This provider represents a logical abstraction of the Table Storage,
/// not the Table Storage itself. In particular, implementations handle paging
/// and query splitting internally. Also, this provider implicitly relies on
/// serialization to handle generic entities (not constrained by the few datatypes
/// available to the Table Storage).</remarks>
public interface ITableStorageProvider
{
/// <summary>Creates a new table if it does not exist already.</summary>
/// <returns><c>true</c> if a new table has been created.
/// <c>false</c> if the table already exists.
/// </returns>
bool CreateTable(string tableName);
/// <summary>Deletes a table if it exists.</summary>
/// <returns><c>true</c> if the table has been deleted.
/// <c>false</c> if the table does not exist.
/// </returns>
bool DeleteTable(string tableName);
/// <summary>Returns the list of all the tables that exist in the storage.</summary>
IEnumerable<string> GetTables();
/// <summary>Iterates through all entities of a given table.</summary>
/// <remarks>The enumeration is typically expected to be lazy, iterating through
/// all the entities with paged request. If the table does not exist, an
/// empty enumeration is returned.
/// </remarks>
IEnumerable<CloudEntity<T>> Get<T>(string tableName);
/// <summary>Iterates through all entities of a given table and partition.</summary>
/// <remarks><para>The enumeration is typically expected to be lazy, iterating through
/// all the entities with paged request. If the table does not exists, or if the partition
/// does not exists, an empty enumeration is returned.</para>
/// </remarks>
IEnumerable<CloudEntity<T>> Get<T>(string tableName, string partitionKey);
/// <summary>Iterates through a range of entities of a given table and partition.</summary>
/// <param name="tableName">Name of the Table.</param>
/// <param name="partitionKey">Name of the partition which can not be null.</param>
/// <param name="startRowKey">Inclusive start row key. If <c>null</c>, no start range
/// constraint is enforced.</param>
/// <param name="endRowKey">Exclusive end row key. If <c>null</c>, no ending range
/// constraint is enforced.</param>
/// <remarks>
/// The enumeration is typically expected to be lazy, iterating through
/// all the entities with paged request.The enumeration is ordered by row key.
/// If the table or the partition key does not exist, the returned enumeration is empty.
/// </remarks>
IEnumerable<CloudEntity<T>> Get<T>(string tableName, string partitionKey, string startRowKey, string endRowKey);
/// <summary>Iterates through all entities specified by their row keys.</summary>
/// <param name="tableName">The name of the table. This table should exists otherwise the method will fail.</param>
/// <param name="partitionKey">Partition key (can not be null).</param>
/// <param name="rowKeys">lazy enumeration of non null string representing rowKeys.</param>
/// <remarks>The enumeration is typically expected to be lazy, iterating through
/// all the entities with paged request. If the table or the partition key does not exist,
/// the returned enumeration is empty.</remarks>
IEnumerable<CloudEntity<T>> Get<T>(string tableName, string partitionKey, IEnumerable<string> rowKeys);
/// <summary>Inserts a collection of new entities into the table storage.</summary>
/// <remarks>
/// <para>The call is expected to fail on the first encountered already-existing
/// entity. Results are not garanteed if one or several entities already exist.
/// </para>
/// <para>There is no upper limit on the number of entities provided through
/// the enumeration. The implementations are expected to lazily iterates
/// and to create batch requests as the move forward.
/// </para>
/// <para>If the table does not exist then it should be created.</para>
/// <warning>Idempotence is not enforced.</warning>
/// </remarks>
///<exception cref="InvalidOperationException"> if an already existing entity has been encountered.</exception>
void Insert<T>(string tableName, IEnumerable<CloudEntity<T>> entities);
/// <summary>Updates a collection of existing entities into the table storage.</summary>
/// <remarks>
/// <para>The call is expected to fail on the first non-existing entity.
/// Results are not garanteed if one or several entities do not exist already.
/// </para>
/// <para>If <paramref name="force"/> is <c>false</c>, the call is expected to
/// fail if one or several entities have changed in the meantime. If <c>true</c>,
/// the entities are overwritten even if they've been changed remotely in the meantime.
/// </para>
/// <para>There is no upper limit on the number of entities provided through
/// the enumeration. The implementations are expected to lazily iterates
/// and to create batch requests as the move forward.
/// </para>
/// <para>Idempotence of the implementation is required.</para>
/// </remarks>
/// <exception cref="InvalidOperationException"> thrown if the table does not exist
/// or an non-existing entity has been encountered.</exception>
void Update<T>(string tableName, IEnumerable<CloudEntity<T>> entities, bool force);
/// <summary>Updates or insert a collection of existing entities into the table storage.</summary>
/// <remarks>
/// <para>New entities will be inserted. Existing entities will be updated,
/// even if they have changed remotely in the meantime.
/// </para>
/// <para>There is no upper limit on the number of entities provided through
/// the enumeration. The implementations are expected to lazily iterates
/// and to create batch requests as the move forward.
/// </para>
/// <para>If the table does not exist then it should be created.</para>
/// <para>Idempotence of the implementation is required.</para>
/// </remarks>
void Upsert<T>(string tableName, IEnumerable<CloudEntity<T>> entities);
/// <summary>Deletes all specified entities.</summary>
/// <param name="tableName">Name of the table.</param>
/// <param name="partitionKey">The partition key (assumed to be non null).</param>
/// <param name="rowKeys">Lazy enumeration of non null string representing the row keys.</param>
/// <remarks>
/// <para>
/// The implementation is expected to lazily iterate through all row keys
/// and send batch deletion request to the underlying storage.</para>
/// <para>Idempotence of the method is required.</para>
/// <para>The method should not fail if the table does not exist.</para>
/// </remarks>
void Delete<T>(string tableName, string partitionKey, IEnumerable<string> rowKeys);
/// <summary>Deletes a collection of entities.</summary>
/// <remarks>
/// <para>
/// The implementation is expected to lazily iterate through all row keys
/// and send batch deletion request to the underlying storage.</para>
/// <para>Idempotence of the method is required.</para>
/// <para>The method should not fail if the table does not exist.</para>
/// <para>If <paramref name="force"/> is <c>false</c>, the call is expected to
/// fail if one or several entities have changed remotely in the meantime. If <c>true</c>,
/// the entities are deleted even if they've been changed remotely in the meantime.
/// </para>
/// </remarks>
void Delete<T>(string tableName, IEnumerable<CloudEntity<T>> entities, bool force);
}
} | zyyin2005-lokad | Source/Lokad.Cloud.Storage/Tables/ITableStorageProvider.cs | C# | bsd | 8,612 |
// Imported from Lokad.Shared, 2011-02-08
using System;
namespace Lokad.Cloud.Storage
{
/// <summary>
/// Improved version of the Result[T], that could serve as a basis for it.
/// </summary>
/// <typeparam name="TValue">The type of the value.</typeparam>
/// <typeparam name="TError">The type of the error.</typeparam>
/// <remarks>It is to be moved up-stream if found useful in other projects.</remarks>
public class Result<TValue, TError> : IEquatable<Result<TValue, TError>>
{
readonly bool _isSuccess;
readonly TValue _value;
readonly TError _error;
Result(bool isSuccess, TValue value, TError error)
{
_isSuccess = isSuccess;
_value = value;
_error = error;
}
/// <summary>
/// Creates the success result.
/// </summary>
/// <param name="value">The value.</param>
/// <returns>result encapsulating the success value</returns>
/// <exception cref="ArgumentNullException">if value is a null reference type</exception>
public static Result<TValue, TError> CreateSuccess(TValue value)
{
// ReSharper disable CompareNonConstrainedGenericWithNull
if (null == value) throw new ArgumentNullException("value");
// ReSharper restore CompareNonConstrainedGenericWithNull
return new Result<TValue, TError>(true, value, default(TError));
}
/// <summary>
/// Creates the error result.
/// </summary>
/// <param name="error">The error.</param>
/// <returns>result encapsulating the error value</returns>
/// <exception cref="ArgumentNullException">if error is a null reference type</exception>
public static Result<TValue, TError> CreateError(TError error)
{
// ReSharper disable CompareNonConstrainedGenericWithNull
if (null == error) throw new ArgumentNullException("error");
// ReSharper restore CompareNonConstrainedGenericWithNull
return new Result<TValue, TError>(false, default(TValue), error);
}
/// <summary>
/// item associated with this result
/// </summary>
public TValue Value
{
get
{
if (!_isSuccess)
throw new InvalidOperationException("Dont access result on error. " + _error);
return _value;
}
}
/// <summary>
/// Error message associated with this failure
/// </summary>
public TError Error
{
get
{
if (_isSuccess)
throw new InvalidOperationException("Dont access error on valid result.");
return _error;
}
}
/// <summary>
/// Gets a value indicating whether this result is valid.
/// </summary>
/// <value><c>true</c> if this result is valid; otherwise, <c>false</c>.</value>
public bool IsSuccess
{
get { return _isSuccess; }
}
/// <summary>
/// Performs an implicit conversion from <typeparamref name="TValue"/> to <see cref="Result{TValue,TError}"/>.
/// </summary>
/// <param name="value">The value.</param>
/// <returns>The result of the conversion.</returns>
/// <exception cref="ArgumentNullException">If value is a null reference type</exception>
public static implicit operator Result<TValue, TError>(TValue value)
{
// ReSharper disable CompareNonConstrainedGenericWithNull
if (null == value) throw new ArgumentNullException("value");
// ReSharper restore CompareNonConstrainedGenericWithNull
return CreateSuccess(value);
}
/// <summary>
/// Performs an implicit conversion from <typeparamref name="TError"/> to <see cref="Result{TValue,TError}"/>.
/// </summary>
/// <param name="error">The error.</param>
/// <returns>The result of the conversion.</returns>
/// <exception cref="ArgumentNullException">If value is a null reference type</exception>
public static implicit operator Result<TValue, TError>(TError error)
{
// ReSharper disable CompareNonConstrainedGenericWithNull
if (null == error) throw new ArgumentNullException("error");
// ReSharper restore CompareNonConstrainedGenericWithNull
return CreateError(error);
}
/// <summary>
/// Indicates whether the current object is equal to another object of the same type.
/// </summary>
/// <param name="other">An object to compare with this object.</param>
/// <returns>
/// true if the current object is equal to the <paramref name="other"/> parameter; otherwise, false.
/// </returns>
public bool Equals(Result<TValue, TError> other)
{
if (ReferenceEquals(null, other)) return false;
if (ReferenceEquals(this, other)) return true;
return other._isSuccess.Equals(_isSuccess) && Equals(other._value, _value) && Equals(other._error, _error);
}
/// <summary>
/// Determines whether the specified <see cref="T:System.Object"/> is equal to the current <see cref="T:System.Object"/>.
/// </summary>
/// <param name="obj">The <see cref="T:System.Object"/> to compare with the current <see cref="T:System.Object"/>.</param>
/// <returns>
/// true if the specified <see cref="T:System.Object"/> is equal to the current <see cref="T:System.Object"/>; otherwise, false.
/// </returns>
/// <exception cref="T:System.NullReferenceException">
/// The <paramref name="obj"/> parameter is null.
/// </exception>
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj)) return false;
if (ReferenceEquals(this, obj)) return true;
if (obj.GetType() != typeof (Result<TValue, TError>)) return false;
return Equals((Result<TValue, TError>) obj);
}
/// <summary>
/// Serves as a hash function for a particular type.
/// </summary>
/// <returns>
/// A hash code for the current <see cref="T:System.Object"/>.
/// </returns>
public override int GetHashCode()
{
unchecked
{
int result = _isSuccess.GetHashCode();
// ReSharper disable CompareNonConstrainedGenericWithNull
result = (result*397) ^ (_value != null ? _value.GetHashCode() : 1);
result = (result*397) ^ (_error != null ? _error.GetHashCode() : 0);
// ReSharper restore CompareNonConstrainedGenericWithNull
return result;
}
}
/// <summary>
/// Returns a <see cref="System.String"/> that represents this instance.
/// </summary>
/// <returns>
/// A <see cref="System.String"/> that represents this instance.
/// </returns>
public override string ToString()
{
if (!_isSuccess)
return "<Error: '" + _error + "'>";
return "<Value: '" + _value + "'>";
}
}
} | zyyin2005-lokad | Source/Lokad.Cloud.Storage/Shared/Monads/Result.2.cs | C# | bsd | 7,583 |
// Imported from Lokad.Shared, 2011-02-08
using System;
namespace Lokad.Cloud.Storage
{
/// <summary>
/// Helper class that indicates nullable value in a good-citizenship code
/// </summary>
/// <typeparam name="T">underlying type</typeparam>
[Serializable]
public class Maybe<T> : IEquatable<Maybe<T>>
{
readonly T _value;
readonly bool _hasValue;
Maybe(T item, bool hasValue)
{
_value = item;
_hasValue = hasValue;
}
internal Maybe(T value)
: this(value, true)
{
// ReSharper disable CompareNonConstrainedGenericWithNull
if (value == null)
{
throw new ArgumentNullException("value");
}
// ReSharper restore CompareNonConstrainedGenericWithNull
}
/// <summary>
/// Default empty instance.
/// </summary>
public static readonly Maybe<T> Empty = new Maybe<T>(default(T), false);
/// <summary>
/// Gets the underlying value.
/// </summary>
/// <value>The value.</value>
public T Value
{
get
{
if (!_hasValue)
{
throw new InvalidOperationException("Dont access value when Maybe is empty.");
}
return _value;
}
}
/// <summary>
/// Gets a value indicating whether this instance has value.
/// </summary>
/// <value><c>true</c> if this instance has value; otherwise, <c>false</c>.</value>
public bool HasValue
{
get { return _hasValue; }
}
/// <summary>
/// Retrieves value from this instance, using a
/// <paramref name="defaultValue"/> if it is absent.
/// </summary>
/// <param name="defaultValue">The default value.</param>
/// <returns>value</returns>
public T GetValue(Func<T> defaultValue)
{
return _hasValue ? _value : defaultValue();
}
/// <summary>
/// Retrieves value from this instance, using a
/// <paramref name="defaultValue"/> if it is absent.
/// </summary>
/// <param name="defaultValue">The default value.</param>
/// <returns>value</returns>
public T GetValue(T defaultValue)
{
return _hasValue ? _value : defaultValue;
}
/// <summary>
/// Retrieves value from this instance, using a <paramref name="defaultValue"/>
/// factory, if it is absent
/// </summary>
/// <param name="defaultValue">The default value to provide.</param>
/// <returns>maybe value</returns>
public Maybe<T> GetValue(Func<Maybe<T>> defaultValue)
{
return _hasValue ? this : defaultValue();
}
/// <summary>
/// Retrieves value from this instance, using a <paramref name="defaultValue"/>
/// if it is absent
/// </summary>
/// <param name="defaultValue">The default value to provide.</param>
/// <returns>maybe value</returns>
public Maybe<T> GetValue(Maybe<T> defaultValue)
{
return _hasValue ? this : defaultValue;
}
/// <summary>
/// Applies the specified action to the value, if it is present.
/// </summary>
/// <param name="action">The action.</param>
/// <returns>same instance for inlining</returns>
public Maybe<T> Apply(Action<T> action)
{
if (_hasValue)
{
action(_value);
}
return this;
}
/// <summary>
/// Executes the specified action, if the value is absent
/// </summary>
/// <param name="action">The action.</param>
/// <returns>same instance for inlining</returns>
public Maybe<T> Handle(Action action)
{
if (!_hasValue)
{
action();
}
return this;
}
/// <summary>
/// Converts this instance to <see cref="Maybe{T}"/>,
/// while applying <paramref name="converter"/> if there is a value.
/// </summary>
/// <typeparam name="TTarget">The type of the target.</typeparam>
/// <param name="converter">The converter.</param>
/// <returns></returns>
public Maybe<TTarget> Convert<TTarget>(Func<T, TTarget> converter)
{
return _hasValue ? converter(_value) : Maybe<TTarget>.Empty;
}
/// <summary>
/// Retrieves converted value, using a
/// <paramref name="defaultValue"/> if it is absent.
/// </summary>
/// <typeparam name="TTarget">type of the conversion target</typeparam>
/// <param name="converter">The converter.</param>
/// <param name="defaultValue">The default value.</param>
/// <returns>value</returns>
public TTarget Convert<TTarget>(Func<T, TTarget> converter, Func<TTarget> defaultValue)
{
return _hasValue ? converter(_value) : defaultValue();
}
/// <summary>
/// Retrieves converted value, using a
/// <paramref name="defaultValue"/> if it is absent.
/// </summary>
/// <typeparam name="TTarget">type of the conversion target</typeparam>
/// <param name="converter">The converter.</param>
/// <param name="defaultValue">The default value.</param>
/// <returns>value</returns>
public TTarget Convert<TTarget>(Func<T, TTarget> converter, TTarget defaultValue)
{
return _hasValue ? converter(_value) : defaultValue;
}
/// <summary>
/// Determines whether the specified <see cref="Maybe{T}"/> is equal to the current <see cref="Maybe{T}"/>.
/// </summary>
/// <param name="maybe">The <see cref="Maybe{T}"/> to compare with.</param>
/// <returns>true if the objects are equal</returns>
public bool Equals(Maybe<T> maybe)
{
if (ReferenceEquals(null, maybe)) return false;
if (ReferenceEquals(this, maybe)) return true;
if (_hasValue != maybe._hasValue) return false;
if (!_hasValue) return true;
return _value.Equals(maybe._value);
}
/// <summary>
/// Determines whether the specified <see cref="T:System.Object"/> is equal to the current <see cref="T:System.Object"/>.
/// </summary>
/// <param name="obj">The <see cref="T:System.Object"/> to compare with the current <see cref="T:System.Object"/>.</param>
/// <returns>
/// true if the specified <see cref="T:System.Object"/> is equal to the current <see cref="T:System.Object"/>; otherwise, false.
/// </returns>
/// <exception cref="T:System.NullReferenceException">
/// The <paramref name="obj"/> parameter is null.
/// </exception>
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj)) return false;
if (ReferenceEquals(this, obj)) return true;
var maybe = obj as Maybe<T>;
if (maybe == null) return false;
return Equals(maybe);
}
/// <summary>
/// Serves as a hash function for this instance.
/// </summary>
/// <returns>
/// A hash code for the current <see cref="Maybe{T}"/>.
/// </returns>
public override int GetHashCode()
{
unchecked
{
// ReSharper disable CompareNonConstrainedGenericWithNull
return ((_value != null ? _value.GetHashCode() : 0)*397) ^ _hasValue.GetHashCode();
// ReSharper restore CompareNonConstrainedGenericWithNull
}
}
/// <summary>
/// Implements the operator ==.
/// </summary>
/// <param name="left">The left.</param>
/// <param name="right">The right.</param>
/// <returns>The result of the operator.</returns>
public static bool operator ==(Maybe<T> left, Maybe<T> right)
{
return Equals(left, right);
}
/// <summary>
/// Implements the operator !=.
/// </summary>
/// <param name="left">The left.</param>
/// <param name="right">The right.</param>
/// <returns>The result of the operator.</returns>
public static bool operator !=(Maybe<T> left, Maybe<T> right)
{
return !Equals(left, right);
}
/// <summary>
/// Performs an implicit conversion from <typeparamref name="T"/> to <see cref="Maybe{T}"/>.
/// </summary>
/// <param name="item">The item.</param>
/// <returns>The result of the conversion.</returns>
public static implicit operator Maybe<T>(T item)
{
// ReSharper disable CompareNonConstrainedGenericWithNull
if (item == null) throw new ArgumentNullException("item");
// ReSharper restore CompareNonConstrainedGenericWithNull
return new Maybe<T>(item);
}
/// <summary>
/// Performs an explicit conversion from <see cref="Maybe{T}"/> to <typeparamref name="T"/>.
/// </summary>
/// <param name="item">The item.</param>
/// <returns>The result of the conversion.</returns>
public static explicit operator T(Maybe<T> item)
{
if (item == null) throw new ArgumentNullException("item");
if (!item.HasValue) throw new ArgumentException("May be must have value");
return item.Value;
}
/// <summary>
/// Returns a <see cref="System.String"/> that represents this instance.
/// </summary>
/// <returns>
/// A <see cref="System.String"/> that represents this instance.
/// </returns>
public override string ToString()
{
if (_hasValue)
{
return "<" + _value + ">";
}
return "<Empty>";
}
}
} | zyyin2005-lokad | Source/Lokad.Cloud.Storage/Shared/Monads/Maybe.1.cs | C# | bsd | 10,559 |
// Imported from Lokad.Shared, 2011-02-08
using System;
namespace Lokad.Cloud.Storage
{
/// <summary>
/// Helper class that allows to pass out method call results without using exceptions
/// </summary>
/// <typeparam name="T">type of the associated data</typeparam>
public class Result<T> : IEquatable<Result<T>>
{
readonly bool _isSuccess;
readonly T _value;
readonly string _error;
Result(bool isSuccess, T value, string error)
{
_isSuccess = isSuccess;
_value = value;
_error = error;
}
/// <summary>
/// Creates the success result.
/// </summary>
/// <param name="value">The value.</param>
/// <returns>result encapsulating the success value</returns>
/// <exception cref="ArgumentNullException">if value is a null reference type</exception>
public static Result<T> CreateSuccess(T value)
{
// ReSharper disable CompareNonConstrainedGenericWithNull
if (null == value) throw new ArgumentNullException("value");
// ReSharper restore CompareNonConstrainedGenericWithNull
return new Result<T>(true, value, default(string));
}
/// <summary>
/// Creates the error result.
/// </summary>
/// <param name="error">The error.</param>
/// <returns>result encapsulating the error value</returns>
/// <exception cref="ArgumentNullException">if error is null</exception>
public static Result<T> CreateError(string error)
{
if (null == error) throw new ArgumentNullException("error");
return new Result<T>(false, default(T), error);
}
/// <summary>
/// Performs an implicit conversion from <typeparamref name="T"/> to <see cref="Result{T}"/>.
/// </summary>
/// <param name="value">The item.</param>
/// <returns>The result of the conversion.</returns>
/// <exception cref="ArgumentNullException">if <paramref name="value"/> is a reference type that is null</exception>
public static implicit operator Result<T>(T value)
{
// ReSharper disable CompareNonConstrainedGenericWithNull
if (null == value) throw new ArgumentNullException("value");
// ReSharper restore CompareNonConstrainedGenericWithNull
return new Result<T>(true, value, null);
}
/// <summary>
/// Determines whether the specified <see cref="T:System.Object"/> is equal to the current <see cref="T:System.Object"/>.
/// </summary>
/// <param name="obj">The <see cref="T:System.Object"/> to compare with the current <see cref="T:System.Object"/>.</param>
/// <returns>
/// true if the specified <see cref="T:System.Object"/> is equal to the current <see cref="T:System.Object"/>; otherwise, false.
/// </returns>
/// <exception cref="T:System.NullReferenceException">
/// The <paramref name="obj"/> parameter is null.
/// </exception>
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj)) return false;
if (ReferenceEquals(this, obj)) return true;
if (obj.GetType() != typeof (Result<T>)) return false;
return Equals((Result<T>) obj);
}
/// <summary>
/// Serves as a hash function for a particular type.
/// </summary>
/// <returns>
/// A hash code for the current <see cref="T:System.Object"/>.
/// </returns>
public override int GetHashCode()
{
unchecked
{
int result = _isSuccess.GetHashCode();
result = (result*397) ^ _value.GetHashCode();
result = (result*397) ^ (_error != null ? _error.GetHashCode() : 0);
return result;
}
}
/// <summary>
/// Indicates whether the current object is equal to another object of the same type.
/// </summary>
/// <param name="other">An object to compare with this object.</param>
/// <returns>
/// true if the current object is equal to the <paramref name="other"/> parameter; otherwise, false.
/// </returns>
public bool Equals(Result<T> other)
{
if (ReferenceEquals(null, other)) return false;
if (ReferenceEquals(this, other)) return true;
return other._isSuccess.Equals(_isSuccess) && Equals(other._value, _value) && Equals(other._error, _error);
}
/// <summary>
/// Gets a value indicating whether this result is valid.
/// </summary>
/// <value><c>true</c> if this result is valid; otherwise, <c>false</c>.</value>
public bool IsSuccess
{
get { return _isSuccess; }
}
/// <summary>
/// item associated with this result
/// </summary>
public T Value
{
get
{
if (!_isSuccess)
throw new InvalidOperationException("Dont access result on error. " + _error);
return _value;
}
}
/// <summary>
/// Error message associated with this failure
/// </summary>
public string Error
{
get
{
if (_isSuccess)
throw new InvalidOperationException("Dont access error on valid result.");
return _error;
}
}
/// <summary>
/// Performs an implicit conversion from <see cref="System.String"/> to <see cref="Result{T}"/>.
/// </summary>
/// <param name="error">The error.</param>
/// <returns>The result of the conversion.</returns>
/// <exception cref="ArgumentNullException">If value is a null reference type</exception>
public static implicit operator Result<T>(string error)
{
if (null == error) throw new ArgumentNullException("error");
return CreateError(error);
}
/// <summary>
/// Returns a <see cref="System.String"/> that represents this instance.
/// </summary>
/// <returns>
/// A <see cref="System.String"/> that represents this instance.
/// </returns>
public override string ToString()
{
if (!_isSuccess)
return "<Error: '" + _error + "'>";
return "<Value: '" + _value + "'>";
}
}
} | zyyin2005-lokad | Source/Lokad.Cloud.Storage/Shared/Monads/Result.1.cs | C# | bsd | 6,824 |
// Imported from Lokad.Shared, 2011-02-08
using System;
namespace Lokad.Cloud.Storage
{
/// <summary> Helper class for creating <see cref="Result{T}"/> instances </summary>
public static class Result
{
/// <summary> Creates success result </summary>
/// <typeparam name="TValue">The type of the result.</typeparam>
/// <param name="value">The item.</param>
/// <returns>new result instance</returns>
/// <seealso cref="Result{T}.CreateSuccess"/>
public static Result<TValue> CreateSuccess<TValue>(TValue value)
{
return Result<TValue>.CreateSuccess(value);
}
}
} | zyyin2005-lokad | Source/Lokad.Cloud.Storage/Shared/Monads/Result.cs | C# | bsd | 675 |
#region (c)2009-2011 Lokad - New BSD license
// Company: http://www.lokad.com
// This code is released under the terms of the new BSD licence
#endregion
using System.Diagnostics;
using System.Linq;
using System.Threading;
namespace Lokad.Cloud.Storage.Shared.Diagnostics
{
/// <summary> <para>
/// Class to provide simple measurement of some method calls.
/// This class has been designed to provide light performance monitoring
/// that could be used for instrumenting methods in production. It does
/// not use any locks and uses design to avoid 90% of concurrency issues.
/// </para><para>
/// Counters are designed to be "cheap" and throwaway, so we basically we
/// don't care about the remaining 10%
/// </para><para>
/// The usage idea is simple - data is captured from the counters at
/// regular intervals of time (i.e. 5-10 minutes). Counters are reset
/// after that. Data itself is aggregated on the monitoring side.
/// If there are some bad values (i.e. due to some rare race condition
/// between multiple threads and monitoring scan) then the counter data
/// is simply discarded.
/// </para></summary>
public sealed class ExecutionCounter
{
long _openCount;
long _closeCount;
long _runningTime;
readonly long[] _openCounters;
readonly long[] _closeCounters;
readonly string _name;
/// <summary>
/// Initializes a new instance of the <see cref="ExecutionCounter"/> class.
/// </summary>
/// <param name="name">The name.</param>
/// <param name="openCounterCount">The open counter count.</param>
/// <param name="closeCounterCount">The close counter count.</param>
public ExecutionCounter(string name, int openCounterCount, int closeCounterCount)
{
_name = name;
_openCounters = new long[openCounterCount];
_closeCounters = new long[closeCounterCount];
}
/// <summary>
/// Open the specified counter and adds the provided values to the openCounters collection
/// </summary>
/// <param name="openCounters">The open counters.</param>
/// <returns>timestamp for the operation</returns>
public long Open(params long[] openCounters)
{
// abdullin: this is not really atomic and precise,
// but we do not care that much
unchecked
{
Interlocked.Increment(ref _openCount);
for (int i = 0; i < openCounters.Length; i++)
{
Interlocked.Add(ref _openCounters[i], openCounters[i]);
}
}
return Stopwatch.GetTimestamp();
}
/// <summary>
/// Closes the specified timestamp.
/// </summary>
/// <param name="timestamp">The timestamp.</param>
/// <param name="closeCounters">The close counters.</param>
public void Close(long timestamp, params long[] closeCounters)
{
var runningTime = Stopwatch.GetTimestamp() - timestamp;
// this counter has been reset after opening - discard
if ((_openCount == 0) || (runningTime < 0))
return;
// abdullin: this is not really atomic and precise,
// but we do not care that much
unchecked
{
Interlocked.Add(ref _runningTime, runningTime);
Interlocked.Increment(ref _closeCount);
for (int i = 0; i < closeCounters.Length; i++)
{
Interlocked.Add(ref _closeCounters[i], closeCounters[i]);
}
}
}
/// <summary>
/// Resets this instance.
/// </summary>
public void Reset()
{
_runningTime = 0;
_openCount = 0;
_closeCount = 0;
for (int i = 0; i < _closeCounters.Length; i++)
{
_closeCounters[i] = 0;
}
for (int i = 0; i < _openCounters.Length; i++)
{
_openCounters[i] = 0;
}
}
/// <summary>
/// Converts this instance to <see cref="ExecutionStatistics"/>
/// </summary>
/// <returns></returns>
public ExecutionStatistics ToStatistics()
{
long dateTimeTicks = _runningTime;
if (Stopwatch.IsHighResolution)
{
double num2 = dateTimeTicks;
num2 *= 10000000.0 / Stopwatch.Frequency;
dateTimeTicks = (long)num2;
}
return new ExecutionStatistics(
_name,
_openCount,
_closeCount,
_openCounters.Concat(_closeCounters).ToArray(),
dateTimeTicks);
}
}
}
| zyyin2005-lokad | Source/Lokad.Cloud.Storage/Shared/Diagnostics/ExecutionCounter.cs | C# | bsd | 5,095 |
#region (c)2009-2011 Lokad - New BSD license
// Company: http://www.lokad.com
// This code is released under the terms of the new BSD licence
#endregion
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Lokad.Cloud.Storage.Shared.Diagnostics
{
/// <summary>
/// In-memory thread-safe collection of <see cref="ExecutionCounter"/>
/// </summary>
public sealed class ExecutionCounters
{
/// <summary>
/// Default instance of this counter
/// </summary>
public static readonly ExecutionCounters Default = new ExecutionCounters();
readonly object _lock = new object();
readonly IList<ExecutionCounter> _counters = new List<ExecutionCounter>();
/// <summary>
/// Registers the execution counters within this collection.
/// </summary>
/// <param name="counters">The counters.</param>
public void RegisterRange(IEnumerable<ExecutionCounter> counters)
{
lock (_lock)
{
foreach(var c in counters)
{
_counters.Add(c);
}
}
}
/// <summary>
/// Retrieves statistics for all exception counters in this collection
/// </summary>
/// <returns></returns>
public IList<ExecutionStatistics> ToList()
{
lock (_lock)
{
return _counters.Select(c => c.ToStatistics()).ToList();
}
}
/// <summary>
/// Resets all counters.
/// </summary>
public void ResetAll()
{
lock (_lock)
{
foreach (var counter in _counters)
{
counter.Reset();
}
}
}
}
}
| zyyin2005-lokad | Source/Lokad.Cloud.Storage/Shared/Diagnostics/ExceptionCounters.cs | C# | bsd | 1,929 |
#region (c)2009-2011 Lokad - New BSD license
// Company: http://www.lokad.com
// This code is released under the terms of the new BSD licence
#endregion
using System.Linq;
using Lokad.Cloud.Storage.Shared.Diagnostics;
namespace Lokad.Diagnostics.Persist
{
/// <summary>
/// Helper extensions for converting to/from data classes in the Diagnostics namespace
/// </summary>
public static class ConversionExtensions
{
/// <summary>
/// Converts immutable statistics objects to the persistence objects
/// </summary>
/// <param name="statisticsArray">The immutable statistics objects.</param>
/// <returns>array of persistence objects</returns>
public static ExecutionData[] ToPersistence(this ExecutionStatistics[] statisticsArray)
{
return statisticsArray.Select(es => new ExecutionData
{
CloseCount = es.CloseCount,
Counters = es.Counters,
Name = es.Name,
OpenCount = es.OpenCount,
RunningTime = es.RunningTime
}).ToArray();
}
/// <summary>
/// Converts persistence objects to immutable statistics objects
/// </summary>
/// <param name="dataArray">The persistence data objects.</param>
/// <returns>array of statistics objects</returns>
public static ExecutionStatistics[] FromPersistence(this ExecutionData[] dataArray)
{
return dataArray.Select(
d => new ExecutionStatistics(
d.Name,
d.OpenCount,
d.CloseCount,
d.Counters,
d.RunningTime)).ToArray();
}
}
} | zyyin2005-lokad | Source/Lokad.Cloud.Storage/Shared/Diagnostics/Persistence/ConvertionExtensions.cs | C# | bsd | 1,807 |
#region (c)2009-2011 Lokad - New BSD license
// Company: http://www.lokad.com
// This code is released under the terms of the new BSD licence
#endregion
using System;
using System.ComponentModel;
using System.Diagnostics;
using System.Runtime.Serialization;
using System.Xml.Serialization;
// CAUTION: do not touch namespace as it would be likely to break the persistence of this entity.
namespace Lokad.Diagnostics.Persist
{
/// <summary>
/// Diagnostics: Persistence class for aggregated method calls and timing.
/// </summary>
[Serializable]
[DataContract]
[DebuggerDisplay("{Name}: {OpenCount}, {RunningTime}")]
public sealed class ExecutionData
{
/// <summary>
/// Name of the executing method
/// </summary>
[XmlAttribute]
[DataMember(Order = 1)]
public string Name { get; set; }
/// <summary>
/// Number of times the counter has been opened
/// </summary>
[XmlAttribute, DefaultValue(0)]
[DataMember(Order = 2)]
public long OpenCount { get; set; }
/// <summary>
/// Gets or sets the counter has been closed
/// </summary>
/// <value>The close count.</value>
[XmlAttribute, DefaultValue(0)]
[DataMember(Order = 3)]
public long CloseCount { get; set; }
/// <summary>
/// Total execution count of the method in ticks
/// </summary>
[XmlAttribute, DefaultValue(0)]
[DataMember(Order = 4)]
public long RunningTime { get; set; }
/// <summary>
/// Method-specific counters
/// </summary>
[DataMember(Order = 5)]
public long[] Counters { get; set; }
/// <summary>
/// Initializes a new instance of the <see cref="ExecutionData"/> class.
/// </summary>
public ExecutionData()
{
Counters = new long[0];
}
}
} | zyyin2005-lokad | Source/Lokad.Cloud.Storage/Shared/Diagnostics/Persistence/ExecutionData.cs | C# | bsd | 2,016 |
#region (c)2009-2011 Lokad - New BSD license
// Company: http://www.lokad.com
// This code is released under the terms of the new BSD licence
#endregion
using System;
namespace Lokad.Cloud.Storage.Shared.Diagnostics
{
/// <summary>
/// Statistics about some execution counter
/// </summary>
[Serializable]
public sealed class ExecutionStatistics
{
readonly long _openCount;
readonly long _closeCount;
readonly long[] _counters;
readonly long _runningTime;
readonly string _name;
/// <summary>
/// Initializes a new instance of the <see cref="ExecutionStatistics"/> class.
/// </summary>
/// <param name="name">The name.</param>
/// <param name="openCount">The open count.</param>
/// <param name="closeCount">The close count.</param>
/// <param name="counters">The counters.</param>
/// <param name="runningTime">The running time.</param>
public ExecutionStatistics(string name, long openCount, long closeCount, long[] counters, long runningTime)
{
_openCount = openCount;
_closeCount = closeCount;
_counters = counters;
_runningTime = runningTime;
_name = name;
}
/// <summary>
/// Gets the number of times the counter has been opened
/// </summary>
/// <value>The open count.</value>
public long OpenCount
{
get { return _openCount; }
}
/// <summary>
/// Gets the number of times the counter has been properly closed.
/// </summary>
/// <value>The close count.</value>
public long CloseCount
{
get { return _closeCount; }
}
/// <summary>
/// Gets the native counters collected by this counter.
/// </summary>
/// <value>The counters.</value>
public long[] Counters
{
get { return _counters; }
}
/// <summary>
/// Gets the total running time between open and close statements in ticks.
/// </summary>
/// <value>The running time expressed in 100-nanosecond units.</value>
public long RunningTime
{
get { return _runningTime; }
}
/// <summary>
/// Gets the name for this counter.
/// </summary>
/// <value>The name.</value>
public string Name
{
get { return _name; }
}
}
}
| zyyin2005-lokad | Source/Lokad.Cloud.Storage/Shared/Diagnostics/ExecutionStatistics.cs | C# | bsd | 2,622 |
#region (c)2009-2011 Lokad - New BSD license
// Company: http://www.lokad.com
// This code is released under the terms of the new BSD licence
#endregion
using System;
using System.Diagnostics;
using System.Threading;
namespace Lokad.Cloud.Storage.Shared.Threading
{
///<summary>
/// Quick alternatives to PLinq with minimal overhead and simple implementations.
///</summary>
public static class ParallelExtensions
{
static int ThreadCount = Environment.ProcessorCount;
/// <summary>Executes the specified function in parallel over an array.</summary>
/// <param name="input">Input array to processed in parallel.</param>
/// <param name="func">The action to perform. Parameters and all the members should be immutable.</param>
/// <remarks>Threads are recycled. Synchronization overhead is minimal.</remarks>
public static TResult[] SelectInParallel<TItem, TResult>(this TItem[] input, Func<TItem, TResult> func)
{
return SelectInParallel(input, func, ThreadCount);
}
/// <summary>
/// Executes the specified function in parallel over an array, using the provided number of threads.
/// </summary>
/// <typeparam name="TItem">The type of the item.</typeparam>
/// <typeparam name="TResult">The type of the result.</typeparam>
/// <param name="input">Input array to processed in parallel.</param>
/// <param name="func">The action to perform. Parameters and all the members should be immutable.</param>
/// <param name="threadCount">The thread count.</param>
/// <returns></returns>
/// <remarks>Threads are recycled. Synchronization overhead is minimal.</remarks>
public static TResult[] SelectInParallel<TItem, TResult>(this TItem[] input, Func<TItem, TResult> func,
int threadCount)
{
if (input == null) throw new ArgumentNullException("input");
if (func == null) throw new ArgumentNullException("func");
if (threadCount < 1)
throw new ArgumentOutOfRangeException("threadCount");
if (input.Length == 0)
return new TResult[0];
var results = new TResult[input.Length];
if (threadCount == 1 || input.Length == 1)
{
for (int i = 0; i < input.Length; i++)
{
try
{
results[i] = func(input[i]);
}
catch (Exception ex)
{
WrapAndThrow(ex);
}
}
return results;
}
// perf: no more threads than items in collection
var actualThreadCount = Math.Min(threadCount, input.Length);
// perf: start by syncless process, then finish with light index-based sync
// to adjust varying execution time of the various threads.
var threshold = Math.Max(0, input.Length - (int)Math.Sqrt(input.Length) - 2 * actualThreadCount);
var workingIndex = threshold - 1;
var sync = new object();
Exception exception = null;
int completedCount = 0;
WaitCallback worker = index =>
{
try
{
// no need for lock - disjoint processing
for (var i = (int)index; i < threshold; i += actualThreadCount)
{
results[i] = func(input[i]);
}
// joint processing
int j;
while ((j = Interlocked.Increment(ref workingIndex)) < input.Length)
{
results[j] = func(input[j]);
}
var r = Interlocked.Increment(ref completedCount);
// perf: only the terminating thread actually acquires a lock.
if (r == actualThreadCount && (int)index != 0)
{
lock (sync) Monitor.Pulse(sync);
}
}
catch (Exception ex)
{
exception = ex;
lock (sync) Monitor.Pulse(sync);
}
};
for (int i = 1; i < actualThreadCount; i++)
{
ThreadPool.QueueUserWorkItem(worker, i);
}
worker((object)0); // perf: recycle current thread
// waiting until completion or failure
while (completedCount < actualThreadCount && exception == null)
{
// CAUTION: limit on wait time is needed because if threads
// have terminated
// - AFTER the test of the 'while' loop, and
// - BEFORE the inner 'lock'
// then, there is no one left to call for 'Pulse'.
lock (sync) Monitor.Wait(sync, TimeSpan.FromMilliseconds(10));
}
if (exception != null)
{
WrapAndThrow(exception);
}
return results;
}
[DebuggerNonUserCode]
static void WrapAndThrow(Exception exception)
{
throw new Exception("Exception caught in SelectInParallel", exception);
}
}
}
| zyyin2005-lokad | Source/Lokad.Cloud.Storage/Shared/Threading/ParallelExtensions.cs | C# | bsd | 5,625 |
#region (c)2009-2011 Lokad - New BSD license
// Company: http://www.lokad.com
// This code is released under the terms of the new BSD licence
#endregion
using System;
using System.Threading;
namespace Lokad.Cloud.Storage.Shared.Threading
{
// HACK: imported back from Lokad.Shared
/// <summary>
/// Helper class for invoking tasks with timeout. Overhead is 0,005 ms.
/// </summary>
/// <typeparam name="TResult">The type of the result.</typeparam>
public sealed class WaitFor<TResult>
{
readonly TimeSpan _timeout;
/// <summary>
/// Initializes a new instance of the <see cref="WaitFor{T}"/> class,
/// using the specified timeout for all operations.
/// </summary>
/// <param name="timeout">The timeout.</param>
public WaitFor(TimeSpan timeout)
{
_timeout = timeout;
}
/// <summary>
/// Executes the specified function within the current thread, aborting it
/// if it does not complete within the specified timeout interval.
/// </summary>
/// <param name="function">The function.</param>
/// <returns>result of the function</returns>
/// <remarks>
/// The performance trick is that we do not interrupt the current
/// running thread. Instead, we just create a watcher that will sleep
/// until the originating thread terminates or until the timeout is
/// elapsed.
/// </remarks>
/// <exception cref="ArgumentNullException">if function is null</exception>
/// <exception cref="TimeoutException">if the function does not finish in time </exception>
public TResult Run(Func<TResult> function)
{
if (function == null) throw new ArgumentNullException("function");
var sync = new object();
var isCompleted = false;
WaitCallback watcher = obj =>
{
var watchedThread = obj as Thread;
lock (sync)
{
if (!isCompleted)
{
Monitor.Wait(sync, _timeout);
}
}
// CAUTION: the call to Abort() can be blocking in rare situations
// http://msdn.microsoft.com/en-us/library/ty8d3wta.aspx
// Hence, it should not be called with the 'lock' as it could deadlock
// with the 'finally' block below.
if (!isCompleted)
{
watchedThread.Abort();
}
};
try
{
ThreadPool.QueueUserWorkItem(watcher, Thread.CurrentThread);
return function();
}
catch (ThreadAbortException)
{
// This is our own exception.
Thread.ResetAbort();
throw new TimeoutException(string.Format("The operation has timed out after {0}.", _timeout));
}
finally
{
lock (sync)
{
isCompleted = true;
Monitor.Pulse(sync);
}
}
}
/// <summary>
/// Executes the specified function within the current thread, aborting it
/// if it does not complete within the specified timeout interval.
/// </summary>
/// <param name="timeout">The timeout.</param>
/// <param name="function">The function.</param>
/// <returns>result of the function</returns>
/// <remarks>
/// The performance trick is that we do not interrupt the current
/// running thread. Instead, we just create a watcher that will sleep
/// until the originating thread terminates or until the timeout is
/// elapsed.
/// </remarks>
/// <exception cref="ArgumentNullException">if function is null</exception>
/// <exception cref="TimeoutException">if the function does not finish in time </exception>
public static TResult Run(TimeSpan timeout, Func<TResult> function)
{
return new WaitFor<TResult>(timeout).Run(function);
}
}
}
| zyyin2005-lokad | Source/Lokad.Cloud.Storage/Shared/Threading/WaitFor.cs | C# | bsd | 4,389 |
#region (c)2009-2011 Lokad - New BSD license
// Company: http://www.lokad.com
// This code is released under the terms of the new BSD licence
#endregion
using System;
using System.Globalization;
namespace Lokad.Cloud.Storage.Shared.Logging
{
/// <summary>
/// Helper extensions for any class that implements <see cref="ILog"/>
/// </summary>
public static class ILogExtensions
{
static readonly CultureInfo _culture = CultureInfo.InvariantCulture;
/// <summary>
/// Determines whether the specified log is recording debug messages.
/// </summary>
/// <param name="log">The log.</param>
/// <returns>
/// <c>true</c> if the specified log is recording debug messages; otherwise, <c>false</c>.
/// </returns>
public static bool IsDebugEnabled(this ILog log)
{
return log.IsEnabled(LogLevel.Debug);
}
/// <summary>
/// Writes message with <see cref="LogLevel.Debug"/> level
/// </summary>
/// <param name="log">Log instance being extended</param>
/// <param name="message">Message</param>
public static void Debug(this ILog log, object message)
{
log.Log(LogLevel.Debug, message);
}
/// <summary>
/// Writes message with <see cref="LogLevel.Debug"/> level
/// </summary>
/// <param name="log">Log instance being extended</param>
/// <param name="format">Format string as in
/// <see cref="string.Format(string,object[])"/></param>
/// <param name="args">Arguments</param>
public static void DebugFormat(this ILog log, string format, params object[] args)
{
log.Log(LogLevel.Debug, string.Format(_culture, format, args));
}
/// <summary>
/// Writes message with <see cref="LogLevel.Debug"/> level and
/// appends the specified <see cref="Exception"/>
/// </summary>
/// <param name="log">Log instance being extended</param>
/// <param name="ex">Exception to add to the message</param>
/// <param name="message">Message</param>
public static void Debug(this ILog log, Exception ex, object message)
{
log.Log(LogLevel.Debug, ex, message);
}
/// <summary>
/// Writes message with <see cref="LogLevel.Debug"/> level and
/// appends the specified <see cref="Exception"/>
/// </summary>
/// <param name="log">Log instance being extended</param>
/// <param name="ex">Exception to add to the message</param>
/// <param name="format">Format string as in
/// <see cref="string.Format(string,object[])"/></param>
/// <param name="args">Arguments</param>
public static void DebugFormat(this ILog log, Exception ex, string format, params object[] args)
{
log.Log(LogLevel.Debug, ex, string.Format(_culture, format, args));
}
/// <summary>
/// Determines whether the specified log is recording info messages.
/// </summary>
/// <param name="log">The log.</param>
/// <returns>
/// <c>true</c> if the specified log is recording info messages; otherwise, <c>false</c>.
/// </returns>
public static bool IsInfoEnabled(this ILog log)
{
return log.IsEnabled(LogLevel.Info);
}
/// <summary>
/// Writes message with <see cref="LogLevel.Info"/> level
/// </summary>
/// <param name="log">Log instance being extended</param>
/// <param name="message">Message</param>
public static void Info(this ILog log, object message)
{
log.Log(LogLevel.Info, message);
}
/// <summary>
/// Writes message with <see cref="LogLevel.Info"/> level
/// </summary>
/// <param name="log">Log instance being extended</param>
/// <param name="format">Format string as in
/// <see cref="string.Format(string,object[])"/></param>
/// <param name="args">Arguments</param>
public static void InfoFormat(this ILog log, string format, params object[] args)
{
log.Log(LogLevel.Info, string.Format(_culture, format, args));
}
/// <summary>
/// Writes message with <see cref="LogLevel.Info"/> level and
/// appends the specified <see cref="Exception"/>
/// </summary>
/// <param name="log">Log instance being extended</param>
/// <param name="ex">Exception to add to the message</param>
/// <param name="message">Message</param>
public static void Info(this ILog log, Exception ex, object message)
{
log.Log(LogLevel.Info, ex, message);
}
/// <summary>
/// Writes message with <see cref="LogLevel.Info"/> level and
/// appends the specified <see cref="Exception"/>
/// </summary>
/// <param name="log">Log instance being extended</param>
/// <param name="ex">Exception to add to the message</param>
/// <param name="format">Format string as in
/// <see cref="string.Format(string,object[])"/></param>
/// <param name="args">Arguments</param>
public static void InfoFormat(this ILog log, Exception ex, string format, params object[] args)
{
log.Log(LogLevel.Info, ex, string.Format(_culture, format, args));
}
/// <summary>
/// Determines whether the specified log is recording warning messages.
/// </summary>
/// <param name="log">The log.</param>
/// <returns>
/// <c>true</c> if the specified log is recording warning messages; otherwise, <c>false</c>.
/// </returns>
public static bool IsWarnEnabled(this ILog log)
{
return log.IsEnabled(LogLevel.Warn);
}
/// <summary>
/// Writes message with <see cref="LogLevel.Warn"/> level
/// </summary>
/// <param name="log">Log instance being extended</param>
/// <param name="message">Message</param>
public static void Warn(this ILog log, object message)
{
log.Log(LogLevel.Warn, message);
}
/// <summary>
/// Writes message with <see cref="LogLevel.Warn"/> level
/// </summary>
/// <param name="log">Log instance being extended</param>
/// <param name="format">Format string as in
/// <see cref="string.Format(string,object[])"/></param>
/// <param name="args">Arguments</param>
public static void WarnFormat(this ILog log, string format, params object[] args)
{
log.Log(LogLevel.Warn, string.Format(_culture, format, args));
}
/// <summary>
/// Writes message with <see cref="LogLevel.Warn"/> level and
/// appends the specified <see cref="Exception"/>
/// </summary>
/// <param name="log">Log instance being extended</param>
/// <param name="ex">Exception to add to the message</param>
/// <param name="message">Message</param>
public static void Warn(this ILog log, Exception ex, object message)
{
log.Log(LogLevel.Warn, ex, message);
}
/// <summary>
/// Writes message with <see cref="LogLevel.Warn"/> level and
/// appends the specified <see cref="Exception"/>
/// </summary>
/// <param name="log">Log instance being extended</param>
/// <param name="ex">Exception to add to the message</param>
/// <param name="format">Format string as in
/// <see cref="string.Format(string,object[])"/></param>
/// <param name="args">Arguments</param>
public static void WarnFormat(this ILog log, Exception ex, string format, params object[] args)
{
log.Log(LogLevel.Warn, ex, string.Format(_culture, format, args));
}
/// <summary>
/// Determines whether the specified log is recording error messages.
/// </summary>
/// <param name="log">The log.</param>
/// <returns>
/// <c>true</c> if the specified log is recording error messages; otherwise, <c>false</c>.
/// </returns>
public static bool IsErrorEnabled(this ILog log)
{
return log.IsEnabled(LogLevel.Error);
}
/// <summary>
/// Writes message with <see cref="LogLevel.Error"/> level
/// </summary>
/// <param name="log">Log instance being extended</param>
/// <param name="message">Message</param>
public static void Error(this ILog log, object message)
{
log.Log(LogLevel.Error, message);
}
/// <summary>
/// Writes message with <see cref="LogLevel.Error"/> level
/// </summary>
/// <param name="log">Log instance being extended</param>
/// <param name="format">Format string as in
/// <see cref="string.Format(string,object[])"/></param>
/// <param name="args">Arguments</param>
public static void ErrorFormat(this ILog log, string format, params object[] args)
{
log.Log(LogLevel.Error, string.Format(_culture, format, args));
}
/// <summary>
/// Writes message with <see cref="LogLevel.Error"/> level and
/// appends the specified <see cref="Exception"/>
/// </summary>
/// <param name="log">Log instance being extended</param>
/// <param name="ex">Exception to add to the message</param>
/// <param name="message">Message</param>
public static void Error(this ILog log, Exception ex, object message)
{
log.Log(LogLevel.Error, ex, message);
}
/// <summary>
/// Writes message with <see cref="LogLevel.Error"/> level and
/// appends the specified <see cref="Exception"/>
/// </summary>
/// <param name="log">Log instance being extended</param>
/// <param name="ex">Exception to add to the message</param>
/// <param name="format">Format string as in
/// <see cref="string.Format(string,object[])"/></param>
/// <param name="args">Arguments</param>
public static void ErrorFormat(this ILog log, Exception ex, string format, params object[] args)
{
log.Log(LogLevel.Error, ex, string.Format(_culture, format, args));
}
/// <summary>
/// Determines whether the specified log is recording Fatal messages.
/// </summary>
/// <param name="log">The log.</param>
/// <returns>
/// <c>true</c> if the specified log is recording datal messages; otherwise, <c>false</c>.
/// </returns>
public static bool IsFatalEnabled(this ILog log)
{
return log.IsEnabled(LogLevel.Fatal);
}
/// <summary>
/// Writes message with <see cref="LogLevel.Fatal"/> level
/// </summary>
/// <param name="log">Log instance being extended</param>
/// <param name="message">Message</param>
public static void Fatal(this ILog log, object message)
{
log.Log(LogLevel.Fatal, message);
}
/// <summary>
/// Writes message with <see cref="LogLevel.Fatal"/> level
/// </summary>
/// <param name="log">Log instance being extended</param>
/// <param name="format">Format string as in
/// <see cref="string.Format(string,object[])"/></param>
/// <param name="args">Arguments</param>
public static void FatalFormat(this ILog log, string format, params object[] args)
{
log.Log(LogLevel.Fatal, string.Format(_culture, format, args));
}
/// <summary>
/// Writes message with <see cref="LogLevel.Fatal"/> level and
/// appends the specified <see cref="Exception"/>
/// </summary>
/// <param name="log">Log instance being extended</param>
/// <param name="ex">Exception to add to the message</param>
/// <param name="message">Message</param>
public static void Fatal(this ILog log, Exception ex, object message)
{
log.Log(LogLevel.Fatal, ex, message);
}
/// <summary>
/// Writes message with <see cref="LogLevel.Fatal"/> level and
/// appends the specified <see cref="Exception"/>
/// </summary>
/// <param name="log">Log instance being extended</param>
/// <param name="ex">Exception to add to the message</param>
/// <param name="format">Format string as in
/// <see cref="string.Format(string,object[])"/></param>
/// <param name="args">Arguments</param>
public static void FatalFormat(this ILog log, Exception ex, string format, params object[] args)
{
log.Log(LogLevel.Fatal, ex, string.Format(_culture, format, args));
}
}
}
| zyyin2005-lokad | Source/Lokad.Cloud.Storage/Shared/Logging/ILogExtensions.cs | C# | bsd | 13,428 |
#region (c)2009-2011 Lokad - New BSD license
// Company: http://www.lokad.com
// This code is released under the terms of the new BSD licence
#endregion
using System;
namespace Lokad.Cloud.Storage.Shared.Logging
{
/// <summary> <see cref="ILog"/> that does not do anything.</summary>
[Serializable]
public sealed class NullLog : ILog
{
/// <summary>
/// Singleton instance of the <see cref="NullLog"/>.
/// </summary>
public static readonly ILog Instance = new NullLog();
/// <summary>
/// Singleton instance of the <see cref="NullLogProvider"/>.
/// </summary>
public static readonly ILogProvider Provider = new NullLogProvider();
NullLog()
{
}
void ILog.Log(LogLevel level, object message)
{
}
void ILog.Log(LogLevel level, Exception ex, object message)
{
}
bool ILog.IsEnabled(LogLevel level)
{
return false;
}
}
/// <summary>Returns the <see cref="ILog"/> that does not do anything.</summary>
public sealed class NullLogProvider : ILogProvider
{
/// <remarks></remarks>
public ILog Get(string key)
{
return NullLog.Instance;
}
}
}
| zyyin2005-lokad | Source/Lokad.Cloud.Storage/Shared/Logging/NullLog.cs | C# | bsd | 1,349 |