2017.12.14 LINQ查询、图片上传及预览、存储过程使

2017-12-15  本文已影响0人  胡諾

第一组:陈辉 LINQ中的方法语法和查询语法

介绍性的语言集成查询 (LINQ) 文档中的大多数查询是使用 LINQ 声明性查询语法编写的。 但是在编译代码时,查询语法必须转换为针对 .NET 公共语言运行时 (CLR) 的方法调用。 这些方法调用会调用标准查询运算符(名称为 Where、Select、GroupBy、Join、Max 和 Average 等)。 可以使用方法语法(而不查询语法)来直接调用它们。

查询语法和方法语法在语义上是相同的,但是许多人发现查询语法更简单且更易于阅读。 某些查询必须表示为方法调用。 例如,必须使用方法调用表示检索与指定条件匹配的元素数的查询。 还必须对检索源序列中具有最大值的元素的查询使用方法调用。 System.Linq 命名空间中的标准查询运算符的参考文档通常使用方法语法。 因此,即使在开始编写 LINQ 查询时,熟悉如何在查询和查询表达式本身中使用方法语法也十分有用。

下面展示查询语法和方法语法以及他们的混合使用的例子:

C#复制

class QueryVMethodSyntax
{
    static void Main()
    {
        int[] numbers = { 5, 10, 8, 3, 6, 12};

        //Query syntax:
        IEnumerable<int> numQuery1 = 
            from num in numbers
            where num % 2 == 0
            orderby num
            select num;          //<------查询语法
       
        //Method syntax:
        IEnumerable<int> numQuery2 = numbers.Where(num => num % 2 == 0).OrderBy(n => n);       //<-------方法语法


       //Mix syntax:
       Int numCount = (from num in number where num % 2 == 0
orderby num select num).Count();//<-----两者混合方法

        foreach (int i in numQuery1)
        {
            Console.Write(i + " ");
        }
        Console.WriteLine(System.Environment.NewLine);
        foreach (int i in numQuery2)
        {
            Console.Write(i + " ");
        }
        
        // Keep the console open in debug mode.
        Console.WriteLine(System.Environment.NewLine);
        Console.WriteLine("Press any key to exit");
        Console.ReadKey();
    }
}
/*
    Output:
    6 8 10 12
    6 8 10 12
 */

第二组:徐晋 图片上传及预览功能

Webapp图片上传的问题,请教王敏和叶佳意后,完成的代码。

前台代码:

<input type="text" id="filesPath" style="display:none"/>
            <div id="DivLocker" style="color: #ffffff; text-align: center; font-size: 18px; display: none;" data-lang="uploading">
                <div id="progressNumber" style="font-size: 60px; font-family: 'Microsoft YaHei';" data-lang="app_setting_loading">上传中</div>
            </div>
            上传图片:<input type="file" name="fileData" id="fileToUpload" onchange="uploadFilePress()" style="z-index: 999" multiple="multiple"/>


//canvas压缩上传
function uploadFilePress() {
    var files = document.getElementById('fileToUpload').files;
    if (files.length > 0) {
        for (var i = 0; i < files.length; i++) {
            var _file = files[i];
            var filename = _file.name;
            var fileType = _file.type;
            if (/image\/\w+/.test(fileType)) {
                var fileReader = new FileReader();
                fileReader.readAsDataURL(_file);
                fileReader.onload = function (event) {
                    var result = event.target.result;   //返回的dataURL  
                    var image = new Image();
                    image.src = result;
                    image.onload = function () {  //创建一个image对象,给canvas绘制使用  
                        var cvs = document.createElement('canvas');
                        var scale = 1;
                        if (this.width > 500 || this.height > 500) {  //1000只是示例,可以根据具体的要求去设定    
                            if (this.width > this.height) {
                                scale = 500 / this.width;
                            } else {
                                scale = 500 / this.height;
                            }
                        }
                        cvs.width = this.width * scale;
                        cvs.height = this.height * scale;     //计算等比缩小后图片宽高  
                        var ctx = cvs.getContext('2d');
                        ctx.drawImage(this, 0, 0, cvs.width, cvs.height);
                        var newImageData = cvs.toDataURL(fileType, 0.8);   //重新生成图片,<span style="font-family: Arial, Helvetica, sans-serif;">fileType为用户选择的图片类型</span>  
                        var sendData = newImageData.replace("data:" + fileType + ";base64,", '');
                        $.post('/Action/UploadFiles.ashx?act=uploadpress&path=Upload/File/&filename=' + filename, { type: 'photo', value: sendData }, function (data) {
                            $('#filesPath').val($('#filesPath').val() + data + ',');
                            uploadComplete_(data);
                        });
                    }
                }
            } else {
                $.toast("只允许上传图片!");
            }
        }
    }
    else {
        alert('请选择上传的图片!');
    }
}
function uploadComplete_(evt) {//上传完成
    $.ajax({
        url: "/Action/UploadFiles.ashx",
        type: "POST",
        data: { act: "ifsuccess", filename: evt },
        dataType: "text",
        async: false,
        success: function (data) {
            if (data == "上传失败") {
                $("#filePath").val("");
                $.toast(data);
            } else {
                $("#filePath").val(evt);
                $.toast("上传成功");
                var img = '<div class="imgBox">' +
                            '<img src="' + evt + '" style="width:' + imgWidth + 'px;"/>' +
                            '<div onclick="delImg(this)" style="height:1rem; width:1rem; font-size:1.2rem; color:red; position:absolute; top:0; right:10px;">×</div>' + '</div>';
                $('.content').append(img);
            }
            $("#progressNumber").empty();
            $("#DivLocker").hide();
        }
    });
}
function delImg(delButton) {
    var curPath = $(delButton).parent().find("img")[0].src;
    var i = curPath.indexOf("/Upload");
    curPath = curPath.substring(i, curPath.length) + ',';
    $(delButton).parent().remove();
    var fullPath = $('#filesPath').val();
    $('#filesPath').val(fullPath.replace(curPath, ''));

    $("#fileToUpload").remove();
    $("#uploadImg").append('<input type="file" name="fileData" id="fileToUpload" onchange="uploadFilePress()" multiple="multiple"/>');

}

后台代码:

case "uploadpress"://canvans压缩后,base64上传
   {
       try
       {
           string filePath = context.Request["path"];
           string fileName = context.Request["filename"];
           string packName = DateTime.Now.ToString("yyyyMMdd");//文件夹
           string dir = context.Server.MapPath("~/" + filePath + "/" + packName);

           if (!Directory.Exists(dir))    
           {
               Directory.CreateDirectory(dir);   
           }
           var fileStr = context.Request["value"];
           if (fileStr.Length > 0)
           {
               Random ran = new Random();
               string imgindex = DateTime.Now.ToString("yyyyMMddHHmmssttt") + ran.Next(100, 999).ToString();
               string fileNameSecret = LoongAir.Common.Encryptor.Get16MD5Str(imgindex) + LoongAir.Common.Config.ServerId + System.IO.Path.GetExtension(System.IO.Path.GetFileName(fileName));
               string path = System.IO.Path.Combine(dir, fileNameSecret);
               Base64StringToImage(fileStr, dir, fileNameSecret);
               savepath = "/" + filePath + "/" + packName + "/" + fileNameSecret;
           }
           msg = savepath;
       }
       catch (Exception ex)
       {
           msg = "false";
       }
       break;
   }
case "ifsuccess"://验证文件是否上传成功
   {
       try
       {
           string filename = context.Request["filename"];
           string dir = context.Server.MapPath("~/" + filename);
           bool ifExists = File.Exists(dir);
           if (ifExists)     
           {
               msg = "上传成功";
           }
           else
           {
               msg = "上传失败";
           }
       }
       catch (Exception ex)
       {
           msg = "上传失败";
       }
       break;
   }

实现效果:
点击上传图片选择图片即可上传,可一次上传多张,也可分别上传多张,上传成功后每张图片在下方有预览,并附带删除按钮。


image.png

第三组:蔡永坚 存储过程-存储过程使用

系统存储过程放在master数据库下,以sp_开头,用户新建数据表,系统会自动创建一些系统存过程。


image.png

一下介绍几个系统存储过程:
exec sp_databases; --查看数据库
exec sp_tables; --查看表
exec sp_columns student;--查看列
exec sp_helpIndex student;--查看索引
exec sp_helpConstraint student;--约束
exec sp_helptext 'sp_stored_procedures';--查看存储过程创建、定义语句
exec sp_rename student, stuInfo;--修改表、索引、列的名称
exec sp_renamedb myTempDB, myDB;--更改数据库名称
exec sp_defaultdb 'master', 'myDB';--更改登录名的默认数据库
exec sp_helpdb;--数据库帮助,查询数据库信息
exec sp_helpdb master;

用户自定义存储过程:

create proc | procedure pro_name
    [{@参数数据类型} [=默认值] [output],
     {@参数数据类型} [=默认值] [output],
     ....
    ]
as
    SQL_statements
if (exists (select * from sys.objects where name = 'proc_get_student'))
    drop proc proc_get_student
go
create proc proc_get_student
as
  select * from student;
exec proc_get_student;
alter proc proc_get_student
as
  select * from student;
if (object_id('proc_find_stu', 'P') is not null)
    drop proc proc_find_stu
go
create proc proc_find_stu(@startId int, @endId int)
as
    select * from student where id between @startId and @endId
go

exec proc_find_stu 2, 4;
if (object_id('proc_findStudentByName', 'P') is not null)
    drop proc proc_findStudentByName
go
create proc proc_findStudentByName(@name varchar(20) = '%j%', @nextName varchar(20) = '%')
as
    select * from student where name like @name and name like @nextName;
go

exec proc_findStudentByName;
exec proc_findStudentByName '%o%', 't%';

if (object_id('proc_getStudentRecord', 'P') is not null)
    drop proc proc_getStudentRecord
go
create proc proc_getStudentRecord(
    @id int, --默认输入参数
    @name varchar(20) out, --输出参数
    @age varchar(20) output--输入输出参数
)
as
    select @name = name, @age = age  from student where id = @id and sex = @age;
go

-- 
declare @id int,
        @name varchar(20),
        @temp varchar(20);
set @id = 7; 
set @temp = 1;
exec proc_getStudentRecord @id, @name out, @temp output;
select @name, @temp;
print @name + '#' + @temp;

第四组 :张元一 Cookie/Session机制详解

1.1.8 Cookie的修改、删除

Cookie并不提供修改、删除操作。如果要修改某个Cookie,只需要新建一个同名的Cookie,添加到response中覆盖原来的Cookie。

如果要删除某个Cookie,只需要新建一个同名的Cookie,并将maxAge设置为0,并添加到response中覆盖原来的Cookie。注意是0而不是负数。负数代表其他的意义。读者可以通过上例的程序进行验证,设置不同的属性。

注意:修改、删除Cookie时,新建的Cookie除value、maxAge之外的所有属性,例如name、path、domain等,都要与原Cookie完全一样。否则,浏览器将视为两个不同的Cookie不予覆盖,导致修改、删除失败。

1.1.9 Cookie的域名

Cookie是不可跨域名的。域名www.google.com颁发的Cookie不会被提交到域名www.baidu.com去。这是由Cookie的隐私安全机制决定的。隐私安全机制能够禁止网站非法获取其他网站的Cookie。

正常情况下,同一个一级域名下的两个二级域名如www.helloweenvsfei.comimages.helloweenvsfei.com也不能交互使用Cookie,因为二者的域名并不严格相同。如果想所有helloweenvsfei.com名下的二级域名都可以使用该Cookie,需要设置Cookie的domain参数,例如:

Cookie cookie = new Cookie("time","20080808"); // 新建Cookie
cookie.setDomain(".helloweenvsfei.com");           // 设置域名
cookie.setPath("/");                              // 设置路径
cookie.setMaxAge(Integer.MAX_VALUE);               // 设置有效期
response.addCookie(cookie);                       // 输出到客户端

读者可以修改本机C:\WINDOWS\system32\drivers\etc下的hosts文件来配置多个临时域名,然后使用setCookie.jsp程序来设置跨域名Cookie验证domain属性。

注意:domain参数必须以点(".")开始。另外,name相同但domain不同的两个Cookie是两个不同的Cookie。如果想要两个域名完全不同的网站共有Cookie,可以生成两个Cookie,domain属性分别为两个域名,输出到客户端。

1.1.10 Cookie的路径

domain属性决定运行访问Cookie的域名,而path属性决定允许访问Cookie的路径(ContextPath)。例如,如果只允许/sessionWeb/下的程序使用Cookie,可以这么写:

Cookie cookie = new Cookie("time","20080808");     // 新建Cookie
cookie.setPath("/session/");                          // 设置路径
response.addCookie(cookie);                           // 输出到客户端

设置为“/”时允许所有路径使用Cookie。path属性需要使用符号“/”结尾。name相同但domain相同的两个Cookie也是两个不同的Cookie。

注意:页面只能获取它属于的Path的Cookie。例如/session/test/a.jsp不能获取到路径为/session/abc/的Cookie。使用时一定要注意。


第五组:王炳钧 Dev GridView 绑定List<T>、BindingList <T>、BindingSource

处理数据结构的时候特意处理为了 BindingList<T>,可以直接绑定到Dev GridView上:

  1. 在Dev GridView中新增三列,三列的FieldName分别对应与FormItem类对应:ItemKey、Name、Enable


    image.png

在Form窗体上增加一个Buntton按钮事件,并添加Click事件,在Click事件中填充List<T>、BindingList <T>、BindingSource,并进行绑定测试:


image.png
  1. 通过测试发现List<T>、BindingList <T>、BindingSource均可以绑定到Dev GridView上

  2. 用过Dev GridView的朋友应该知道,给Dev GridView绑定DataTable后,在GridView上的修改会同步到到DataTable上,那么问题来了Dev GridView 绑定List<T>、BindingList <T>、BindingSource会不会同步呢?

于是添加GridView的CellValueChanged事件,在该事件中监视变量itemsBindingList、itemsList、bs,可以发现修改也是同步的。

上一篇下一篇

猜你喜欢

热点阅读