diff options
32 files changed, 1443 insertions, 22 deletions
| diff --git a/.gitignore b/.gitignore deleted file mode 100644 index 16e54e2..0000000 --- a/.gitignore +++ /dev/null @@ -1,22 +0,0 @@ -/.web-server-pid -/app/config/parameters.yml -/build/ -/phpunit.xml -/var/* -!/var/cache -/var/cache/* -!var/cache/.gitkeep -!/var/logs -/var/logs/* -!var/logs/.gitkeep -!/var/sessions -/var/sessions/* -!var/sessions/.gitkeep -!var/SymfonyRequirements.php -/vendor/ -/web/bundles/ -<<<<<<< HEAD -.idea -======= -/.idea/ ->>>>>>> 72114be2d32b090f68996acb87cef7fde748b534 diff --git a/PollutometerWebApi.Tests/AqiCalculatorTests.cs b/PollutometerWebApi.Tests/AqiCalculatorTests.cs new file mode 100644 index 0000000..e84b687 --- /dev/null +++ b/PollutometerWebApi.Tests/AqiCalculatorTests.cs @@ -0,0 +1,51 @@ +using Microsoft.VisualStudio.TestTools.UnitTesting; +using PollutometerWebApi.Models; + +namespace PollutometerWebApi.Tests +{ +    [TestClass()] +    public class AqiCalculatorTests +    { +        [TestMethod()] +        public void CalculateAqiPerfectTest() +        { +            var reading = new Reading +            { +                Co = 2.2, +                No = 0.1, +                So = 0.8 +            }; + +            var result = AqiCalculator.CalculateAqi(reading); +            Assert.AreEqual(398.0100502512563, result.Value); +        } + +        [TestMethod()] +        public void CalculateAqiBigNumbersTest() +        { +            var reading = new Reading +            { +                Co = 100.2, +                No = 100.1, +                So = 100.8 +            }; + +            var result = AqiCalculator.CalculateAqi(reading); +            Assert.AreEqual(0, result.Value); +        } + +        [TestMethod()] +        public void CalculateAqiZerosTest() +        { +            var reading = new Reading +            { +                Co = 0, +                No = 0, +                So = 0 +            }; + +            var result = AqiCalculator.CalculateAqi(reading); +            Assert.AreEqual(0, result.Value); +        } +    } +}
\ No newline at end of file diff --git a/PollutometerWebApi.Tests/EmailSenderTests.cs b/PollutometerWebApi.Tests/EmailSenderTests.cs new file mode 100644 index 0000000..427ec92 --- /dev/null +++ b/PollutometerWebApi.Tests/EmailSenderTests.cs @@ -0,0 +1,21 @@ +using Microsoft.VisualStudio.TestTools.UnitTesting; +using PollutometerWebApi.Models; + +namespace PollutometerWebApi.Tests +{ +    [TestClass()] +    public class EmailSenderTests +    { +        [TestMethod()] +        public void SendEmailTest() +        { +            var aqi = new Aqi +            { +                GasName = "SO", +                Value = 69, +                Level = "Moderate" +            }; +            EmailSender.SendEmail(aqi); +        } +    } +}
\ No newline at end of file diff --git a/PollutometerWebApi.Tests/PollutometerWebApi.Tests.csproj b/PollutometerWebApi.Tests/PollutometerWebApi.Tests.csproj new file mode 100644 index 0000000..6ff37aa --- /dev/null +++ b/PollutometerWebApi.Tests/PollutometerWebApi.Tests.csproj @@ -0,0 +1,125 @@ +<?xml version="1.0" encoding="utf-8"?>
 +<Project ToolsVersion="15.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
 +  <Import Project="..\packages\MSTest.TestAdapter.1.1.18\build\net45\MSTest.TestAdapter.props" Condition="Exists('..\packages\MSTest.TestAdapter.1.1.18\build\net45\MSTest.TestAdapter.props')" />
 +  <PropertyGroup>
 +    <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
 +    <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
 +    <ProjectGuid>{94A21C38-920E-42EF-8D48-B133D635EAFA}</ProjectGuid>
 +    <OutputType>Library</OutputType>
 +    <AppDesignerFolder>Properties</AppDesignerFolder>
 +    <RootNamespace>PollutometerWebApi.Tests</RootNamespace>
 +    <AssemblyName>PollutometerWebApi.Tests</AssemblyName>
 +    <TargetFrameworkVersion>v4.6.2</TargetFrameworkVersion>
 +    <FileAlignment>512</FileAlignment>
 +    <ProjectTypeGuids>{3AC096D0-A1C2-E12C-1390-A8335801FDAB};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}</ProjectTypeGuids>
 +    <VisualStudioVersion Condition="'$(VisualStudioVersion)' == ''">10.0</VisualStudioVersion>
 +    <VSToolsPath Condition="'$(VSToolsPath)' == ''">$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)</VSToolsPath>
 +    <ReferencePath>$(ProgramFiles)\Common Files\microsoft shared\VSTT\$(VisualStudioVersion)\UITestExtensionPackages</ReferencePath>
 +    <IsCodedUITest>False</IsCodedUITest>
 +    <TestProjectType>UnitTest</TestProjectType>
 +    <TargetFrameworkProfile />
 +    <NuGetPackageImportStamp>
 +    </NuGetPackageImportStamp>
 +  </PropertyGroup>
 +  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
 +    <DebugSymbols>true</DebugSymbols>
 +    <DebugType>full</DebugType>
 +    <Optimize>false</Optimize>
 +    <OutputPath>bin\Debug\</OutputPath>
 +    <DefineConstants>DEBUG;TRACE</DefineConstants>
 +    <ErrorReport>prompt</ErrorReport>
 +    <WarningLevel>4</WarningLevel>
 +  </PropertyGroup>
 +  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
 +    <DebugType>pdbonly</DebugType>
 +    <Optimize>true</Optimize>
 +    <OutputPath>bin\Release\</OutputPath>
 +    <DefineConstants>TRACE</DefineConstants>
 +    <ErrorReport>prompt</ErrorReport>
 +    <WarningLevel>4</WarningLevel>
 +  </PropertyGroup>
 +  <ItemGroup>
 +    <Reference Include="Microsoft.VisualStudio.TestPlatform.TestFramework, Version=14.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL">
 +      <HintPath>..\packages\MSTest.TestFramework.1.1.18\lib\net45\Microsoft.VisualStudio.TestPlatform.TestFramework.dll</HintPath>
 +    </Reference>
 +    <Reference Include="Microsoft.VisualStudio.TestPlatform.TestFramework.Extensions, Version=14.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL">
 +      <HintPath>..\packages\MSTest.TestFramework.1.1.18\lib\net45\Microsoft.VisualStudio.TestPlatform.TestFramework.Extensions.dll</HintPath>
 +    </Reference>
 +    <Reference Include="Newtonsoft.Json, Version=6.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed, processorArchitecture=MSIL">
 +      <HintPath>..\packages\Newtonsoft.Json.6.0.4\lib\net45\Newtonsoft.Json.dll</HintPath>
 +      <Private>True</Private>
 +    </Reference>
 +    <Reference Include="System" />
 +    <Reference Include="System.Net.Http" />
 +    <Reference Include="System.Net.Http.Formatting, Version=5.2.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL">
 +      <HintPath>..\packages\Microsoft.AspNet.WebApi.Client.5.2.0\lib\net45\System.Net.Http.Formatting.dll</HintPath>
 +    </Reference>
 +    <Reference Include="System.Transactions" />
 +    <Reference Include="System.Web.Http, Version=5.2.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL">
 +      <HintPath>..\packages\Microsoft.AspNet.WebApi.Core.5.2.0\lib\net45\System.Web.Http.dll</HintPath>
 +    </Reference>
 +    <Reference Include="System.Web.Http.WebHost, Version=5.2.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL">
 +      <HintPath>..\packages\Microsoft.AspNet.WebApi.WebHost.5.2.0\lib\net45\System.Web.Http.WebHost.dll</HintPath>
 +    </Reference>
 +  </ItemGroup>
 +  <Choose>
 +    <When Condition="('$(VisualStudioVersion)' == '10.0' or '$(VisualStudioVersion)' == '') and '$(TargetFrameworkVersion)' == 'v3.5'">
 +      <ItemGroup>
 +        <Reference Include="Microsoft.VisualStudio.QualityTools.UnitTestFramework, Version=10.1.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL" />
 +      </ItemGroup>
 +    </When>
 +    <Otherwise />
 +  </Choose>
 +  <ItemGroup>
 +    <Compile Include="AqiCalculatorTests.cs" />
 +    <Compile Include="EmailSenderTests.cs" />
 +    <Compile Include="ReadingsControllerTests.cs" />
 +    <Compile Include="Properties\AssemblyInfo.cs" />
 +    <Compile Include="SqlOperatorTests.cs" />
 +  </ItemGroup>
 +  <ItemGroup>
 +    <None Include="app.config" />
 +    <None Include="packages.config" />
 +  </ItemGroup>
 +  <ItemGroup>
 +    <ProjectReference Include="..\PollutometerWebApi\PollutometerWebApi.csproj">
 +      <Project>{22C32F4C-0DEB-40EA-9D56-48942CBB2A07}</Project>
 +      <Name>PollutometerWebApi</Name>
 +    </ProjectReference>
 +  </ItemGroup>
 +  <Choose>
 +    <When Condition="'$(VisualStudioVersion)' == '10.0' And '$(IsCodedUITest)' == 'True'">
 +      <ItemGroup>
 +        <Reference Include="Microsoft.VisualStudio.QualityTools.CodedUITestFramework, Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL">
 +          <Private>False</Private>
 +        </Reference>
 +        <Reference Include="Microsoft.VisualStudio.TestTools.UITest.Common, Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL">
 +          <Private>False</Private>
 +        </Reference>
 +        <Reference Include="Microsoft.VisualStudio.TestTools.UITest.Extension, Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL">
 +          <Private>False</Private>
 +        </Reference>
 +        <Reference Include="Microsoft.VisualStudio.TestTools.UITesting, Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL">
 +          <Private>False</Private>
 +        </Reference>
 +      </ItemGroup>
 +    </When>
 +  </Choose>
 +  <Import Project="$(VSToolsPath)\TeamTest\Microsoft.TestTools.targets" Condition="Exists('$(VSToolsPath)\TeamTest\Microsoft.TestTools.targets')" />
 +  <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
 +  <Target Name="EnsureNuGetPackageBuildImports" BeforeTargets="PrepareForBuild">
 +    <PropertyGroup>
 +      <ErrorText>This project references NuGet package(s) that are missing on this computer. Use NuGet Package Restore to download them.  For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}.</ErrorText>
 +    </PropertyGroup>
 +    <Error Condition="!Exists('..\packages\MSTest.TestAdapter.1.1.18\build\net45\MSTest.TestAdapter.props')" Text="$([System.String]::Format('$(ErrorText)', '..\packages\MSTest.TestAdapter.1.1.18\build\net45\MSTest.TestAdapter.props'))" />
 +    <Error Condition="!Exists('..\packages\MSTest.TestAdapter.1.1.18\build\net45\MSTest.TestAdapter.targets')" Text="$([System.String]::Format('$(ErrorText)', '..\packages\MSTest.TestAdapter.1.1.18\build\net45\MSTest.TestAdapter.targets'))" />
 +  </Target>
 +  <Import Project="..\packages\MSTest.TestAdapter.1.1.18\build\net45\MSTest.TestAdapter.targets" Condition="Exists('..\packages\MSTest.TestAdapter.1.1.18\build\net45\MSTest.TestAdapter.targets')" />
 +  <!-- To modify your build process, add your task inside one of the targets below and uncomment it. 
 +       Other similar extension points exist, see Microsoft.Common.targets.
 +  <Target Name="BeforeBuild">
 +  </Target>
 +  <Target Name="AfterBuild">
 +  </Target>
 +  -->
 +</Project>
\ No newline at end of file diff --git a/PollutometerWebApi.Tests/Properties/AssemblyInfo.cs b/PollutometerWebApi.Tests/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..d6c3cc7 --- /dev/null +++ b/PollutometerWebApi.Tests/Properties/AssemblyInfo.cs @@ -0,0 +1,36 @@ +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("PollutometerWebApi.Tests")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("PollutometerWebApi.Tests")] +[assembly: AssemblyCopyright("Copyright ©  2017")] +[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("94a21c38-920e-42ef-8d48-b133d635eafa")] + +// 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 Build and Revision Numbers  +// by using the '*' as shown below: +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/PollutometerWebApi.Tests/ReadingsControllerTests.cs b/PollutometerWebApi.Tests/ReadingsControllerTests.cs new file mode 100644 index 0000000..647649d --- /dev/null +++ b/PollutometerWebApi.Tests/ReadingsControllerTests.cs @@ -0,0 +1,116 @@ +using Microsoft.VisualStudio.TestTools.UnitTesting; +using PollutometerWebApi.Models; +using System; +using System.Collections.Generic; +using System.Web.Http.Results; + +namespace PollutometerWebApi.Controllers.Tests +{ +    [TestClass()] +    public class ReadingsControllerTests +    { +        ReadingsController controller = new ReadingsController(); + +        [TestMethod()] +        public void GetAllReadingsTest() +        { +            var actionResult = controller.GetAllReadings(); +            var content = ((OkNegotiatedContentResult<List<Reading>>)actionResult).Content; +            Assert.IsTrue(content.Count >= 1); +        } + + +        [TestMethod()] +        public void GetReadingTest() +        { +            var actionResult = controller.GetReading(0); +            Assert.IsInstanceOfType(actionResult, typeof(OkNegotiatedContentResult<Reading>)); +        } + +        [TestMethod()] +        public void GetLatestReadingTest() +        { +            var actionResult = controller.GetLatestReading(); +            var content = ((OkNegotiatedContentResult<Reading>)actionResult).Content; +            Assert.IsNotNull(content); +        } + +        [TestMethod()] +        public void GetReadingsFromLastWeekTest() +        { +            var actionResult = controller.GetReadingsFromLastWeek(); +            var content = ((OkNegotiatedContentResult<List<Reading>>)actionResult).Content; +            foreach(var reading in content) +            { +                var now = DateTimeOffset.Now.ToUnixTimeSeconds(); +                Assert.IsTrue(reading.TimeStamp < now && reading.TimeStamp > now - 7*24*3600); +            } +        } + +        [TestMethod()] +        public void PostReadingPassTest() +        { +            var newReading = new Reading +            { +                TimeStamp = (int)DateTimeOffset.Now.ToUnixTimeSeconds(), +                Co = 1.0, +                No = 1.0, +                So = 1.0 +            }; +            var actionResult = controller.PostReading(newReading); +            var reading = controller.GetLatestReading(); +            var content = ((OkNegotiatedContentResult<Reading>)reading).Content; +            Assert.AreEqual(newReading.TimeStamp, content.TimeStamp); +        } + +        [TestMethod()] +        public void PostReadingFailTest() +        { +            var actionResult = controller.PostReading(null); +            Assert.IsInstanceOfType(actionResult, typeof(BadRequestResult)); +        } + +        [TestMethod()] +        public void PutReadingPassTest() +        { +            var latest = controller.GetLatestReading(); +            var content = ((OkNegotiatedContentResult<Reading>)latest).Content; +            var actionResult = controller.PutReading(content.Id, +                new Reading +                { +                    TimeStamp = (int)DateTimeOffset.Now.ToUnixTimeSeconds(), +                    Co = 2.0, +                    No = 2.0, +                    So = 2.0 +                } +                ); +            Assert.AreEqual(typeof(OkResult), actionResult.GetType()); +        } + +        [TestMethod()] +        public void PutReadingFailTest() +        { +            var latest = controller.GetLatestReading(); +            var content = ((OkNegotiatedContentResult<Reading>)latest).Content; +            var actionResult = controller.PutReading(content.Id, null); +            Assert.AreEqual(typeof(BadRequestResult), actionResult.GetType()); +        } + +        [TestMethod()] +        public void DeleteReadingPassTest() +        { +            var latest = controller.GetLatestReading(); +            var content = ((OkNegotiatedContentResult<Reading>)latest).Content; +            var actionResult = controller.DeleteReading(content.Id); +            var reading = controller.GetReading(content.Id); +            Assert.IsInstanceOfType(reading, typeof(NotFoundResult)); +        } + +        [TestMethod()] +        public void DeleteReadingFailTest() +        { +            var actionResult = controller.DeleteReading(1337); +            Assert.IsInstanceOfType(actionResult, typeof(NotFoundResult)); +        } +    } +}
\ No newline at end of file diff --git a/PollutometerWebApi.Tests/SqlOperatorTests.cs b/PollutometerWebApi.Tests/SqlOperatorTests.cs new file mode 100644 index 0000000..2930679 --- /dev/null +++ b/PollutometerWebApi.Tests/SqlOperatorTests.cs @@ -0,0 +1,68 @@ +using Microsoft.VisualStudio.TestTools.UnitTesting; +using PollutometerWebApi.Models; +using System; + +namespace PollutometerWebApi.Tests +{ +    [TestClass()] +    public class SqlOperatorTests +    { +        [TestMethod()] +        public void GetReadingsTest() +        { +            var readings = SqlOperator.GetReadings("SELECT * FROM Readings"); +            Assert.IsTrue(readings.Count >= 1); +        } + +        [TestMethod()] +        public void PostReadingTest() +        { +            var newReading = new Reading +            { +                TimeStamp = (int)DateTimeOffset.Now.ToUnixTimeSeconds(), +                Co = 0.0, +                No = 0.0, +                So = 0.0 +            }; +            SqlOperator.PostReading(newReading); +            var command = "SELECT * FROM Readings " + +                "WHERE TimeStamp IN(SELECT MAX(TimeStamp) FROM Readings)"; +            var latestReading = SqlOperator.GetReadings(command)[0]; +            var command2 = $"SELECT * FROM Readings WHERE Id={latestReading.Id}"; +            var reading = SqlOperator.GetReadings(command2)[0]; +            Assert.AreEqual(newReading.TimeStamp, reading.TimeStamp); +        } + +        [TestMethod()] +        public void PutReadingTest() +        { +            var newReading = new Reading +            { +                TimeStamp = (int)DateTimeOffset.Now.ToUnixTimeSeconds(), +                Co = 0.5, +                No = 0.5, +                So = 0.5 + +            }; +            var command = "SELECT * FROM Readings " + +                "WHERE TimeStamp IN(SELECT MAX(TimeStamp) FROM Readings)"; +            var latestReading = SqlOperator.GetReadings(command)[0]; +            SqlOperator.PutReading(latestReading.Id, newReading); +            var command2 = $"SELECT * FROM Readings WHERE Id={latestReading.Id}"; +            var reading = SqlOperator.GetReadings(command2)[0]; +            Assert.AreEqual(newReading.TimeStamp, reading.TimeStamp); +        } + +        [TestMethod()] +        public void DeleteReadingTest() +        { +            var command = "SELECT * FROM Readings " + +                   "WHERE TimeStamp IN(SELECT MAX(TimeStamp) FROM Readings)"; +            var latestReading = SqlOperator.GetReadings(command)[0]; +            SqlOperator.DeleteReading(latestReading.Id); +            var command2 = $"SELECT * FROM Readings WHERE Id={latestReading.Id}"; +            var readings = SqlOperator.GetReadings(command2); +            Assert.IsTrue(readings.Count == 0); +        } +    } +}
\ No newline at end of file diff --git a/PollutometerWebApi.Tests/app.config b/PollutometerWebApi.Tests/app.config new file mode 100644 index 0000000..4429813 --- /dev/null +++ b/PollutometerWebApi.Tests/app.config @@ -0,0 +1,11 @@ +<?xml version="1.0" encoding="utf-8"?> +<configuration> +  <runtime> +    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1"> +      <dependentAssembly> +        <assemblyIdentity name="Newtonsoft.Json" publicKeyToken="30ad4fe6b2a6aeed" culture="neutral" /> +        <bindingRedirect oldVersion="0.0.0.0-6.0.0.0" newVersion="6.0.0.0" /> +      </dependentAssembly> +    </assemblyBinding> +  </runtime> +</configuration>
\ No newline at end of file diff --git a/PollutometerWebApi.Tests/packages.config b/PollutometerWebApi.Tests/packages.config new file mode 100644 index 0000000..7472064 --- /dev/null +++ b/PollutometerWebApi.Tests/packages.config @@ -0,0 +1,10 @@ +<?xml version="1.0" encoding="utf-8"?> +<packages> +  <package id="Microsoft.AspNet.WebApi" version="5.2.0" targetFramework="net462" /> +  <package id="Microsoft.AspNet.WebApi.Client" version="5.2.0" targetFramework="net462" /> +  <package id="Microsoft.AspNet.WebApi.Core" version="5.2.0" targetFramework="net462" /> +  <package id="Microsoft.AspNet.WebApi.WebHost" version="5.2.0" targetFramework="net462" /> +  <package id="MSTest.TestAdapter" version="1.1.18" targetFramework="net462" /> +  <package id="MSTest.TestFramework" version="1.1.18" targetFramework="net462" /> +  <package id="Newtonsoft.Json" version="6.0.4" targetFramework="net462" /> +</packages>
\ No newline at end of file diff --git a/PollutometerWebApi.sln b/PollutometerWebApi.sln new file mode 100644 index 0000000..b4180e0 --- /dev/null +++ b/PollutometerWebApi.sln @@ -0,0 +1,30 @@ +Microsoft Visual Studio Solution File, Format Version 12.00
 +# Visual Studio 15
 +VisualStudioVersion = 15.0.27004.2009
 +MinimumVisualStudioVersion = 10.0.40219.1
 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "PollutometerWebApi", "PollutometerWebApi\PollutometerWebApi.csproj", "{22C32F4C-0DEB-40EA-9D56-48942CBB2A07}"
 +EndProject
 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "PollutometerWebApi.Tests", "PollutometerWebApi.Tests\PollutometerWebApi.Tests.csproj", "{94A21C38-920E-42EF-8D48-B133D635EAFA}"
 +EndProject
 +Global
 +	GlobalSection(SolutionConfigurationPlatforms) = preSolution
 +		Debug|Any CPU = Debug|Any CPU
 +		Release|Any CPU = Release|Any CPU
 +	EndGlobalSection
 +	GlobalSection(ProjectConfigurationPlatforms) = postSolution
 +		{22C32F4C-0DEB-40EA-9D56-48942CBB2A07}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
 +		{22C32F4C-0DEB-40EA-9D56-48942CBB2A07}.Debug|Any CPU.Build.0 = Debug|Any CPU
 +		{22C32F4C-0DEB-40EA-9D56-48942CBB2A07}.Release|Any CPU.ActiveCfg = Release|Any CPU
 +		{22C32F4C-0DEB-40EA-9D56-48942CBB2A07}.Release|Any CPU.Build.0 = Release|Any CPU
 +		{94A21C38-920E-42EF-8D48-B133D635EAFA}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
 +		{94A21C38-920E-42EF-8D48-B133D635EAFA}.Debug|Any CPU.Build.0 = Debug|Any CPU
 +		{94A21C38-920E-42EF-8D48-B133D635EAFA}.Release|Any CPU.ActiveCfg = Release|Any CPU
 +		{94A21C38-920E-42EF-8D48-B133D635EAFA}.Release|Any CPU.Build.0 = Release|Any CPU
 +	EndGlobalSection
 +	GlobalSection(SolutionProperties) = preSolution
 +		HideSolutionNode = FALSE
 +	EndGlobalSection
 +	GlobalSection(ExtensibilityGlobals) = postSolution
 +		SolutionGuid = {0EB49A9B-6175-4CB9-8202-5918BA7D2525}
 +	EndGlobalSection
 +EndGlobal
 diff --git a/PollutometerWebApi.userprefs b/PollutometerWebApi.userprefs new file mode 100644 index 0000000..822fb73 --- /dev/null +++ b/PollutometerWebApi.userprefs @@ -0,0 +1,21 @@ +<Properties StartupConfiguration="{D19CA1E0-796F-480A-996D-3DFABFC6203F}|Unit Tests"> +  <MonoDevelop.Ide.Workbench ActiveDocument="PollutometerWebApi/Models/Aqi.cs"> +    <Files> +      <File FileName="PollutometerWebApi/AqiCalculator.cs" Line="7" Column="16" /> +      <File FileName="PollutometerWebApi.Tests/Test.cs" Line="16" Column="1" /> +      <File FileName="PollutometerWebApi/Controllers/ReadingsController.cs" Line="71" Column="48" /> +      <File FileName="PollutometerWebApi/EmailSender.cs" Line="25" Column="23" /> +      <File FileName="PollutometerWebApi/Models/Aqi.cs" Line="10" Column="14" /> +    </Files> +  </MonoDevelop.Ide.Workbench> +  <MonoDevelop.Ide.Workspace ActiveConfiguration="Debug" /> +  <MonoDevelop.Ide.ItemProperties.PollutometerWebApi PreferredExecutionTarget="MonoDevelop.Default" /> +  <MonoDevelop.Ide.DebuggingService.Breakpoints> +    <BreakpointStore> +      <Breakpoint file="/home/marcin/MonoDevelop Projects/Pollutometer-WebAPI/PollutometerWebApi/EmailSender.cs" relfile="PollutometerWebApi/EmailSender.cs" line="31" column="13" /> +    </BreakpointStore> +  </MonoDevelop.Ide.DebuggingService.Breakpoints> +  <MonoDevelop.Ide.ItemProperties.PollutometerWebApi.Tests PreferredExecutionTarget="MonoDevelop.Default" /> +  <MonoDevelop.Ide.DebuggingService.PinnedWatches /> +  <MultiItemStartupConfigurations /> +</Properties>
\ No newline at end of file diff --git a/PollutometerWebApi/.gitignore b/PollutometerWebApi/.gitignore new file mode 100644 index 0000000..940794e --- /dev/null +++ b/PollutometerWebApi/.gitignore @@ -0,0 +1,288 @@ +## Ignore Visual Studio temporary files, build results, and +## files generated by popular Visual Studio add-ons. +## +## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore + +# User-specific files +*.suo +*.user +*.userosscache +*.sln.docstates + +# User-specific files (MonoDevelop/Xamarin Studio) +*.userprefs + +# Build results +[Dd]ebug/ +[Dd]ebugPublic/ +[Rr]elease/ +[Rr]eleases/ +x64/ +x86/ +bld/ +[Bb]in/ +[Oo]bj/ +[Ll]og/ + +# Visual Studio 2015 cache/options directory +.vs/ +# Uncomment if you have tasks that create the project's static files in wwwroot +#wwwroot/ + +# MSTest test Results +[Tt]est[Rr]esult*/ +[Bb]uild[Ll]og.* + +# NUNIT +*.VisualState.xml +TestResult.xml + +# Build Results of an ATL Project +[Dd]ebugPS/ +[Rr]eleasePS/ +dlldata.c + +# .NET Core +project.lock.json +project.fragment.lock.json +artifacts/ +**/Properties/launchSettings.json + +*_i.c +*_p.c +*_i.h +*.ilk +*.meta +*.obj +*.pch +*.pdb +*.pgc +*.pgd +*.rsp +*.sbr +*.tlb +*.tli +*.tlh +*.tmp +*.tmp_proj +*.log +*.vspscc +*.vssscc +.builds +*.pidb +*.svclog +*.scc + +# Chutzpah Test files +_Chutzpah* + +# Visual C++ cache files +ipch/ +*.aps +*.ncb +*.opendb +*.opensdf +*.sdf +*.cachefile +*.VC.db +*.VC.VC.opendb + +# Visual Studio profiler +*.psess +*.vsp +*.vspx +*.sap + +# TFS 2012 Local Workspace +$tf/ + +# Guidance Automation Toolkit +*.gpState + +# ReSharper is a .NET coding add-in +_ReSharper*/ +*.[Rr]e[Ss]harper +*.DotSettings.user + +# JustCode is a .NET coding add-in +.JustCode + +# TeamCity is a build add-in +_TeamCity* + +# DotCover is a Code Coverage Tool +*.dotCover + +# Visual Studio code coverage results +*.coverage +*.coveragexml + +# NCrunch +_NCrunch_* +.*crunch*.local.xml +nCrunchTemp_* + +# MightyMoose +*.mm.* +AutoTest.Net/ + +# Web workbench (sass) +.sass-cache/ + +# Installshield output folder +[Ee]xpress/ + +# DocProject is a documentation generator add-in +DocProject/buildhelp/ +DocProject/Help/*.HxT +DocProject/Help/*.HxC +DocProject/Help/*.hhc +DocProject/Help/*.hhk +DocProject/Help/*.hhp +DocProject/Help/Html2 +DocProject/Help/html + +# Click-Once directory +publish/ + +# Publish Web Output +*.[Pp]ublish.xml +*.azurePubxml +# TODO: Comment the next line if you want to checkin your web deploy settings +# but database connection strings (with potential passwords) will be unencrypted +*.pubxml +*.publishproj + +# Microsoft Azure Web App publish settings. Comment the next line if you want to +# checkin your Azure Web App publish settings, but sensitive information contained +# in these scripts will be unencrypted +PublishScripts/ + +# NuGet Packages +*.nupkg +# The packages folder can be ignored because of Package Restore +**/packages/* +# except build/, which is used as an MSBuild target. +!**/packages/build/ +# Uncomment if necessary however generally it will be regenerated when needed +#!**/packages/repositories.config +# NuGet v3's project.json files produces more ignorable files +*.nuget.props +*.nuget.targets + +# Microsoft Azure Build Output +csx/ +*.build.csdef + +# Microsoft Azure Emulator +ecf/ +rcf/ + +# Windows Store app package directories and files +AppPackages/ +BundleArtifacts/ +Package.StoreAssociation.xml +_pkginfo.txt + +# Visual Studio cache files +# files ending in .cache can be ignored +*.[Cc]ache +# but keep track of directories ending in .cache +!*.[Cc]ache/ + +# Others +ClientBin/ +~$* +*~ +*.dbmdl +*.dbproj.schemaview +*.jfm +*.pfx +*.publishsettings +orleans.codegen.cs + +# Since there are multiple workflows, uncomment next line to ignore bower_components +# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) +#bower_components/ + +# RIA/Silverlight projects +Generated_Code/ + +# Backup & report files from converting an old project file +# to a newer Visual Studio version. Backup files are not needed, +# because we have git ;-) +_UpgradeReport_Files/ +Backup*/ +UpgradeLog*.XML +UpgradeLog*.htm + +# SQL Server files +*.mdf +*.ldf +*.ndf + +# Business Intelligence projects +*.rdl.data +*.bim.layout +*.bim_*.settings + +# Microsoft Fakes +FakesAssemblies/ + +# GhostDoc plugin setting file +*.GhostDoc.xml + +# Node.js Tools for Visual Studio +.ntvs_analysis.dat +node_modules/ + +# Typescript v1 declaration files +typings/ + +# Visual Studio 6 build log +*.plg + +# Visual Studio 6 workspace options file +*.opt + +# Visual Studio 6 auto-generated workspace file (contains which files were open etc.) +*.vbw + +# Visual Studio LightSwitch build output +**/*.HTMLClient/GeneratedArtifacts +**/*.DesktopClient/GeneratedArtifacts +**/*.DesktopClient/ModelManifest.xml +**/*.Server/GeneratedArtifacts +**/*.Server/ModelManifest.xml +_Pvt_Extensions + +# Paket dependency manager +.paket/paket.exe +paket-files/ + +# FAKE - F# Make +.fake/ + +# JetBrains Rider +.idea/ +*.sln.iml + +# CodeRush +.cr/ + +# Python Tools for Visual Studio (PTVS) +__pycache__/ +*.pyc + +# Cake - Uncomment if you are using it +# tools/** +# !tools/packages.config + +# Telerik's JustMock configuration file +*.jmconfig + +# BizTalk build output +*.btp.cs +*.btm.cs +*.odx.cs +*.xsd.cs diff --git a/PollutometerWebApi/App_Start/RouteConfig.cs b/PollutometerWebApi/App_Start/RouteConfig.cs new file mode 100644 index 0000000..7455a55 --- /dev/null +++ b/PollutometerWebApi/App_Start/RouteConfig.cs @@ -0,0 +1,19 @@ +using System.Web.Mvc; +using System.Web.Routing; + +namespace PollutometerWebApi +{ +    public class RouteConfig +    { +        public static void RegisterRoutes(RouteCollection routes) +        { +            routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); + +            routes.MapRoute( +                name: "Default", +                url: "{controller}/{action}/{id}", +                defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional } +            ); +        } +    } +} diff --git a/PollutometerWebApi/App_Start/WebApiConfig.cs b/PollutometerWebApi/App_Start/WebApiConfig.cs new file mode 100644 index 0000000..d3b2dca --- /dev/null +++ b/PollutometerWebApi/App_Start/WebApiConfig.cs @@ -0,0 +1,24 @@ +using System.Net.Http.Formatting;
 +using System.Web.Http;
 +
 +namespace PollutometerWebApi
 +{
 +    public static class WebApiConfig
 +    {
 +        public static void Register(HttpConfiguration config)
 +        {
 +			// Web API configuration and services
 +			config.Formatters.Clear();
 +			config.Formatters.Add(new JsonMediaTypeFormatter());
 +
 +            // Web API routes
 +            config.MapHttpAttributeRoutes();
 +
 +            config.Routes.MapHttpRoute(
 +                name: "DefaultApi",
 +                routeTemplate: "api/{controller}/{id}",
 +                defaults: new { id = RouteParameter.Optional }
 +            );
 +        }
 +    }
 +}
 diff --git a/PollutometerWebApi/AqiCalculator.cs b/PollutometerWebApi/AqiCalculator.cs new file mode 100644 index 0000000..58f6194 --- /dev/null +++ b/PollutometerWebApi/AqiCalculator.cs @@ -0,0 +1,102 @@ +using PollutometerWebApi.Models;
 +
 +namespace PollutometerWebApi
 +{
 +    public static class AqiCalculator
 +    {
 +        public static Aqi CalculateAqi(Reading reading)
 +        {
 +            double[,,] breakpoints =
 +            {
 +                {
 +                    {0, 4.4},
 +                    {4.5, 9.4},
 +                    {9.5, 12.4},
 +                    {12.5, 15.4},
 +                    {15.5, 30.4},
 +                    {30.5, 40.4},
 +                    {40.5, 50.4}
 +                },
 +                {
 +                    {0.000, 0.034},
 +                    {0.035, 0.144},
 +                    {0.145, 0.224},
 +                    {0.225, 0.304},
 +                    {0.305, 0.604},
 +                    {0.605, 0.804},
 +                    {0.805, 1.004}
 +                },
 +                {
 +                    {0, 0.05},
 +                    {0.08, 0.10},
 +                    {0.15, 0.20},
 +                    {0.25, 0.31},
 +                    {0.65, 1.24},
 +                    {1.25, 1.64},
 +                    {1.65, 2.04}
 +                },
 +                {
 +                    {0, 50},
 +                    {51, 100},
 +                    {101, 150},
 +                    {151, 200},
 +                    {201, 300},
 +                    {301, 400},
 +                    {401, 500}
 +                }
 +            };
 +
 +            double i, c = 0, cLow = 0, cHigh = 0, iLow = 0, iHigh = 0;
 +            Aqi aqi = new Aqi();
 +           
 +            for (int x = 0; x < 4; x++)
 +            {
 +                switch (x)
 +                {
 +                    case 0:
 +                        c = reading.Co;
 +                        break;
 +                    case 1:
 +                        c = reading.So;
 +                        break;
 +                    case 2:
 +                        c = reading.No;
 +                        break;
 +                }
 +
 +                for (int y = 0; y < 7; y++)
 +				{
 +					if (c >= breakpoints[x, y, 0] && c <= breakpoints[x, y, 1])
 +					{
 +						cLow = breakpoints[x, y, 0];
 +						cHigh = breakpoints[x, y, 1];
 +						iLow = breakpoints[3, y, 0];
 +						iHigh = breakpoints[3, y, 1];
 +                        break;
 +					}
 +				}
 +
 +                i = (iHigh - iLow) / (cHigh - cLow) * (c - cLow) + iLow;
 +
 +                if (i > aqi.Value)
 +                { 
 +                    aqi.Value = i;
 +                    switch (x)
 +                    {
 +                        case 0:
 +                            aqi.GasName = "CO";
 +                            break;
 +                        case 1:
 +                            aqi.GasName = "SO";
 +                            break;
 +                        case 2:
 +                            aqi.GasName = "NO";
 +                            break;
 +                    }
 +                }
 +            }
 +
 +            return aqi;
 +        }
 +    }
 +}
 diff --git a/PollutometerWebApi/Controllers/HomeController.cs b/PollutometerWebApi/Controllers/HomeController.cs new file mode 100644 index 0000000..69e4846 --- /dev/null +++ b/PollutometerWebApi/Controllers/HomeController.cs @@ -0,0 +1,19 @@ +using System; +using System.Web.Mvc; + +namespace PollutometerWebApi.Controllers +{ +    public class HomeController : Controller +    { +        public ActionResult Index() +        { +            var mvcName = typeof(Controller).Assembly.GetName(); +            var isMono = Type.GetType("Mono.Runtime") != null; + +            ViewData["Version"] = mvcName.Version.Major + "." + mvcName.Version.Minor; +            ViewData["Runtime"] = isMono ? "Mono" : ".NET"; + +            return View(); +        } +    } +} diff --git a/PollutometerWebApi/Controllers/ReadingsController.cs b/PollutometerWebApi/Controllers/ReadingsController.cs new file mode 100644 index 0000000..adf4d5d --- /dev/null +++ b/PollutometerWebApi/Controllers/ReadingsController.cs @@ -0,0 +1,85 @@ +using System;
 +using System.Web.Http;
 +using PollutometerWebApi.Models;
 +
 +namespace PollutometerWebApi.Controllers
 +{
 +    public class ReadingsController : ApiController
 +    {
 +		public ReadingsController() {}
 +
 +		public IHttpActionResult GetAllReadings()
 +		{
 +            var command = "SELECT * FROM Readings";
 +            var readings = SqlOperator.GetReadings(command);
 +
 +            if (readings.Count > 0) return Ok(readings);
 +            else return NotFound();
 +		}
 +
 +		public IHttpActionResult GetReading(int id)
 +		{
 +            var command = $"SELECT * FROM Readings WHERE Id={id}";
 +            var readings = SqlOperator.GetReadings(command);
 +
 +			if (readings.Count == 1) return Ok(readings[0]);
 +			else return NotFound();
 +		}
 +
 +        [Route("api/Readings/latest")]
 +        public IHttpActionResult GetLatestReading()
 +        {
 +            var command = "SELECT * FROM Readings " +
 +                "WHERE TimeStamp IN(SELECT MAX(TimeStamp) FROM Readings)";
 +            var reading = SqlOperator.GetReadings(command)[0];
 +
 +			if (reading != null) return Ok(reading);
 +			else return NotFound();
 +        }
 +
 +        [Route("api/Readings/lastweek")]
 +		public IHttpActionResult GetReadingsFromLastWeek()
 +		{
 +            var timeNow = DateTimeOffset.Now.ToUnixTimeSeconds();
 +            var command = "SELECT * FROM Readings " +
 +                $"WHERE TimeStamp BETWEEN {timeNow-7*24*3600} AND {timeNow}";
 +			var readings = SqlOperator.GetReadings(command);
 +
 +			if (readings.Count > 0) return Ok(readings);
 +			else return NotFound();
 +		}
 +
 +		public IHttpActionResult PutReading(int id, Reading reading)
 +		{
 +			if (reading != null)
 +			{
 +				SqlOperator.PutReading(id, reading);
 +				return Ok();
 +			}
 +			else return BadRequest();
 +		}
 +
 +		public IHttpActionResult PostReading(Reading reading)
 +		{
 +			if (reading != null)
 +			{
 +                SqlOperator.PostReading(reading);
 +                var aqi = AqiCalculator.CalculateAqi(reading);
 +                if (aqi.Value >= 151)
 +                    EmailSender.SendEmail(aqi);
 +				return Ok(reading);
 +			}
 +			else return BadRequest();
 +		}
 +
 +		public IHttpActionResult DeleteReading(int id)
 +		{
 +            var command = $"SELECT * FROM Readings WHERE Id={id}";
 +            var readings = SqlOperator.GetReadings(command);
 +			if (readings.Count == 0) return NotFound();
 +			SqlOperator.DeleteReading(id);
 +            
 +			return Ok(readings[0]);
 +		}
 +    }
 +}
\ No newline at end of file diff --git a/PollutometerWebApi/EmailSender.cs b/PollutometerWebApi/EmailSender.cs new file mode 100644 index 0000000..6cc60fc --- /dev/null +++ b/PollutometerWebApi/EmailSender.cs @@ -0,0 +1,34 @@ +using System; +using System.Net.Mail; +using PollutometerWebApi.Models; + +namespace PollutometerWebApi +{ +    public static class EmailSender +    { +        public static void SendEmail(Aqi aqi) +        { +            MailMessage mail = new MailMessage("***REMOVED***", "alek2026@edu.easj.dk"); +            SmtpClient client = new SmtpClient() +            { +                Host = "mail.cock.li", +                Port = 587, +                EnableSsl = true, +                Timeout = 100, +                DeliveryMethod = SmtpDeliveryMethod.Network, +                UseDefaultCredentials = false, +                Credentials = new System.Net.NetworkCredential("***REMOVED***", "***REMOVED***") +            }; +            mail.Subject = $"Pollutometer warning - {DateTime.Now}"; +            mail.IsBodyHtml = true; +            mail.Body = "<h3>WARNING!</h3>\n" + +                "\n" + +                "<img src=\"https://i.imgflip.com/20b4q2.jpg\"/>\n" + +                "\n" + +                $"<p>The warning was triggered by {aqi.GasName}.</p>\n" + +                $"<p>Air quality index: {aqi.Value}</p>" + +                $"<p>The AQI level is {aqi.Level}!"; +            client.Send(mail); +        } +    } +}
\ No newline at end of file diff --git a/PollutometerWebApi/Global.asax b/PollutometerWebApi/Global.asax new file mode 100644 index 0000000..ee57536 --- /dev/null +++ b/PollutometerWebApi/Global.asax @@ -0,0 +1 @@ +<%@ Application Inherits="PollutometerWebApi.Global" %> diff --git a/PollutometerWebApi/Global.asax.cs b/PollutometerWebApi/Global.asax.cs new file mode 100644 index 0000000..3a03cf6 --- /dev/null +++ b/PollutometerWebApi/Global.asax.cs @@ -0,0 +1,17 @@ +using System.Web; +using System.Web.Mvc; +using System.Web.Routing; +using System.Web.Http; + +namespace PollutometerWebApi +{ +    public class Global : HttpApplication +    { +        protected void Application_Start() +        { +            AreaRegistration.RegisterAllAreas(); +            GlobalConfiguration.Configure(WebApiConfig.Register); +            RouteConfig.RegisterRoutes(RouteTable.Routes); +        } +    } +} diff --git a/PollutometerWebApi/Models/Aqi.cs b/PollutometerWebApi/Models/Aqi.cs new file mode 100644 index 0000000..b13ddb0 --- /dev/null +++ b/PollutometerWebApi/Models/Aqi.cs @@ -0,0 +1,34 @@ +namespace PollutometerWebApi.Models +{ +    public class Aqi +    { +        double _value; +         +        public string GasName { get; set; } +        public double Value +        { +            get  +            { +                return _value; +			} +            set +            { +                _value = value; + +                if (_value >= 0 && _value <= 50) +                    Level = "Good"; +                else if (_value >= 51 && _value <= 100) +                    Level = "Moderate"; +                else if (_value >= 101 && _value <= 150) +                    Level = "Unhealthy for Sensitive Groups"; +                else if (_value >= 151 && _value <= 200) +                    Level = "Unhealthy"; +                else if (_value >= 201 && _value <= 300) +                    Level = "Very Unhealthy"; +                else if (_value >= 301 && _value <= 500) +                    Level = "Hazardous"; +            } +        } +        public string Level { get; set; } +    } +} diff --git a/PollutometerWebApi/Models/Reading.cs b/PollutometerWebApi/Models/Reading.cs new file mode 100644 index 0000000..18b2326 --- /dev/null +++ b/PollutometerWebApi/Models/Reading.cs @@ -0,0 +1,11 @@ +namespace PollutometerWebApi.Models +{ +    public class Reading +    { +        public int Id { get; set; } +        public int TimeStamp { get; set; } +        public double Co { get; set; } +        public double No { get; set; } +        public double So { get; set; } +    } +} diff --git a/PollutometerWebApi/PollutometerWebApi.csproj b/PollutometerWebApi/PollutometerWebApi.csproj new file mode 100644 index 0000000..6e5eb45 --- /dev/null +++ b/PollutometerWebApi/PollutometerWebApi.csproj @@ -0,0 +1,151 @@ +<?xml version="1.0" encoding="utf-8"?>
 +<Project DefaultTargets="Build" ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
 +  <Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
 +  <PropertyGroup>
 +    <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
 +    <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
 +    <ProjectGuid>{22C32F4C-0DEB-40EA-9D56-48942CBB2A07}</ProjectGuid>
 +    <ProjectTypeGuids>{349C5851-65DF-11DA-9384-00065B846F21};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}</ProjectTypeGuids>
 +    <OutputType>Library</OutputType>
 +    <RootNamespace>PollutometerWebApi</RootNamespace>
 +    <AssemblyName>PollutometerWebApi</AssemblyName>
 +    <TargetFrameworkVersion>v4.6.2</TargetFrameworkVersion>
 +    <FileUpgradeFlags>
 +    </FileUpgradeFlags>
 +    <UpgradeBackupLocation>
 +    </UpgradeBackupLocation>
 +    <OldToolsVersion>4.0</OldToolsVersion>
 +    <UseIISExpress>true</UseIISExpress>
 +    <Use64BitIISExpress />
 +    <IISExpressSSLPort />
 +    <IISExpressAnonymousAuthentication />
 +    <IISExpressWindowsAuthentication />
 +    <IISExpressUseClassicPipelineMode />
 +    <UseGlobalApplicationHostFile />
 +  </PropertyGroup>
 +  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
 +    <DebugSymbols>true</DebugSymbols>
 +    <DebugType>full</DebugType>
 +    <Optimize>false</Optimize>
 +    <OutputPath>bin</OutputPath>
 +    <DefineConstants>DEBUG;</DefineConstants>
 +    <ErrorReport>prompt</ErrorReport>
 +    <WarningLevel>4</WarningLevel>
 +  </PropertyGroup>
 +  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
 +    <Optimize>true</Optimize>
 +    <OutputPath>bin</OutputPath>
 +    <ErrorReport>prompt</ErrorReport>
 +    <WarningLevel>4</WarningLevel>
 +  </PropertyGroup>
 +  <ItemGroup>
 +    <Reference Include="System" />
 +    <Reference Include="System.Web" />
 +    <Reference Include="System.Xml" />
 +    <Reference Include="System.Core" />
 +    <Reference Include="System.Web.Services" />
 +    <Reference Include="System.Web.Routing" />
 +    <Reference Include="System.Web.Extensions" />
 +    <Reference Include="System.Web.Abstractions" />
 +    <Reference Include="System.Web.DynamicData" />
 +    <Reference Include="System.ComponentModel.DataAnnotations" />
 +    <Reference Include="System.Xml.Linq" />
 +    <Reference Include="Microsoft.CSharp" />
 +    <Reference Include="System.Web.Razor">
 +      <HintPath>..\packages\Microsoft.AspNet.Razor.3.2.3\lib\net45\System.Web.Razor.dll</HintPath>
 +    </Reference>
 +    <Reference Include="Microsoft.Web.Infrastructure">
 +      <HintPath>..\packages\Microsoft.Web.Infrastructure.1.0.0.0\lib\net40\Microsoft.Web.Infrastructure.dll</HintPath>
 +    </Reference>
 +    <Reference Include="System.Web.Helpers">
 +      <HintPath>..\packages\Microsoft.AspNet.WebPages.3.2.3\lib\net45\System.Web.Helpers.dll</HintPath>
 +    </Reference>
 +    <Reference Include="System.Web.WebPages.Deployment">
 +      <HintPath>..\packages\Microsoft.AspNet.WebPages.3.2.3\lib\net45\System.Web.WebPages.Deployment.dll</HintPath>
 +    </Reference>
 +    <Reference Include="System.Web.WebPages">
 +      <HintPath>..\packages\Microsoft.AspNet.WebPages.3.2.3\lib\net45\System.Web.WebPages.dll</HintPath>
 +    </Reference>
 +    <Reference Include="System.Web.WebPages.Razor">
 +      <HintPath>..\packages\Microsoft.AspNet.WebPages.3.2.3\lib\net45\System.Web.WebPages.Razor.dll</HintPath>
 +    </Reference>
 +    <Reference Include="System.Web.Mvc">
 +      <HintPath>..\packages\Microsoft.AspNet.Mvc.5.2.3\lib\net45\System.Web.Mvc.dll</HintPath>
 +    </Reference>
 +    <Reference Include="System.Net.Http" />
 +    <Reference Include="System.Data" />
 +    <Reference Include="System.Net.Http.Formatting">
 +      <HintPath>..\packages\Microsoft.AspNet.WebApi.Client.5.2.0\lib\net45\System.Net.Http.Formatting.dll</HintPath>
 +    </Reference>
 +    <Reference Include="System.Web.Http">
 +      <HintPath>..\packages\Microsoft.AspNet.WebApi.Core.5.2.0\lib\net45\System.Web.Http.dll</HintPath>
 +    </Reference>
 +    <Reference Include="System.Web.Http.WebHost">
 +      <HintPath>..\packages\Microsoft.AspNet.WebApi.WebHost.5.2.0\lib\net45\System.Web.Http.WebHost.dll</HintPath>
 +    </Reference>
 +    <Reference Include="Newtonsoft.Json">
 +      <HintPath>..\packages\Newtonsoft.Json.6.0.4\lib\net45\Newtonsoft.Json.dll</HintPath>
 +    </Reference>
 +  </ItemGroup>
 +  <ItemGroup>
 +    <Folder Include="Content\" />
 +    <Folder Include="Scripts\" />
 +  </ItemGroup>
 +  <ItemGroup>
 +    <Compile Include="Controllers\HomeController.cs" />
 +    <Compile Include="Global.asax.cs">
 +      <DependentUpon>Global.asax</DependentUpon>
 +    </Compile>
 +    <Compile Include="App_Start\WebApiConfig.cs" />
 +    <Compile Include="App_Start\RouteConfig.cs" />
 +    <Compile Include="Controllers\ReadingsController.cs" />
 +    <Compile Include="Models\Reading.cs" />
 +    <Compile Include="SqlOperator.cs" />
 +    <Compile Include="EmailSender.cs" />
 +    <Compile Include="AqiCalculator.cs" />
 +    <Compile Include="Models\Aqi.cs" />
 +  </ItemGroup>
 +  <ItemGroup>
 +    <Content Include="Views\Web.config">
 +      <SubType>Designer</SubType>
 +    </Content>
 +    <Content Include="Views\Home\Index.cshtml" />
 +    <Content Include="Views\Shared\_Layout.cshtml" />
 +    <Content Include="Views\Shared\Error.cshtml" />
 +    <Content Include="Views\_ViewStart.cshtml" />
 +    <Content Include="Web.config" />
 +    <Content Include="Global.asax" />
 +    <Content Include="packages.config" />
 +  </ItemGroup>
 +  <PropertyGroup>
 +    <VisualStudioVersion Condition="'$(VisualStudioVersion)' == ''">10.0</VisualStudioVersion>
 +    <VSToolsPath Condition="'$(VSToolsPath)' == ''">$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)</VSToolsPath>
 +  </PropertyGroup>
 +  <Import Project="$(MSBuildBinPath)\Microsoft.CSharp.targets" />
 +  <Import Project="$(VSToolsPath)\WebApplications\Microsoft.WebApplication.targets" Condition="'$(VSToolsPath)' !=''" />
 +  <Import Project="$(VSToolsPath)\WebApplications\Microsoft.WebApplication.targets" Condition="'$(VSToolsPath)' != ''" />
 +  <Import Project="$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v10.0\WebApplications\Microsoft.WebApplication.targets" Condition="false" />
 +  <ProjectExtensions>
 +    <MonoDevelop>
 +      <Properties>
 +        <XspParameters Port="8080" Address="127.0.0.1" SslMode="None" SslProtocol="Default" KeyType="None" CertFile="" KeyFile="" PasswordOptions="None" Password="" Verbose="True" />
 +      </Properties>
 +    </MonoDevelop>
 +    <VisualStudio>
 +      <FlavorProperties GUID="{349C5851-65DF-11DA-9384-00065B846F21}">
 +        <WebProjectProperties>
 +          <UseIIS>True</UseIIS>
 +          <AutoAssignPort>True</AutoAssignPort>
 +          <DevelopmentServerPort>0</DevelopmentServerPort>
 +          <DevelopmentServerVPath>/</DevelopmentServerVPath>
 +          <IISUrl>http://localhost:50114/</IISUrl>
 +          <NTLMAuthentication>False</NTLMAuthentication>
 +          <UseCustomServer>False</UseCustomServer>
 +          <CustomServerUrl>
 +          </CustomServerUrl>
 +          <SaveServerSettingsInUserFile>False</SaveServerSettingsInUserFile>
 +        </WebProjectProperties>
 +      </FlavorProperties>
 +    </VisualStudio>
 +  </ProjectExtensions>
 +</Project>
\ No newline at end of file diff --git a/PollutometerWebApi/SqlOperator.cs b/PollutometerWebApi/SqlOperator.cs new file mode 100644 index 0000000..1e296a1 --- /dev/null +++ b/PollutometerWebApi/SqlOperator.cs @@ -0,0 +1,83 @@ +using System.Collections.Generic; +using System.Data.SqlClient; +using PollutometerWebApi.Models; + +namespace PollutometerWebApi +{ +	public static class SqlOperator +	{ +		const string ConnectionString =  +            "Server=tcp:forschool.database.windows.net,1433;" + +            "Initial Catalog=schooldb;" + +            "Persist Security Info=False;" + +            "User ID=***REMOVED***;" + +            "Password=***REMOVED***;" + +            "MultipleActiveResultSets=False;" + +            "Encrypt=True;" + +            "TrustServerCertificate=False;" + +            "Connection Timeout=30;"; + +        public static List<Reading> GetReadings(string command) +		{ +			var readings = new List<Reading>(); + +			using (SqlConnection databaseConnection = new SqlConnection(ConnectionString)) +			{ +				databaseConnection.Open(); +				SqlCommand selectCommand = new SqlCommand(command, databaseConnection); +				var reader = selectCommand.ExecuteReader(); +				while (reader.Read()) +				{ +					readings.Add(new Reading +					{ +                        Id = reader.GetInt32(0), +                        TimeStamp = reader.GetInt32(1), +                        Co = reader.GetDouble(2), +						No = reader.GetDouble(3), +						So = reader.GetDouble(4) +					}); +				} +			} + +            return readings; +		} + +        public static void PutReading(int id, Reading reading) +		{ +			using (SqlConnection dbCon = new SqlConnection(ConnectionString)) +			{ +				dbCon.Open(); +                string query = $"UPDATE Readings SET TimeStamp='{reading.TimeStamp}'," + +                    $"Co='{reading.Co}', No='{reading.No}', So='{reading.So}' WHERE Id={id};"; +				var cmd = new SqlCommand(query, dbCon); +				cmd.ExecuteNonQuery(); +				dbCon.Close(); +			} +		} + +        public static void PostReading(Reading reading) +		{ +			using (SqlConnection dbCon = new SqlConnection(ConnectionString)) +			{ +				dbCon.Open(); +                string query = $"INSERT INTO Readings (TimeStamp,Co,No,So)" + +                    $"VALUES('{reading.TimeStamp}',{reading.Co},{reading.No},{reading.So});"; +				var cmd = new SqlCommand(query, dbCon); +				cmd.ExecuteNonQuery(); +				dbCon.Close(); +			} +		} + +        public static void DeleteReading(int id) +		{ +			using (SqlConnection dbCon = new SqlConnection(ConnectionString)) +			{ +				dbCon.Open(); +				string query = $"DELETE FROM Readings WHERE Id={id};"; +				var cmd = new SqlCommand(query, dbCon); +				cmd.ExecuteNonQuery(); +				dbCon.Close(); +			} +		} +	} +}
\ No newline at end of file diff --git a/PollutometerWebApi/Views/Home/Index.cshtml b/PollutometerWebApi/Views/Home/Index.cshtml new file mode 100644 index 0000000..2501eee --- /dev/null +++ b/PollutometerWebApi/Views/Home/Index.cshtml @@ -0,0 +1 @@ +<h2>Welcome to ASP.NET MVC @ViewData["Version"] on @ViewData["Runtime"]!</h2> diff --git a/PollutometerWebApi/Views/Shared/Error.cshtml b/PollutometerWebApi/Views/Shared/Error.cshtml new file mode 100644 index 0000000..20ec06a --- /dev/null +++ b/PollutometerWebApi/Views/Shared/Error.cshtml @@ -0,0 +1,5 @@ +@model System.Web.Mvc.HandleErrorInfo + +<div> +	<h2>An error occurred while processing your request.</h2> +</div> diff --git a/PollutometerWebApi/Views/Shared/_Layout.cshtml b/PollutometerWebApi/Views/Shared/_Layout.cshtml new file mode 100644 index 0000000..54f6729 --- /dev/null +++ b/PollutometerWebApi/Views/Shared/_Layout.cshtml @@ -0,0 +1,9 @@ +<!DOCTYPE html> +<html> +<head> +    <title>@ViewBag.Title</title> +</head> +<body> +	@RenderBody() +</body> +</html> diff --git a/PollutometerWebApi/Views/Web.config b/PollutometerWebApi/Views/Web.config new file mode 100644 index 0000000..35da8d0 --- /dev/null +++ b/PollutometerWebApi/Views/Web.config @@ -0,0 +1,30 @@ +<?xml version="1.0"?> +<configuration> +	<configSections> +		<sectionGroup name="system.web.webPages.razor" type="System.Web.WebPages.Razor.Configuration.RazorWebSectionGroup, System.Web.WebPages.Razor, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"> +			<section name="host" type="System.Web.WebPages.Razor.Configuration.HostSection, System.Web.WebPages.Razor, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" /> +			<section name="pages" type="System.Web.WebPages.Razor.Configuration.RazorPagesSection, System.Web.WebPages.Razor, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" /> +		</sectionGroup> +	</configSections> +	<system.web.webPages.razor> +		<host factoryType="System.Web.Mvc.MvcWebRazorHostFactory, System.Web.Mvc, Version=5.2.3.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" /> +		<pages pageBaseType="System.Web.Mvc.WebViewPage"> +			<namespaces> +				<add namespace="System.Web.Mvc" /> +				<add namespace="System.Web.Mvc.Ajax" /> +				<add namespace="System.Web.Mvc.Html" /> +				<add namespace="System.Web.Routing" /> +				<add namespace="PollutometerWebApi" /> +			</namespaces> +		</pages> +	</system.web.webPages.razor> +	<appSettings> +		<add key="webpages:Enabled" value="false" /> +	</appSettings> +	<system.webServer> +		<handlers> +			<remove name="BlockViewHandler" /> +			<add name="BlockViewHandler" path="*" verb="*" preCondition="integratedMode" type="System.Web.HttpNotFoundHandler" /> +		</handlers> +	</system.webServer> +</configuration> diff --git a/PollutometerWebApi/Views/_ViewStart.cshtml b/PollutometerWebApi/Views/_ViewStart.cshtml new file mode 100644 index 0000000..2de6241 --- /dev/null +++ b/PollutometerWebApi/Views/_ViewStart.cshtml @@ -0,0 +1,3 @@ +@{ +    Layout = "~/Views/Shared/_Layout.cshtml"; +} diff --git a/PollutometerWebApi/Web.config b/PollutometerWebApi/Web.config new file mode 100644 index 0000000..77dd8b3 --- /dev/null +++ b/PollutometerWebApi/Web.config @@ -0,0 +1,25 @@ +<?xml version="1.0"?> +<!-- +Web.config file for PollutometerWebApi. + +The settings that can be used in this file are documented at  +http://www.mono-project.com/Config_system.web and  +http://msdn2.microsoft.com/en-us/library/b5ysx397.aspx +--> +<configuration> +  <system.web> +    <compilation debug="true" targetFramework="4.5"> +      <assemblies /> +    </compilation> +    <httpRuntime targetFramework="4.5" /> +    <customErrors mode="Off" /> +  </system.web> +  <runtime> +    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1"> +      <dependentAssembly> +        <assemblyIdentity name="Newtonsoft.Json" publicKeyToken="30ad4fe6b2a6aeed" culture="neutral" /> +        <bindingRedirect oldVersion="0.0.0.0-4.5.0.0" newVersion="6.0.0.0" /> +      </dependentAssembly> +    </assemblyBinding> +  </runtime> +</configuration>
\ No newline at end of file diff --git a/PollutometerWebApi/packages.config b/PollutometerWebApi/packages.config new file mode 100644 index 0000000..8631ca7 --- /dev/null +++ b/PollutometerWebApi/packages.config @@ -0,0 +1,12 @@ +<?xml version="1.0" encoding="utf-8"?> +<packages> +  <package id="Microsoft.AspNet.Mvc" version="5.2.3" targetFramework="net45" /> +  <package id="Microsoft.AspNet.Razor" version="3.2.3" targetFramework="net45" /> +  <package id="Microsoft.AspNet.WebApi" version="5.2.0" targetFramework="net45" /> +  <package id="Microsoft.AspNet.WebApi.Client" version="5.2.0" targetFramework="net45" /> +  <package id="Microsoft.AspNet.WebApi.Core" version="5.2.0" targetFramework="net45" /> +  <package id="Microsoft.AspNet.WebApi.WebHost" version="5.2.0" targetFramework="net45" /> +  <package id="Microsoft.AspNet.WebPages" version="3.2.3" targetFramework="net45" /> +  <package id="Microsoft.Web.Infrastructure" version="1.0.0.0" targetFramework="net45" /> +  <package id="Newtonsoft.Json" version="6.0.4" targetFramework="net45" /> +</packages>
\ No newline at end of file diff --git a/README.md b/README.md new file mode 100644 index 0000000..3bd9044 --- /dev/null +++ b/README.md @@ -0,0 +1 @@ +# PollutometerWebApi |