C#,js和sql实用技巧选1

我刚开始.net 开发的那几年,差不多每天坚持搜集实用的技巧和代码片断。几年下来也搜集了上千条。现在选出一些不太容易找或者自己有较多体会的,写在这里。内容太多,分两次发。

1.上传文件超过设置允许的最大值时,显示自定义出错页面。

这个帖子说得最好:https://stackoverflow.com/questions/2759193/display-custom-error-page-when-file-upload-exceeds-allowed-size-in-asp-net-mvc

自己的一点心得:这个帖子里引用了这个链接:https://www.thecodingforums.com/threads/how-to-handle-maximum-request-length-exceeded-exception.97027/ 实践发现,还需要在Application_Error里压制相应的exception。

在php里,不存在这个问题。如果上传文件超过设置允许的最大值,php不会象asp.net 那样抛出一个让人不知道发生什么的空页面。

2.检查当前用户是否属于某个数据库角色

ALTER PROCEDURE [dbo].[ssp_IsDbRole]
    @RoleName        VARCHAR(50)
AS

DECLARE @IsMember        BIT
,        @CurrentUser    VARCHAR(60)     
,        @UserLogin        VARCHAR(60) 
,        @SIndex            INT 

CREATE TABLE #tmp_Roles 
(
        RoleName        VARCHAR(60)
,        RoleID            SMALLINT
,        IsAppRole        INT
)

INSERT INTO #tmp_Roles 
EXEC    sp_helprole 

IF NOT EXISTS 
(
    SELECT NULL 
    FROM #tmp_Roles 
    WHERE RoleName = @RoleName
)
  SET @IsMember = 0
ELSE
  BEGIN 
      SET @CurrentUser = SYSTEM_USER
      SET @SIndex = CHARINDEX('\', @CurrentUser)
      IF @SIndex > 0 
        SET @UserLogin = SUBSTRING(@CurrentUser, @SIndex + 1, LEN(@CurrentUser) - @SIndex)
      ELSE 
        SET @UserLogin = @CurrentUser

      CREATE TABLE #tmp_Members 
      (
            DBRole         VARCHAR(60)
      ,        MemberName     VARCHAR(60)
      ,        MemberSID     VARBINARY(85)
      )
      INSERT INTO #tmp_Members EXEC sp_helprolemember @RoleName  
      IF EXISTS 
      (
        SELECT MemberSID 
        FROM #tmp_Members 
        WHERE MemberName IN (@CurrentUser, @UserLogin)
      )
        SET @IsMember = 1
      ELSE
        SET @IsMember = 0
      DROP TABLE #tmp_Members
  END
DROP TABLE #tmp_Roles
SELECT @IsMember AS IsMember

3. sql server 2005和2008 报表服务有不同的缺省web服务地址,一个检测到底是2005还是2008的方法是:向这个地址

http://<服务器地址>:<端口号>/reportserver/reportservice.asmx 发一个http请求,然后看返回的文本,如以<html开头就是2008,如以<?xml开始,就是2005。

4. 在报表服务器上创建新目录

string reportPath = "/foo/bar";
bool exists = true;
string parentPath = "/";
string[] reportPaths = reportPath.Split(new char[] { '/' }, StringSplitOptions.RemoveEmptyEntries);
if (reportPaths.Length > 0)
{

    SearchCondition[] conditions = new SearchCondition[1];
    SearchCondition condition = new SearchCondition();
    condition.Condition = ConditionEnum.Equals;
    condition.ConditionSpecified = true;
    condition.Name = "Name";


    for (int i = 0; i < reportPaths.Length; i++)
    {
        condition.Value = reportPaths[i];
        conditions[0] = condition;
        var result = myreportingServiceWebServiceClient.FindItems(parentPath, BooleanOperatorEnum.And, conditions);
        if (result == null || result.Length == 0)
        {
            exists = false;
            myreportingServiceWebServiceClient.CreateFolder(reportPaths[i], parentPath, null);
        }
        if (parentPath != "/")
        {
            parentPath += "/";
        }
        parentPath += reportPaths[i];
    }
}

 

5. 以下sql

select abc from dbo.a left join dbo.b where b.t = 'a'

如果b.t是null就没有任何返回结果

应改成

select abc from dbo.a left join dbo.b on b.t = 'a'

6. asp.net应用,如果服务器和客户端使用不同的地理区域设置,可能会有不同的日期格式,在解析时要注意这个问题,一种方法是:

                DateTime dt = DateTime.MinValue;
                string strDate = Request["Date"];
                System.Globalization.CultureInfo[] cultures = System.Globalization.CultureInfo.GetCultures(System.Globalization.CultureTypes.AllCultures);
                foreach (var item in cultures)
                {
                    if (DateTime.TryParse(strDate, item, System.Globalization.DateTimeStyles.None, out dt))
                    {//合法的日期
                           ......
                            break;
                     }
                 }

7. asp.net应用里,检查Cache是否过期,最好是if (Cache["mykey"] == null || ((MyObj)Cache["mykey"]).MyProperty == null)

而不仅仅是if (Cache["mykey"] == null)

8. 通过连接服务器(linked server)执行存储过程时,触发了错误:

Server 'foo' is not configured for rpc.

如果打开Sql Server Management Studio,linker server properties -- server options -- RPC and RPC out,企图将值改成true,可能会触发错误:

Ad hoc updates to system catalogs are not allowed.

正确做法是执行:

exec sp_serveroption @server='foo', @optname='rpc', @optvalue='true'
exec sp_serveroption @server='foo', @optname='rpc out', @optvalue='true'

9. javascript:列出对象的所有属性名称和值:

function dumpProps(obj, parent) {
   for (var i in obj) {
      if (parent) { 
         var msg = parent + "." + i + "\n" + obj[i];
      }
      else {
         var msg = i + "\n" + obj[i];
      }
      alert(msg);
      if (typeof obj[i] === "object") {
         if (parent) {
            dumpProps(obj[i], parent + "." + i);
         }
         else {
            dumpProps(obj[i], i);
         }
      }
   }
   
}

10. sql server: 在计算列(computed column)上建索引要小心,可能会触发错误:

INSERT failed because the following SET options have incorrect settings: 'ANSI_NULLS'. Verify that SET options are correct for use with indexed views and/or indexes on computed columns and/or filtered indexes and/or query notifications and/or XML data type methods and/or spatial index operations.

解决办法是正确设置这些标志值:

SET NUMERIC_ROUNDABORT OFF
GO
SET ANSI_PADDING,ANSI_WARNINGS,CONCAT_NULL_YIELDS_NULL ,ARITHABORT,QUOTED_IDENTIFIER,ANSI_NULLS ON
GO

11. 使用windows的Task Scheduler,运行一个批处理文件(.bat)将文件拷贝到一个网络盘:

copy c:\temp\a.txt  q:\abc\

这不会成功,得用完整地址:

copy c:\temp\a.txt \\<域名>\\<机器名>\\abc

尽管这个路径已经映射为q:,可是Task Scheduler好像不知道这回事。

另一个方法就是在上面的copy命令前,先执行一条net use映射命令。

 

posted @ 2018-01-10 03:59  平静寄居者  阅读(330)  评论(0编辑  收藏  举报