使用Rest服务,开发的一款小型数据访问工具

30 篇文章 0 订阅
1 篇文章 0 订阅

背景

之前项目有涉及到访问远程传感器数据功能,所以,基于Rest服务,写了一款小工具软件

效果预览

 由于服务器访问不了,只能看看样子

实现代码:

 UI 文件 xaml代码.

 <Border>
        <Grid>
            <Grid.RowDefinitions>
                <RowDefinition Height="0"></RowDefinition>
                <RowDefinition></RowDefinition>
                <RowDefinition Height="0"></RowDefinition>
            </Grid.RowDefinitions>
            <Border Grid.Row="0"></Border>
            <Border Grid.Row="1" BorderBrush="LightCyan" BorderThickness="0,1,0,1">
                <Grid>
                    <Grid>
                        <Grid.ColumnDefinitions>
                            <ColumnDefinition MinWidth="80" MaxWidth="260"></ColumnDefinition>
                            <ColumnDefinition Width="3*"></ColumnDefinition>
                            <ColumnDefinition Width="10"></ColumnDefinition>
                        </Grid.ColumnDefinitions>
                        <!--/功能选区/-->
                        <Border Grid.Column="0" BorderBrush="Gray" BorderThickness="0,0,1,0">
                            <DockPanel LastChildFill="True">
                                <GroupBox Header="地 址 连 接" 
                                           Style="{DynamicResource MaterialDesignGroupBox}"
    materialDesign:ColorZoneAssist.Mode="Custom"
  materialDesign:ColorZoneAssist.Background="{StaticResource BackGroundStyle}"
  materialDesign:ColorZoneAssist.Foreground="White" Height="260" DockPanel.Dock="Top" Margin="5,5,5,0">
                                    <Grid>
                                        <Grid.RowDefinitions>
                                            <RowDefinition></RowDefinition>
                                            <RowDefinition></RowDefinition>
                                            <RowDefinition></RowDefinition>
                                            <RowDefinition></RowDefinition>
                                            <RowDefinition></RowDefinition>
                                        </Grid.RowDefinitions>
                                        <Border Grid.Row="0">
                                            <Grid>
                                                <Grid>
                                                    <Grid.ColumnDefinitions>
                                                        <ColumnDefinition>
                                                        </ColumnDefinition>
                                                        <ColumnDefinition Width="2*"></ColumnDefinition>
                                                    </Grid.ColumnDefinitions>
                                                    <Border Grid.Column="0">
                                                        <Label VerticalAlignment="Center" Content="站点ID:"></Label>
                                                    </Border>
                                                    <Border Grid.Column="1">
                                                        <TextBox x:Name="webIDName" VerticalAlignment="Center" Text=""></TextBox>
                                                    </Border>
                                                </Grid>
                                            </Grid>
                                        </Border>
                                        <Border Grid.Row="1">
                                            <Grid>
                                                <Grid>
                                                    <Grid.ColumnDefinitions>
                                                        <ColumnDefinition>
                                                        </ColumnDefinition>
                                                        <ColumnDefinition Width="2*"></ColumnDefinition>
                                                    </Grid.ColumnDefinitions>
                                                    <Border Grid.Column="0">
                                                        <Label VerticalAlignment="Center" Content="站点名字:"></Label>
                                                    </Border>
                                                    <Border Grid.Column="1">
                                                        <TextBox x:Name="StationName" VerticalAlignment="Center" Text=""></TextBox>
                                                    </Border>
                                                </Grid>
                                            </Grid>
                                        </Border>
                                        <Border Grid.Row="2">
                                            <Grid>
                                                <Grid>
                                                    <Grid.ColumnDefinitions>
                                                        <ColumnDefinition>
                                                        </ColumnDefinition>
                                                        <ColumnDefinition Width="2*"></ColumnDefinition>
                                                    </Grid.ColumnDefinitions>
                                                    <Border Grid.Column="0">
                                                        <Label VerticalAlignment="Center" Content="站点编号:"></Label>
                                                    </Border>
                                                    <Border Grid.Column="1">
                                                        <TextBox x:Name="StationHardWareName" VerticalAlignment="Center" Text=""></TextBox>
                                                    </Border>
                                                </Grid>
                                            </Grid>
                                        </Border>
                                        <Border Grid.Row="3">
                                            <Grid>
                                                <Grid>
                                                    <Grid.ColumnDefinitions>
                                                        <ColumnDefinition>
                                                        </ColumnDefinition>
                                                        <ColumnDefinition Width="2*"></ColumnDefinition>
                                                    </Grid.ColumnDefinitions>
                                                    <Border Grid.Column="0">
                                                        <Label VerticalAlignment="Center" Content="站点类型:"></Label>
                                                    </Border>
                                                    <Border Grid.Column="1">
                                                        <TextBox x:Name="StationTypeName" VerticalAlignment="Center" Text=""></TextBox>
                                                    </Border>
                                                </Grid>
                                            </Grid>
                                        </Border>
                                        <Border Grid.Row="4" Margin="0,5,0,0">
                                            <Grid>
                                                <Button x:Name="ConnectBtnName" 
                                                        FontSize="12"
                                                        Background="{StaticResource BackGroundStyle}"
                                                        Click="ConnectBtnNameClicked"
                                                 Content="建  立  站  点  连  接"
                                                Margin="2,0" />
                                            </Grid>
                                        </Border>
                                    </Grid>
                                </GroupBox>
                                <GroupBox Header="功 能 选 区 域"   Margin="5,5,5,0"     
                                   materialDesign:ColorZoneAssist.Mode="Custom"
                                  materialDesign:ColorZoneAssist.Background="{StaticResource BackGroundStyle}"
                                  materialDesign:ColorZoneAssist.Foreground="White">                    
                                    <StackPanel>
                                        <Button x:Name="WeatherBtnName" Margin="0,40,0,0"  materialDesign:ShadowAssist.ShadowDepth="Depth3"
                                             Background="{StaticResource BackGroundStyle}"    Content="气    象    数    据" FontSize="12" Padding="-5,0,0,0" Click="onFunctionControlClicked">
                                        </Button>
                                        <Button x:Name="WaterBtnName" Margin="0,30,0,0"  materialDesign:ShadowAssist.ShadowDepth="Depth3"
                                             Background="{StaticResource BackGroundStyle}"    Content="水    位    数    据" FontSize="12" Padding="-5,0,0,0" Click="onFunctionControlClicked">
                                        </Button>
                                        <Button x:Name="SoilBtnName" Margin="0,30,0,0"  materialDesign:ShadowAssist.ShadowDepth="Depth3"
                                             Background="{StaticResource BackGroundStyle}"    Content="土    壤    墒    情" FontSize="12" Padding="-5,0,0,0" Click="onFunctionControlClicked">
                                        </Button>
                                        <Button x:Name="PictureBtnName" Margin="0,30,0,0"  materialDesign:ShadowAssist.ShadowDepth="Depth3"
                                             Background="{StaticResource BackGroundStyle}"    Content="图    像    数    据"  FontSize="12" Padding="-5,0,0,0" Click="onFunctionControlClicked">
                                        </Button>
                                    </StackPanel>
                                </GroupBox>
                            </DockPanel>
                        </Border>
                        <Border Grid.Column="1">
                            <Grid>
                                <Grid.RowDefinitions>
                                    <RowDefinition Height="80"></RowDefinition>
                                    <RowDefinition></RowDefinition>
                                    <RowDefinition Height="30"></RowDefinition>
                                </Grid.RowDefinitions>
                                <!--查询区域-->
                                <Border Grid.Row="0">
                                    <Grid>
                                        <Grid.ColumnDefinitions>
                                            <ColumnDefinition></ColumnDefinition>
                                            <ColumnDefinition></ColumnDefinition>
                                            <ColumnDefinition></ColumnDefinition>
                                            <ColumnDefinition Width="50"></ColumnDefinition>
                                        </Grid.ColumnDefinitions>
                                        <Border Grid.Column="0">
                                            <Button
                                              Style="{StaticResource MaterialDesignFloatingActionDarkButton}"
                                              ToolTip="查 询 数 据" Click="onSearthDataClicked"
                                              Background="{StaticResource BackGroundStyle}">
                                              <materialDesign:PackIcon
                                                Kind="CloudSearchOutline"
                                                Height="30"
                                                Width="30"/>
                                            </Button>
                                        </Border>
                                        <Border Grid.Column="1" Background="Transparent">
                                            <StackPanel Orientation="Horizontal">
                                                <DatePicker
                                                  Name="LocaleDatePickerStartDay"
                                                  Width="120"
                                                  materialDesign:HintAssist.Hint="启始日期" />
                                                <materialDesign:TimePicker 
                                                  materialDesign:HintAssist.Hint="启始时间"
                                                  Is24Hours="True"
                                                  x:Name="WithSecondsTimePickerStartTime"
                                                  WithSeconds="True"
                                                  Width="100" />
                                            </StackPanel>
                                        </Border>
                                        <Border Grid.Column="2" x:Name="HourBorderName" Background="Transparent">
                                            <StackPanel Orientation="Horizontal">
                                                <StackPanel Orientation="Horizontal">
                                                    <DatePicker
                                                  Name="LocaleDatePickerStopDay"
                                                  Width="120"
                                                   Style="{StaticResource MaterialDesignDatePicker}"
                                                  materialDesign:HintAssist.Hint="结束日期"/>

                                                    <materialDesign:TimePicker Margin="0,0,0,0"
                                                  materialDesign:HintAssist.Hint=" 结束时间"
                                                  Is24Hours="True"
                                                  x:Name="WithSecondsTimePickerStopTime"
                                                  Style="{StaticResource MaterialDesignTimePicker}"
                                                  WithSeconds="True"
                                                  Width="100" />
                                                </StackPanel>
                                            </StackPanel>
                                        </Border>
                                        <Border Grid.Column="3">
                                            <materialDesign:PopupBox Padding="0 0 0 0" PopupMode="Click" StaysOpen="True">
                                                <GroupBox Header="站 点 设 置" Width="250" Height="200"
                                                             materialDesign:ColorZoneAssist.Mode="Custom"
                                  materialDesign:ColorZoneAssist.Background="{StaticResource BackGroundStyle}"
                                  materialDesign:ColorZoneAssist.Foreground="White">
                                                    <Grid>
                                                        <Grid.RowDefinitions>
                                                            <RowDefinition></RowDefinition>
                                                            <RowDefinition></RowDefinition>
                                                            <RowDefinition></RowDefinition>
                                                            <RowDefinition></RowDefinition>
                                                        </Grid.RowDefinitions>
                                                        <Border Grid.Row="0" Margin="0,5,0,0">
                                                            <Grid>
                                                                <Grid>
                                                                    <Grid.ColumnDefinitions>
                                                                        <ColumnDefinition></ColumnDefinition>
                                                                        <ColumnDefinition Width="2*"></ColumnDefinition>
                                                                    </Grid.ColumnDefinitions>
                                                                    <Border Grid.Column="0">
                                                                        <Label VerticalAlignment="Center" Content="IP地址:"></Label>
                                                                    </Border>
                                                                    <Border Grid.Column="1">
                                                                        <TextBox x:Name="IpName" VerticalAlignment="Center" Text="116.62.21.158"></TextBox>
                                                                    </Border>
                                                                </Grid>
                                                            </Grid>
                                                        </Border>
                                                        <Border Grid.Row="1" Margin="0,5,0,0">
                                                            <Grid>
                                                                <Grid>
                                                                    <Grid.ColumnDefinitions>
                                                                        <ColumnDefinition>
                                                                        </ColumnDefinition>
                                                                        <ColumnDefinition Width="2*"></ColumnDefinition>
                                                                    </Grid.ColumnDefinitions>
                                                                    <Border Grid.Column="0">
                                                                        <Label VerticalAlignment="Center" Content="端口地址:"></Label>
                                                                    </Border>
                                                                    <Border Grid.Column="1">
                                                                        <TextBox x:Name="PortName" VerticalAlignment="Center" Text="7070"></TextBox>
                                                                    </Border>
                                                                </Grid>
                                                            </Grid>
                                                        </Border>
                                                        <Border Grid.Row="2" Margin="0,5,0,0">
                                                            <Grid>
                                                                <Grid>
                                                                    <Grid.ColumnDefinitions>
                                                                        <ColumnDefinition>
                                                                        </ColumnDefinition>
                                                                        <ColumnDefinition Width="2*"></ColumnDefinition>
                                                                    </Grid.ColumnDefinitions>
                                                                    <Border Grid.Column="0">
                                                                        <Label VerticalAlignment="Center" Content="站点编号:"></Label>
                                                                    </Border>
                                                                    <Border Grid.Column="1">
                                                                        <TextBox x:Name="StationIDName" VerticalAlignment="Center" Text="10001234"></TextBox>
                                                                    </Border>
                                                                </Grid>
                                                            </Grid>
                                                        </Border>
                                                        <Border Grid.Row="3" Margin="0,5,0,0">
                                                            <Grid>
                                                                <Grid>
                                                                    <Grid.ColumnDefinitions>
                                                                        <ColumnDefinition>
                                                                        </ColumnDefinition>
                                                                        <ColumnDefinition Width="2*"></ColumnDefinition>
                                                                    </Grid.ColumnDefinitions>
                                                                    <Border Grid.Column="0">
                                                                        <Label VerticalAlignment="Center" Content="用户令牌:"></Label>
                                                                    </Border>
                                                                    <Border Grid.Column="1">
                                                                        <TextBox x:Name="StationKeyName" VerticalAlignment="Center" Text="d809b7ae-2560-4f9d-b1b0-4456a521b7b2"></TextBox>
                                                                    </Border>
                                                                </Grid>
                                                            </Grid>
                                                        </Border>
                                                    </Grid>
                                                </GroupBox>
                                            </materialDesign:PopupBox>
                                        </Border>
                                    </Grid>
                                </Border>
                                <!--展示区域-->
                                <Border Grid.Row="1" BorderBrush="LightCyan" BorderThickness="0,1,0,1">
                                    <TabControl x:Name="FunctionTabName" Background="WhiteSmoke">
                                        <TabItem x:Name="weatherTabControl" Height="0" TabIndex="0">
                                            <Border>
                                                <Grid  Margin="15">
                                                    <Grid.RowDefinitions>
                                                        <RowDefinition Height="50"/>
                                                        <RowDefinition/>
                                                    </Grid.RowDefinitions>

                                                    <TextBlock Margin="15 0 0 0" VerticalAlignment="Center" Text="气 象 数 据 展 示" FontSize="15" Foreground="#959595"/>

                                                    <DataGrid x:Name="WeatherDataGridName" Grid.Row="1" Background="Transparent" HeadersVisibility="Column"
                          AutoGenerateColumns="False" CanUserAddRows="False"
                          VerticalGridLinesBrush="Transparent" HorizontalGridLinesBrush="WhiteSmoke"
                          BorderThickness="0">
                                                        <DataGrid.ColumnHeaderStyle>
                                                            <Style TargetType="DataGridColumnHeader">
                                                                <Setter Property="BorderThickness" Value="0"/>
                                                                <Setter Property="VerticalAlignment" Value="Center"/>
                                                                <Setter Property="HorizontalContentAlignment" Value="Center"/>
                                                                <Setter Property="Background" Value="Transparent"/>
                                                                <Setter Property="Foreground" Value="#959595"/>
                                                                <Setter Property="FontWeight" Value="Bold"/>
                                                                <Setter Property="Height" Value="35"/>
                                                            </Style>
                                                        </DataGrid.ColumnHeaderStyle>

                                                        <DataGrid.RowStyle>
                                                            <Style TargetType="DataGridRow">
                                                                <Setter Property="Height" Value="40"/>
                                                                <Setter Property="Foreground" Value="#959595"/>
                                                                <Setter Property="HorizontalAlignment" Value="Center"/>
                                                                <Setter Property="HorizontalContentAlignment" Value="Center"/>
                                                            </Style>
                                                        </DataGrid.RowStyle>

                                                        <DataGrid.Columns>
                                                            <DataGridTextColumn Header="时间" Width="*"  Binding="{Binding time,Converter={StaticResource timeConvertStyle}}" ElementStyle="{StaticResource ContentStyle}">
                                                            </DataGridTextColumn>
                                                            <DataGridTextColumn Header="雨量" Width="*" Binding="{Binding amount}" ElementStyle="{StaticResource ContentStyle}"/>
                                                            <DataGridTextColumn Header="记录间隔" Width="*"     Binding="{Binding interval}" ElementStyle="{StaticResource ContentStyle}"/>
                                                            <DataGridTextColumn Header="天气类型" Width="*"    Binding="{Binding weatherType}"  ElementStyle="{StaticResource ContentStyle}"/>
                                                        </DataGrid.Columns>
                                                    </DataGrid>
                                                </Grid>
                                            </Border>
                                        </TabItem>
                                        <TabItem x:Name="waterTabControl"   Height="0" TabIndex="1" >
                                            <Border Background="AliceBlue">
                                                <Grid  Margin="15">
                                                    <Grid.RowDefinitions>
                                                        <RowDefinition Height="50"/>
                                                        <RowDefinition/>
                                                    </Grid.RowDefinitions>
                                                    <TextBlock Margin="15 0 0 0" VerticalAlignment="Center" Text="水 位 数 据 展 示" FontSize="15" Foreground="#959595"/>
                                                    <DataGrid x:Name="WaterDataGridName" Grid.Row="1" Background="Transparent" HeadersVisibility="Column"
                          AutoGenerateColumns="False" CanUserAddRows="False"
                          VerticalGridLinesBrush="Transparent" HorizontalGridLinesBrush="WhiteSmoke"
                          BorderThickness="0">
                                                        <DataGrid.ColumnHeaderStyle>
                                                            <Style TargetType="DataGridColumnHeader">
                                                                <Setter Property="BorderThickness" Value="0"/>
                                                                <Setter Property="VerticalAlignment" Value="Center"/>
                                                                <Setter Property="HorizontalContentAlignment" Value="Center"/>
                                                                <Setter Property="Background" Value="Transparent"/>
                                                                <Setter Property="Foreground" Value="#959595"/>
                                                                <Setter Property="FontWeight" Value="Bold"/>
                                                                <Setter Property="Height" Value="35"/>
                                                            </Style>
                                                        </DataGrid.ColumnHeaderStyle>

                                                        <DataGrid.RowStyle>
                                                            <Style TargetType="DataGridRow">
                                                                <Setter Property="Height" Value="40"/>
                                                                <Setter Property="Foreground" Value="#959595"/>
                                                                <Setter Property="HorizontalAlignment" Value="Center"/>
                                                                <Setter Property="HorizontalContentAlignment" Value="Center"/>
                                                            </Style>
                                                        </DataGrid.RowStyle>

                                                        <DataGrid.Columns>
                                                            <DataGridTextColumn Header="时间" Width="*"  Binding="{Binding time,Converter={StaticResource timeConvertStyle}}" ElementStyle="{StaticResource ContentStyle}"/>
                                                            <DataGridTextColumn Header="雨水位" Width="*" Binding="{Binding surfaceLevel}" ElementStyle="{StaticResource ContentStyle}"/>
                                                            <DataGridTextColumn Header="地下水埋深度" Width="*"     Binding="{Binding groundLevel}" ElementStyle="{StaticResource ContentStyle}"/>
                                                            <DataGridTextColumn Header="时段水量" Width="*"    Binding="{Binding amountOfInterval}"  ElementStyle="{StaticResource ContentStyle}"/>
                                                            <DataGridTextColumn Header="日水量" Width="*"    Binding="{Binding amountOfDay}"  ElementStyle="{StaticResource ContentStyle}"/>
                                                        </DataGrid.Columns>
                                                    </DataGrid>
                                                </Grid>
                                            </Border>
                                        </TabItem>
                                        <TabItem x:Name="SoilTabControl"    Height="0"   TabIndex="2">
                                            <Border>
                                                <Grid  Margin="15">
                                                    <Grid.RowDefinitions>
                                                        <RowDefinition Height="50"/>
                                                        <RowDefinition/>
                                                    </Grid.RowDefinitions>
                                                    <TextBlock Margin="15 0 0 0" VerticalAlignment="Center" Text="土  壤  墒  情" FontSize="15" Foreground="#959595"/>
                                                    <DataGrid x:Name="SoilDataGridName" Grid.Row="1" Background="Transparent" HeadersVisibility="Column"
                          AutoGenerateColumns="False" CanUserAddRows="False"
                          VerticalGridLinesBrush="Transparent" HorizontalGridLinesBrush="WhiteSmoke"
                          BorderThickness="0">
                                                        <DataGrid.ColumnHeaderStyle>
                                                            <Style TargetType="DataGridColumnHeader">
                                                                <Setter Property="BorderThickness" Value="0"/>
                                                                <Setter Property="VerticalAlignment" Value="Center"/>
                                                                <Setter Property="HorizontalContentAlignment" Value="Center"/>
                                                                <Setter Property="Background" Value="Transparent"/>
                                                                <Setter Property="Foreground" Value="#959595"/>
                                                                <Setter Property="FontWeight" Value="Bold"/>
                                                                <Setter Property="Height" Value="35"/>
                                                            </Style>
                                                        </DataGrid.ColumnHeaderStyle>

                                                        <DataGrid.RowStyle>
                                                            <Style TargetType="DataGridRow">
                                                                <Setter Property="Height" Value="40"/>
                                                                <Setter Property="Foreground" Value="#959595"/>
                                                                <Setter Property="HorizontalAlignment" Value="Center"/>
                                                                <Setter Property="HorizontalContentAlignment" Value="Center"/>
                                                            </Style>
                                                        </DataGrid.RowStyle>

                                                        <DataGrid.Columns>
                                                            <DataGridTextColumn Header="时间" Width="*"  Binding="{Binding time,Converter={StaticResource timeConvertStyle}}" ElementStyle="{StaticResource ContentStyle}"/>
                                                            <DataGridTextColumn Header="10厘米土壤含水" Width="*" Binding="{Binding moisture10CM}" ElementStyle="{StaticResource ContentStyle}"/>
                                                            <DataGridTextColumn Header="20厘米土壤含水" Width="*"     Binding="{Binding moisture20C}" ElementStyle="{StaticResource ContentStyle}"/>
                                                            <DataGridTextColumn Header="40厘米土壤含水" Width="*"    Binding="{Binding moisture40CM}"  ElementStyle="{StaticResource ContentStyle}"/>
                                                        </DataGrid.Columns>
                                                    </DataGrid>
                                                </Grid>
                                            </Border>
                                        </TabItem>
                                        <TabItem x:Name="imageTabControl"   Height="0"  TabIndex="3">
                                            <Border Background="AliceBlue">
                                                <Grid  Margin="15">
                                                    <Grid.RowDefinitions>
                                                        <RowDefinition Height="50"/>
                                                        <RowDefinition/>
                                                    </Grid.RowDefinitions>
                                                    <TextBlock Margin="15 0 0 0" VerticalAlignment="Center" Text="图  像  列  表" FontSize="15" Foreground="#959595"/>
                                                    <DataGrid x:Name="PictureDataGridName" Grid.Row="1" Background="Transparent" HeadersVisibility="Column"
                          AutoGenerateColumns="False" CanUserAddRows="False"
                          VerticalGridLinesBrush="Transparent" HorizontalGridLinesBrush="WhiteSmoke"
                          BorderThickness="0">
                                                        <DataGrid.ContextMenu>
                                                            <!--Header="选择下载" Click="onSelectedImageDataClicked"-->
                                                            <ContextMenu>
                                                                <MenuItem >
                                                                    <MenuItem.Header>
                                                                        <Button
                                                                            Style="{StaticResource MaterialDesignFlatButton}"
                                                                            ToolTip="右键点击下载图像"
                                                                            Content="下 载 图 像" FontSize="14"
                                                                            Click="onSelectedImageDataClicked">
                                                                        </Button>
                                                                    </MenuItem.Header>
                                                                </MenuItem>
                                                            </ContextMenu>
                                                        </DataGrid.ContextMenu>
                                                        <DataGrid.ColumnHeaderStyle>
                                                            <Style TargetType="DataGridColumnHeader">
                                                                <Setter Property="BorderThickness" Value="0"/>
                                                                <Setter Property="VerticalAlignment" Value="Center"/>
                                                                <Setter Property="HorizontalContentAlignment" Value="Center"/>
                                                                <Setter Property="Background" Value="Transparent"/>
                                                                <Setter Property="Foreground" Value="#959595"/>
                                                                <Setter Property="FontWeight" Value="Bold"/>
                                                                <Setter Property="Height" Value="35"/>
                                                            </Style>
                                                        </DataGrid.ColumnHeaderStyle>

                                                        <DataGrid.RowStyle>
                                                            <Style TargetType="DataGridRow">
                                                                <Setter Property="Height" Value="40"/>
                                                                <Setter Property="Foreground" Value="#959595"/>
                                                                <Setter Property="HorizontalAlignment" Value="Center"/>
                                                                <Setter Property="HorizontalContentAlignment" Value="Center"/>
                                                            </Style>
                                                        </DataGrid.RowStyle>

                                                        <DataGrid.Columns>
                                                            <DataGridTextColumn Header="时间" Width="*"  Binding="{Binding time,Converter={StaticResource timeConvertStyle}}" ElementStyle="{StaticResource ContentStyle}"/>
                                                            <DataGridTextColumn Header="图像名字" Width="*" Binding="{Binding name}" ElementStyle="{StaticResource ContentStyle}"/>
                                                        </DataGrid.Columns>
                                                    </DataGrid>
                                                </Grid>
                                            </Border>
                                        </TabItem>
                                    </TabControl>
                                </Border>
                                <!--命令区域显示-->
                                <Border Grid.Row="2">
                                    <Label x:Name="showCommandLabelName" VerticalContentAlignment="Center" HorizontalContentAlignment="Center"></Label>
                                </Border>
                            </Grid>
                        </Border>
                        <Border Grid.Column="2"></Border>
                    </Grid>
                </Grid>
            </Border>
            <Border Grid.Row="2"></Border>
            <materialDesign:PopupBox Style="{StaticResource MaterialDesignMultiFloatingActionPopupBox}"
                                         HorizontalAlignment="Right" VerticalAlignment="Bottom"
                                         Margin="10,0,20,10" Grid.Row="1" Background="{StaticResource BackGroundStyle}">
                <StackPanel>
                    <Button ToolTip="清空" Click="onClearCurrentDataClicked" Background="Transparent">
                        <materialDesign:PackIcon Kind="DeleteEmpty"  Height="20" Width="20" />
                    </Button>
                </StackPanel>
            </materialDesign:PopupBox>
        </Grid>
    </Border>

关键代码:

namespace RestHttp
{
    public class HttpRestClass : IDisposable
    {

        public enum RequestEnum : int
        {
            stationEnum = 0,
            weatherEnum = 1,
            waterEnum = 2,
            SoilEnum = 3,
            ImageListsEnum = 4,
            imageDataEnum = 5
        }

        private List<string> requestPaths = new List<string>();
        private void initRequestSource()
        { 
            requestPaths.Clear();
            requestPaths.Add(@"/IMS/rest/station/");                //测站
            requestPaths.Add(@"/IMS/rest/weather/precipitation?");  //天气.
            requestPaths.Add(@"/IMS/rest/water/level?");            //水位.
            requestPaths.Add(@"/IMS/rest/soil/moisture?");          //土壤
            requestPaths.Add(@"/IMS/rest/video/picture/list?");     //图像列表.
            requestPaths.Add(@"/IMS/rest/video/picture?");          //图像数据.
        }

        /// <summary>
        /// 这里暂不做T的类型约束
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="_requestEnum"></param>
        /// <param name="date"></param>
        /// <returns></returns>
        public string getRequestStationTypeUrl<T>(RequestEnum _requestEnum, T _date) where T : class
        {
            string _rul = null;
            switch (_requestEnum)
            {
                case RequestEnum.stationEnum:
                    {
                        StationReques stationReques = _date as StationReques;
                        if (stationReques != null)
                        {
                            _rul = string.Format("http://{0}:{1}{2}{3}?key={4}", GethttpAddress, getPort, requestPaths[(int)_requestEnum], stationReques.stationId, stationReques.key);
                        }
                        break;
                    }
                case RequestEnum.weatherEnum:
                    {
                        WeatherRequest weather = _date as WeatherRequest;
                        if (weather != null)
                        {
                            _rul = string.Format("http://{0}:{1}{2}" +
                                "stationId={3}&" +
                                @"startTime={4}%20{5}%3A{6}%3A{7}&" +
                                @"endTime={8}%20{9}%3A{10}%3A{11}&" +
                                "key={12}",
                                GethttpAddress, getPort, requestPaths[(int)_requestEnum],
                                weather.stationId,
                                weather.startTime.ToString("yyyy-MM-dd").Trim(), weather.startTime.Hour, weather.startTime.Minute, weather.startTime.Second,
                                weather.endTime.ToString("yyyy-MM-dd").Trim(), weather.endTime.Hour, weather.endTime.Minute, weather.endTime.Second,
                                weather.key
                                );
                        }

                        break;
                    }
                case RequestEnum.waterEnum:
                    {
                        WaterRequest water = _date as WaterRequest;
                        if (water != null)
                        {
                            _rul = string.Format("http://{0}:{1}{2}" +
                               "stationId={3}&" +
                               "startTime={4}%20{5}%3A{6}%3A{7}&" +
                               "endTime={8}%20{9}%3A{10}%3A{11}&" +
                               "key={12}",
                               GethttpAddress, getPort, requestPaths[(int)_requestEnum],
                               water.stationId,
                               water.startTime.ToString("yyyy-MM-dd").Trim(), water.startTime.Hour, water.startTime.Minute, water.startTime.Second,
                               water.endTime.ToString("yyyy-MM-dd").Trim(), water.endTime.Hour, water.endTime.Minute, water.endTime.Second,
                               water.key
                               );
                        }

                        break;
                    }
                case RequestEnum.SoilEnum:
                    {
                        SoilRequest soil = _date as SoilRequest;
                        if (soil != null)
                        {
                            _rul = string.Format("http://{0}:{1}{2}" +
                               "stationId={3}&" +
                               "startTime={4}%20{5}%3A{6}%3A{7}&" +
                               "endTime={8}%20{9}%3A{10}%3A{11}&" +
                               "key={12}",
                               GethttpAddress, getPort, requestPaths[(int)_requestEnum],
                               soil.stationId,
                               soil.startTime.ToString("yyyy-MM-dd").Trim(), soil.startTime.Hour, soil.startTime.Minute, soil.startTime.Second,
                               soil.endTime.ToString("yyyy-MM-dd").Trim(), soil.endTime.Hour, soil.endTime.Minute, soil.endTime.Second,
                               soil.key
                               );
                        }
                        break;
                    }
                case RequestEnum.ImageListsEnum:
                    {
                        PictureRequest pictureRequest = _date as PictureRequest;
                        if (pictureRequest != null)
                        {
                            _rul = string.Format("http://{0}:{1}{2}" +
                                "date={3}&stationId={4}&" +
                                "key={5}",
                                 GethttpAddress, getPort, requestPaths[(int)_requestEnum],
                                 pictureRequest.date.ToString("yyyy-MM-dd").Trim(),
                                 pictureRequest.stationId,
                                 pictureRequest.key
                                ); ;
                        }
                        break;
                    }
                case RequestEnum.imageDataEnum:
                    {
                        pictureDataRequest pictureData = _date as pictureDataRequest;
                        if (pictureData != null)
                        {
                            _rul = string.Format("http://{0}:{1}{2}" +
                                "date={3}&" +
                                "stationId={4}&" +
                                "name={5}&" +
                                "key={6}",
                                 GethttpAddress, getPort, requestPaths[(int)_requestEnum],
                                 pictureData.date.ToString("yyyy-MM-dd").Trim(),
                                 pictureData.stationId,
                                 pictureData.name,
                                 pictureData.key
                                );
                        }
                        break;
                    }
                default:
                    break;
            }
            getUriPathMsg = _rul;
            return _rul;

        }

        public string GethttpAddress { get; set; }

        public string getPort { get; set; }

        public string StationID { get; set; }

        public string StationKey { get; set; }

        /// <summary>
        /// 获取uil路劲信息以及指令信息.
        /// </summary>
        public string getUriPathMsg { get; set; }

        private HttpClient client = null;
        public HttpRestClass(string httpAddress, string port)
        {
            client = new HttpClient();
            initRequestSource();
            GethttpAddress = httpAddress;
            getPort = port;
            StationKey = @"d809b7ae-2560-4f9d-b1b0-4456a521b7b2";
            StationID = "10001234";
        }

        public void showStationInfo(StationResponse stationResponse)
        {
            string str = $" id: {stationResponse.id} \r\n name: {stationResponse.name} \r\n " +
                $"hardware: {stationResponse.hardware} \r\n stationType: {stationResponse.stationType}";
            Console.WriteLine(str);
        }

        public async Task<List<T>> GetStationResposeDataAsyncList<T>(string path)
        {
            List<T> station = null;
            HttpResponseMessage response = await client.GetAsync(path).ConfigureAwait(false);
            if (response.IsSuccessStatusCode)
            {
                station = await response.Content.ReadAsAsync<List<T>>().ConfigureAwait(false);
            }
            else
            {
                Console.WriteLine(@"响应失败...");
            }
            return station;
        }

        public async Task<byte[]> getStationResposeImageDataAsyncByte(string path)
        {
            byte[] imageData = new byte[1024 * 10];
            HttpResponseMessage response = await client.GetAsync(path);
            if (response.IsSuccessStatusCode)
            {
                imageData = await response.Content.ReadAsByteArrayAsync();
            }
            return imageData;
        }


        public async Task<T> GetStationResposeDataAsync<T>(string path)
        {
            try
            {
                T station = default(T);
                HttpResponseMessage response = await client.GetAsync(path).ConfigureAwait(false);
                if (response.IsSuccessStatusCode)
                {
                    station = await response.Content.ReadAsAsync<T>().ConfigureAwait(false);
                }
                return station;
            }
            catch (Exception ex)
            {
                throw new Exception(string.Format("Error: GetStationResposeDataAsync(...): {0} (无法连接或者无法访问)", ex.Message));
            }
        }

        public void Dispose()
        {
            if (client != null)
            {
                client.Dispose();
            }
        }

        private async void downImage(string urlPath, string outImageFullName)
        {
            try
            {
                HttpResponseMessage response = await client.GetAsync(urlPath).ConfigureAwait(false);
                if (response.IsSuccessStatusCode)
                {
                    using (System.IO.Stream strem = response.Content.ReadAsStreamAsync().Result)
                    {
                        byte[] arry = new byte[strem.Length];
                        strem.Read(arry, 0, (int)strem.Length);
                        MemoryStream ms = new MemoryStream(arry);
                        System.Drawing.Image img = System.Drawing.Image.FromStream(strem);
                        img.Save(outImageFullName, System.Drawing.Imaging.ImageFormat.Png);
                        ms.Close();
                    }
                }
                else
                {
                    throw new Exception(@"响应失败...");
                }

#if false
                if (response.IsSuccessStatusCode)
                {
                    using (FileStream fs = File.Create(@"F:\2017\skyLineGlobel_prp\skyLineStudy_projects\WPF\WPF\rest-http-console\temp22222"))
                    {
                        Stream streamFromService = await response.Content.ReadAsStreamAsync();
                        streamFromService.CopyTo(fs);
                        Console.WriteLine(@"数据流的大小: " + streamFromService.Length);
                    }
                } 
#endif
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }

        }
        #region 功能函数.

        public void getStationData(out StationResponse stationResponse)
        {
            try
            {
                StationReques _station = new StationReques()
                {
                    key = StationKey,
                    stationId = StationID
                };
                if (_station.key.Length < 1 || _station.stationId.Length < 1)
                {
                    throw new Exception(@"key or stationId ` length is null");
                }

                string strpath = getRequestStationTypeUrl<StationReques>(HttpRestClass.RequestEnum.stationEnum, _station).ToString();
                stationResponse = GetStationResposeDataAsync<StationResponse>(strpath).Result;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }


        /// <summary>
        ///图像下载
        /// </summary>
        /// <param name="StartTimageData"></param>
        /// <param name="_name"></param>
        /// <param name="outImageDir"></param>
        public void getAndDownImageData(DateTime StartTimageData, string _name, string outImageDir)
        {
            try
            {
                if(!Directory.Exists(outImageDir))
                {
                    throw new Exception(@"getAndDownImageData(...): 传入的文件夹路径不存在");
                }
                //注意数据name转码.
                pictureDataRequest pictureDataRequest = new pictureDataRequest()
                {
                    key = StationKey,
                    stationId = StationID,
                    date = StartTimageData,
                    name = HttpUtility.UrlEncode(_name)

                };
                string strpath = getRequestStationTypeUrl<pictureDataRequest>(HttpRestClass.RequestEnum.imageDataEnum, pictureDataRequest).ToString();
                Task.Delay(20);
                string imageFullName = string.Format(@"{0}/{1}.png", outImageDir, _name);
                downImage(strpath, imageFullName);
                if (!File.Exists(imageFullName))
                {
                    getUriPathMsg = $"图像路径: {imageFullName}";
                }
                else
                {
                    getUriPathMsg = $"图像下载失败.._name: {_name},此资源在服务器可能已经被删除";
                }
               
            }
            catch (Exception ex)
            {
                throw ex;
            }

        }

        /// <summary>
        /// 获取气象数据.
        /// </summary>
        /// <param name="starttime"></param>
        /// <param name="endtime"></param>
        /// <param name="observableCollection"></param>
        public void getWeatherListData(ref DateTime starttime, ref DateTime endtime, ref ObservableCollection<WeatherResponse> observableCollection)
        {
            try
            {
                WeatherRequest weatherRequest = new WeatherRequest()
                {
                    key = StationKey,
                    stationId = StationID,
                    startTime = starttime,
                    endTime = endtime
                };
                string strpath = getRequestStationTypeUrl<WeatherRequest>(HttpRestClass.RequestEnum.weatherEnum, weatherRequest).ToString();
                Thread.Sleep(1000);
                List<WeatherResponse> weatherResponseList = new List<WeatherResponse>();
                weatherResponseList = GetStationResposeDataAsyncList<WeatherResponse>(strpath).Result;

                if (weatherResponseList != null && weatherResponseList.Count > 0)
                {
                    observableCollection.Clear();
                    foreach (var item in weatherResponseList)
                    {
                        observableCollection.Add(item);
                    }
                }
                else
                {
                    throw new Exception(@"请求数据为空.请重新选择时间区间");
                }

            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        /// <summary>
        /// 水位数据获取.
        /// </summary>
        /// <param name="starttime"></param>
        /// <param name="endtime"></param>
        /// <param name="observableCollection"></param>
        public void getWaterListDate(ref DateTime starttime, ref DateTime endtime, ref ObservableCollection<WaterResponse> observableCollection)
        {
            try
            {
                WaterRequest waterRequest = new WaterRequest()
                {
                    key = StationKey,
                    stationId = StationID,
                    startTime = starttime,
                    endTime = endtime
                };
                string strpath = getRequestStationTypeUrl<WaterRequest>(HttpRestClass.RequestEnum.waterEnum, waterRequest).ToString();
                Thread.Sleep(1000);
                List<WaterResponse> waterResponseList = new List<WaterResponse>();
                waterResponseList = GetStationResposeDataAsyncList<WaterResponse>(strpath).Result;

                if (waterResponseList != null && waterResponseList.Count > 0)
                {
                    observableCollection.Clear();
                    foreach (var item in waterResponseList)
                    {
                        observableCollection.Add(item);
                    }
                }
                else
                {
                    throw new Exception(@"请求数据为空.请重新选择时间区间");
                }

            }
            catch (Exception ex)
            {
                throw ex;
            }
        }


        /// <summary>
        /// 土壤数据获取.
        /// </summary>
        /// <param name="starttime"></param>
        /// <param name="endtime"></param>
        /// <param name="observableCollection"></param>
        public void getSoilListDate(ref DateTime starttime, ref DateTime endtime, ref ObservableCollection<SoilResponse> observableCollection)
        {
            try
            {
                SoilRequest soilRequest = new SoilRequest()
                {
                    key = StationKey,
                    stationId = StationID,
                    startTime = starttime,
                    endTime = endtime
                };
                string strpath = getRequestStationTypeUrl<SoilRequest>(HttpRestClass.RequestEnum.SoilEnum, soilRequest).ToString();
                Thread.Sleep(1000);
                List<SoilResponse> soilResponseList = new List<SoilResponse>();
                soilResponseList = GetStationResposeDataAsyncList<SoilResponse>(strpath).Result;

                if (soilResponseList != null && soilResponseList.Count > 0)
                {
                    observableCollection.Clear();
                    foreach (var item in soilResponseList)
                    {
                        observableCollection.Add(item);
                    }
                }
                else
                {
                    throw new Exception(@"请求数据为空.请重新选择时间区间");
                }

            }
            catch (Exception ex)
            {
                throw ex;
            }
        }


        /// <summary>
        /// 图像数据获取.
        /// </summary>
        /// <param name="starttime"></param>
        /// <param name="observableCollection"></param>
        public void getImageListDate(ref DateTime starttime, ref ObservableCollection<PictureResponse> observableCollection)
        {
            try
            {
                PictureRequest pictureRequest = new PictureRequest()
                {
                    key = StationKey,
                    stationId = StationID,
                    date = starttime
                };
                string strpath = getRequestStationTypeUrl<PictureRequest>(HttpRestClass.RequestEnum.ImageListsEnum, pictureRequest).ToString();
                Thread.Sleep(1000);
                List<PictureResponse> pictureResponseList = new List<PictureResponse>();
                pictureResponseList = GetStationResposeDataAsyncList<PictureResponse>(strpath).Result;

                if (pictureResponseList != null && pictureResponseList.Count > 0)
                {
                    observableCollection.Clear();
                    foreach (var item in pictureResponseList)
                    {
                        observableCollection.Add(item);
                    }
                }
                else
                {
                    throw new Exception(@"请求数据为空.请重新选择时间区间");
                }

            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        #endregion

    }
}

 注意事项:

 在进行地址访问设置的时候,要注意http本身的格式转换,依据其格式,进行一个请求指令的书写

后言:

 这里只供参考. 并做一个记录

安装包:

 

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值