init: 潍柴发动机线 管理后端 项目首次入库

This commit is contained in:
XingCheng3
2026-06-08 12:04:29 +08:00
commit 973692401d
152 changed files with 116669 additions and 0 deletions

16
.gitignore vendored Normal file
View File

@@ -0,0 +1,16 @@
.vs/
obj/
TestResults/
*.user
*.suo
*.cache
*.pdb
*.log
MW_Log/
_ReSharper*/
*.vsp
*.vspscc
*.vssscc
*.nupkg
*.tmp
~$*

View File

View File

@@ -0,0 +1,21 @@
<?xml version="1.0" encoding="utf-8"?>
<!--
您 Web 项目的发布/打包进程将使用此文件。您可以通过编辑此 MSBuild 文件
来自定义该进程的行为。若要了解与此相关的详细信息,请访问 http://go.microsoft.com/fwlink/?LinkID=208121。
-->
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<WebPublishMethod>FileSystem</WebPublishMethod>
<LastUsedBuildConfiguration>Debug</LastUsedBuildConfiguration>
<LastUsedPlatform>Any CPU</LastUsedPlatform>
<SiteUrlToLaunchAfterPublish />
<LaunchSiteAfterPublish>True</LaunchSiteAfterPublish>
<PrecompileBeforePublish>True</PrecompileBeforePublish>
<EnableUpdateable>True</EnableUpdateable>
<DebugSymbols>False</DebugSymbols>
<WDPMergeOption>DonotMerge</WDPMergeOption>
<ExcludeApp_Data>True</ExcludeApp_Data>
<publishUrl>C:\test</publishUrl>
<DeleteExistingFiles>True</DeleteExistingFiles>
</PropertyGroup>
</Project>

0
App_Data/_system~.ini Normal file
View File

View File

@@ -0,0 +1,543 @@
using System;
using System.Data;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI.WebControls;
/// <summary>
///CommonFunction 的摘要说明
/// </summary>
public partial class CommonFunction
{
/// <summary>
/// 基本报表
/// </summary>
/// <param name="table"></param>
public static void ExcelTable_QualityData_XR(string image)
{
System.Web.HttpContext web = System.Web.HttpContext.Current;
string str;
//if (table == null) return;
web.Response.Clear();
web.Response.Charset = "GB2312";
web.Response.Buffer = true;
web.Response.ContentEncoding = System.Text.Encoding.UTF8;
web.Response.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode("Sheet.xls", System.Text.Encoding.UTF8).ToString());
HttpContext.Current.Response.Write("<meta http-equiv=Content-Type content=\"text/html; charset=UTF-8\">");
web.Response.ContentType = "application/ms-excel";
//表头
int table_Columns_Count = 5;
string table_TableName = "标题";
web.Response.Write("<table border=1>");
web.Response.Write("<tr>");
web.Response.Write("<td align=\"center\" valign=\"middle\" colspan=\"" + table_Columns_Count + "\">" + table_TableName + "</td>");
web.Response.Write("<tr>");
web.Response.Write("<tr>");
//SPC.WebUI.PageBase.UrlBase
str = "<td align=\"center\" valign=\"middle\" colspan=\"" + table_Columns_Count + "\">" +
"<img alt=\"\" src=\"F:/MES系统工作/UA格特拉克项目/B5ASpc2010/SPC_Web/TempImages/chart_a78fa46a868743a494aaba7f3ed8c456_2.png\" />" + "</td>";
//str = "<td align=\"center\" valign=\"middle\" colspan=\"" + table_Columns_Count + "\">" +
// "<img alt=\"\" src=\"" + SPC.WebUI.PageBase.UrlBase + "/TempImages/chart_a78fa46a868743a494aaba7f3ed8c456_2.png\" />" + "</td>";
//str = "<td align=\"center\" valign=\"middle\" colspan=\"" + table_Columns_Count + "\">" +
// "<img alt=\"\" src=\"" + SPC.WebUI.PageBase.UrlBase + "/TempImages/ChartPic_#SEQ(300,3)\" />" + "</td>";
string in_str = "<input type=\"hidden\" name=\"__VIEWSTATE\" id=\"__VIEWSTATE\" value=\"/wEPDwULLTE0MjQ0Mzc5ODIPZBYCZg9kFgICAw9kFgQCCw88KwAJAQAPFgQeCERhdGFLZXlzFgAeC18hSXRlbUNvdW50AgZkFgxmD2QWBAIDDw8WAh4EVGV4dAUM6LSo6YeP5pWw5o2uZGQCBQ88KwARAgAPFgQeC18hRGF0YUJvdW5kZx8BAgFkARAWABYAFgAWAmYPZBYGZg8PFgIeB1Zpc2libGVoZGQCAQ9kFgJmD2QWAgIBDw8WBB4LTmF2aWdhdGVVcmwFNmh0dHA6Ly9sb2NhbGhvc3QvU1BDX0I1QS9tb2R1bGUvUXVhbGl0eURhdGFfUXVlcnkuYXNweB8CBRLotKjph4/mlbDmja7mn6Xor6JkZAICDw8WAh8EaGRkAgEPZBYEAgMPDxYCHwIFFei0qOmHj+aVsOaNrlNQQ+WIhuaekGRkAgUPPCsAEQIADxYEHwNnHwECB2QBEBYAFgAWABYCZg9kFhJmDw8WAh8EaGRkAgEPZBYCZg9kFgICAQ8PFgQfBQVCaHR0cDovL2xvY2FsaG9zdC9TUENfQjVBL21vZHVsZS9RdWFsaXR5RGF0YV9UcmVuZFBpY3R1cmVCYXNpYy5hc3B4HwIFD+WfuuacrOi2i+WKv+WbvmRkAgIPZBYCZg9kFgICAQ8PFgQfBQU9aHR0cDovL2xvY2FsaG9zdC9TUENfQjVBL21vZHVsZS9RdWFsaXR5RGF0YV9UcmVuZFBpY3R1cmUuYXNweB8CBQ/moLfmnKzotovlir/lm75kZAIDD2QWAmYPZBYCAgEPDxYEHwUFOmh0dHA6Ly9sb2NhbGhvc3QvU1BDX0I1QS9tb2R1bGUvUXVhbGl0eURhdGFfSGlzdG9ncmFtLmFzcHgfAgUJ55u05pa55Zu+ZGQCBA9kFgJmD2QWAgIBDw8WBB8FBUNodHRwOi8vbG9jYWxob3N0L1NQQ19CNUEvbW9kdWxlL1F1YWxpdHlEYXRhX05vcm1hbERpc3RyaWJ1dGlvbi5hc3B4HwIFEuW3peW6j+iDveWKm+WIhuaekGRkAgUPZBYCZg9kFgICAQ8PFgQfBQU3aHR0cDovL2xvY2FsaG9zdC9TUENfQjVBL21vZHVsZS9RdWFsaXR5RGF0YV9QYXJldG8uYXNweB8CBQnmjpLliJflm75kZAIGD2QWAmYPZBYCAgEPDxYEHwUFM2h0dHA6Ly9sb2NhbGhvc3QvU1BDX0I1QS9tb2R1bGUvUXVhbGl0eURhdGFfWFIuYXNweB8CBQ/lnYflgLzmnoHlt67lm75kZAIHD2QWAmYPZBYCAgEPDxYEHwUFM2h0dHA6Ly9sb2NhbGhvc3QvU1BDX0I1QS9tb2R1bGUvUXVhbGl0eURhdGFfWFMuYXNweB8CBQ/lnYflgLzmoIflh4blt65kZAIIDw8WAh8EaGRkAgIPZBYEAgMPDxYCHwIFEuacuuW6iueKtuaAgeWIhuaekGRkAgUPPCsAEQIADxYEHwNnHwECAmQBEBYAFgAWABYCZg9kFghmDw8WAh8EaGRkAgEPZBYCZg9kFgICAQ8PFgQfBQU4aHR0cDovL2xvY2FsaG9zdC9TUENfQjVBL21vZHVsZS9NYWNoaW5lU3RhdHVzX1F1ZXJ5LmFzcHgfAgUS5py65bqK54q25oCB5p+l6K+iZGQCAg9kFgJmD2QWAgIBDw8WBB8FBTtodHRwOi8vbG9jYWxob3N0L1NQQ19CNUEvbW9kdWxlL01pc01hY2hpbmVTdGF0dXNfUXVlcnkuYXNweB8CBRLmnLrluornirbmgIHnm5HmjqdkZAIDDw8WAh8EaGRkAgMPZBYEAgMPDxYCHwIFEuacuuW6iuaKpeitpuWIhuaekGRkAgUPPCsAEQIADxYEHwNnHwECAWQBEBYAFgAWABYCZg9kFgZmDw8WAh8EaGRkAgEPZBYCZg9kFgICAQ8PFgQfBQUzaHR0cDovL2xvY2FsaG9zdC9TUENfQjVBL21vZHVsZS9NaXNBbGFybV9RdWVyeS5hc3B4HwIFEuacuuW6iuaKpeitpuebkeaOp2RkAgIPDxYCHwRoZGQCBA9kFgQCAw8PFgIfAgUS5bel5Lu25Zyo57q/54q25oCBZGQCBQ88KwARAgAPFgQfA2cfAQICZAEQFgAWABYAFgJmD2QWCGYPDxYCHwRoZGQCAQ9kFgJmD2QWAgIBDw8WBB8FBT1odHRwOi8vbG9jYWxob3N0L1NQQ19CNUEvbW9kdWxlL01pc0VuZ2luZUFycml2ZUxlYXZlVGltZS5hc3B4HwIFEui/h+ermeS/oeaBr+ebkeaOp2RkAgIPZBYCZg9kFgICAQ8PFgQfBQU6aHR0cDovL2xvY2FsaG9zdC9TUENfQjVBL21vZHVsZS9FbmdpbmVBcnJpdmVMZWF2ZVRpbWUuYXNweB8CBRLov4fnq5nkv6Hmga/mn6Xor6JkZAIDDw8WAh8EaGRkAgUPZBYEAgMPDxYCHwIFDOezu+e7n+e7tOaKpGRkAgUPPCsAEQIADxYEHwNnHwECAWQBEBYAFgAWABYCZg9kFgZmDw8WAh8EaGRkAgEPZBYCZg9kFgICAQ8PFgQfBQU7aHR0cDovL2xvY2FsaG9zdC9TUENfQjVBL21vZHVsZS9RdWFsaXR5RGF0YV9EYXRhRXh0ZW50LmFzcHgfAgUS5rWL6YeP6IyD5Zu057u05oqkZGQCAg8PFgIfBGhkZAIPD2QWBgIFD2QWAmYPZBYMAgEPDxYCHwIFCTIwMTItMy0zMGRkAgMPEGRkFgECCGQCBQ8QZGQWAQI7ZAIJDxAPFgYeDURhdGFUZXh0RmllbGQFCeW3peS9jeWPtx4ORGF0YVZhbHVlRmllbGQFCeW3peS9jeWPtx8DZ2QQFQwGT1AxMDgwBk9QMjA0MAZPUDIxMzAGT1AyMTM1Bk9QMjE0MAZPUDIxNTAGT1AyMTU1Bk9QMjIyMAZPUDIyMjUGT1AzMDEwCE9QMzA5MC4xCE9QMzA5MC4yFQwGT1AxMDgwBk9QMjA0MAZPUDIxMzAGT1AyMTM1Bk9QMjE0MAZPUDIxNTAGT1AyMTU1Bk9QMjIyMAZPUDIyMjUGT1AzMDEwCE9QMzA5MC4xCE9QMzA5MC4yFCsDDGdnZ2dnZ2dnZ2dnZxYBZmQCDQ8QDxYGHwYFDOa1i+mHj+S9jee9rh8HBQzmtYvph4/kvY3nva4fA2dkEBUFETAx5beu6YCf5Zmo6J665qCTETAy5beu6YCf5Zmo6J665qCTETAz5beu6YCf5Zmo6J665qCTETA05beu6YCf5Zmo6J665qCTDOWQiOagvOagh+W/lxUFETAx5beu6YCf5Zmo6J665qCTETAy5beu6YCf5Zmo6J665qCTETAz5beu6YCf5Zmo6J665qCTETA05beu6YCf5Zmo6J665qCTDOWQiOagvOagh+W/lxQrAwVnZ2dnZxYBZmQCEQ8QDxYGHwYFDOa1i+mHj+mhueebrh8HBQzmtYvph4/pobnnm64fA2dkEBUCCeinkuW6puWAvAnnu4jmia3lgLwVAgnop5LluqblgLwJ57uI5omt5YC8FCsDAmdnFgFmZAIHD2QWAmYPZBYEAgEPEGRkFgECA2QCAw8QZGQWAQIDZAIjD2QWAmYPZBYCAgEPPCsAEQEBEBYAFgAWAGQYBwUwY3RsMDAkQ29udGVudFBsYWNlSG9sZGVyMSRHcmlkVmlld19NZWFzdXJlUmVzdWx0D2dkBSdjdGwwMCREYXRhTGlzdF9NZW51JGN0bDAxJEdyaWRWaWV3X01lbnUPPCsADAEIAgFkBSdjdGwwMCREYXRhTGlzdF9NZW51JGN0bDAyJEdyaWRWaWV3X01lbnUPPCsADAEIAgFkBSdjdGwwMCREYXRhTGlzdF9NZW51JGN0bDAzJEdyaWRWaWV3X01lbnUPPCsADAEIAgFkBSdjdGwwMCREYXRhTGlzdF9NZW51JGN0bDA1JEdyaWRWaWV3X01lbnUPPCsADAEIAgFkBSdjdGwwMCREYXRhTGlzdF9NZW51JGN0bDAwJEdyaWRWaWV3X01lbnUPPCsADAEIAgFkBSdjdGwwMCREYXRhTGlzdF9NZW51JGN0bDA0JEdyaWRWaWV3X01lbnUPPCsADAEIAgFkKo7dlJvsid8UctqPsMtKk5WYai/HtyAKwVLvV8eR3kE=\" />";
str = "<td align=\"center\" valign=\"middle\" colspan=\"" + table_Columns_Count + "\">" +
in_str + "</td>";
web.Response.Write(str);
web.Response.Write("<tr>");
////输出表字段
//for (int i = 0; i < table.Columns.Count; i++)
//{
// web.Response.Write("<td align=\"center\" valign=\"middle\">" + table.Columns[i].ColumnName + "</td>");
//}
//foreach (DataRow dataRow in table.Rows)
//{
// web.Response.Write("<tr>");
// for (int i = 0; i < table.Columns.Count; i++)
// {
// if (Convert.ToInt32(dataRow["合格标志"]) == 0)
// {
// web.Response.Write("<td style =\" background-color:Red\">" + dataRow[i] + "</td>");
// }
// else
// {
// web.Response.Write("<td>" + dataRow[i] + "</td>");
// }
// }
// web.Response.Write("</tr>");
//}
web.Response.Write("</table>");
web.Response.End();
}
//2012_04_17 chenghai
/// <summary>
/// 基本报表_图片
/// </summary>
/// <param name="table"></param>
public static void ExcelTable_QualityData_tupian(string path, string tupian_name)
{
int cloumn = 1;
int with = 800;
int height = 600;
string str;
System.Web.HttpContext web = System.Web.HttpContext.Current;
web.Response.Clear();
web.Response.Charset = "GB2312";
web.Response.Buffer = true;
web.Response.ContentEncoding = System.Text.Encoding.UTF8;
web.Response.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode("Sheet.xls", System.Text.Encoding.UTF8).ToString());
HttpContext.Current.Response.Write("<meta http-equiv=Content-Type content=\"text/html; charset=UTF-8\">");
web.Response.ContentType = "application/ms-excel";
//表头
web.Response.Write("<table border=1>");
web.Response.Write("<tr>");
web.Response.Write("<td align=\"center\" valign=\"middle\" colspan=\"" + cloumn + "\">" + tupian_name + "</td>");
web.Response.Write("</tr>");
web.Response.Write("<tr>");
str = "<td align=\"center\" valign=\"middle\" >" +
// "<img alt=\"\" src=\"" + "/Chart_excel/" + path + "\" width=\" " + with + " \" height= \" " + height + " \" />" + "</td>";
"<img alt=\"\" src=\"" + SPC.WebUI.PageBase.UrlBase + "/Chart_excel/" + path + "\" width=\" " + with + " \" height= \" " + height + " \" />" + "</td>";
web.Response.Write(str);
web.Response.Write("</tr>");
//输出表字段
web.Response.Write("</table>");
web.Response.End();
}
//2012_04_17 chenghai
/// <summary>
/// 基本报表_图片_数据
/// </summary>
/// <param name="table"></param>
public static void ExcelTable_QualityData_tupian_and_data(string path, DataTable table)
{
//导出excel 时 每个字段宽度 统一 设置为100
int excel_biaoge_width = 100;
//图片的高度
int height = 400;
//图片所占用的excel表的行数
int excel_tupian_gaodu_hangshu = 22;
string str;
if (table == null) return;
System.Web.HttpContext web = System.Web.HttpContext.Current;
web.Response.Clear();
web.Response.Charset = "GB2312";
web.Response.Buffer = true;
web.Response.ContentEncoding = System.Text.Encoding.UTF8;
web.Response.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode("Sheet.xls", System.Text.Encoding.UTF8).ToString());
HttpContext.Current.Response.Write("<meta http-equiv=Content-Type content=\"text/html; charset=UTF-8\">");
web.Response.ContentType = "application/ms-excel";
//表头
web.Response.Write("<table border=1>");
web.Response.Write("<tr>");
web.Response.Write("<td align=\"center\" valign=\"middle\" colspan=\"" + table.Columns.Count + "\">" + table.TableName + "</td>");
web.Response.Write("</tr>");
web.Response.Write("<tr>");
//string webPath = SPC.WebUI.PageBase.UrlBase;
//webPath = webPath.Remove(webPath.Length - 1, 1);
str = "<td align=\"center\" valign=\"middle\" rowspan=\"" + excel_tupian_gaodu_hangshu + "\" colspan=\"" + table.Columns.Count + "\">" +
"<img alt=\"\" src=\"" + SPC.WebUI.PageBase.UrlBase + "/Chart_excel/" + path + "\" width=\" " + excel_biaoge_width * table.Columns.Count + " \" height= \" " + height + " \" />" + "</td>";
web.Response.Write(str);
web.Response.Write("</tr>");
for (int i = 0; i < excel_tupian_gaodu_hangshu; i++)
{
web.Response.Write("<tr>");
}
//输出表字段
for (int i = 0; i < table.Columns.Count; i++)
{
web.Response.Write("<td width=\"" + excel_biaoge_width + "\" align=\"center\" valign=\"middle\">" + table.Columns[i].ColumnName + "</td>");
}
foreach (DataRow dataRow in table.Rows)
{
web.Response.Write("<tr>");
for (int i = 0; i < table.Columns.Count; i++)
{
web.Response.Write("<td>" + dataRow[i] + "</td>");
}
web.Response.Write("</tr>");
}
web.Response.Write("</table>");
web.Response.End();
}
/// <summary>
/// 基本报表
/// </summary>
/// <param name="table"></param>
public static void ExcelTable_QualityData_Query2(DataTable table)
{
System.Web.HttpContext web = System.Web.HttpContext.Current;
string str;
if (table == null) return;
web.Response.Clear();
web.Response.Charset = "GB2312";
web.Response.Buffer = true;
web.Response.ContentEncoding = System.Text.Encoding.UTF8;
web.Response.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode("Sheet.xls", System.Text.Encoding.UTF8).ToString());
HttpContext.Current.Response.Write("<meta http-equiv=Content-Type content=\"text/html; charset=UTF-8\">");
web.Response.ContentType = "application/ms-excel";
string tableName;
tableName = table.TableName;
///////////////////////////////////////////
//图标
web.Response.Write("<table>");
web.Response.Write("<tr>");
str = "<td>" +
//"<img alt=\"\" src=\"" + SPC.WebUI.PageBase.UrlBase + "/images/report_icon.jpg\" />" + "</td>";
"<img alt=\"\" src=\"" + "/images/report_icon.jpg\" />" + "</td>";
web.Response.Write(str);
web.Response.Write("</tr>");
///////////////////////////////////////////
//表头
web.Response.Write("<tr>");
web.Response.Write("<td align=\"center\" valign=\"middle\" colspan=\"" + table.Columns.Count + "\">" + table.TableName + "</td>");
web.Response.Write("</tr>");
web.Response.Write("</table>");
web.Response.Write("<table border=1>");
//输出表字段
for (int i = 0; i < table.Columns.Count; i++)
{
web.Response.Write("<td align=\"center\" valign=\"middle\">" + GetColumnName_Ver(table.Columns[i].ColumnName) + "</td>");
}
string columnName;
foreach (DataRow dataRow in table.Rows)
{
web.Response.Write("<tr>");
for (int i = 0; i < table.Columns.Count; i++)
{
columnName = table.Columns[i].ColumnName;
switch (tableName)
{
case "不合格质量数据报表":
switch (columnName)
{
case "数据":
web.Response.Write("<td style =\" background-color:Red\">" + dataRow[i] + "</td>");
break;
default:
web.Response.Write("<td>" + dataRow[i] + "</td>");
break;
}
break;
case "工序能力":
switch (columnName)
{
case "能力状况":
switch (Convert.ToInt32(dataRow["能力状况"]))
{
case 1:
web.Response.Write("<td style =\" background-color:Green\">" + "" + "</td>");
break;
case 2:
web.Response.Write("<td style =\" background-color:Yellow\">" + "" + "</td>");
break;
case 3:
web.Response.Write("<td style =\" background-color:Red\">" + "" + "</td>");
break;
}
break;
default:
web.Response.Write("<td>" + dataRow[i] + "</td>");
break;
}
break;
default:
switch (columnName)
{
case "工序状况":
//工序状况=0 不合格NOK=1 合格OK
if (Convert.ToInt32(dataRow["工序状况"]) == 0)
{
web.Response.Write("<td style =\" background-color:Red\">" + "NOK" + "</td>");
}
else
{
web.Response.Write("<td>" + "OK" + "</td>");
}
break;
case "总合格标志":
//工序状况=0 合格OK=1 合格NOK
if (Convert.ToInt32(dataRow["总合格标志"]) == 0)
{
web.Response.Write("<td>" + "OK" + "</td>");
}
else
{
web.Response.Write("<td style =\" background-color:Red\">" + "NOK" + "</td>");
}
break;
default:
web.Response.Write("<td>" + dataRow[i] + "</td>");
break;
}
break;
}
}
web.Response.Write("</tr>");
}
web.Response.Write("</table>");
web.Response.End();
}
/// <summary>
/// 字段名称各个字符中间增加回车,以保证文本竖着书写。
/// </summary>
/// <param name="columnName"></param>
/// <returns></returns>
private static string GetColumnName_Ver(string columnName)
{
string columnName_tr;
columnName_tr = "";
for (int i = 0; i < columnName.Length; i++)
{
columnName_tr = columnName_tr + columnName[i] + "<br>";
}
return columnName_tr;
}
/// <summary>
/// 基本报表
/// </summary>
/// <param name="table"></param>
public static void ExcelTable_QualityData_Query(DataTable table)
{
System.Web.HttpContext web = System.Web.HttpContext.Current;
if (table == null) return;
web.Response.Clear();
web.Response.Charset = "GB2312";
web.Response.Buffer = true;
web.Response.ContentEncoding = System.Text.Encoding.UTF8;
web.Response.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode("Sheet.xls", System.Text.Encoding.UTF8).ToString());
HttpContext.Current.Response.Write("<meta http-equiv=Content-Type content=\"text/html; charset=UTF-8\">");
web.Response.ContentType = "application/ms-excel";
//表头
web.Response.Write("<table border=1>");
web.Response.Write("<tr>");
web.Response.Write("<td align=\"center\" valign=\"middle\" colspan=\"" + table.Columns.Count + "\">" + table.TableName + "</td>");
web.Response.Write("<tr>");
//输出表字段
for (int i = 0; i < table.Columns.Count; i++)
{
web.Response.Write("<td align=\"center\" valign=\"middle\">" + table.Columns[i].ColumnName + "</td>");
}
foreach (DataRow dataRow in table.Rows)
{
web.Response.Write("<tr>");
for (int i = 0; i < table.Columns.Count; i++)
{
//if (Convert.ToInt32(dataRow["合格标志"]) == 0) --20140919 wt
if (Convert.ToString(dataRow["合格标志"]) == "不合格")
{
web.Response.Write("<td style =\" background-color:Red ;vnd.ms-excel.numberformat:@\">" + dataRow[i] + "</td>");
}
else
{
//去除科学计数法
web.Response.Write("<td style='vnd.ms-excel.numberformat:@'>" + dataRow[i] + "</td>");
}
}
web.Response.Write("</tr>");
}
web.Response.Write("</table>");
web.Response.End();
}
/// <summary>
/// 2012-07-19-chenghai基本报表_称重 kg
/// </summary>
/// <param name="table"></param>
public static void ExcelTable_QualityData_Query_kg(DataTable table)
{
System.Web.HttpContext web = System.Web.HttpContext.Current;
if (table == null) return;
web.Response.Clear();
web.Response.Charset = "GB2312";
web.Response.Buffer = true;
web.Response.ContentEncoding = System.Text.Encoding.UTF8;
web.Response.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode("Sheet.xls", System.Text.Encoding.UTF8).ToString());
HttpContext.Current.Response.Write("<meta http-equiv=Content-Type content=\"text/html; charset=UTF-8\">");
web.Response.ContentType = "application/ms-excel";
//表头
web.Response.Write("<table border=1>");
web.Response.Write("<tr>");
web.Response.Write("<td align=\"center\" valign=\"middle\" colspan=\"" + table.Columns.Count + "\">" + table.TableName + "</td>");
web.Response.Write("<tr>");
//输出表字段
for (int i = 0; i < table.Columns.Count; i++)
{
if (i == 2 || i == 3 || i == 4 || i == 6 || i == 7 )
{
web.Response.Write("<td align=\"center\" valign=\"middle\">" + table.Columns[i].ColumnName + "(kg)" + "</td>");
}
else
{
if (i == 5)
{
web.Response.Write("<td align=\"center\" valign=\"middle\">" + table.Columns[i].ColumnName + "(L)" + "</td>");
}
else
{
web.Response.Write("<td align=\"center\" valign=\"middle\">" + table.Columns[i].ColumnName + "</td>");
}
}
}
foreach (DataRow dataRow in table.Rows)
{
web.Response.Write("<tr>");
for (int i = 0; i < table.Columns.Count; i++)
{
//if (Convert.ToInt32(dataRow["合格标志"]) == 0) --20140919 wt
if (Convert.ToString(dataRow["合格标志"]) == "不合格")
{
web.Response.Write("<td style =\" background-color:Red\">" + dataRow[i] + "</td>");
}
else
{
web.Response.Write("<td>" + dataRow[i] + "</td>");
}
}
web.Response.Write("</tr>");
}
web.Response.Write("</table>");
web.Response.End();
}
/// <summary>
/// 基本报表
/// </summary>
/// <param name="table"></param>
public static void ExcelTable(DataTable table)
{
System.Web.HttpContext web = System.Web.HttpContext.Current;
if (table == null) return;
web.Response.Clear();
web.Response.Charset = "GB2312";
web.Response.Buffer = true;
web.Response.ContentEncoding = System.Text.Encoding.UTF8;
web.Response.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode("Sheet.xls", System.Text.Encoding.UTF8).ToString());
HttpContext.Current.Response.Write("<meta http-equiv=Content-Type content=\"text/html; charset=UTF-8\">");
web.Response.ContentType = "application/ms-excel";
//表头
web.Response.Write("<table border=1>");
web.Response.Write("<tr>");
web.Response.Write("<td align=\"center\" valign=\"middle\" colspan=\"" + table.Columns.Count + "\">" + table.TableName + "</td>");
web.Response.Write("<tr>");
//输出表字段
for (int i = 0; i < table.Columns.Count; i++)
{
web.Response.Write("<td align=\"center\" valign=\"middle\">" + table.Columns[i].ColumnName + "</td>");
}
foreach (DataRow dataRow in table.Rows)
{
web.Response.Write("<tr>");
for (int i = 0; i < table.Columns.Count; i++)
{
web.Response.Write("<td>" + dataRow[i] + "</td>");
}
web.Response.Write("</tr>");
}
web.Response.Write("</table>");
web.Response.End();
}
public static void ExcelTable_RecipeProof(int cutnum, int cutnum1, DataTable dt)
{
System.Web.HttpContext web = System.Web.HttpContext.Current;
web.Response.ClearContent();
web.Response.Charset = "GB2312";
web.Response.Buffer = true;
web.Response.ContentEncoding = System.Text.Encoding.UTF8;
web.Response.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode("Sheet.xls", System.Text.Encoding.UTF8).ToString());
HttpContext.Current.Response.Write("<meta http-equiv=Content-Type content=\"text/html; charset=UTF-8\">");
web.Response.ContentType = "application/ms-excel";
//SheetCount代表生成的 Sheet 数目。
for (int i = 0; i < 2; i++)
{
//计算该 Sheet 中的数据起始行和结束行。
int start = cutnum * i;
int end = cutnum;
if (i == 1) end = cutnum1 + cutnum;
web.Response.Write(" < 配方校验:'Sheet" + (i + 1) + "'>");
web.Response.Write("<table border=1>");
web.Response.Write("<tr>");
web.Response.Write("<td align=\"center\" valign=\"middle\" colspan=\"" + dt.Columns.Count + "\">" + dt.TableName + "</td>");
web.Response.Write("<tr>");
//输出表字段
for (int j = 0; j < dt.Columns.Count; j++)
{
web.Response.Write("<td align=\"center\" valign=\"middle\">" + dt.Columns[j].ColumnName + "</td>");
}
for (int j = start; j < end; j++)
{
web.Response.Write("<tr>");
for (int r = 0; r < dt.Columns.Count; r++)
{
web.Response.Write("<td>" + dt.Rows[j][r] + "</td>");
}
web.Response.Write("</tr>");
}
web.Response.Write("</table>");
web.Response.Write("</Worksheet>");
web.Response.Flush();
}
//web.Response.Write("</Workbook>");
web.Response.End();
}
}

115
App_code/CommonFunction.cs Normal file
View File

@@ -0,0 +1,115 @@
using System;
using System.Data;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI.WebControls;
/// <summary>
///CommonFunction 的摘要说明
/// </summary>
public partial class CommonFunction
{
public CommonFunction()
{
//
//TODO: 在此处添加构造函数逻辑
//
}
/// <summary>
/// 保持GridView状态
/// </summary>
/// <param name="GridView1"></param>
public static void SetGridViewSelection(GridView GridView1)
{
if (GridView1.Rows.Count > 0)
{
if (GridView1.SelectedIndex != -1)
{
if (GridView1.SelectedIndex >= GridView1.Rows.Count)
GridView1.SelectedIndex = GridView1.Rows.Count - 1;
}
else
GridView1.SelectedIndex = 0;
//去掉gridview的空格
for (int i = 0; i < GridView1.Rows.Count; i++)
{
for (int j = 1; j < GridView1.Columns.Count-1; j++)
GridView1.Rows[i].Cells[j].Text = GridView1.Rows[i].Cells[j].Text.Trim().Replace("&nbsp;", "");
}
}
else
{
GridView1.SelectedIndex = -1;
}
}
public static void OutPutDataAndPic(string path, DataTable table)
{
//导出excel 时 每个字段宽度 统一 设置为100
int excel_biaoge_width = 170;
//图片的高度
int height = 400;
int with = 800;
//图片所占用的excel表的行数
int excel_tupian_gaodu_hangshu = 22;
string str;
if (table == null) return;
System.Web.HttpContext web = System.Web.HttpContext.Current;
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.Charset = "GB2312";
HttpContext.Current.Response.Buffer = true;
HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.UTF8;
HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode("Sheet.xls", System.Text.Encoding.UTF8).ToString());
HttpContext.Current.Response.Write("<meta http-equiv=Content-Type content=\"text/html; charset=UTF-8\">");
HttpContext.Current.Response.ContentType = "application/ms-excel";
//表头
HttpContext.Current.Response.Write("<table border=1>");
HttpContext.Current.Response.Write("<tr>");
HttpContext.Current.Response.Write("<td align=\"center\" valign=\"middle\" colspan=\"" + table.Columns.Count + "\"></td>");
HttpContext.Current.Response.Write("</tr>");
HttpContext.Current.Response.Write("<tr>");
//string webPath = SPC.WebUI.PageBase.UrlBase;
//webPath = webPath.Remove(webPath.Length - 1, 1);
//str = "<td align=\"center\" valign=\"middle\" rowspan=\"" + excel_tupian_gaodu_hangshu + "\" colspan=\"" + table.Columns.Count + "\">" +
//"<img alt=\"\" src=\"" + path + "\" width=\" " + excel_biaoge_width * table.Columns.Count + " \" height= \" " + height + " \" />" + "</td>";
str = "<td align=\"center\" valign=\"middle\" >" +
// "<img alt=\"\" src=\"" + "/Chart_excel/" + path + "\" width=\" " + with + " \" height= \" " + height + " \" />" + "</td>";
"<img alt=\"\" src=\"" + SPC.WebUI.PageBase.UrlBase + "/Chart_excel/" + path + "\" width=\" " + with + " \" height= \" " + height + " \" />" + "</td>";
HttpContext.Current.Response.Write(str);
HttpContext.Current.Response.Write("</tr>");
for (int i = 0; i < excel_tupian_gaodu_hangshu; i++)
{
HttpContext.Current.Response.Write("<tr>");
}
//输出表字段
for (int i = 0; i < table.Columns.Count; i++)
{
HttpContext.Current.Response.Write("<td width=\"" + excel_biaoge_width + "\" align=\"center\" valign=\"middle\">" + table.Columns[i].ColumnName + "</td>");
}
foreach (DataRow dataRow in table.Rows)
{
HttpContext.Current.Response.Write("<tr>");
for (int i = 0; i < table.Columns.Count; i++)
{
HttpContext.Current.Response.Write("<td>" + dataRow[i] + "</td>");
}
HttpContext.Current.Response.Write("</tr>");
}
HttpContext.Current.Response.Write("</table>");
HttpContext.Current.Response.End();
}
}

848
App_code/DirectExcel.cs Normal file
View File

@@ -0,0 +1,848 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
//using ADODB;
using System.Data.SqlClient;
using System.Data;
using System.Drawing;
using MES_SPC;
//using Microsoft.Office.Core;
public class DirectExcel
{//直接操作Excel
public DirectExcel()
{
//逻辑区域
}
/// <summary>
/// 质量数据查询
/// 引用页质量数据查询页面QualityData_Query.aspx
/// </summary>
/// <param name="sql"></param>
/// <param name="fileName"></param>
/// <param name="Count"></param>
public static void ExcelTable_QualityData_Query_Direct(ref string sql, ref string fileName, ref int Count,ref int ColCount,ref object[,] ColsArray)
{
//新建一个excel
//string connectionString = ApplicationConfiguration.ERP_ConnectionString;
//Microsoft.Office.Interop.Excel.Application excel = new Microsoft.Office.Interop.Excel.Application();
//excel.Application.Workbooks.Add(true);
//Microsoft.Office.Interop.Excel.Workbook wb = (Microsoft.Office.Interop.Excel.Workbook)excel.Application.Workbooks[1];
//excel.Visible = false;
//Microsoft.Office.Interop.Excel.Worksheet ws = new Microsoft.Office.Interop.Excel.Worksheet();
//ws = (Microsoft.Office.Interop.Excel.Worksheet)excel.ActiveSheet;
//ws.Name = "Sheet1";//新建的Table名称
//string LastCol = GetLastCellName(ColCount);
////设置头
//Microsoft.Office.Interop.Excel.Range rangeHeader =ws.get_Range("A1", LastCol+"1");
//rangeHeader.Merge(0);
//ws.Cells[1, 1] = "合格质量数据";
////rangeHeader.Font.Name = "黑体";
//rangeHeader.HorizontalAlignment = Microsoft.Office.Interop.Excel.XlHAlign.xlHAlignCenter;
////rangeHeader.Borders.LineStyle = 1; //设置单元格边框的粗细
////rangeHeader.EntireColumn.AutoFit(); //自动调整列宽
////序号,订单号,发动机号,工位号,测量位置, 测量项目 ,测量值,测量单位,理论值 ,上限值,下限值,合格标志,生产日期
////第二部设置列头
//Microsoft.Office.Interop.Excel.Range rangeCol =ws.get_Range("A2", LastCol+"2");
////Excel.Range rangeCol = (Excel.Range)ws.get_Range(ws.Cells[2, 1], ws.Cells[2, ColCount]);
//object[,] arycol = (object[,])(rangeCol.Value2);
////arycol = new object[,] { { "序号", "订单号", "发动机号", "工位号", "测量位置", "测量项目", "测量值", "测量单位", "理论值", "上限值", "下限值", "合格标志", "生产日期" } };
//arycol = ColsArray;
////for (int j = 1; j < SourceTable.Columns.Count + 1; j++)
////{
//// arycol[1, j] = SourceTable.Columns[j - 1].ColumnName.ToString();
////}
//rangeCol.Value2 = arycol;
//rangeCol.HorizontalAlignment = Microsoft.Office.Interop.Excel.XlHAlign.xlHAlignCenter;
//rangeCol.Borders.LineStyle = 1; //设置单元格边框的粗细
////rangeCol.EntireColumn.AutoFit(); //自动调整列宽
//try
//{
// ADODB.Connection conn = new ADODB.Connection();
// conn.CommandTimeout = 120;
// conn.Open("driver={SQL Server};" + connectionString, "", "", 0);
// ADODB.Recordset rs = new ADODB.Recordset();
// rs.Open(sql, conn, ADODB.CursorTypeEnum.adOpenStatic, ADODB.LockTypeEnum.adLockReadOnly, 0);
// Microsoft.Office.Interop.Excel.Range range = ws.get_Range("A3", Missing.Value);
// //range.CopyFromRecordset(rs, SourceTable.Rows.Count + 3, SourceTable.Columns.Count);//rs, 65535, 65535
// range.CopyFromRecordset(rs, 1000000, 30);//rs, 65535, 65535
// //设置序号
// Microsoft.Office.Interop.Excel.Range Drange = ws.get_Range("A3","A"+(Count+2).ToString());
// Microsoft.Office.Interop.Excel.Range DrangeFirst = ws.get_Range("A3");
// DrangeFirst.Value2 = 1;
// Drange.DataSeries(Missing.Value, Microsoft.Office.Interop.Excel.XlDataSeriesType.xlDataSeriesLinear, Microsoft.Office.Interop.Excel.XlDataSeriesDate.xlDay, 1, Count, false);
// //设置日期格式
// //int index = SourceTable.Columns["生产日期"].Ordinal + 1;
// Microsoft.Office.Interop.Excel.Range rangeDate = ws.get_Range(LastCol + "3", LastCol + (Count + 2).ToString());
// rangeDate.NumberFormatLocal = @"yyyy-mm-dd hh:mm";//日期型格式
// Microsoft.Office.Interop.Excel.Range RangeOfAll = ws.get_Range("A3", LastCol + (Count + 2).ToString());
// RangeOfAll.Borders.LineStyle = 1; //设置单元格边框的粗细
// RangeOfAll.HorizontalAlignment = Microsoft.Office.Interop.Excel.XlHAlign.xlHAlignCenter;
// RangeOfAll.EntireColumn.AutoFit(); //自动调整列宽
// //设置不合格的就为红色
// Microsoft.Office.Interop.Excel.FormatCondition cond =
// (Microsoft.Office.Interop.Excel.FormatCondition)RangeOfAll.FormatConditions.Add(Microsoft.Office.Interop.Excel.XlFormatConditionType.xlExpression,
// Missing.Value, "=$L1=0", Missing.Value);
// cond.Interior.PatternColorIndex = Microsoft.Office.Interop.Excel.Constants.xlAutomatic;
// cond.Interior.TintAndShade = 0;
// cond.Interior.Color = ColorTranslator.ToWin32(Color.Red);
// cond.StopIfTrue = false;
//}
//catch (Exception ex)
//{
// string str = ex.Message;
//}
//finally
//{
// wb.Saved = true;
// wb.SaveCopyAs(fileName);//保存
// //excel.SaveWorkspace(fileName);
// //app.Quit();//关闭进程
// wb.Close();
// excel.Quit();
// GC.Collect();
//}
}
/// <summary>
/// 工件总成质量数据报表
/// 引用页QualityData_Query_2.aspx(质量数据导出excel)
/// </summary>
/// <param name="sql"></param>
/// <param name="fileName"></param>
/// <param name="Count"></param>
public static void ExcelTable_QualityData_Query_xml_Direct(ref string sql, ref string fileName, ref int Count, ref int ColCount, ref object[,] ColsArray)
{
//新建一个excel
string connectionString = ApplicationConfiguration.ERP_ConnectionString;
//Microsoft.Office.Interop.Excel.Application excel = new Microsoft.Office.Interop.Excel.Application();
//excel.Application.Workbooks.Add(true);
//Microsoft.Office.Interop.Excel.Workbook wb = (Microsoft.Office.Interop.Excel.Workbook)excel.Application.Workbooks[1];
//excel.Visible = false;
//Microsoft.Office.Interop.Excel.Worksheet ws = new Microsoft.Office.Interop.Excel.Worksheet();
//ws = (Microsoft.Office.Interop.Excel.Worksheet)excel.ActiveSheet;
//ws.Name = "Sheet1";//新建的Table名称
//string LastCol = GetLastCellName(ColCount);
////设置头
//Microsoft.Office.Interop.Excel.Range rangeHeader = ws.get_Range("A1", LastCol+"1");
//rangeHeader.Merge(0);
//ws.Cells[1, 1] = "工件总成质量数据报表";
////rangeHeader.Font.Name = "黑体";
//rangeHeader.HorizontalAlignment = Microsoft.Office.Interop.Excel.XlHAlign.xlHAlignCenter;
////rangeHeader.Borders.LineStyle = 1; //设置单元格边框的粗细
////rangeHeader.EntireColumn.AutoFit(); //自动调整列宽
////序号,订单号总成型号总成流水号工序号工序名称托盘编号操作者测量位置数据1类型数据1理论值上限数据1数据1理论值下限数据1单位数据2类型数据2理论值上限数据2数据2理论值下限数据2单位工序状况总合格标志生产日期
////Orientation = 90以90度进行旋转
////第二部设置列头
//Microsoft.Office.Interop.Excel.Range rangeCol = ws.get_Range("A2", LastCol+"2");
////Excel.Range rangeCol = (Excel.Range)ws.get_Range(ws.Cells[2, 1], ws.Cells[2, ColCount]);
//object[,] arycol = (object[,])(rangeCol.Value2);
////arycol = new object[,]
////{{ GetColumnName_Ver("序号"),
//// GetColumnName_Ver("订单号"),
//// GetColumnName_Ver("总成型号"),
//// GetColumnName_Ver("总成流水号"),
//// GetColumnName_Ver("工序号"),
//// GetColumnName_Ver("工序名称"),
//// GetColumnName_Ver("托盘编号"),
//// GetColumnName_Ver("操作者"),
//// GetColumnName_Ver("测量位置"),
//// GetColumnName_Ver("数据1类型"),
//// GetColumnName_Ver("数据1理论值上限 "),
//// GetColumnName_Ver("数据1"),
//// GetColumnName_Ver("数据1理论值下限 "),
//// GetColumnName_Ver("数据1单位"),
//// GetColumnName_Ver("数据2类型"),
//// GetColumnName_Ver("数据2理论值上限 "),
//// GetColumnName_Ver("数据2"),
//// GetColumnName_Ver("数据2理论值下限 "),
//// GetColumnName_Ver("数据2单位"),
//// GetColumnName_Ver("工序状况"),
//// GetColumnName_Ver("总合格标志"),
//// GetColumnName_Ver("生产日期")
////} };
//arycol = ColsArray;
//rangeCol.Value2 = arycol;
//rangeCol.HorizontalAlignment = Microsoft.Office.Interop.Excel.XlHAlign.xlHAlignCenter;
//rangeCol.VerticalAlignment = Microsoft.Office.Interop.Excel.Constants.xlTop;
//rangeCol.Borders.LineStyle = 1; //设置单元格边框的粗细
////rangeCol.EntireColumn.AutoFit(); //自动调整列宽
////rangeCol.Orientation = 90;
//try
//{
// ADODB.Connection conn = new ADODB.Connection();
// conn.CommandTimeout = 120;
// conn.Open("driver={SQL Server};" + connectionString, "", "", 0);
// ADODB.Recordset rs = new ADODB.Recordset();
// rs.Open(sql, conn, ADODB.CursorTypeEnum.adOpenStatic, ADODB.LockTypeEnum.adLockReadOnly, 0);
// Microsoft.Office.Interop.Excel.Range range = ws.get_Range("A3", Missing.Value);
// //range.CopyFromRecordset(rs, SourceTable.Rows.Count + 3, SourceTable.Columns.Count);//rs, 65535, 65535
// range.CopyFromRecordset(rs, 1000000, 30);//rs, 65535, 65535
// //设置序号
// Microsoft.Office.Interop.Excel.Range Drange = ws.get_Range("A3", "A" + (Count + 2).ToString());
// Microsoft.Office.Interop.Excel.Range DrangeFirst = ws.get_Range("A3");
// DrangeFirst.Value2 = 1;
// Drange.DataSeries(Missing.Value, Microsoft.Office.Interop.Excel.XlDataSeriesType.xlDataSeriesLinear, Microsoft.Office.Interop.Excel.XlDataSeriesDate.xlDay, 1, Count, false);
// //设置日期格式
// //int index = SourceTable.Columns["生产日期"].Ordinal + 1;
// Microsoft.Office.Interop.Excel.Range rangeDate = ws.get_Range(LastCol+"3", LastCol + (Count + 2).ToString());
// rangeDate.NumberFormatLocal = @"yyyy-mm-dd hh:mm";//日期型格式
// Microsoft.Office.Interop.Excel.Range RangeOfAll = ws.get_Range("A3", LastCol + (Count + 2).ToString());
// RangeOfAll.Borders.LineStyle = 1; //设置单元格边框的粗细
// RangeOfAll.HorizontalAlignment = Microsoft.Office.Interop.Excel.XlHAlign.xlHAlignCenter;
// RangeOfAll.EntireColumn.AutoFit(); //自动调整列宽
// //设置工序状况不合格的就为红色
// Microsoft.Office.Interop.Excel.Range RangeOfgongxu = ws.get_Range("T3", "T" + (Count + 2).ToString());
// Microsoft.Office.Interop.Excel.FormatCondition cond =
// (Microsoft.Office.Interop.Excel.FormatCondition)RangeOfgongxu.FormatConditions.Add(Microsoft.Office.Interop.Excel.XlFormatConditionType.xlExpression,
// Missing.Value, @"=$T1=""NOK""", Missing.Value);
// cond.Interior.PatternColorIndex = Microsoft.Office.Interop.Excel.Constants.xlAutomatic;
// cond.Interior.TintAndShade = 0;
// cond.Interior.Color = ColorTranslator.ToWin32(Color.Red);
// cond.StopIfTrue = false;
// //设置工序状况不合格的就为红色
// Microsoft.Office.Interop.Excel.Range RangeOfhege = ws.get_Range("U3", "U" + (Count + 2).ToString());
// Microsoft.Office.Interop.Excel.FormatCondition cond2 =
// (Microsoft.Office.Interop.Excel.FormatCondition)RangeOfhege.FormatConditions.Add(Microsoft.Office.Interop.Excel.XlFormatConditionType.xlExpression,
// Missing.Value, @"=$U1=""NOK""", Missing.Value);
// cond2.Interior.PatternColorIndex = Microsoft.Office.Interop.Excel.Constants.xlAutomatic;
// cond2.Interior.TintAndShade = 0;
// cond2.Interior.Color = ColorTranslator.ToWin32(Color.Red);
// cond2.StopIfTrue = false;
//}
//catch (Exception ex)
//{
// string str = ex.Message;
//}
//finally
//{
// wb.Saved = true;
// wb.SaveCopyAs(fileName);//保存
// //excel.SaveWorkspace(fileName);
// //app.Quit();//关闭进程
// wb.Close();
// excel.Quit();
// GC.Collect();
//}
}
/// <summary>
/// 不合格质量数据报表
/// </summary>
/// <param name="sql"></param>
/// <param name="fileName"></param>
/// <param name="Count"></param>
public static void ExcelTable_QualityData_Query2(ref string sql, ref string fileName, ref int Count, ref int ColCount, ref object[,] ColsArray)
{
//新建一个excel
string connectionString = ApplicationConfiguration.ERP_ConnectionString;
//Microsoft.Office.Interop.Excel.Application excel = new Microsoft.Office.Interop.Excel.Application();
//excel.Application.Workbooks.Add(true);
//Microsoft.Office.Interop.Excel.Workbook wb = (Microsoft.Office.Interop.Excel.Workbook)excel.Application.Workbooks[1];
//excel.Visible = false;
//Microsoft.Office.Interop.Excel.Worksheet ws = new Microsoft.Office.Interop.Excel.Worksheet();
//ws = (Microsoft.Office.Interop.Excel.Worksheet)excel.ActiveSheet;
//ws.Name = "Sheet1";//新建的Table名称
//string LastCol = GetLastCellName(ColCount);
////插入图片
//float PicLeft,PicTop;
//string imgPath = System.Web.HttpContext.Current.Server.MapPath("~/images/report_icon.jpg");
////转换成字节,再由字节转换成图片
////byte[] bytesArr = PicToByteArr(imgPath);
////System.Drawing.Image bmp = ReturnPhoto(bytesArr);//图片数据
////string imgPath=System.Web.HttpContext.Current.Application.
//Microsoft.Office.Interop.Excel.Range rangePic = ws.get_Range("A1", LastCol+"1");
//rangePic.Merge(0);
//PicLeft = Convert.ToSingle(rangePic.Left)+2;
//PicTop = Convert.ToSingle(rangePic.Top)+ 1;
//ws.Shapes.AddPicture(imgPath,Microsoft.Office.Core.MsoTriState.msoFalse,
//Microsoft.Office.Core.MsoTriState.msoTrue,
//PicLeft,PicTop,(float)305,(float)12);
////设置头
//Microsoft.Office.Interop.Excel.Range rangeHeader = ws.get_Range("A2", LastCol+"2");
//rangeHeader.Merge(0);
//ws.Cells[2, 1] = "不合格质量数据报表";
////rangeHeader.Font.Name = "黑体";
//rangeHeader.HorizontalAlignment = Microsoft.Office.Interop.Excel.XlHAlign.xlHAlignCenter;
////rangeHeader.Borders.LineStyle = 1; //设置单元格边框的粗细
////rangeHeader.EntireColumn.AutoFit(); //自动调整列宽
////序号,订单号总成型号总成流水号工序号工序名称托盘编号操作者测量位置数据1类型数据1理论值上限数据1数据1理论值下限数据1单位数据2类型数据2理论值上限数据2数据2理论值下限数据2单位工序状况总合格标志生产日期
////Orientation = 90以90度进行旋转
////第二部设置列头
//Microsoft.Office.Interop.Excel.Range rangeCol = ws.get_Range("A3", LastCol+"3");
////Excel.Range rangeCol = (Excel.Range)ws.get_Range(ws.Cells[2, 1], ws.Cells[2, ColCount]);
//object[,] arycol = (object[,])(rangeCol.Value2);
////arycol = new object[,]
////{{ GetColumnName_Ver("序号"),
//// GetColumnName_Ver("订单号"),
//// GetColumnName_Ver("总成型号"),
//// GetColumnName_Ver("总成流水号"),
//// GetColumnName_Ver("工序号"),
//// GetColumnName_Ver("工序名称"),
//// GetColumnName_Ver("测量位置"),
//// GetColumnName_Ver("数据类型"),
//// GetColumnName_Ver("数据理论值上限"),
//// GetColumnName_Ver("数据"),
//// GetColumnName_Ver("数据理论值下限 "),
//// GetColumnName_Ver("备注"),
////} };
//arycol = ColsArray;
//rangeCol.Value2 = arycol;
//rangeCol.HorizontalAlignment = Microsoft.Office.Interop.Excel.XlHAlign.xlHAlignCenter;
//rangeCol.VerticalAlignment = Microsoft.Office.Interop.Excel.Constants.xlTop;
//rangeCol.Borders.LineStyle = 1; //设置单元格边框的粗细
////rangeCol.EntireColumn.AutoFit(); //自动调整列宽
////rangeCol.Orientation = 90;
//try
//{
// ADODB.Connection conn = new ADODB.Connection();
// conn.Open("driver={SQL Server};" + connectionString, "", "", 0);
// ADODB.Recordset rs = new ADODB.Recordset();
// rs.Open(sql, conn, ADODB.CursorTypeEnum.adOpenStatic, ADODB.LockTypeEnum.adLockReadOnly, 0);
// Microsoft.Office.Interop.Excel.Range range = ws.get_Range("A4", Missing.Value);
// //range.CopyFromRecordset(rs, SourceTable.Rows.Count + 3, SourceTable.Columns.Count);//rs, 65535, 65535
// range.CopyFromRecordset(rs, 1000000, 30);//rs, 65535, 65535
// //设置序号
// Microsoft.Office.Interop.Excel.Range Drange = ws.get_Range("A4", "A" + (Count + 3).ToString());
// Microsoft.Office.Interop.Excel.Range DrangeFirst = ws.get_Range("A4");
// DrangeFirst.Value2 = 1;
// Drange.DataSeries(Missing.Value, Microsoft.Office.Interop.Excel.XlDataSeriesType.xlDataSeriesLinear, Microsoft.Office.Interop.Excel.XlDataSeriesDate.xlDay, 1, Count, false);
// Microsoft.Office.Interop.Excel.Range RangeOfAll = ws.get_Range("A4", LastCol + (Count + 3).ToString());
// RangeOfAll.Borders.LineStyle = 1; //设置单元格边框的粗细
// RangeOfAll.HorizontalAlignment = Microsoft.Office.Interop.Excel.XlHAlign.xlHAlignCenter;
// RangeOfAll.EntireColumn.AutoFit(); //自动调整列宽
// //设置数据列为红色
// Microsoft.Office.Interop.Excel.Range RangeOfshuju = ws.get_Range("J4", "J" + (Count + 3).ToString());
// RangeOfshuju.Cells.Interior.Color = Color.Red;
//}
//catch (Exception ex)
//{
// string str = ex.Message;
//}
//finally
//{
// wb.Saved = true;
// wb.SaveCopyAs(fileName);//保存
// //excel.SaveWorkspace(fileName);
// //app.Quit();//关闭进程
// wb.Close();
// excel.Quit();
// GC.Collect();
//}
}
/// <summary>
/// 合格质量数据
/// 变速器称重
/// </summary>
/// <param name="sql"></param>
/// <param name="fileName"></param>
/// <param name="Count"></param>
public static void ExcelTable_QualityData_Query_kg(ref string sql, ref string fileName, ref int Count, ref int ColCount, ref object[,] ColsArray)
{
//新建一个excel
string connectionString = ApplicationConfiguration.ERP_ConnectionString;
//Microsoft.Office.Interop.Excel.Application excel = new Microsoft.Office.Interop.Excel.Application();
//excel.Application.Workbooks.Add(true);
//Microsoft.Office.Interop.Excel.Workbook wb = (Microsoft.Office.Interop.Excel.Workbook)excel.Application.Workbooks[1];
//excel.Visible = false;
//Microsoft.Office.Interop.Excel.Worksheet ws = new Microsoft.Office.Interop.Excel.Worksheet();
//ws = (Microsoft.Office.Interop.Excel.Worksheet)excel.ActiveSheet;
//ws.Name = "Sheet1";//新建的Table名称
//string LastCol = GetLastCellName(ColCount);
////设置头
//Microsoft.Office.Interop.Excel.Range rangeHeader = ws.get_Range("A1", LastCol+"1");
//rangeHeader.Merge(0);
//ws.Cells[1, 1] = "合格质量数据";
////rangeHeader.Font.Name = "黑体";
//rangeHeader.HorizontalAlignment = Microsoft.Office.Interop.Excel.XlHAlign.xlHAlignCenter;
////rangeHeader.Borders.LineStyle = 1; //设置单元格边框的粗细
////rangeHeader.EntireColumn.AutoFit(); //自动调整列宽
////序号,发动机号,工件重量,抽油后重量,重量差,允许重量差,合格标志,操作时间
////Orientation = 90以90度进行旋转
////第二部设置列头
//Microsoft.Office.Interop.Excel.Range rangeCol = ws.get_Range("A2", LastCol+"2");
////Excel.Range rangeCol = (Excel.Range)ws.get_Range(ws.Cells[2, 1], ws.Cells[2, ColCount]);
//object[,] arycol = (object[,])(rangeCol.Value2);
////arycol = new object[,] { { "序号", "发动机号", "工件重量(kg)", "抽油后重量(kg)", "重量差(kg)", "允许重量差(kg)", "合格标志", "操作时间" } };
//arycol = ColsArray;
//rangeCol.Value2 = arycol;
//rangeCol.HorizontalAlignment = Microsoft.Office.Interop.Excel.XlHAlign.xlHAlignCenter;
//rangeCol.VerticalAlignment = Microsoft.Office.Interop.Excel.Constants.xlTop;
//rangeCol.Borders.LineStyle = 1; //设置单元格边框的粗细
////rangeCol.EntireColumn.AutoFit(); //自动调整列宽
////rangeCol.Orientation = 90;
//try
//{
// ADODB.Connection conn = new ADODB.Connection();
// conn.Open("driver={SQL Server};" + connectionString, "", "", 0);
// ADODB.Recordset rs = new ADODB.Recordset();
// rs.Open(sql, conn, ADODB.CursorTypeEnum.adOpenStatic, ADODB.LockTypeEnum.adLockReadOnly, 0);
// Microsoft.Office.Interop.Excel.Range range = ws.get_Range("A3", Missing.Value);
// //range.CopyFromRecordset(rs, SourceTable.Rows.Count + 3, SourceTable.Columns.Count);//rs, 65535, 65535
// range.CopyFromRecordset(rs, 1000000, 30);//rs, 65535, 65535
// //设置序号
// Microsoft.Office.Interop.Excel.Range Drange = ws.get_Range("A3", "A" + (Count + 2).ToString());
// Microsoft.Office.Interop.Excel.Range DrangeFirst = ws.get_Range("A3");
// DrangeFirst.Value2 = 1;
// Drange.DataSeries(Missing.Value, Microsoft.Office.Interop.Excel.XlDataSeriesType.xlDataSeriesLinear, Microsoft.Office.Interop.Excel.XlDataSeriesDate.xlDay, 1, Count, false);
// //设置日期格式
// //int index = SourceTable.Columns["生产日期"].Ordinal + 1;
// Microsoft.Office.Interop.Excel.Range rangeDate = ws.get_Range("J3", "J" + (Count + 2).ToString());
// rangeDate.NumberFormatLocal = @"yyyy-mm-dd hh:mm";//日期型格式
// Microsoft.Office.Interop.Excel.Range RangeOfAll = ws.get_Range("A3", LastCol + (Count + 2).ToString());
// RangeOfAll.Borders.LineStyle = 1; //设置单元格边框的粗细
// RangeOfAll.HorizontalAlignment = Microsoft.Office.Interop.Excel.XlHAlign.xlHAlignCenter;
// RangeOfAll.EntireColumn.AutoFit(); //自动调整列宽
// //设置工序状况不合格的就为红色
// Microsoft.Office.Interop.Excel.FormatCondition cond =
// (Microsoft.Office.Interop.Excel.FormatCondition)RangeOfAll.FormatConditions.Add(Microsoft.Office.Interop.Excel.XlFormatConditionType.xlExpression,
// Missing.Value, "=$I1=0", Missing.Value);
// cond.Interior.PatternColorIndex = Microsoft.Office.Interop.Excel.Constants.xlAutomatic;
// cond.Interior.TintAndShade = 0;
// cond.Interior.Color = ColorTranslator.ToWin32(Color.Red);
// cond.StopIfTrue = false;
//}
//catch (Exception ex)
//{
// string str = ex.Message;
//}
//finally
//{
// wb.Saved = true;
// wb.SaveCopyAs(fileName);//保存
// //excel.SaveWorkspace(fileName);
// //app.Quit();//关闭进程
// wb.Close();
// excel.Quit();
// GC.Collect();
//}
}
/// <summary>
/// 人工合格放行
/// </summary>
/// <param name="sql"></param>
/// <param name="fileName"></param>
/// <param name="Count"></param>
public static void ExcelTable_QualityData_Query_okgo(ref string sql, ref string fileName, ref int Count, ref int ColCount, ref object[,] ColsArray)
{
//新建一个excel
//string connectionString = ApplicationConfiguration.ERP_ConnectionString;
//Microsoft.Office.Interop.Excel.Application excel = new Microsoft.Office.Interop.Excel.Application();
//excel.Application.Workbooks.Add(true);
//Microsoft.Office.Interop.Excel.Workbook wb = (Microsoft.Office.Interop.Excel.Workbook)excel.Application.Workbooks[1];
//excel.Visible = false;
//Microsoft.Office.Interop.Excel.Worksheet ws = new Microsoft.Office.Interop.Excel.Worksheet();
//ws = (Microsoft.Office.Interop.Excel.Worksheet)excel.ActiveSheet;
//ws.Name = "Sheet1";//新建的Table名称
//string LastCol = GetLastCellName(ColCount);
////设置头
//Microsoft.Office.Interop.Excel.Range rangeHeader = ws.get_Range("A1", LastCol + "1");
//rangeHeader.Merge(0);
//ws.Cells[1, 1] = "人工合格放行";
////rangeHeader.Font.Name = "黑体";
//rangeHeader.HorizontalAlignment = Microsoft.Office.Interop.Excel.XlHAlign.xlHAlignCenter;
////rangeHeader.Borders.LineStyle = 1; //设置单元格边框的粗细
////rangeHeader.EntireColumn.AutoFit(); //自动调整列宽
////序号,发动机号,工件重量,抽油后重量,重量差,允许重量差,合格标志,操作时间
////Orientation = 90以90度进行旋转
////第二部设置列头
//Microsoft.Office.Interop.Excel.Range rangeCol = ws.get_Range("A2", LastCol + "2");
////Excel.Range rangeCol = (Excel.Range)ws.get_Range(ws.Cells[2, 1], ws.Cells[2, ColCount]);
//object[,] arycol = (object[,])(rangeCol.Value2);
////arycol = new object[,] { { "序号", "发动机号", "工件重量(kg)", "抽油后重量(kg)", "重量差(kg)", "允许重量差(kg)", "合格标志", "操作时间" } };
//arycol = ColsArray;
//rangeCol.Value2 = arycol;
//rangeCol.HorizontalAlignment = Microsoft.Office.Interop.Excel.XlHAlign.xlHAlignCenter;
//rangeCol.VerticalAlignment = Microsoft.Office.Interop.Excel.Constants.xlTop;
//rangeCol.Borders.LineStyle = 1; //设置单元格边框的粗细
////rangeCol.EntireColumn.AutoFit(); //自动调整列宽
////rangeCol.Orientation = 90;
//try
//{
// ADODB.Connection conn = new ADODB.Connection();
// conn.Open("driver={SQL Server};" + connectionString, "", "", 0);
// ADODB.Recordset rs = new ADODB.Recordset();
// rs.Open(sql, conn, ADODB.CursorTypeEnum.adOpenStatic, ADODB.LockTypeEnum.adLockReadOnly, 0);
// Microsoft.Office.Interop.Excel.Range range = ws.get_Range("A3", Missing.Value);
// //range.CopyFromRecordset(rs, SourceTable.Rows.Count + 3, SourceTable.Columns.Count);//rs, 65535, 65535
// range.CopyFromRecordset(rs, 1000000, 30);//rs, 65535, 65535
// //设置序号
// Microsoft.Office.Interop.Excel.Range Drange = ws.get_Range("A3", "A" + (Count + 2).ToString());
// Microsoft.Office.Interop.Excel.Range DrangeFirst = ws.get_Range("A3");
// DrangeFirst.Value2 = 1;
// Drange.DataSeries(Missing.Value, Microsoft.Office.Interop.Excel.XlDataSeriesType.xlDataSeriesLinear, Microsoft.Office.Interop.Excel.XlDataSeriesDate.xlDay, 1, Count, false);
// //设置日期格式
// //int index = SourceTable.Columns["生产日期"].Ordinal + 1;
// Microsoft.Office.Interop.Excel.Range rangeDate = ws.get_Range("F3", "F" + (Count + 2).ToString());
// rangeDate.NumberFormatLocal = @"yyyy-mm-dd hh:mm";//日期型格式
// Microsoft.Office.Interop.Excel.Range RangeOfAll = ws.get_Range("A3", LastCol + (Count + 2).ToString());
// RangeOfAll.Borders.LineStyle = 1; //设置单元格边框的粗细
// RangeOfAll.HorizontalAlignment = Microsoft.Office.Interop.Excel.XlHAlign.xlHAlignCenter;
// RangeOfAll.EntireColumn.AutoFit(); //自动调整列宽
// //设置工序状况不合格的就为红色
// //Microsoft.Office.Interop.Excel.FormatCondition cond =
// // (Microsoft.Office.Interop.Excel.FormatCondition)RangeOfAll.FormatConditions.Add(Microsoft.Office.Interop.Excel.XlFormatConditionType.xlExpression,
// // Missing.Value, "=$I1=0", Missing.Value);
// //cond.Interior.PatternColorIndex = Microsoft.Office.Interop.Excel.Constants.xlAutomatic;
// //cond.Interior.TintAndShade = 0;
// //cond.Interior.Color = ColorTranslator.ToWin32(Color.Red);
// //cond.StopIfTrue = false;
//}
//catch (Exception ex)
//{
// string str = ex.Message;
//}
//finally
//{
// wb.Saved = true;
// wb.SaveCopyAs(fileName);//保存
// //excel.SaveWorkspace(fileName);
// //app.Quit();//关闭进程
// wb.Close();
// excel.Quit();
// GC.Collect();
//}
}
//ExcelTable
/// <summary>
/// 物料数据
/// </summary>
/// <param name="sql"></param>
/// <param name="fileName"></param>
/// <param name="Count"></param>
public static void ExcelTable_Materials(ref string sql, ref string fileName, ref int Count, ref int ColCount, ref object[,] ColsArray)
{
//新建一个excel
//string connectionString = ApplicationConfiguration.ERP_ConnectionString;
//Microsoft.Office.Interop.Excel.Application excel = new Microsoft.Office.Interop.Excel.Application();
//excel.Application.Workbooks.Add(true);
//Microsoft.Office.Interop.Excel.Workbook wb = (Microsoft.Office.Interop.Excel.Workbook)excel.Application.Workbooks[1];
//excel.Visible = false;
//Microsoft.Office.Interop.Excel.Worksheet ws = new Microsoft.Office.Interop.Excel.Worksheet();
//ws = (Microsoft.Office.Interop.Excel.Worksheet)excel.ActiveSheet;
//ws.Name = "Sheet1";//新建的Table名称
//string LastCol = GetLastCellName(ColCount);
////设置头
//Microsoft.Office.Interop.Excel.Range rangeHeader = ws.get_Range("A1", LastCol+"1");
//rangeHeader.Merge(0);
//ws.Cells[1, 1] = "物料数据";
//rangeHeader.Font.Name = "黑体";
//rangeHeader.HorizontalAlignment = Microsoft.Office.Interop.Excel.XlHAlign.xlHAlignCenter;
////rangeHeader.Borders.LineStyle = 1; //设置单元格边框的粗细
////rangeHeader.EntireColumn.AutoFit(); //自动调整列宽
////第二部设置列头
//Microsoft.Office.Interop.Excel.Range rangeCol = ws.get_Range("A2", LastCol+"2");
////Excel.Range rangeCol = (Excel.Range)ws.get_Range(ws.Cells[2, 1], ws.Cells[2, ColCount]);
//object[,] arycol = (object[,])(rangeCol.Value2);
////arycol = new object[,] { { "序号", "订单号", "发动机型号", "总成流水号", "工序号", "工序名称", "零件数量", "零件名称", "零件图号", "零件数量", "物料号", "生产厂家" } };
//arycol = ColsArray;
//rangeCol.Value2 = arycol;
//rangeCol.HorizontalAlignment = Microsoft.Office.Interop.Excel.XlHAlign.xlHAlignCenter;
//rangeCol.VerticalAlignment = Microsoft.Office.Interop.Excel.Constants.xlTop;
//rangeCol.Borders.LineStyle = 1; //设置单元格边框的粗细
////rangeCol.EntireColumn.AutoFit(); //自动调整列宽
////rangeCol.Orientation = 90;
//try
//{
// ADODB.Connection conn = new ADODB.Connection();
// conn.Open("driver={SQL Server};" + connectionString, "", "", 0);
// ADODB.Recordset rs = new ADODB.Recordset();
// rs.Open(sql, conn, ADODB.CursorTypeEnum.adOpenStatic, ADODB.LockTypeEnum.adLockReadOnly, 0);
// Microsoft.Office.Interop.Excel.Range range = ws.get_Range("A3", Missing.Value);
// //range.CopyFromRecordset(rs, SourceTable.Rows.Count + 3, SourceTable.Columns.Count);//rs, 65535, 65535
// range.CopyFromRecordset(rs, 1000000, 30);//rs, 65535, 65535
// //设置序号
// Microsoft.Office.Interop.Excel.Range Drange = ws.get_Range("A3", "A" + (Count + 2).ToString());
// Microsoft.Office.Interop.Excel.Range DrangeFirst = ws.get_Range("A3");
// DrangeFirst.Value2 = 1;
// Drange.DataSeries(Missing.Value, Microsoft.Office.Interop.Excel.XlDataSeriesType.xlDataSeriesLinear, Microsoft.Office.Interop.Excel.XlDataSeriesDate.xlDay, 1, Count, false);
// ////设置日期格式
// ////int index = SourceTable.Columns["生产日期"].Ordinal + 1;
// //Microsoft.Office.Interop.Excel.Range rangeDate = ws.get_Range("H3", "H" + (Count + 2).ToString());
// //rangeDate.NumberFormatLocal = @"yyyy-mm-dd hh:mm";//日期型格式
// Microsoft.Office.Interop.Excel.Range RangeOfAll = ws.get_Range("A3", LastCol + (Count + 2).ToString());
// RangeOfAll.Borders.LineStyle = 1; //设置单元格边框的粗细
// RangeOfAll.HorizontalAlignment = Microsoft.Office.Interop.Excel.XlHAlign.xlHAlignCenter;
// RangeOfAll.EntireColumn.AutoFit(); //自动调整列宽
//}
//catch (Exception ex)
//{
// string str = ex.Message;
//}
//finally
//{
// wb.Saved = true;
// wb.SaveCopyAs(fileName);//保存
// //excel.SaveWorkspace(fileName);
// //app.Quit();//关闭进程
// wb.Close();
// excel.Quit();
// GC.Collect();
//}
}
/// <summary>
/// 字段名称各个字符中间增加回车,以保证文本竖着书写。
/// </summary>
/// <param name="columnName"></param>
/// <returns></returns>
private static string GetColumnName_Ver(string columnName)
{
string columnName_tr;
columnName_tr = "";
for (int i = 0; i < columnName.Length; i++)
{
columnName_tr = columnName_tr + columnName[i] + Environment.NewLine;
}
return columnName_tr;
}
/// <summary>
/// 将图片转换为字节数组
/// </summary>
/// <param name="path">图片的路径</param>
/// <returns>字节数组</returns>
public static byte[] PicToByteArr(string path)
{
System.IO.FileStream fs = new System.IO.FileStream(path,System.IO.FileMode.Open);//将图片写入流中。
int filelength = 0;
filelength = (int)fs.Length; //获得文件长度
Byte[] byteArr = new Byte[filelength]; //建树一个字节数组
fs.Read(byteArr,0,filelength); //按字节俭读取
fs.Close();
return byteArr;
}
/// <summary>
/// 参数是byte返回图片
/// </summary>
/// <param name="byteArr">字节数组</param>
/// <returns>图片</returns>
public static System.Drawing.Image ReturnPhoto(byte[] byteArr)
{
System.IO.MemoryStream ms = new System.IO.MemoryStream(byteArr);
System.Drawing.Image img = System.Drawing.Image.FromStream(ms);
ms.Close();
return img;
}
/// <summary>
/// 根据列和行号得到最终
/// </summary>
/// <param name="ColCount"></param>
/// <param name="RowCount"></param>
/// <returns></returns>
public static string GetLastCellName(int ColCount)
{
string LastCellName = String.Empty;
switch (ColCount)
{
case 1:
LastCellName = "A";
break;
case 2:
LastCellName = "B";
break;
case 3:
LastCellName = "C";
break;
case 4:
LastCellName = "D";
break;
case 5:
LastCellName = "E";
break;
case 6:
LastCellName = "F";
break;
case 7:
LastCellName = "G";
break;
case 8:
LastCellName = "H";
break;
case 9:
LastCellName = "I";
break;
case 10:
LastCellName = "J";
break;
case 11:
LastCellName = "K";
break;
case 12:
LastCellName = "L";
break;
case 13:
LastCellName = "M";
break;
case 14:
LastCellName = "N";
break;
case 15:
LastCellName = "O";
break;
case 16:
LastCellName = "P";
break;
case 17:
LastCellName = "Q";
break;
case 18:
LastCellName = "R";
break;
case 19:
LastCellName = "S";
break;
case 20:
LastCellName = "T";
break;
case 21:
LastCellName = "U";
break;
case 22:
LastCellName = "V";
break;
case 23:
LastCellName = "W";
break;
case 24:
LastCellName = "X";
break;
case 25:
LastCellName = "Y";
break;
case 26:
LastCellName = "Z";
break;
default: break;
}
return LastCellName;
}
}

View File

@@ -0,0 +1,69 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.IO;
/// <summary>
///DownLoadFromServer 的摘要说明
/// </summary>
public class DownLoadFromServer
{
/// <summary>
/// 从服务器下载
/// </summary>
public DownLoadFromServer()
{
//
//TODO: 在此处添加构造函数逻辑
//
}
/// <summary>
/// 下载Excele文件
/// </summary>
/// <param name="ServerPath">服务器存放Excel路径</param>
public static void DownLoad(ref string ServerPath)
{
try
{
System.IO.FileInfo file = new System.IO.FileInfo(ServerPath);
if (file.Exists == true)
{
System.Web.HttpContext.Current.Response.Clear();
System.Web.HttpContext.Current.Response.Charset = "GB2312";
System.Web.HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.UTF8;
// 添加头信息,为"文件下载/另存为"对话框指定默认文件名
System.Web.HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment; filename=" + System.Web.HttpContext.Current.Server.UrlEncode("Sheet1.xlsx"));
// 添加头信息,指定文件大小,让浏览器能够显示下载进度
System.Web.HttpContext.Current.Response.AddHeader("Content-Length", file.Length.ToString());
// 指定返回的是一个不能被客户端读取的流,必须被下载
System.Web.HttpContext.Current.Response.ContentType = "application/ms-excel";
// 把文件流发送到客户端
System.Web.HttpContext.Current.Response.WriteFile(file.FullName);
// 停止页面的执行
//Response.End();
System.Web.HttpContext.Current.Response.Flush();
//System.Web.HttpContext.Current.Response.End();
HttpContext.Current.ApplicationInstance.CompleteRequest();
}
else
{
System.Web.HttpContext.Current.Response.Write("<script>alert('请尽快与管理员联系.')</script>");
}
}
catch (Exception ex)
{
System.Web.HttpContext.Current.Response.Write("<script>alert('系统出现以下错误://n" + ex.Message + "!//n请尽快与管理员联系.')</script>");
}
}
public static void DeleteExcel(ref string ServerPath)
{
System.IO.FileInfo file = new System.IO.FileInfo(ServerPath);
if (file.Exists == true)
{
File.Delete(ServerPath);
}
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,29 @@
using System;
using System.Data;
using System.Drawing;
using System.Drawing.Imaging;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Xml;
using SPC.SystemFrameworks;
using ASPNet_Drawing;
namespace SPC.WebUI
{
/// <summary>
///DrawPicture 的摘要说明
/// </summary>
public class DrawPicture
{
private Graph obGraph = null;
public DrawPicture()
{
//
//TODO: 在此处添加构造函数逻辑
//
}
}
}

587
App_code/GetSQL_Output.cs Normal file
View File

@@ -0,0 +1,587 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.SqlClient;
using System.Data;
using System.Collections;
using MES_SPC;
/// <summary>
///GetSQL_Output 的摘要说明
/// </summary>
public class GetSQL_Output
{//返回新的SQL语句
public GetSQL_Output()
{
//
//TODO: 在此处添加构造函数逻辑
//
}
//-----------------------专门由于导出excel数据量过多而造成下载速度慢和打开excel慢而做的存储过程--------------------------------------------------------------------
/// <summary>
/// 质量数据查询
/// </summary>
/// <param name="EnginIDCheck"></param>
/// <param name="EnginID"></param>
/// <param name="OPNameCheck"></param>
/// <param name="OPName"></param>
/// <param name="shaftNameCheck"></param>
/// <param name="shaftName"></param>
/// <param name="itemNameCheck"></param>
/// <param name="itemName"></param>
/// <param name="startTime"></param>
/// <param name="endTime"></param>
/// <param name="isOK"></param>
/// <param name="Isuse"></param>
/// <param name="sql"></param>
/// <param name="Count"></param>
public static void SelectGoodDataReport_ADODB_New
(bool EnginIDCheck, string EnginID,
bool OPNameCheck, string OPName,
bool shaftNameCheck, string shaftName,
bool itemNameCheck, string itemName,
string startTime, string endTime, int isOK, bool Isuse, out string sql, out int Count,out int ColCount,out object[,] ColsArray)
{
try
{
string procedureName;
procedureName = "质量数据查询_综合查询_ReturnSql";
DateTime dt_startTime;
DateTime dt_endTime;
dt_startTime = DateTime.Parse(startTime);
dt_endTime = DateTime.Parse(endTime);
string constr = ApplicationConfiguration.ERP_ConnectionString;
SqlConnection conn = new SqlConnection(constr);
conn.Open();
SqlCommand MyCommand = new SqlCommand(procedureName, conn);
MyCommand.CommandType = CommandType.StoredProcedure;
MyCommand.Parameters.Add(new System.Data.SqlClient.SqlParameter("@发动机号_ischeck", EnginIDCheck));
MyCommand.Parameters.Add(new System.Data.SqlClient.SqlParameter("@发动机号", EnginID));
MyCommand.Parameters.Add(new System.Data.SqlClient.SqlParameter("@工位号_ischeck", OPNameCheck));
MyCommand.Parameters.Add(new System.Data.SqlClient.SqlParameter("@工位号", OPName));
MyCommand.Parameters.Add(new System.Data.SqlClient.SqlParameter("@测量位置_ischeck", shaftNameCheck));
MyCommand.Parameters.Add(new System.Data.SqlClient.SqlParameter("@测量位置", shaftName));
MyCommand.Parameters.Add(new System.Data.SqlClient.SqlParameter("@测量项目_ischeck", itemNameCheck));
MyCommand.Parameters.Add(new System.Data.SqlClient.SqlParameter("@测量项目", itemName));
MyCommand.Parameters.Add(new System.Data.SqlClient.SqlParameter("@开始时间", dt_startTime));
MyCommand.Parameters.Add(new System.Data.SqlClient.SqlParameter("@结束时间", dt_endTime));
MyCommand.Parameters.Add(new System.Data.SqlClient.SqlParameter("@合格标志", isOK.ToString()));
MyCommand.Parameters.Add(new System.Data.SqlClient.SqlParameter("@是否禁用", Isuse));
MyCommand.Parameters.Add(new System.Data.SqlClient.SqlParameter("@selectStr_OutPut", SqlDbType.NVarChar,4000));
MyCommand.Parameters["@selectStr_OutPut"].Direction = ParameterDirection.Output;
MyCommand.Parameters.Add(new System.Data.SqlClient.SqlParameter("@Count", SqlDbType.Int));
MyCommand.Parameters["@Count"].Direction = ParameterDirection.Output;
MyCommand.Parameters.Add(new System.Data.SqlClient.SqlParameter("@ColsArray", SqlDbType.NVarChar, 4000));
MyCommand.Parameters["@ColsArray"].Direction = ParameterDirection.Output;
MyCommand.ExecuteNonQuery();
sql = Convert.ToString(MyCommand.Parameters["@selectStr_OutPut"].Value);
Count = Convert.ToInt32(MyCommand.Parameters["@Count"].Value);//返回SQL语句
string[] ColsArrayString = Convert.ToString(MyCommand.Parameters["@ColsArray"].Value).Split('|'); ;//所有列名的集合
ColsArray = new object[1, ColsArrayString.Length];
for (int i = 0; i < ColsArrayString.Length; i++)
{
ColsArray[0, i] = ColsArrayString[i];
}
ColCount = ColsArrayString.Length;
}
catch
{
sql = "";
Count = 0;
ColsArray = null;
ColCount = 0;
}
}
/// <summary>
/// 质量数据查询_数据备份_综合查询_ReturnSql
/// </summary>
/// <param name="EnginIDCheck"></param>
/// <param name="EnginID"></param>
/// <param name="OPNameCheck"></param>
/// <param name="OPName"></param>
/// <param name="shaftNameCheck"></param>
/// <param name="shaftName"></param>
/// <param name="itemNameCheck"></param>
/// <param name="itemName"></param>
/// <param name="startTime"></param>
/// <param name="endTime"></param>
/// <param name="isOK"></param>
/// <param name="Isuse"></param>
/// <param name="sql"></param>
/// <param name="Count"></param>
public static void SelectGoodDataReport_ADODB_New_DataBak
(bool EngineTypeCheck, string EngineType, bool EnginIDCheck, string EnginID,
bool OPNameCheck, string OPName,
bool shaftNameCheck, string shaftName,
bool itemNameCheck, string itemName,
string startTime, string endTime, int isOK, bool Isuse, out string sql, out int Count, out int ColCount, out object[,] ColsArray)
{
try
{
string procedureName;
procedureName = "质量数据查询_数据备份_综合查询_ReturnSql";
DateTime dt_startTime;
DateTime dt_endTime;
dt_startTime = DateTime.Parse(startTime);
dt_endTime = DateTime.Parse(endTime);
string constr = ApplicationConfiguration.ERP_ConnectionString;
SqlConnection conn = new SqlConnection(constr);
conn.Open();
SqlCommand MyCommand = new SqlCommand(procedureName, conn);
MyCommand.CommandTimeout = 120;
MyCommand.CommandType = CommandType.StoredProcedure;
MyCommand.Parameters.Add(new System.Data.SqlClient.SqlParameter("@发动机型号_ischeck", EngineTypeCheck));
MyCommand.Parameters.Add(new System.Data.SqlClient.SqlParameter("@发动机型号", EngineType));
MyCommand.Parameters.Add(new System.Data.SqlClient.SqlParameter("@发动机号_ischeck", EnginIDCheck));
MyCommand.Parameters.Add(new System.Data.SqlClient.SqlParameter("@发动机号", EnginID));
MyCommand.Parameters.Add(new System.Data.SqlClient.SqlParameter("@工位号_ischeck", OPNameCheck));
MyCommand.Parameters.Add(new System.Data.SqlClient.SqlParameter("@工位号", OPName));
MyCommand.Parameters.Add(new System.Data.SqlClient.SqlParameter("@测量位置_ischeck", shaftNameCheck));
MyCommand.Parameters.Add(new System.Data.SqlClient.SqlParameter("@测量位置", shaftName));
MyCommand.Parameters.Add(new System.Data.SqlClient.SqlParameter("@测量项目_ischeck", itemNameCheck));
MyCommand.Parameters.Add(new System.Data.SqlClient.SqlParameter("@测量项目", itemName));
MyCommand.Parameters.Add(new System.Data.SqlClient.SqlParameter("@开始时间", dt_startTime));
MyCommand.Parameters.Add(new System.Data.SqlClient.SqlParameter("@结束时间", dt_endTime));
MyCommand.Parameters.Add(new System.Data.SqlClient.SqlParameter("@合格标志", isOK.ToString()));
MyCommand.Parameters.Add(new System.Data.SqlClient.SqlParameter("@是否禁用", Isuse));
MyCommand.Parameters.Add(new System.Data.SqlClient.SqlParameter("@selectStr_OutPut", SqlDbType.NVarChar, 4000));
MyCommand.Parameters["@selectStr_OutPut"].Direction = ParameterDirection.Output;
MyCommand.Parameters.Add(new System.Data.SqlClient.SqlParameter("@Count", SqlDbType.Int));
MyCommand.Parameters["@Count"].Direction = ParameterDirection.Output;
MyCommand.Parameters.Add(new System.Data.SqlClient.SqlParameter("@ColsArray", SqlDbType.NVarChar, 4000));
MyCommand.Parameters["@ColsArray"].Direction = ParameterDirection.Output;
MyCommand.ExecuteNonQuery();
sql = Convert.ToString(MyCommand.Parameters["@selectStr_OutPut"].Value);
Count = Convert.ToInt32(MyCommand.Parameters["@Count"].Value);//返回SQL语句
string[] ColsArrayString = Convert.ToString(MyCommand.Parameters["@ColsArray"].Value).Split('|'); ;//所有列名的集合
ColsArray = new object[1, ColsArrayString.Length];
for (int i = 0; i < ColsArrayString.Length; i++)
{
ColsArray[0, i] = ColsArrayString[i];
}
ColCount = ColsArrayString.Length;
}
catch
{
sql = "";
Count = 0;
ColsArray = null;
ColCount = 0;
}
}
/// <summary>
/// 工件总成质量数据报表
/// 引用页QualityData_Query_2.aspx(质量数据导出excel)
/// </summary>
/// <param name="EnginIDCheck"></param>
/// <param name="EnginID"></param>
/// <param name="OPNameCheck"></param>
/// <param name="OPName"></param>
/// <param name="engineTypeIDCheck"></param>
/// <param name="engineTypeID"></param>
/// <param name="itemNameCheck"></param>
/// <param name="itemName"></param>
/// <param name="startTime"></param>
/// <param name="endTime"></param>
/// <param name="isOK"></param>
/// <param name="sql"></param>
/// <param name="Count"></param>
public static void SelectGoodDataReport_2_ADODB_New
(bool EnginIDCheck, string EnginID,
bool OPNameCheck, string OPName,
bool engineTypeIDCheck, int engineTypeID,
bool itemNameCheck, string itemName,
string startTime, string endTime, int isOK, out string sql, out int Count,out int ColCount,out object[,] ColsArray)
{
try
{
string procedureName;
procedureName = "测量数据合格_合并_视图_查询_ReturnSql";
DateTime dt_startTime;
DateTime dt_endTime;
dt_startTime = DateTime.Parse(startTime);
dt_endTime = DateTime.Parse(endTime);
string constr = ApplicationConfiguration.ERP_ConnectionString;
SqlConnection conn = new SqlConnection(constr);
conn.Open();
SqlCommand MyCommand = new SqlCommand(procedureName, conn);
MyCommand.CommandType = CommandType.StoredProcedure;
MyCommand.Parameters.Add(new System.Data.SqlClient.SqlParameter("@发动机号_ischeck", EnginIDCheck));
MyCommand.Parameters.Add(new System.Data.SqlClient.SqlParameter("@发动机号", EnginID));
MyCommand.Parameters.Add(new System.Data.SqlClient.SqlParameter("@工位号_ischeck", OPNameCheck));
MyCommand.Parameters.Add(new System.Data.SqlClient.SqlParameter("@工位号", OPName));
MyCommand.Parameters.Add(new System.Data.SqlClient.SqlParameter("@发动机型号代码_ischeck", engineTypeIDCheck));
MyCommand.Parameters.Add(new System.Data.SqlClient.SqlParameter("@发动机型号代码", engineTypeID));
MyCommand.Parameters.Add(new System.Data.SqlClient.SqlParameter("@测量位置_ischeck", itemNameCheck));
MyCommand.Parameters.Add(new System.Data.SqlClient.SqlParameter("@测量位置", itemName));
MyCommand.Parameters.Add(new System.Data.SqlClient.SqlParameter("@开始时间", dt_startTime));
MyCommand.Parameters.Add(new System.Data.SqlClient.SqlParameter("@结束时间", dt_endTime));
MyCommand.Parameters.Add(new System.Data.SqlClient.SqlParameter("@总合格标志", isOK.ToString()));
MyCommand.Parameters.Add(new System.Data.SqlClient.SqlParameter("@selectStr_OutPut", SqlDbType.NVarChar, 4000));
MyCommand.Parameters["@selectStr_OutPut"].Direction = ParameterDirection.Output;
MyCommand.Parameters.Add(new System.Data.SqlClient.SqlParameter("@Count", SqlDbType.Int));
MyCommand.Parameters["@Count"].Direction = ParameterDirection.Output;
MyCommand.Parameters.Add(new System.Data.SqlClient.SqlParameter("@ColsArray", SqlDbType.NVarChar, 4000));
MyCommand.Parameters["@ColsArray"].Direction = ParameterDirection.Output;
MyCommand.CommandTimeout = 120;
MyCommand.ExecuteNonQuery();
sql = Convert.ToString(MyCommand.Parameters["@selectStr_OutPut"].Value);
Count = Convert.ToInt32(MyCommand.Parameters["@Count"].Value);//返回SQL语句
string[] ColsArrayString = Convert.ToString(MyCommand.Parameters["@ColsArray"].Value).Split('|'); ;//所有列名的集合
ColsArray = new object[1, ColsArrayString.Length];
for (int i = 0; i < ColsArrayString.Length; i++)
{
ColsArray[0, i] = GetColumnName_Ver(ColsArrayString[i]);
}
ColCount = ColsArrayString.Length;
}
catch
{
sql = "";
Count = 0;
ColsArray = null;
ColCount = 0;
}
}
/// <summary>
/// 不合格质量数据
/// 引用页QualityData_Query_2.aspx
/// </summary>
/// <param name="EnginIDCheck"></param>
/// <param name="EnginID"></param>
/// <param name="OPNameCheck"></param>
/// <param name="OPName"></param>
/// <param name="engineTypeIDCheck"></param>
/// <param name="engineTypeID"></param>
/// <param name="itemNameCheck"></param>
/// <param name="itemName"></param>
/// <param name="startTime"></param>
/// <param name="endTime"></param>
/// <param name="sql"></param>
/// <param name="Count"></param>
public static void SelectGoodDataReport_2_ADODB_New
(bool EnginIDCheck, string EnginID,
bool OPNameCheck, string OPName,
bool engineTypeIDCheck, int engineTypeID,
bool itemNameCheck, string itemName,
string startTime, string endTime, out string sql, out int Count, out int ColCount, out object[,] ColsArray)
{
try
{
string procedureName;
procedureName = "测量数据合格_合并_视图_不合格数据_查询_ReturnSql";
DateTime dt_startTime;
DateTime dt_endTime;
dt_startTime = DateTime.Parse(startTime);
dt_endTime = DateTime.Parse(endTime);
string constr = ApplicationConfiguration.ERP_ConnectionString;
SqlConnection conn = new SqlConnection(constr);
conn.Open();
SqlCommand MyCommand = new SqlCommand(procedureName, conn);
MyCommand.CommandType = CommandType.StoredProcedure;
MyCommand.Parameters.Add(new System.Data.SqlClient.SqlParameter("@发动机号_ischeck", EnginIDCheck));
MyCommand.Parameters.Add(new System.Data.SqlClient.SqlParameter("@发动机号", EnginID));
MyCommand.Parameters.Add(new System.Data.SqlClient.SqlParameter("@工位号_ischeck", OPNameCheck));
MyCommand.Parameters.Add(new System.Data.SqlClient.SqlParameter("@工位号", OPName));
MyCommand.Parameters.Add(new System.Data.SqlClient.SqlParameter("@发动机型号代码_ischeck", engineTypeIDCheck));
MyCommand.Parameters.Add(new System.Data.SqlClient.SqlParameter("@发动机型号代码", engineTypeID));
MyCommand.Parameters.Add(new System.Data.SqlClient.SqlParameter("@测量位置_ischeck", itemNameCheck));
MyCommand.Parameters.Add(new System.Data.SqlClient.SqlParameter("@测量位置", itemName));
MyCommand.Parameters.Add(new System.Data.SqlClient.SqlParameter("@开始时间", dt_startTime));
MyCommand.Parameters.Add(new System.Data.SqlClient.SqlParameter("@结束时间", dt_endTime));
MyCommand.Parameters.Add(new System.Data.SqlClient.SqlParameter("@selectStr_OutPut", SqlDbType.NVarChar, 4000));
MyCommand.Parameters["@selectStr_OutPut"].Direction = ParameterDirection.Output;
MyCommand.Parameters.Add(new System.Data.SqlClient.SqlParameter("@Count", SqlDbType.Int));
MyCommand.Parameters["@Count"].Direction = ParameterDirection.Output;
MyCommand.Parameters.Add(new System.Data.SqlClient.SqlParameter("@ColsArray", SqlDbType.NVarChar, 4000));
MyCommand.Parameters["@ColsArray"].Direction = ParameterDirection.Output;
MyCommand.ExecuteNonQuery();
sql = Convert.ToString(MyCommand.Parameters["@selectStr_OutPut"].Value);
Count = Convert.ToInt32(MyCommand.Parameters["@Count"].Value);//返回SQL语句
string[] ColsArrayString = Convert.ToString(MyCommand.Parameters["@ColsArray"].Value).Split('|'); ;//所有列名的集合
ColsArray = new object[1, ColsArrayString.Length];
for (int i = 0; i < ColsArrayString.Length; i++)
{
ColsArray[0, i] = GetColumnName_Ver(ColsArrayString[i]);
}
ColCount = ColsArrayString.Length;
}
catch
{
sql = "";
Count = 0;
ColsArray = null;
ColCount = 0;
}
}
/// <summary>
/// 测量数据合格_变速器总成称重_报表
/// </summary>
/// <param name="EnginIDCheck"></param>
/// <param name="EnginID"></param>
/// <param name="startTime"></param>
/// <param name="endTime"></param>
/// <param name="isOK"></param>
/// <param name="sql"></param>
/// <param name="Count"></param>
public static void SelectGoodData_weight_Report_ADODB_New
(bool EnginIDCheck, string EnginID,
string startTime, string endTime, int isOK, out string sql, out int Count, out int ColCount, out object[,] ColsArray)
{
try
{
string procedureName;
procedureName = "测量数据合格_变速器总成称重_报表_ReturnSql";
DateTime dt_startTime;
DateTime dt_endTime;
dt_startTime = DateTime.Parse(startTime);
dt_endTime = DateTime.Parse(endTime);
string constr = ApplicationConfiguration.ERP_ConnectionString;
SqlConnection conn = new SqlConnection(constr);
conn.Open();
SqlCommand MyCommand = new SqlCommand(procedureName, conn);
MyCommand.CommandType = CommandType.StoredProcedure;
MyCommand.Parameters.Add(new System.Data.SqlClient.SqlParameter("@发动机号_ischeck", EnginIDCheck));
MyCommand.Parameters.Add(new System.Data.SqlClient.SqlParameter("@发动机号", EnginID));
MyCommand.Parameters.Add(new System.Data.SqlClient.SqlParameter("@开始时间", dt_startTime));
MyCommand.Parameters.Add(new System.Data.SqlClient.SqlParameter("@结束时间", dt_endTime));
MyCommand.Parameters.Add(new System.Data.SqlClient.SqlParameter("@合格标志", isOK.ToString()));
MyCommand.Parameters.Add(new System.Data.SqlClient.SqlParameter("@selectStr_OutPut", SqlDbType.NVarChar, 4000));
MyCommand.Parameters["@selectStr_OutPut"].Direction = ParameterDirection.Output;
MyCommand.Parameters.Add(new System.Data.SqlClient.SqlParameter("@Count", SqlDbType.Int));
MyCommand.Parameters["@Count"].Direction = ParameterDirection.Output;
MyCommand.Parameters.Add(new System.Data.SqlClient.SqlParameter("@ColsArray", SqlDbType.NVarChar, 4000));
MyCommand.Parameters["@ColsArray"].Direction = ParameterDirection.Output;
MyCommand.ExecuteNonQuery();
sql = Convert.ToString(MyCommand.Parameters["@selectStr_OutPut"].Value);
Count = Convert.ToInt32(MyCommand.Parameters["@Count"].Value);//返回SQL语句
string[] ColsArrayString = Convert.ToString(MyCommand.Parameters["@ColsArray"].Value).Split('|'); ;//所有列名的集合
ColsArray = new object[1, ColsArrayString.Length];
for (int i = 0; i < ColsArrayString.Length; i++)
{
ColsArray[0, i] = ColsArrayString[i];
}
ColCount = ColsArrayString.Length;
}
catch
{
sql = "";
Count = 0;
ColsArray = null;
ColCount = 0;
}
}
/// <summary>
///
/// </summary>
/// <param name="EnginIDCheck"></param>
/// <param name="EnginID"></param>
/// <param name="startTime"></param>
/// <param name="endTime"></param>
/// <param name="sql"></param>
/// <param name="Count"></param>
/// <param name="ColCount"></param>
/// <param name="ColsArray"></param>
public static void SelectGoodData_OKGO_Report_ADODB
(bool EnginIDCheck, string EnginID,
string startTime, string endTime, out string sql, out int Count, out int ColCount, out object[,] ColsArray)
{
try
{
string procedureName;
procedureName = "电子看板_发动机号_人工合格放行记录_查询_ReturnSql";
DateTime dt_startTime;
DateTime dt_endTime;
dt_startTime = DateTime.Parse(startTime);
dt_endTime = DateTime.Parse(endTime);
string constr = ApplicationConfiguration.ERP_ConnectionString;
SqlConnection conn = new SqlConnection(constr);
conn.Open();
SqlCommand MyCommand = new SqlCommand(procedureName, conn);
MyCommand.CommandType = CommandType.StoredProcedure;
MyCommand.Parameters.Add(new System.Data.SqlClient.SqlParameter("@领班工号_ischeck", EnginIDCheck));
MyCommand.Parameters.Add(new System.Data.SqlClient.SqlParameter("@领班工号", EnginID));
MyCommand.Parameters.Add(new System.Data.SqlClient.SqlParameter("@开始时间", dt_startTime));
MyCommand.Parameters.Add(new System.Data.SqlClient.SqlParameter("@结束时间", dt_endTime));
MyCommand.Parameters.Add(new System.Data.SqlClient.SqlParameter("@selectStr_OutPut", SqlDbType.NVarChar, 4000));
MyCommand.Parameters["@selectStr_OutPut"].Direction = ParameterDirection.Output;
MyCommand.Parameters.Add(new System.Data.SqlClient.SqlParameter("@Count", SqlDbType.Int));
MyCommand.Parameters["@Count"].Direction = ParameterDirection.Output;
MyCommand.Parameters.Add(new System.Data.SqlClient.SqlParameter("@ColsArray", SqlDbType.NVarChar, 4000));
MyCommand.Parameters["@ColsArray"].Direction = ParameterDirection.Output;
MyCommand.ExecuteNonQuery();
sql = Convert.ToString(MyCommand.Parameters["@selectStr_OutPut"].Value);
Count = Convert.ToInt32(MyCommand.Parameters["@Count"].Value);//返回SQL语句
string[] ColsArrayString = Convert.ToString(MyCommand.Parameters["@ColsArray"].Value).Split('|'); ;//所有列名的集合
ColsArray = new object[1, ColsArrayString.Length];
for (int i = 0; i < ColsArrayString.Length; i++)
{
ColsArray[0, i] = ColsArrayString[i];
}
ColCount = ColsArrayString.Length;
}
catch
{
sql = "";
Count = 0;
ColsArray = null;
ColCount = 0;
}
}
/// <summary>
/// 物料数据报表
/// </summary>
/// <param name="EnginIDCheck"></param>
/// <param name="EnginID"></param>
/// <param name="OPNameCheck"></param>
/// <param name="OPName"></param>
/// <param name="startTime"></param>
/// <param name="endTime"></param>
/// <param name="sql"></param>
/// <param name="Count"></param>
public static void SelectMaterialReport_ADODB_New
(bool EnginIDCheck, string EnginID,
bool OPNameCheck, string OPName,
string startTime, string endTime, out string sql, out int Count, out int ColCount, out object[,] ColsArray)
{
try
{
string procedureName;
procedureName = "物料数据查询_报表_ReturnSql";
DateTime dt_startTime;
DateTime dt_endTime;
dt_startTime = DateTime.Parse(startTime);
dt_endTime = DateTime.Parse(endTime);
string constr = ApplicationConfiguration.ERP_ConnectionString;
SqlConnection conn = new SqlConnection(constr);
conn.Open();
SqlCommand MyCommand = new SqlCommand(procedureName, conn);
MyCommand.CommandType = CommandType.StoredProcedure;
MyCommand.Parameters.Add(new System.Data.SqlClient.SqlParameter("@发动机号_ischeck", EnginIDCheck));
MyCommand.Parameters.Add(new System.Data.SqlClient.SqlParameter("@发动机号", EnginID));
MyCommand.Parameters.Add(new System.Data.SqlClient.SqlParameter("@工位号_ischeck", OPNameCheck));
MyCommand.Parameters.Add(new System.Data.SqlClient.SqlParameter("@工位号", OPName));
MyCommand.Parameters.Add(new System.Data.SqlClient.SqlParameter("@开始时间", dt_startTime));
MyCommand.Parameters.Add(new System.Data.SqlClient.SqlParameter("@结束时间", dt_endTime));
MyCommand.Parameters.Add(new System.Data.SqlClient.SqlParameter("@selectStr_OutPut", SqlDbType.NVarChar, 4000));
MyCommand.Parameters["@selectStr_OutPut"].Direction = ParameterDirection.Output;
MyCommand.Parameters.Add(new System.Data.SqlClient.SqlParameter("@Count", SqlDbType.Int));
MyCommand.Parameters["@Count"].Direction = ParameterDirection.Output;
MyCommand.Parameters.Add(new System.Data.SqlClient.SqlParameter("@ColsArray", SqlDbType.NVarChar, 4000));
MyCommand.Parameters["@ColsArray"].Direction = ParameterDirection.Output;
MyCommand.ExecuteNonQuery();
sql = Convert.ToString(MyCommand.Parameters["@selectStr_OutPut"].Value);
Count = Convert.ToInt32(MyCommand.Parameters["@Count"].Value);//返回SQL语句
string[] ColsArrayString = Convert.ToString(MyCommand.Parameters["@ColsArray"].Value).Split('|'); ;//所有列名的集合
ColsArray = new object[1, ColsArrayString.Length];
for (int i = 0; i < ColsArrayString.Length; i++)
{
ColsArray[0, i] = ColsArrayString[i];
}
ColCount = ColsArrayString.Length;
}
catch
{
sql = "";
Count = 0;
ColsArray = null;
ColCount = 0;
}
}
/// <summary>
/// 字段名称各个字符中间增加回车,以保证文本竖着书写。
/// </summary>
/// <param name="columnName"></param>
/// <returns></returns>
private static string GetColumnName_Ver(string columnName)
{
string columnName_tr;
columnName_tr = "";
for (int i = 0; i < columnName.Length; i++)
{
columnName_tr = columnName_tr + columnName[i] + Environment.NewLine;
}
return columnName_tr;
}
}

190
App_code/PageBase.cs Normal file
View File

@@ -0,0 +1,190 @@
using System;
using System.Web;
using System.Web.UI;
using System.ComponentModel;
using System.Data;
//using SPC.Common;
//using SPC.Common.Data;
/// <summary>
///PageBase 的摘要说明
/// </summary>
namespace SPC.WebUI
{
public class PageBase:System.Web.UI.Page
{
private const String UNHANDLED_EXCEPTION = "Unhandled Exception:";
private const String KEY_CACHEUSERS = "Cache:Users";
private const String KEY_CACHEASSEMBLELINEWORKPLACE = "Cache:AssembleLineWorkPlace";
private const String KEY_CACHEWORKPLACEMEASUREPART = "Cache:WorkPlaceMeasurePart";
private const String KEY_CACHEWORKPLACEMEASUREPARTCONTENT = "Cache:WorkPlaceMeasurePartContent";
private static string UrlSuffix
{
get
{
//return HttpContext.Current.Request.Url.Host + HttpContext.Current.Request.ApplicationPath; //多加端口号与网站发布方式有关,与发布网站带不带端口号有关
return HttpContext.Current.Request.Url.Host + ":" + HttpContext.Current.Request.Url.Port + HttpContext.Current.Request.ApplicationPath;
}
}
public static String SecureUrlBase
{
get
{
//return (SPCWebConfiguration.EnableSsl ? @"https://" : @"http://") + UrlSuffix;
return @"http://" + UrlSuffix;
}
}
public static String UrlBase
{
get
{
return @"http://" + UrlSuffix;
}
}
public DataSet UserSys
{
get
{
try
{
return (DataSet)(Session[KEY_CACHEUSERS]);
}
catch
{
return (null);
}
}
set
{
if (null == value)
{
Session.Remove(KEY_CACHEUSERS);
}
else
{
Session[KEY_CACHEUSERS] = value;
}
}
}
///// <summary>
///// Retrieves the Cart for the session, forcing it to be created
///// if it does not already exist.
///// </summary>
//public MeasureContent AssembleLineWorkPlace()
//{
// return AssembleLineWorkPlace(true);
//}
///// <summary>
///// Retrieves the Cart for the session, optionally forcing it to
///// be created if it does not already exist.
///// <param name="forceCreate">Create the shopping cart if it does not exist.</param>
///// </summary>
//public MeasureContent AssembleLineWorkPlace(bool forceCreate)
//{
// //
// // Try to get the cart from the Session
// //
// MeasureContent returnValue = (MeasureContent)(Session[KEY_CACHEASSEMBLELINEWORKPLACE]);
// if (null == returnValue)
// {
// //
// // If there is no cart, create it now
// //
// returnValue = new MeasureContent();
// //
// // Save it for later
// //
// Session.Add(KEY_CACHEASSEMBLELINEWORKPLACE, returnValue);
// }
// if (forceCreate) returnValue.EnsureWritable();
// return returnValue;
//}
///// <summary>
///// Retrieves the Cart for the session, forcing it to be created
///// if it does not already exist.
///// </summary>
//public MeasureContent WorkPlaceMeasurePart()
//{
// return WorkPlaceMeasurePart(true);
//}
///// <summary>
///// Retrieves the Cart for the session, optionally forcing it to
///// be created if it does not already exist.
///// <param name="forceCreate">Create the shopping cart if it does not exist.</param>
///// </summary>
//public MeasureContent WorkPlaceMeasurePart(bool forceCreate)
//{
// //
// // Try to get the cart from the Session
// //
// MeasureContent returnValue = (MeasureContent)(Session[KEY_CACHEWORKPLACEMEASUREPART]);
// if (null == returnValue)
// {
// //
// // If there is no cart, create it now
// //
// returnValue = new MeasureContent();
// //
// // Save it for later
// //
// Session.Add(KEY_CACHEWORKPLACEMEASUREPART, returnValue);
// }
// if (forceCreate) returnValue.EnsureWritable();
// return returnValue;
//}
///// <summary>
///// Retrieves the Cart for the session, forcing it to be created
///// if it does not already exist.
///// </summary>
//public MeasureContent WorkPlaceMeasurePartContent()
//{
// return WorkPlaceMeasurePartContent(true);
//}
///// <summary>
///// Retrieves the Cart for the session, optionally forcing it to
///// be created if it does not already exist.
///// <param name="forceCreate">Create the shopping cart if it does not exist.</param>
///// </summary>
//public MeasureContent WorkPlaceMeasurePartContent(bool forceCreate)
//{
// //
// // Try to get the cart from the Session
// //
// MeasureContent returnValue = (MeasureContent)(Session[KEY_CACHEWORKPLACEMEASUREPARTCONTENT]);
// if (null == returnValue)
// {
// //
// // If there is no cart, create it now
// //
// returnValue = new MeasureContent();
// //
// // Save it for later
// //
// Session.Add(KEY_CACHEWORKPLACEMEASUREPARTCONTENT, returnValue);
// }
// if (forceCreate) returnValue.EnsureWritable();
// return returnValue;
//}
protected override void OnError(EventArgs e)
{
//ApplicationLog.WriteError(ApplicationLog.FormatException(Server.GetLastError(), UNHANDLED_EXCEPTION));
base.OnError(e);
}
}
}

79
App_code/QualityData2.cs Normal file
View File

@@ -0,0 +1,79 @@
#region MES_SPC, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null
// F:\项目文件备份\15.潍柴\MES_Manage\Bin\MES_SPC.dll
// Decompiled with ICSharpCode.Decompiler 8.1.1.7464
#endregion
using System;
using System.Data;
using System.Data.SqlClient;
using DataLinkMesWork;
using MES_SPC;
namespace MES_SPC2
{
public class QualityData2
{
public static void GetQualityDataEveryOpNameDataListTable_Trend(string startTime, string endTime, bool EngineTypeIDCheck, string EngineTypeID, bool EnginIDCheck, string EnginID, bool OPNameCheck, string OPName, bool shaftNameCheck, string shaftName, bool itemNameCheck, string itemName, int isOK, string uuidCheck,string uuid , int PageCurrent, int PageSize, out int PageCount, out int ItemCount, out DataTable dt)
{
dt = null;
PageCount = 0;
ItemCount = 0;
string procedureName = "[质量数据_发动机质量数据_各个工位_视图_综合查询_趋势图_LLJ]";
SqlParameter[] sqlParameters = new SqlParameter[16]
{
new SqlParameter("@开始时间", startTime),
new SqlParameter("@结束时间", endTime),
new SqlParameter("@发动机型号代码_ischeck", EngineTypeIDCheck),
new SqlParameter("@发动机型号代码", EngineTypeID),
new SqlParameter("@工位号_ischeck", OPNameCheck),
new SqlParameter("@工位号", OPName),
new SqlParameter("@测量位置_ischeck", shaftNameCheck),
new SqlParameter("@测量位置", shaftName),
new SqlParameter("@测量项目_ischeck", itemNameCheck),
new SqlParameter("@测量项目", itemName),
new SqlParameter("@导入编号_ischeck", uuidCheck),
new SqlParameter("@导入编号", uuid),
new SqlParameter("@PageCurrent", PageCurrent),
new SqlParameter("@PageSize", PageSize),
new SqlParameter("@PageCount", PageCount),
new SqlParameter("@ItemCount", ItemCount)
};
//sqlParameters[14].Direction = ParameterDirection.Output;
//sqlParameters[15].Direction = ParameterDirection.Output;
string errorMessage;
SQLCommon.ExecuteStoredProcedure(procedureName, ApplicationConfiguration.ERP_ConnectionString, ref sqlParameters, out dt, out errorMessage);
}
public static void SelectGoodDataReport_TrendPictureBasic(bool EnginIDCheck, string EnginID, bool OPNameCheck, string OPName, bool shaftNameCheck, string shaftName, bool itemNameCheck, string itemName, string startTime, string endTime, string uuidCheck, string uuid, out DataTable dt)
{
try
{
string procedureName = "质量数据查询_综合查询_绘趋势图";
DateTime dateTime = DateTime.Parse(startTime);
DateTime dateTime2 = DateTime.Parse(endTime);
SqlParameter[] sqlParameters = new SqlParameter[10]
{
new SqlParameter("@发动机号_ischeck", EnginIDCheck),
new SqlParameter("@发动机号", EnginID),
new SqlParameter("@工位号_ischeck", OPNameCheck),
new SqlParameter("@工位号", OPName),
new SqlParameter("@测量位置_ischeck", shaftNameCheck),
new SqlParameter("@测量位置", shaftName),
new SqlParameter("@测量项目_ischeck", itemNameCheck),
new SqlParameter("@测量项目", itemName),
//new SqlParameter("@导入编号_ischeck", uuidCheck),
//new SqlParameter("@导入编号", uuid),
new SqlParameter("@开始时间", dateTime),
new SqlParameter("@结束时间", dateTime2)
};
string errorMessage;
SQLCommon.ExecuteStoredProcedure(procedureName, ApplicationConfiguration.ERP_ConnectionString, ref sqlParameters, out dt, out errorMessage);
}
catch
{
dt = null;
}
}
}
}

139
App_code/SendGPRS.cs Normal file
View File

@@ -0,0 +1,139 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using ChatClient;
/// <summary>
///SendGPRS 的摘要说明
/// </summary>
public static class SendGPRS
{
private static string GPRShead = "GPRS|WEB|";
/// <summary>
///1.通断器实时数据查询
///命令格式CXTD|通断器编号||
/// </summary>
/// <param name="CJQ"></param>
/// <param name="TQC"></param>
public static void SendGPRS_CXTD(string CJQ,string TDQ)
{
//"GPRS|WEB|0001|CXTD|0002|!";
string command = GPRShead + CJQ + "|" + "CXTD|" + TDQ + "||!";
webChatClient.sentmessage(command);
}
/// <summary>
//2、 热量表实时数据查询
//命令格式CXRB|热量表类型|热量表编号|
/// </summary>
public static void SendGPRS_CXRB(string CJQ, string RLBtype, string RLB)
{
string command = GPRShead + CJQ +"|" + "CXRB|" + RLBtype + "|" + RLB + "|!";
webChatClient.sentmessage(command);
}
/// <summary>
//3、 中心统一校时命令
//命令格式TIME|采集器编号|时间(20130805171824)|
/// </summary>
public static void SendGPRS_TIME(string CJQ)
{
string time = System.DateTime.Now.ToString("yyyyMMddHHmmss");
string command = GPRShead + CJQ + "|" + "TIME|" + CJQ + "|" + time + "|!";
webChatClient.sentmessage(command);
}
/// <summary>
//4,强制关断阀门
//命令格式QZGD|通断器编号|ON/OFF|!
//GPRS收到后回传格式QZGD |通断器编号|OK|
/// </summary>
public static void SendGPRS_QZGD(string CJQ, string TDQ, string ONorOFF)
{
string command = GPRShead + CJQ +"|" + "QZGD|" + TDQ+"|" + ONorOFF + "|!";
webChatClient.sentmessage(command);
}
/// <summary>
//5、 设定用户温度 0005 0105
//命令格式TEMP|通断器编号|温度|!
//GPRS收到后回传格式TEMP |通断器编号|OK|
/// </summary>
public static void SendGPRS_TEMP(string CJQ, string TDQ, string WD)
{
if (WD.Length == 1)
{
WD = "0" + WD;
}
string command = GPRShead +CJQ + "|" + "TEMP|" + TDQ +"|"+WD+ "|!";
webChatClient.sentmessage(command);
}
/// <summary>
//7、 遥控器设温使能 00/01
//命令格式YKSN|通断器编号|遥控器不可以控制/遥控器可以控制|!
//GPRS收到后回传格式YKSN|通断器编号|OK|
/// </summary>
public static void SendGPRS_TEMPControl(string CJQ, string TDQ, string ONOFF)
{
if (ONOFF == "ON")
{
ONOFF = "01";
}
else
{
ONOFF = "00";
}
string command = GPRShead + CJQ + "|" + "YKSN|" + TDQ + "|" + ONOFF + "|!";
webChatClient.sentmessage(command);
}
/// <summary>
//6、 配置面积信息
//命令格式AREA|通断器编号|面积|
//GPRS收到后回传格式AREA|通断器编号|OK|
/// </summary>
public static void SendGPRS_AREA(string CJQ, string TDQ, string AREA)
{
string command = GPRShead + CJQ +"|" + "AREA|" + TDQ + "|" + AREA + "|!";
webChatClient.sentmessage(command);
}
/// <summary>
///7 供暖启停
/// 命令格式GNQT|采集器编号| ON/OFF|
///GPRS收到后回传格式GNQT|采集器编号|OK|
/// </summary>
public static void SendGPRS_GNQT(string CJQ,string ONOFF)
{
string command = GPRShead + CJQ + "|" + "GNQT|" + CJQ + "|" + ONOFF + "|!";
webChatClient.sentmessage(command);
}
/// <summary>
///8更换热表
/// 命令格式GHRB|旧热表编号|新热表编号|
///GPRS收到后回传格式GHRB |新热表编号|OK|
/// </summary>
public static void SendGPRS_GHRB(string CJQ, string OldNum, string NewNum, string newtype)
{
string command = GPRShead + CJQ + "|" + "GHRB|" + OldNum + "|" + newtype+"+" + NewNum + "|!";
webChatClient.sentmessage(command);
}
/// <summary>
///9更换通断
/// 命令格式GHTD|旧通断编号|新通断编号|
///GPRS收到后回传格式GHTD |新通断编号|OK|
/// </summary>
public static void SendGPRS_GHTD(string CJQ, string OldNum, string NewNum)
{
string command = GPRShead + CJQ + "|" + "GHTD|" + OldNum + "|" + NewNum + "|!";
webChatClient.sentmessage(command);
}
}

View File

@@ -0,0 +1,86 @@
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using System.Net.Sockets;
namespace ChatClient
{
class TcpClientConnector
{
/// <summary>
/// 在指定时间内尝试连接指定主机上的指定端口。
/// </summary>
/// <param name="hostname">要连接到的远程主机的 DNS 名。</param>
/// <param name="port">要连接到的远程主机的端口号。</param>
/// <param name="millisecondsTimeout">要等待的毫秒数,或 -1 表示无限期等待。</param>
/// <returns>已连接的一个 TcpClient 实例。</returns>
/// <remarks>本方法可能抛出的异常与 TcpClient 的构造函数重载之一
/// public TcpClient(string, int) 相同,并若指定的等待时间是个负数且不等于
/// -1将会抛出 ArgumentOutOfRangeException。</remarks>
public static TcpClient Connect(string hostname, int port, int millisecondsTimeout)
{
ConnectorState cs = new ConnectorState();
cs.Hostname = hostname;
cs.Port = port;
ThreadPool.QueueUserWorkItem(new WaitCallback(ConnectThreaded), cs);
if (cs.Completed.WaitOne(millisecondsTimeout, false))
{
if (cs.TcpClient != null) return cs.TcpClient;
throw cs.Exception;
}
else
{
cs.Abort();
throw new SocketException(11001); // cannot connect
}
}
private static void ConnectThreaded(object state)
{
ConnectorState cs = (ConnectorState)state;
cs.Thread = Thread.CurrentThread;
try
{
TcpClient tc = new TcpClient(cs.Hostname, cs.Port);
if (cs.Aborted)
{
try { tc.GetStream().Close(); }
catch { }
try { tc.Close(); }
catch { }
}
else
{
cs.TcpClient = tc;
cs.Completed.Set();
}
}
catch (Exception e)
{
cs.Exception = e;
cs.Completed.Set();
}
}
private class ConnectorState
{
public string Hostname;
public int Port;
public volatile Thread Thread;
public readonly ManualResetEvent Completed = new ManualResetEvent(false);
public volatile TcpClient TcpClient;
public volatile Exception Exception;
public volatile bool Aborted;
public void Abort()
{
if (Aborted != true)
{
Aborted = true;
try { Thread.Abort(); }
catch { }
}
}
}
}
}

View File

@@ -0,0 +1,623 @@
using System;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Web.UI.DataVisualization.Charting;
using System.Collections;
namespace System.Web.UI.DataVisualization.Charting.Utilities
{
/// <summary>
/// .
/// </summary>
public class ChartDataTableHelper
{
#region Members
protected System.Web.UI.DataVisualization.Charting.Chart ChartObj = null;
protected ArrayList ChartAreas = null;
protected bool AddTableTotals = false;
protected System.Drawing.Color tableColor = Color.White;
protected System.Drawing.Color borderColor = Color.Black;
protected bool enabled = true;
protected bool Initialized = false;
#endregion
#region Properties
/// <summary>
/// Enables or Disables the painting of the Data Table.
/// </summary>
public bool Enabled
{
get
{
return Enabled;
}
set
{
enabled = value;
}
}
/// <summary>
/// Sets or gets the Chart object.
/// </summary>
public System.Web.UI.DataVisualization.Charting.Chart Chart
{
get
{
return ChartObj;
}
set
{
ChartObj = value;
}
}
/// <summary>
/// Sets or gets the Table Color that will be painted.
/// </summary>
public System.Drawing.Color TableColor
{
get
{
return tableColor;
}
set
{
tableColor = value;
}
}
/// <summary>
/// Sets or gets the Table Border Color that will be painted.
/// </summary>
public System.Drawing.Color BorderColor
{
get
{
return borderColor;
}
set
{
borderColor = value;
}
}
#endregion
#region Constructors
/// <summary>
/// Construct a ChartDataTableHelper instance.
/// </summary>
public ChartDataTableHelper()
{
ChartObj = null;
ChartAreas = new ArrayList();
}
/// <summary>
/// Construct a ChartDataTableHelper instance and Initialize all ChartAreas with a table.
/// </summary>
public ChartDataTableHelper(System.Web.UI.DataVisualization.Charting.Chart chartObj)
{
ChartAreas = new ArrayList();
Initialize(chartObj);
}
/// <summary>
/// Construct a ChartDataTableHelper instance and Initialize the specified ChartArea with a table.
/// </summary>
public ChartDataTableHelper(System.Web.UI.DataVisualization.Charting.Chart chartObj, string chartAreaName)
{
ChartAreas = new ArrayList();
Initialize(chartObj, chartAreaName);
}
/// <summary>
/// Construct a ChartDataTableHelper instance, Initialize the specified ChartArea with a table and
/// set a boolean to show or hide total columns.
/// </summary>
public ChartDataTableHelper(System.Web.UI.DataVisualization.Charting.Chart chartObj, string chartAreaName, bool addTableTotals)
{
ChartAreas = new ArrayList();
Initialize(chartObj, chartAreaName, addTableTotals);
}
#endregion
#region Initialization Methods
/// <summary>
/// Initialize all ChartAreas with a table.
/// </summary>
public void Initialize(System.Web.UI.DataVisualization.Charting.Chart chartObj)
{
ChartObj = chartObj;
foreach(ChartArea area in ChartObj.ChartAreas)
{
AddDataTable(area.Name);
}
if(!Initialized)
ChartObj.PostPaint +=new EventHandler<ChartPaintEventArgs>(this.Chart_PostPaint);
Initialized = true;
}
/// <summary>
/// Initialize all ChartAreas with a table and
/// set a boolean to show or hide total columns.
/// </summary>
public void Initialize(System.Web.UI.DataVisualization.Charting.Chart chartObj, bool addTableTotals)
{
AddTableTotals = addTableTotals;
Initialize(chartObj);
}
/// <summary>
/// Initialize the specified ChartArea with a table.
/// </summary>
public void Initialize(System.Web.UI.DataVisualization.Charting.Chart chartObj, string chartAreaName)
{
ChartObj = chartObj;
AddDataTable(chartAreaName);
if(!Initialized)
ChartObj.PostPaint +=new EventHandler<ChartPaintEventArgs>(this.Chart_PostPaint);
Initialized = true;
}
/// <summary>
/// Initialize the specified ChartArea with a table and
/// set a boolean to show or hide total columns.
/// </summary>
public void Initialize(System.Web.UI.DataVisualization.Charting.Chart chartObj, string chartAreaName, bool addTableTotals)
{
ChartObj = chartObj;
AddTableTotals = addTableTotals;
AddDataTable(chartAreaName);
if(!Initialized)
ChartObj.PostPaint +=new EventHandler<ChartPaintEventArgs>(this.Chart_PostPaint);
Initialized = true;
}
/// <summary>
/// Initialize the specified ChartArea with a table.
/// </summary>
public void AddDataTable(string chartAreaName)
{
if(ChartObj == null || ChartAreas.IndexOf(chartAreaName) >= 0)
return;
// add this chart area to the list of chart areas that need to
// have a data table attached
ChartAreas.Add(chartAreaName);
int Row = 0;
if(AddTableTotals)
{
// create a dummy series that will not be shown but is used for
// showing the totals in the data table
ChartObj.Series.Add("DUMMY");
ChartObj.Series["DUMMY"].ChartArea = chartAreaName;
ChartObj.Series["DUMMY"].Enabled = false;
ChartObj.Series["DUMMY"].Color = Color.Gainsboro;
}
// for each of the series that are attached to this
// named chart area, create a custom axis label.
// All tables lines will be drawn on a paint event.
// ****************************************************
// NOTE: ALL SERIES MUST HAVE THE SAME NUMBER OF POINTS!
// ****************************************************
foreach(Series ser in ChartObj.Series)
{
if(chartAreaName == ser.ChartArea)
{
if(AddTableTotals)
{
// shadows must be turned off otherwise
// they will still show up for the transparent points
ser.ShadowOffset = 0;
// adjust the series values to ensure they are not
// indexed and they are sorted... plus adding each point
// to make the dummy series data
AdjustXValues(ser);
}
Row++;
double From = 0.0;
double To = 0.0;
bool firstPoint = true;
double YValueTotal = 0;
foreach(DataPoint dp in ser.Points)
{
if(AddTableTotals)
YValueTotal += dp.YValues[0];
if(firstPoint && dp.XValue == 0)
From = 0.5;
else if(firstPoint)
From = dp.XValue - 0.5;
if(firstPoint)
{
ChartObj.ChartAreas[chartAreaName].AxisX.Minimum = From;
ChartObj.ChartAreas[chartAreaName].AxisX.MajorGrid.Interval = 1;
ChartObj.ChartAreas[chartAreaName].AxisX.MajorTickMark.Interval = 1;
ChartObj.ChartAreas[chartAreaName].AxisX.LabelStyle.Interval = 1;
ChartObj.ChartAreas[chartAreaName].AxisX.MajorGrid.IntervalOffset = 0.5;
ChartObj.ChartAreas[chartAreaName].AxisX.MajorTickMark.IntervalOffset = 0.5;
ChartObj.ChartAreas[chartAreaName].AxisX.LabelStyle.IntervalOffset = 0.5;
}
To = From + 1;
ChartObj.ChartAreas[chartAreaName].AxisX.CustomLabels.Add(
From, To,
" ", // space used as a placeholder
Row, LabelMarkStyle.None, GridTickTypes.None
);
firstPoint = false;
From += 1;
}
if(AddTableTotals)
ser.Points[ser.Points.Count-1].YValues[0] = YValueTotal;
ChartObj.ChartAreas[chartAreaName].AxisX.Maximum = To;
}
}
if(AddTableTotals)
AdjustYMaximum(chartAreaName);
}
/// <summary>
/// With the addition of Totals, the chart will try to set the maximum
/// values according to these totals. This will cause some series to be
/// barely visible. Since the points are transparent this is a poor behavior.
/// This method will find and explicitly set the YAxis maximum to something
/// a little more with the user expectations.
/// </summary>
private void AdjustYMaximum(string chartAreaName)
{
double MaxYValue = 0;
// find the max YValue from all points in all series
foreach(Series ser in ChartObj.Series)
{
if(chartAreaName == ser.ChartArea && ser.Enabled)
{
// check agains all points except the last point
// which is the totals column
for(int index = 0; index < ser.Points.Count-1; index++)
{
DataPoint pt = ser.Points[index];
if(pt.YValues[0] > MaxYValue)
MaxYValue = pt.YValues[0];
}
}
}
double LogValue = (int)(Math.Log10(MaxYValue)) + 1;
double NewMaxYValue = Math.Pow(10, LogValue);
double ratio = MaxYValue / NewMaxYValue;
double divisor = 1;
if(ratio <= 0.1)
divisor = 10;
else if(ratio < 0.2)
divisor = 5;
else if(ratio < 0.25)
divisor = 4;
else if(ratio < 0.4)
divisor = 2.5;
else if(ratio < 0.5)
divisor = 2;
else if(ratio < 0.8)
divisor = 1.25;
ChartObj.ChartAreas[chartAreaName].AxisY.Maximum = NewMaxYValue / divisor;
ChartObj.ChartAreas[chartAreaName].AxisY.RoundAxisValues();
}
/// <summary>
/// A cleanup method that ensures the XValues are sorted accordingly and set explicitly.
/// It will also create the totals for the DUMMY series.
/// </summary>
private void AdjustXValues(System.Web.UI.DataVisualization.Charting.Series series)
{
bool AddDummyPoints = true;
if(series.Name == "DUMMY")
return;
else if(ChartObj.Series["DUMMY"].Points.Count > 0)
AddDummyPoints = false;
// sort the series
series.Sort(PointSortOrder.Ascending, "X");
bool IsIndexed = false;
if(series.IsXValueIndexed)
IsIndexed = true;
else
{
bool IsFirstPoint = true;
bool IsLastPointZero = false;
// the series X values must be set and greater than zero
foreach(DataPoint pt in series.Points)
{
if(pt.XValue == 0 && !IsFirstPoint && IsLastPointZero)
{
IsIndexed = true;
break;
}
else if (pt.XValue == 0 && IsFirstPoint)
IsLastPointZero = true;
IsFirstPoint = false;
}
}
if(IsIndexed)
{
series.IsXValueIndexed = false;
int XValue = 0;
foreach(DataPoint pt in series.Points)
pt.XValue = ++XValue;
}
series.Points.AddXY(series.Points[series.Points.Count-1].XValue + 1, 0);
series.Points[series.Points.Count-1].AxisLabel = "Total";
series.Points[series.Points.Count-1].Color = Color.Transparent;
series.Points[series.Points.Count-1].BorderColor = Color.Transparent;
int index = 0;
foreach(DataPoint pt in series.Points)
{
if(AddDummyPoints)
{
ChartObj.Series["DUMMY"].Points.AddXY(pt.XValue, pt.YValues[0]);
}
else
{
ChartObj.Series["DUMMY"].Points[index].YValues[0] += pt.YValues[0];
}
index++;
}
}
#endregion
#region Remove Table
public void RemoveDataTable(string chartAreaName)
{
if (ChartObj.ChartAreas.IndexOf(chartAreaName) >= 0)
ChartObj.ChartAreas[chartAreaName].AxisX.CustomLabels.Clear();
if(ChartAreas.IndexOf(chartAreaName) >= 0)
{
ChartAreas.RemoveAt(ChartAreas.IndexOf(chartAreaName));
}
}
#endregion
#region Paint Event Handling
/// <summary>
/// Chart Paint event handler.
/// </summary>
private void Chart_PostPaint(object sender, System.Web.UI.DataVisualization.Charting.ChartPaintEventArgs e)
{
if( e.ChartElement is ChartArea )
{
ChartArea area = (ChartArea)e.ChartElement;
// call the paint method.
if(ChartAreas.IndexOf(area.Name) >= 0 && enabled)
{
PaintDataTable(sender, e);
}
}
}
/// <summary>
/// This method does all the work for the painting of the data table.
/// </summary>
private void PaintDataTable(object sender, System.Web.UI.DataVisualization.Charting.ChartPaintEventArgs e)
{
ChartArea area = (ChartArea)e.ChartElement;
// get the rect of the chart area
RectangleF rect = e.ChartGraphics.GetAbsoluteRectangle( area.Position.ToRectangleF() );
// get the inner plot position
ElementPosition elemPos = area.InnerPlotPosition;
// find the coordinates of the inner plot position
float x = rect.X + (rect.Width / 100 * elemPos.X);
float y = rect.Y + (rect.Height / 100 * elemPos.Y);
float ChartAreaBottomY = rect.Y + rect.Height;
float width = (rect.Width / 100 * elemPos.Width);
float height = (rect.Height / 100 * elemPos.Height);
// find the height of the font that will be used
Font axisFont = area.AxisX.LabelStyle.Font;
string testString = "ForFontHeight";
SizeF axisFontSize = e.ChartGraphics.Graphics.MeasureString(testString, axisFont);
// find the height of the font that will be used
Font titleFont = area.AxisX.TitleFont;
testString = area.AxisX.Title;
SizeF titleFontSize = e.ChartGraphics.Graphics.MeasureString(testString, titleFont);
int seriesCount = 0;
// for each series that is attached to the chart area,
// draw some boxes around the labels in the color provided
for(int i = e.Chart.Series.Count-1; i >= 0; i--)
{
if(area.Name == e.Chart.Series[i].ChartArea)
{
seriesCount++;
}
}
// now, if a box was actually drawn, then draw
// the verticle lines to separate the columns of the table.
if(seriesCount > 0)
{
for(int i = 0; i < e.Chart.Series.Count; i++)
{
if(area.Name == e.Chart.Series[i].ChartArea)
{
double min = area.AxisX.Minimum;
double max = area.AxisX.Maximum;
// modify the min value for the current axis view
if(area.AxisX.ScaleView.Position-1 > min)
min = area.AxisX.ScaleView.Position-1;
// modify the max value for the currect axis view
if( (area.AxisX.ScaleView.Position + area.AxisX.ScaleView.Size + 0.5) < max)
max = area.AxisX.ScaleView.Position + area.AxisX.ScaleView.Size + 0.5;
// find the starting point that will be display.
// this is dependent on the current axis view.
// this sample assumes the same number of points in each
// series so always take from the zeroth series
int pointIndex = 0;
foreach(DataPoint pt in ChartObj.Series[0].Points)
{
if(pt.XValue > min)
break;
pointIndex++;
}
bool TableLegendDrawn = false;
for(double AxisValue = min; AxisValue < max; AxisValue++)
{
float pixelX = (float)e.ChartGraphics.GetPositionFromAxis(area.Name, AxisName.X, AxisValue);
float nextPixelX = (float)e.ChartGraphics.GetPositionFromAxis(area.Name, AxisName.X, AxisValue + 1);
float pixelY = ChartAreaBottomY - titleFontSize.Height - (seriesCount * axisFontSize.Height);
PointF point1 = PointF.Empty;
PointF point2 = PointF.Empty;
// Set Maximum and minimum points
point1.X = pixelX;
point1.Y = 0;
// Convert relative coordinates to absolute coordinates.
point1 = e.ChartGraphics.GetAbsolutePoint(point1);
point2.X = point1.X;
point2.Y = ChartAreaBottomY - titleFontSize.Height;
point1.Y = pixelY;
// Draw connection line
e.ChartGraphics.Graphics.DrawLine(new Pen(borderColor), point1,point2);
point2.X = nextPixelX;
point2.Y = 0;
point2 = e.ChartGraphics.GetAbsolutePoint(point2);
StringFormat format = new StringFormat();
format.Alignment = StringAlignment.Center;
format.LineAlignment = StringAlignment.Center;
// for each series draw one value in the column
int row = 0;
foreach(Series ser in ChartObj.Series)
{
if(area.Name == ser.ChartArea)
{
if(!TableLegendDrawn)
{
// draw the series color box
e.ChartGraphics.Graphics.FillRectangle(new SolidBrush(ser.Color),
x-10, row*(axisFont.Height)+(point1.Y), 10, axisFontSize.Height);
e.ChartGraphics.Graphics.DrawRectangle(new Pen(borderColor),
x-10, row*(axisFont.Height)+(point1.Y), 10, axisFontSize.Height);
e.ChartGraphics.Graphics.FillRectangle(new SolidBrush(tableColor),
x,
row*(axisFont.Height)+(point1.Y),
width,
axisFontSize.Height);
e.ChartGraphics.Graphics.DrawRectangle(new Pen(borderColor),
x,
row*(axisFont.Height)+(point1.Y),
width,
axisFontSize.Height);
}
if(pointIndex < ser.Points.Count)
{
string label = ser.Points[pointIndex].YValues[0].ToString();
RectangleF textRect = new RectangleF(point1.X, row*(axisFont.Height)+(point1.Y+1), point2.X-point1.X, axisFont.Height);
e.ChartGraphics.Graphics.DrawString(label, axisFont, new SolidBrush(area.AxisX.LabelStyle.ForeColor), textRect, format);
}
row++;
}
}
TableLegendDrawn = true;
pointIndex++;
}
// do this only once so break!
break;
}
}
}
}
#endregion
}
}

Binary file not shown.

View File

@@ -0,0 +1,258 @@
using System;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Web.UI.DataVisualization.Charting;
using System.Collections;
namespace System.Web.UI.DataVisualization.Charting.Utilities
{
/// <summary>
/// Helper class that creates a histogram chart. Histogram is a data
/// distribution chart which shows how many values, from the data series,
/// are inside each segment interval.
///
/// You can define how many intervals you want to have using the SegmentIntervalNumber
/// field or the exact length of the interval using the SegmentIntervalWidth
/// field. Actual segment interval number can be slightly different due
/// to the automatic interval rounding.
/// </summary>
public class HistogramChartHelper
{
#region Fields
/// <summary>
/// Number of class intervals the data range is devided in.
/// This property only has affect when "SegmentIntervalWidth" is
/// set to double.NaN.
/// </summary>
public int SegmentIntervalNumber = 20;
/// <summary>
/// Histogram class interval width. Setting this value to "double.NaN"
/// will result in automatic width calculation based on the data range
/// and number of required interval specified in "SegmentIntervalNumber".
/// </summary>
public double SegmentIntervalWidth = double.NaN;
/// <summary>
/// Indicates that percent frequency should be shown on the right axis
/// </summary>
public bool ShowPercentOnSecondaryYAxis = true;
#endregion // Fields
#region Methods
/// <summary>
/// Creates a histogram chart.
/// </summary>
/// <param name="chartControl">Chart control reference.</param>
/// <param name="dataSeriesName">Name of the series which stores the original data.</param>
/// <param name="histogramSeriesName">Name of the histogram series.</param>
public void CreateHistogram(
Chart chartControl,
string dataSeriesName,
string histogramSeriesName)
{
// Validate input
if (chartControl == null)
{
throw (new ArgumentNullException("chartControl"));
}
if (chartControl.Series.IndexOf(dataSeriesName) < 0)
{
throw (new ArgumentException("Series with name'" + dataSeriesName + "' was not found.", "dataSeriesName"));
}
// Make data series invisible
chartControl.Series[dataSeriesName].Enabled = false;
// Check if histogram series exsists
Series histogramSeries = null;
if (chartControl.Series.IndexOf(histogramSeriesName) < 0)
{
// Add new series
histogramSeries = chartControl.Series.Add(histogramSeriesName);
// Set new series chart type and other attributes
histogramSeries.ChartType = SeriesChartType.Column;
histogramSeries.BorderColor = Color.Black;
histogramSeries.BorderWidth = 1;
histogramSeries.BorderDashStyle = ChartDashStyle.Solid;
}
else
{
histogramSeries = chartControl.Series[histogramSeriesName];
histogramSeries.Points.Clear();
}
// Get data series minimum and maximum values
double minValue = double.MaxValue;
double maxValue = double.MinValue;
int pointCount = 0;
foreach (DataPoint dataPoint in chartControl.Series[dataSeriesName].Points)
{
// Process only non-empty data points
if (!dataPoint.IsEmpty)
{
if (dataPoint.YValues[0] > maxValue)
{
maxValue = dataPoint.YValues[0];
}
if (dataPoint.YValues[0] < minValue)
{
minValue = dataPoint.YValues[0];
}
++pointCount;
}
}
// Calculate interval width if it's not set
if (double.IsNaN(this.SegmentIntervalWidth))
{
this.SegmentIntervalWidth = (maxValue - minValue) / SegmentIntervalNumber;
this.SegmentIntervalWidth = RoundInterval(this.SegmentIntervalWidth);
}
// Round minimum and maximum values
minValue = Math.Floor(minValue / this.SegmentIntervalWidth) * this.SegmentIntervalWidth;
maxValue = Math.Ceiling(maxValue / this.SegmentIntervalWidth) * this.SegmentIntervalWidth;
// Create histogram series points
double currentPosition = minValue;
for (currentPosition = minValue; currentPosition <= maxValue; currentPosition += this.SegmentIntervalWidth)
{
// Count all points from data series that are in current interval
int count = 0;
foreach (DataPoint dataPoint in chartControl.Series[dataSeriesName].Points)
{
if (!dataPoint.IsEmpty)
{
double endPosition = currentPosition + this.SegmentIntervalWidth;
if (dataPoint.YValues[0] >= currentPosition &&
dataPoint.YValues[0] < endPosition)
{
++count;
}
// Last segment includes point values on both segment boundaries
else if (endPosition >= maxValue)
{
if (dataPoint.YValues[0] >= currentPosition &&
dataPoint.YValues[0] <= endPosition)
{
++count;
}
}
}
}
// Add data point into the histogram series
histogramSeries.Points.AddXY(currentPosition + this.SegmentIntervalWidth / 2.0, count);
//histogramSeries.Points.AddXY("", count);
//histogramSeries.Points.AddY( count);
}
// Adjust series attributes
histogramSeries["PointWidth"] = "1";
// Adjust chart area
ChartArea chartArea = chartControl.ChartAreas[histogramSeries.ChartArea];
chartArea.AxisY.Title = "ƵÊý";
chartArea.AxisX.Minimum = minValue;
chartArea.AxisX.Maximum = maxValue;
// Set axis interval based on the histogram class interval
// and do not allow more than 10 labels on the axis.
double axisInterval = this.SegmentIntervalWidth;
while ((maxValue - minValue) / axisInterval > 10.0)
{
axisInterval *= 2.0;
}
chartArea.AxisX.Interval = axisInterval;
// Set chart area secondary Y axis
chartArea.AxisY2.Enabled = AxisEnabled.Auto;
if (this.ShowPercentOnSecondaryYAxis)
{
chartArea.RecalculateAxesScale();
chartArea.AxisY2.Enabled = AxisEnabled.True;
chartArea.AxisY2.LabelStyle.Format = "P0";
chartArea.AxisY2.MajorGrid.Enabled = false;
chartArea.AxisY2.Title = "Percent of Total";
chartArea.AxisY2.Minimum = 0;
chartArea.AxisY2.Maximum = chartArea.AxisY.Maximum / (pointCount / 100.0);
double minStep = (chartArea.AxisY2.Maximum > 20.0) ? 5.0 : 1.0;
chartArea.AxisY2.Interval = Math.Ceiling((chartArea.AxisY2.Maximum / 5.0 / minStep)) * minStep;
}
}
/// <summary>
/// Helper method which rounds specified axsi interval.
/// </summary>
/// <param name="interval">Calculated axis interval.</param>
/// <returns>Rounded axis interval.</returns>
public double RoundInterval( double interval )
{
// If the interval is zero return error
if( interval == 0.0 )
{
throw( new ArgumentOutOfRangeException("interval", "Interval can not be zero."));
}
// If the real interval is > 1.0
double step = -1;
double tempValue = interval;
while( tempValue > 1.0 )
{
step ++;
tempValue = tempValue / 10.0;
if( step > 1000 )
{
throw( new InvalidOperationException( "Auto interval error due to invalid point values or axis minimum/maximum." ) );
}
}
// If the real interval is < 1.0
tempValue = interval;
if( tempValue < 1.0 )
{
step = 0;
}
while( tempValue < 1.0 )
{
step --;
tempValue = tempValue * 10.0;
if( step < -1000 )
{
throw( new InvalidOperationException( "Auto interval error due to invalid point values or axis minimum/maximum." ) );
}
}
double tempDiff = interval / Math.Pow( 10.0, step );
if( tempDiff < 3.0 )
{
tempDiff = 2.0;
}
else if( tempDiff < 7.0 )
{
tempDiff = 5.0;
}
else
{
tempDiff = 10.0;
}
// Make a correction of the real interval
return tempDiff * Math.Pow( 10.0, step );
}
#endregion // Methods
}
}

Binary file not shown.

View File

@@ -0,0 +1,326 @@
//=================================================================
// File: FFT.cs
//
// Namespace: System.Web.UI.DataVisualization.Charting.Utilities
//
// Classes: FFT
//
// Purpose: Used for the fast fourier transformation algorithm
//
//===================================================================
// Chart Control for ASP.Net
//===================================================================
using System;
using System.Collections.Generic;
using System.Text;
namespace System.Web.UI.DataVisualization.Charting.Utilities
{
/// <summary>
/// Helper class which implements the various window functions for determination of the filter
/// coefficients.
/// </summary>
class FFT
{
#region Members
/// <summary>
/// Filter type enumeration for identification of what type of filter we want coefficients
/// for.
/// </summary>
public enum FilterType { HighPass, LowPass, BandPass };
/// <summary>
/// Algorithm enumeration for choice of algorithm
/// </summary>
public enum Algorithm { Kaiser, Hann, Hamming, Blackman, Rectangular };
private float myRate;
private float myFreqFrom;
private float myFreqTo;
private float myAttenuation;
private float myBand;
private float myAlpha;
private int myOrder;
/// <summary>
/// Shannon sampling frequency
/// </summary>
private float myFS;
#endregion
#region Properties
/// <summary>
/// Sampling rate
/// </summary>
public float Rate
{
get { return myRate; }
set
{
myRate = value;
myFS = 0.5f * myRate;
}
}
/// <summary>
/// Starting frequency for passband. Must be lower than the ending frequency.
/// </summary>
public float FreqFrom
{
get { return myFreqFrom; }
set { myFreqFrom = value; }
}
/// <summary>
/// Ending frequency for passband. Must be higher than the starting frequency.
/// </summary>
public float FreqTo
{
get { return myFreqTo; }
set { myFreqTo = value; }
}
/// <summary>
/// Stopband attenuation.
/// </summary>
public float StopBandAttenuation
{
get { return myAttenuation; }
set { myAttenuation = value; }
}
/// <summary>
/// Transition band.
/// </summary>
public float TransitionBand
{
get { return myBand; }
set { myBand = value; }
}
/// <summary>
/// Alpha value used for the Kaiser algorithm.
/// </summary>
public float Alpha
{
get { return myAlpha; }
set { myAlpha = value; }
}
/// <summary>
/// Filter order. Must be an even number.
/// </summary>
public int Order
{
get { return myOrder; }
set { myOrder = value; }
}
#endregion
#region Constructors
/// <summary>
/// Construct a FFT instance and initialize with default values.
/// </summary>
public FFT()
{
//default rate to 8000
Rate = 8000;
//default attenuation to 60db
this.myAttenuation = 60;
//default transition band to 500hz
this.myBand = 500;
//default order to 0 so that we'll know if it was changed by the user or not
this.myOrder = 0;
//default Alpha to 4
this.myAlpha = 4;
}
#endregion
#region Mathematical Functions
/// <summary>
/// Bessel is the zeroth order Bessel function which is used in the Kaiser window.
/// This is a polynomial approximation of the zeroth order modified Bessel function found in:
/// W.H. Press, B.P. Flannery, S.A. Teukolsky, and W.T. Vetterling.
/// Numerical Recipes in C: The Art of Scientific Computing.
/// Cambridge UP, 1988.
/// P. 237
/// </summary>
/// <param name="x">Input number which the Bessel will be performed on</param>
private float Bessel(float x)
{
double ax, ans;
double y;
ax = System.Math.Abs(x);
if (ax < 3.75)
{
y = x / 3.75;
y *= y;
ans = 1.0 + y * (3.5156229 + y * (3.0899424 + y * (1.2067492
+ y * (0.2659732 + y * (0.360768e-1 + y * 0.45813e-2)))));
}
else
{
y = 3.75 / ax;
ans = (System.Math.Exp(ax) / System.Math.Sqrt(ax)) * (0.39894228 + y * (0.1328592e-1
+ y * (0.225319e-2 + y * (-0.157565e-2 + y * (0.916281e-2
+ y * (-0.2057706e-1 + y * (0.2635537e-1 + y * (-0.1647633e-1
+ y * 0.392377e-2))))))));
}
return (float)ans;
}
#endregion
#region Generate Coefficients
/// <summary>
/// Calculate the coefficients to be used by the filter function.
/// </summary>
/// <param name="filterType">Enum type which specifies the filter to be performed.</param>
/// <param name="alg">Enum type which specifies which algorithm to be used for the window
/// algorithm.</param>
public float[] GenerateCoefficients(FilterType filterType, Algorithm alg)
{
//Calculate order if it hasn't been set
if (this.myOrder == 0)
this.myOrder = (int)(((this.myAttenuation - 7.95f) / (this.myBand * 14.36f / this.myFS) + 1.0f) * 2.0f) - 1;
float[] window = new float[(this.myOrder / 2) + 1];
float[] coEff = new float[this.myOrder + 1];
float ps;
float pe;
const float PI = (float)System.Math.PI;
int o2 = this.myOrder / 2;
//Switch based on algorithm
switch (alg)
{
case Algorithm.Kaiser:
//Kaiser Window function
for (int i = 1; i <= o2; i++)
{
window[i] = Bessel(this.myAlpha * (float)System.Math.Sqrt(1.0f - (float)System.Math.Pow((float)i / o2, 2))) / Bessel(this.myAlpha);
}
//Stopband attenuation and transition band should be set by the user
break;
case Algorithm.Hann:
//Hann window function
for (int i = 1; i <= o2; i++)
{
window[i] = 0.5f + 0.5f * (float)System.Math.Cos((PI / (o2 + 1)) * i);
}
//Set the min stopband attenuation
this.StopBandAttenuation = 44.0f;
//Set the transition band
this.TransitionBand = 6.22f * this.myFS / this.myOrder;
break;
case Algorithm.Hamming:
//Hamming window function
for (int i = 1; i <= o2; i++)
{
window[i] = 0.54f + 0.46f * (float)System.Math.Cos((PI / o2) * i);
}
//Set the min stopband attenuation
this.StopBandAttenuation = 53.0f;
//Set the transition band
this.TransitionBand = 6.64f * this.myFS / this.myOrder;
break;
case Algorithm.Blackman:
//Blackman window function
for (int i = 1; i <= o2; i++)
{
window[i] = 0.42f + 0.5f * (float)Math.Cos((PI / o2) * i) + 0.08f * (float)Math.Cos(2.0f * (PI / o2) * i);
}
//Set the min stopband attenuation
this.StopBandAttenuation = 74.0f;
//Set the transition band
this.TransitionBand = 11.13f * this.myFS / this.myOrder;
break;
case Algorithm.Rectangular:
//Rectangular window function
for (int i = 1; i <= o2; i++)
{
window[i] = 1.0f;
}
//Set the min stopband attenuation
this.StopBandAttenuation = 21.0f;
//Set the transition band
this.TransitionBand = 1.84f * this.myFS / this.myOrder;
break;
default:
//Zero all values if nothing was set (error)
for (int i = 1; i <= o2; i++)
{
window[i] = 0.0f;
}
break;
}
//Switch based on filtertype
switch (filterType)
{
case FilterType.BandPass:
pe = PI / 2 * (this.FreqTo - this.FreqFrom + this.myBand) / this.myFS;
ps = PI / 2 * (this.FreqFrom + this.FreqTo) / this.myFS;
break;
case FilterType.LowPass:
pe = PI * (this.FreqTo + this.myBand / 2) / this.myFS;
ps = 0.0f;
break;
case FilterType.HighPass:
pe = PI * (1.0f - (this.FreqFrom - this.myBand / 2) / this.myFS);
ps = PI;
break;
default:
pe = 0.0f;
ps = 0.0f;
break;
}
//Set first coefficient value
coEff[0] = pe / PI;
//Calculate coefficientsw
for (int i = 1; i <= o2; i++)
{
coEff[i] = window[i] * (float)System.Math.Sin(i * pe) * (float)System.Math.Cos(i * ps) / (i * PI);
}
//Shift Impulse
for (int i = o2 + 1; i <= this.myOrder; i++)
{
coEff[i] = coEff[i - o2];
}
for (int i = 0; i <= o2 - 1; i++)
{
coEff[i] = coEff[this.myOrder - i];
}
coEff[o2] = pe / PI;
return coEff;
}
#endregion
}
}

View File

@@ -0,0 +1,324 @@
//=================================================================
// File: FIRFilters.cs
//
// Namespace: System.Web.UI.DataVisualization.Charting.Utilities
//
// Classes: FIRFilters, FFT
//
// Purpose: Used to perform digital filters on charts
//
//===================================================================
// Chart Control for ASP.Net
//===================================================================
using System;
using System.Collections.Generic;
using System.Text;
using System.Web.UI.DataVisualization.Charting;
namespace System.Web.UI.DataVisualization.Charting.Utilities
{
/// <summary>
/// Helper class which implements the filtering functions. Currently Low Pass, High Pass and
/// Band Pass are implemented.
/// </summary>
class FIRFilters
{
#region Members
/// <summary>
/// The number of samples is the same as the number of points
/// </summary>
private int mySamples;
/// <summary>
/// Holds the coefficient from the window function
/// </summary>
private float[] myCoeff;
/// <summary>
/// Holds the series which has the input data
/// </summary>
private Series myInputSeries;
/// <summary>
/// Holds the series which we are outputting to
/// </summary>
private Series myFilterSeries;
/// <summary>
/// FFT algorithm object
/// </summary>
private FFT myFFT;
/// <summary>
/// Holds the current algorithm selected. Enumeration type is drawn from the FFT object.
/// </summary>
public FFT.Algorithm CurrentAlgorithm;
private float myFreqFrom;
private float myFreqTo;
private float myAttenuation;
private float myBand;
private float myAlpha;
private int myTaps;
private int myOrder;
#endregion
#region Properties
/// <summary>
/// The starting passband frequency, must be lower than ending frequency.
/// </summary>
public float FreqFrom
{
get { return myFreqFrom; }
set { myFreqFrom = value; }
}
/// <summary>
/// The ending passband frequency, must be higher than starting frequency.
/// </summary>
public float FreqTo
{
get { return myFreqTo; }
set { myFreqTo = value; }
}
/// <summary>
/// Stopband attenuation
/// </summary>
public float StopBandAttenuation
{
get { return myAttenuation; }
set {
myAttenuation = value;
this.myFFT.StopBandAttenuation = myAttenuation;
}
}
/// <summary>
/// Transition band
/// </summary>
public float TransitionBand
{
get { return myBand; }
set {
myBand = value;
this.myFFT.TransitionBand = myBand;
}
}
/// <summary>
/// Alpha value used for the Kaiser algorithm.
/// </summary>
public float Alpha
{
get { return myAlpha; }
set {
myAlpha = value;
this.myFFT.Alpha = myAlpha;
}
}
/// <summary>
/// Number of taps to be used. Taps is the number of samples processed at any one time.
/// </summary>
public int Taps
{
get { return myTaps; }
set { myTaps = value; }
}
/// <summary>
/// Filter order. Must be an even number.
/// </summary>
public int Order
{
get { return myOrder; }
set
{
//Assure value is even
if ((value % 2) == 0)
{
myOrder = value;
this.myFFT.Order = myOrder;
}
else
throw new ArgumentOutOfRangeException("Order", "Filter order must be an even number.");
}
}
#endregion
#region Constructors
/// <summary>
/// Main constructor. Resets all settings within the FFT algorithm object.
/// </summary>
public FIRFilters()
{
//Create a new FFT object
this.myFFT = new FFT();
//Default algorithm to Kaiser
this.CurrentAlgorithm = FFT.Algorithm.Kaiser;
//Default taps to 35
this.myTaps = 35;
}
#endregion
#region Methods
/// <summary>
/// Performs a low pass filter. Output series will be cleared before being
/// output to. If passband start and end frequencies are left at 0, defaults are used.
/// </summary>
/// <param name="iseries">Input series that contains input data. Input Y-Values must be contained in YValues[0] or unexpected output will occur</param>
/// <param name="oseries">Output series to which filter will be written. Output Y-Values are written to YValues[0]</param>
public void LowPassFilter(Series iseries, Series oseries)
{
//If no start and end frequencies are specified, default low pass frequency range to:
//0 - 1000hz
if (this.myFreqFrom == 0.0f && this.myFreqTo == 0.0f)
{
this.myFFT.FreqFrom = 0.0f;
this.myFFT.FreqTo = 1000.0f;
}
else
{
this.myFFT.FreqFrom = this.myFreqFrom;
this.myFFT.FreqTo = this.myFreqTo;
}
//Generate the actual coefficients
this.myCoeff = this.myFFT.GenerateCoefficients(FFT.FilterType.LowPass, CurrentAlgorithm);
//Filter the series based on the coefficients generated
Filter(iseries, oseries);
}
/// <summary>
/// Performs a high pass filter. Output series will be cleared before being
/// output to. If passband start and end frequencies are left at 0, defaults are used.
/// </summary>
/// <param name="iseries">Input series that contains input data. Input Y-Values must be contained in YValues[0] or unexpected output will occur</param>
/// <param name="oseries">Output series to which filter will be written. Output Y-Values are written to YValues[0]</param>
public void HighPassFilter(Series iseries, Series oseries)
{
//If no start and end frequencies are specified, default high pass frequency range to:
//2000 - 4000hz
if (this.myFreqFrom == 0.0f && this.myFreqTo == 0.0f)
{
this.myFFT.FreqFrom = 2000.0f;
this.myFFT.FreqTo = 4000.0f;
}
else
{
this.myFFT.FreqFrom = this.myFreqFrom;
this.myFFT.FreqTo = this.myFreqTo;
}
//Generate the actual coefficients
this.myCoeff = this.myFFT.GenerateCoefficients(FFT.FilterType.HighPass, CurrentAlgorithm);
//Filter the series based on the coefficients generated
Filter(iseries, oseries);
}
/// <summary>
/// Performs a band pass filter. Output series will be cleared before being
/// output to. If passband start and end frequencies are left at 0, defaults are used.
/// </summary>
/// <param name="iseries">Input series that contains input data. Input Y-Values must be contained in YValues[0] or unexpected output will occur</param>
/// <param name="oseries">Output series to which filter will be written. Output Y-Values are written to YValues[0]</param>
public void BandPassFilter(Series iseries, Series oseries)
{
//If no start and end frequencies are specified, default band pass frequency range to:
//1000 - 1000hz
if (this.myFreqFrom == 0.0f && this.myFreqTo == 0.0f)
{
this.myFFT.FreqFrom = 1000.0f;
this.myFFT.FreqTo = 1000.0f;
}
else
{
this.myFFT.FreqFrom = this.myFreqFrom;
this.myFFT.FreqTo = this.myFreqTo;
}
//Generate the actual coefficients
this.myCoeff = this.myFFT.GenerateCoefficients(FFT.FilterType.BandPass, CurrentAlgorithm);
//Filter the series based on the coefficients generated
Filter(iseries, oseries);
}
#endregion
#region Initialization
/// <summary>
/// Initializes the FIRFilters object by setting the input and output series members for use
/// by the filter.
/// </summary>
/// <param name="iseries">Input series that contains input data</param>
/// <param name="oseries">Output series to which filter will be written</param>
private void SetIOSeries(Series iseries, Series oseries)
{
this.myInputSeries = iseries;
this.myFilterSeries = oseries;
//Samples is the number of points contained in the input
this.mySamples = myInputSeries.Points.Count;
}
#endregion
#region Filter
/// <summary>
/// Performs the actual filter. Coefficients should have already be generated by the calling
/// function, this function merely applies them and physically adds the points to the output series.
/// </summary>
/// <param name="iseries">Input series that contains input data</param>
/// <param name="oseries">Output series to which filter will be written</param>
private void Filter(Series iseries, Series oseries)
{
float[] x = new float[myTaps];
float y;
//Set the series
SetIOSeries(iseries, oseries);
//Clear series
myFilterSeries.Points.Clear();
//Initialize x
for (int i = 1; i < myTaps; i++)
x[i] = 0.0f;
//Loop through every data point
for (int i = 0; i < mySamples; i++)
{
//Initialize y
y = 0.0f;
//Obtain the data value (Y value) at the specified X value (i)
x[0] = Convert.ToSingle(myInputSeries.Points[i].YValues[0]);
//Loop through from 0 to number of taps and calculate the sum
try
{
for (int j = 0; j < myTaps; j++)
y = y + (x[j] * myCoeff[j]);
}
catch (Exception e)
{
System.Diagnostics.Debug.WriteLine(e.Message + " Check filter order.");
throw;
}
//Shift all x values by 1 to the right
for (int j = myTaps - 1; j > 0; j--)
x[j] = x[j - 1];
//Add the y value to the output series at the current x value
myFilterSeries.Points.Add(new System.Web.UI.DataVisualization.Charting.DataPoint(i, y));
}
}
#endregion
}
}

Binary file not shown.

View File

@@ -0,0 +1,372 @@
using System;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Web.UI.DataVisualization.Charting;
using System.Collections;
namespace System.Web.UI.DataVisualization.Charting.Utilities
{
/// <summary>
/// Helper class which improves the readability of the small segments in the Pie chart.
/// Pie segments which are too small are shown in a supplemental pie chart series.
/// </summary>
public class PieCollectedDataHelper
{
#region Fields
/// <summary>
/// Specifies the percentage of the total series values. This value determines
/// if the data point value is a "small" value and should be shown as collected.
/// </summary>
public double CollectedPercentage = 5.0;
/// <summary>
/// Position in relative coordinates ( 0,0 - top left corner; 100,100 - bottom right corner)
/// where original and supplemental pie charts should be placed.
/// </summary>
public RectangleF ChartAreaPosition = new RectangleF(5f, 5f, 90f, 90f);
/// <summary>
/// Indicates if small segments should be shown as one "collected" segment in the original series
/// </summary>
public bool ShowCollectedDataAsOneSlice = false;
/// <summary>
/// Spacing between the original and supplemental chart areas in percentage
/// </summary>
public float ChartAreaSpacing = 5f;
/// <summary>
/// Size ratio between the original and supplemental chart areas.
/// Value of 1.0f indicates that same area size will be used.
/// </summary>
public float SupplementedAreaSizeRatio = 0.9f;
/// <summary>
/// Color of the connection lines
/// </summary>
public Color ConnectionLinesColor = Color.FromArgb(64, 64, 64);
/// <summary>
/// Collected pie segment label
/// </summary>
public string CollectedLabel = "Other";
// Reference to the parameters
private Chart chartControl = null;
private Series series = null;
// Internal use fields
private Series supplementalSeries = null;
private ChartArea originalChartArea = null;
private ChartArea supplementalChartArea = null;
private float collectedPieSliceAngle = 0f;
#endregion // Fields
#region Constructor
/// <summary>
/// Public constructor.
/// </summary>
/// <param name="chartControl">Reference to the chart control.</param>
public PieCollectedDataHelper(Chart chartControl)
{
this.chartControl = chartControl;
// Handle chart PostPaint event to draw the "connection" between the
// collected pie slice and supplemental chart.
this.chartControl.PostPaint +=new EventHandler<ChartPaintEventArgs>(this.chart_PostPaint);
}
#endregion // Constructor
#region Methods
/// <summary>
/// Shows small pie segments as supplemental pie chart series in the new chart area.
/// </summary>
/// <param name="seriesName">Series name </param>
public void ShowSmallSegmentsAsSupplementalPie(string seriesName)
{
// Validate input
if(this.chartControl == null)
{
throw(new ArgumentNullException("chartControl"));
}
if(this.CollectedPercentage > 100.0 || this.CollectedPercentage < 0.0)
{
throw(new ArgumentException("Value must be in range from 0 to 100 percent.", "CollectedPercentage"));
}
// Initialize reference to the series
this.series = this.chartControl.Series[seriesName];
// Check input series type
if(this.series.ChartType != SeriesChartType.Pie &&
this.series.ChartType != SeriesChartType.Doughnut)
{
throw(new InvalidOperationException("Only series with Pie or Doughnut chart type can be used."));
}
// Check if specified series has data points
if(series.Points.Count == 0)
{
throw(new InvalidOperationException("Cannot perform operatiuon on an empty series."));
}
// Create "collected" pie slice in original series
this.supplementalChartArea = null;
if( CreateCollectedPie() )
{
// Calculate width of supplemental chart area
float supplementalWidth = (this.ChartAreaPosition.Width - this.ChartAreaSpacing) / 2f * this.SupplementedAreaSizeRatio;
// Adjust position of the original chart area
this.originalChartArea = this.chartControl.ChartAreas[this.series.ChartArea];
originalChartArea.Position.X = this.ChartAreaPosition.X;
originalChartArea.Position.Y = this.ChartAreaPosition.Y;
originalChartArea.Position.Width = this.ChartAreaPosition.Width - supplementalWidth - this.ChartAreaSpacing;
originalChartArea.Position.Height = this.ChartAreaPosition.Height;
// Original chart area must be in 2D mode
originalChartArea.Area3DStyle.Enable3D = false;
// Create and adjust position of the supplemental chart area
this.supplementalChartArea = new ChartArea();
supplementalChartArea.Name = originalChartArea.Name + "_Supplemental";
supplementalChartArea.Position.X = originalChartArea.Position.Right + this.ChartAreaSpacing;
supplementalChartArea.Position.Y = this.ChartAreaPosition.Y;
supplementalChartArea.Position.Width = supplementalWidth;
supplementalChartArea.Position.Height = this.ChartAreaPosition.Height;
this.chartControl.ChartAreas.Add(supplementalChartArea);
// Create supplemental pie chart series to show all the collected data
this.supplementalSeries.Name = this.series.Name + "_Supplemental";
this.supplementalSeries.ChartArea = supplementalChartArea.Name;
this.chartControl.Series.Add(supplementalSeries);
// Copy some attributes from the original chart area
supplementalChartArea.BackColor = originalChartArea.BackColor;
supplementalChartArea.BorderColor = originalChartArea.BorderColor;
supplementalChartArea.BorderWidth = originalChartArea.BorderWidth;
supplementalChartArea.ShadowOffset = originalChartArea.ShadowOffset;
// Copy some attributes from the original series
this.supplementalSeries.ChartType = this.series.ChartType;
this.supplementalSeries.Palette = this.series.Palette;
this.supplementalSeries.ShadowOffset = this.series.ShadowOffset;
this.supplementalSeries.BorderColor = this.series.BorderColor;
this.supplementalSeries.BorderWidth = this.series.BorderWidth;
this.supplementalSeries.IsValueShownAsLabel = this.series.IsValueShownAsLabel;
this.supplementalSeries.LabelBackColor = this.series.LabelBackColor;
this.supplementalSeries.LabelBorderColor = this.series.LabelBorderColor;
this.supplementalSeries.LabelBorderWidth = this.series.LabelBorderWidth;
this.supplementalSeries.LabelFormat = this.series.LabelFormat;
this.supplementalSeries.Font = this.series.Font;
}
}
/// <summary>
/// Creates the "collected" pie slice data point by re moving and accumulating all
/// the values of the data points which values are less then specified percentage.
/// </summary>
/// <returns>True if collected pie slice was created.</returns>
private bool CreateCollectedPie()
{
// Create supplemental series
this.supplementalSeries = new Series();
// Calculate total vale of all point in series
double total = 0.0;
foreach(DataPoint dataPoint in this.series.Points)
{
total += Math.Abs(dataPoint.YValues[0]);
}
// Count how many data points will be presented as collected
double minValue = total / 100.0 * this.CollectedPercentage;
int collectedPointsCount = 0;
for(int index = 0; index < this.series.Points.Count; index++)
{
double pointValue = Math.Abs(this.series.Points[index].YValues[0]);
if(pointValue <= minValue)
{
++collectedPointsCount;
}
}
// Do not collect data points if one or less points left in the original series
if( (this.series.Points.Count - collectedPointsCount) <= 1 ||
collectedPointsCount <= 1)
{
return false;
}
// Add Collected data point into series before applying palette colors
DataPoint colectedDataPoint = null;
if(this.ShowCollectedDataAsOneSlice)
{
colectedDataPoint = new DataPoint(this.series);
this.series.Points.Add(colectedDataPoint);
}
// Apply pallete colors to series to save same data point colors
// in supplemental series.
this.chartControl.ApplyPaletteColors();
foreach(DataPoint dataPoint in this.series.Points)
{
// Setting data point color to itself will clear the internal flag which
// indicates that point color should be taken from the palette again when
// control is rendered next time.
dataPoint.Color = dataPoint.Color;
}
// Remove points which value is less than specified percentage from total
double collectedValue = 0.0;
for(int index = 0; index < this.series.Points.Count; index++)
{
double pointValue = Math.Abs(this.series.Points[index].YValues[0]);
if(pointValue <= minValue &&
this.series.Points[index] != colectedDataPoint)
{
// Add point value to the collected value
collectedValue += pointValue;
// Add point to supplemental series
this.supplementalSeries.Points.Add(this.series.Points[index].Clone());
// Remove point from the series
this.series.Points.RemoveAt(index);
--index;
}
}
// Add all collected data points at the end of the series
if(!ShowCollectedDataAsOneSlice)
{
foreach(DataPoint dataPoint in this.supplementalSeries.Points)
{
DataPoint dataPointCollected = dataPoint.Clone();
dataPoint.IsVisibleInLegend = false;
this.series.Points.Add(dataPointCollected);
// Disable labels in collected slices
dataPointCollected.Label = String.Empty;
dataPointCollected.LegendText = dataPointCollected.AxisLabel;
dataPointCollected.AxisLabel = String.Empty;
dataPointCollected.IsValueShownAsLabel = false;
}
}
// Check if we need to add the "collected" data point
if(collectedValue > 0.0)
{
// Set collected data point value and other attributes
if(this.ShowCollectedDataAsOneSlice)
{
colectedDataPoint.YValues[0] = collectedValue;
colectedDataPoint.Label = this.CollectedLabel;
colectedDataPoint.IsVisibleInLegend = false;
// Note: Collected data point may be exploded
//colectedDataPoint["Exploded"] = "true";
}
// Calculate collected pie slice angle
this.collectedPieSliceAngle = (float) ( (360f / 100f) * (collectedValue / (total / 100) ) );
// Adjust the Pie chart start angle, so that the middle of the
// collected slice looks directly at 3 o'clock.
int startAngle = (int)Math.Round(this.collectedPieSliceAngle / 2.0);
this.series["PieStartAngle"] = startAngle.ToString();
return true;
}
else if(colectedDataPoint != null)
{
// Remove collected data point
this.series.Points.Remove(colectedDataPoint);
}
return false;
}
/// <summary>
/// Chart post paint event handler.
/// Used to draw the "connection" lines between the original and supplemental pies.
/// </summary>
/// <param name="sender">Event sender.</param>
/// <param name="e">Event arguments.</param>
private void chart_PostPaint(object sender, System.Web.UI.DataVisualization.Charting.ChartPaintEventArgs e)
{
if(sender is ChartArea)
{
ChartArea area = (ChartArea)sender;
if(this.supplementalChartArea != null &&
area.Name == this.supplementalChartArea.Name)
{
// Get position of the plotting areas in pixels
RectangleF originalPosition = GetChartAreaPlottingPosition(this.originalChartArea, e.ChartGraphics);
RectangleF supplementalPosition = GetChartAreaPlottingPosition(this.supplementalChartArea, e.ChartGraphics);
// Get coordinates of the "connection" lines
PointF p1 = GetRotatedPlotAreaPoint(supplementalPosition, 325f);
PointF p2 = GetRotatedPlotAreaPoint(supplementalPosition, 215f);
PointF p3 = GetRotatedPlotAreaPoint(originalPosition, 90f - this.collectedPieSliceAngle / 2f);
PointF p4 = GetRotatedPlotAreaPoint(originalPosition, 90f + this.collectedPieSliceAngle / 2f);
// Draw "connection lines"
using( Pen pen = new Pen(this.ConnectionLinesColor, 1) )
{
e.ChartGraphics.Graphics.DrawLine(pen, p1, p3);
e.ChartGraphics.Graphics.DrawLine(pen, p2, p4);
}
}
}
}
/// <summary>
/// Helper method which calculates a point on the edje of the pie chart using
/// specified angle.
/// </summary>
/// <param name="areaPosition">Chart are position in pixels.</param>
/// <param name="angle">Point angle in degrees.</param>
/// <returns>Point location in pixels.</returns>
private PointF GetRotatedPlotAreaPoint(RectangleF areaPosition, float angle)
{
PointF[] points = new PointF[1];
points[0] = new PointF(areaPosition.X + areaPosition.Width / 2f, areaPosition.Y);
using( Matrix transformMatrix = new Matrix() )
{
transformMatrix.RotateAt(angle, new PointF(
areaPosition.X + areaPosition.Width / 2f,
areaPosition.Y + areaPosition.Height / 2f) );
transformMatrix.TransformPoints(points);
}
return points[0];
}
/// <summary>
/// Helper method which calculates chart area plotting position in pixels.
/// </summary>
/// <param name="area">Chart area to get the plotting area position.</param>
/// <param name="chartGraphics">Chart graphics object.</param>
/// <returns>Chart area ploting area position in pixels.</returns>
private RectangleF GetChartAreaPlottingPosition(ChartArea area, ChartGraphics chartGraphics)
{
RectangleF plottingRect = area.Position.ToRectangleF();
plottingRect.X += (area.Position.Width / 100F) * area.InnerPlotPosition.X;
plottingRect.Y += (area.Position.Height / 100F) * area.InnerPlotPosition.Y;
plottingRect.Width = (area.Position.Width / 100F) * area.InnerPlotPosition.Width;
plottingRect.Height = (area.Position.Height / 100F) * area.InnerPlotPosition.Height;
plottingRect = chartGraphics.GetAbsoluteRectangle(plottingRect);
return plottingRect;
}
#endregion // Methods
}
}

Binary file not shown.

File diff suppressed because it is too large Load Diff

View File

Binary file not shown.

View File

@@ -0,0 +1,187 @@
//=================================================================
// File: SpikeRemoval.cs
//
// Namespace: System.Web.UI.DataVisualization.Charting.Utilities
//
// Classes: SpikeRemoval
//
// Purpose: Removes spikes from data
//
//
//===================================================================
// Chart Control for ASP.Net
// Copyright ?Microsoft Corporation, all rights reserved
//===================================================================
using System;
using System.Data;
using System.Configuration;
using System.Drawing;
using System.Web.UI.DataVisualization.Charting;
namespace System.Web.UI.DataVisualization.Charting.Utilities
{
/// <summary>
/// Spike removal is a utility used to remove high and low spikes from a graph. This means that the
/// chart axis scaling will be changed so that data that was difficult to see and analyze will be easier
/// to see after anomaly spikes have been removed.
/// </summary>
public class SpikeRemoval
{
#region Members
private bool mySetCutoffLabels;
private MarkerStyle myRemovedPointStyle;
private float myMaximum;
private float myMinimum;
#endregion
#region Properties
/// <summary>
/// Sets whether or not labels are set on each cut off point. If they are, they will show up on the chart and provide
/// extra clarification if the tooltip is not enough.
/// </summary>
public bool SetCutoffLabels
{
get { return mySetCutoffLabels; }
set { mySetCutoffLabels = value; }
}
/// <summary>
/// Holds the style that is used for the marker of any deleted points.
/// </summary>
public MarkerStyle RemovedPointStyle
{
get { return myRemovedPointStyle; }
set { myRemovedPointStyle = value; }
}
/// <summary>
/// Contains the maximum value of the data after it has had the spikes removed. This value also has
/// the tolerance factored in.
/// </summary>
public float Maximum
{
get { return myMaximum; }
}
/// <summary>
/// Contains the minimum value of the data after it has had the spikes removed. This value also has
/// the tolerance factored in.
/// </summary>
public float Minimum
{
get { return myMinimum; }
}
#endregion
#region Constructors
/// <summary>
/// Default Constructor.
/// </summary>
public SpikeRemoval()
{
//Default removed point style to a diamond.
myRemovedPointStyle = MarkerStyle.Diamond;
//Default labels to off.
mySetCutoffLabels = false;
}
#endregion
#region Public Methods
/// <summary>
/// RemoveSpikes will remove the high and low spikes off of a graph. The data within the series
/// provided will be modified, and for best results, the chart containing it should have axis
/// scaled automatically.
/// </summary>
/// <param name="dataseries">The series which contains the data to be analyzed and modified. It is assumed that
/// Y-values are contained in YValues[0]. Cases contrary to this will produce unexpected results.</param>
/// <param name="range">The percentage range of data to be kept. Anything that lies outside of the range
/// will be considered a spike.</param>
/// <param name="tolerance">The percentage a spike can be outside of the range but still included. The percentage
/// is based on the maximum or minimum value in the range.</param>
public void RemoveSpikes(Series dataseries, int range, int tolerance)
{
//Assure range and tolerance are a percentage.
//Range is more strict in that at least 1% of the data must be included in the range, whereas it is
//possible to have 0% tolerance.
if ((range < 1 || range > 100))
throw new ArgumentOutOfRangeException("range", "Range must be a percentage between 1 and 100");
if ((tolerance < 0 || tolerance > 100))
throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be a percentage between 0 and 100");
//Data values and indices hold the y values and the indices of the points in arrays.
float[] datavalues = new float[dataseries.Points.Count];
int[] indices = new int[dataseries.Points.Count];
//Percent and number hold the actual values calculated from the range.
float percent = 0.0f;
int number = 0;
//Copy all y values into an array and store the indices.
for (int i = 0; i < dataseries.Points.Count; i++)
{
datavalues[i] = (float)dataseries.Points[i].YValues[0];
indices[i] = i;
}
//Sort the array and indices.
Array.Sort(datavalues, indices);
//Calculate the percent that has to come off each side of the data.
//ie. With a range of 80%, 20% of the data is being cut off, and 10% is coming off each side.
percent = ((100 - (float)range) / 2) / 100;
//Calculate the actual number of points coming off of each side.
//ie. With a percent of 10% and 100 data points, 10 points are coming off of each side.
number = (int)System.Math.Round(dataseries.Points.Count * percent, 0);
//Set the maximum and minimum values.
myMinimum = (float)(dataseries.Points[indices[number]].YValues[0] - System.Math.Abs(dataseries.Points[indices[number]].YValues[0] * (((float)tolerance / 100))));
myMaximum = (float)(dataseries.Points[indices[dataseries.Points.Count - number - 1]].YValues[0] + System.Math.Abs(dataseries.Points[indices[dataseries.Points.Count - number - 1]].YValues[0] * (((float)tolerance / 100))));
//Cut the low spikes off.
for (int i = 0; i < number; i++)
{
//Don't cut the spike if it's within the tolerance value.
if (dataseries.Points[indices[i]].YValues[0] < (myMinimum))
{
//Assign the tooltip to the point
dataseries.Points[indices[i]].ToolTip = "Value: " + dataseries.Points[indices[i]].YValues[0];
//Assign the label to the point
if (mySetCutoffLabels)
dataseries.Points[indices[i]].Label = "Value: " + dataseries.Points[indices[i]].YValues[0];
//Reassign the value to the minimum number allowed
dataseries.Points[indices[i]].YValues[0] = myMinimum;
//Set the marker point
dataseries.Points[indices[i]].MarkerStyle = myRemovedPointStyle;
}
}
//Cut the high spikes off.
for (int i = dataseries.Points.Count - number; i < dataseries.Points.Count; i++)
{
//Don't cut the spike if it's within the tolerance value.
if (dataseries.Points[indices[i]].YValues[0] > (myMaximum))
{
//Assign the tooltip to the point
dataseries.Points[indices[i]].ToolTip = "Value: " + dataseries.Points[indices[i]].YValues[0];
//Assign the label to the point
if (mySetCutoffLabels)
dataseries.Points[indices[i]].Label = "Value: " + dataseries.Points[indices[i]].YValues[0];
//Reassign the value to the maximum number allowed
dataseries.Points[indices[i]].YValues[0] = myMaximum;
//Set the marker point
dataseries.Points[indices[i]].MarkerStyle = myRemovedPointStyle;
}
}
}
#endregion
}
}

Binary file not shown.

View File

0
App_code/_system~.ini Normal file
View File

View File

@@ -0,0 +1,144 @@
using System;
using System.Drawing;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using System.Web.UI.DataVisualization.Charting;
/// <summary>
///CalculateData 的摘要说明
/// </summary>
public class CalculateData
{
public CalculateData()
{
//
//TODO: 在此处添加构造函数逻辑
//
}
/// <summary>
/// 观测值最大值
/// </summary>
/// <param name="Xn">子组观测值</param>
/// <returns></returns>
static private double Max(double[] Xn)
{
double temp;
temp = Xn[0];
for (int i = 0; i < Xn.Length; i++)
{
temp = (Xn[i] > temp) ? Xn[i] : temp;
}
return temp;
}
/// <summary>
/// 观测值最小值
/// </summary>
/// <param name="Xn">子组观测值</param>
/// <returns></returns>
static private double Min(double[] Xn)
{
double temp;
temp = Xn[0];
for (int i = 0; i < Xn.Length; i++)
{
temp = (Xn[i] < temp) ? Xn[i] : temp;
}
return temp;
}
/// <summary>
/// 计算X在区间[ValueDownValueUp]的数量
/// </summary>
/// <param name="X"></param>
/// <param name="GroupCount"></param>
/// <param name="ValueDown"></param>
/// <param name="ValueUp"></param>
/// <param name="Yk"></param>
static private void SumRang(double[] X, int GroupCount, double[] ValueDown, double[] ValueUp, out double[] Yk, out double[] YkCount)
{
int temp = 0;
//总数量
int allCount = 0;
Yk = new double[GroupCount];
YkCount = new double[GroupCount];
for (int j = 0; j < GroupCount - 1; j++)
{
temp = 0;
for (int i = 0; i < X.Length; i++)
{
if (X[i] >= ValueDown[j] & X[i] < ValueUp[j])
{
temp = temp + 1;
allCount++;
}
}
Yk[j] = temp;
}
for (int i = 0; i < X.Length; i++)
{
if (X[i] >= ValueDown[GroupCount - 1] & X[i] <= ValueUp[GroupCount - 1])
{
temp = temp + 1;
allCount++;
}
}
Yk[GroupCount - 1] = temp;
for (int i = 0; i < Yk.Length; i++)
{
YkCount[i] = Yk[i];
Yk[i] = Yk[i] / (double)allCount * 100;
}
}
public static void DataPareto(double[] Data,int GroupCount)
{
Spc_Data_Pareto m_Spc_Data_Pareto = new Spc_Data_Pareto();
//数组最大值
double minValue = Min(Data);
//数组最小值
double maxValue = Max(Data);
//X轴刻度
double XSpan = (maxValue - minValue) / GroupCount;
//X轴下刻度线
double[] XSpanDown = new double[GroupCount];
//X轴上刻度线
double[] XSpanUp = new double[GroupCount];
double[] Yk=new double[GroupCount];
XSpanDown[0] = minValue;
XSpanUp[0] = minValue + XSpan;
for (int i = 1; i < GroupCount; i++)
{
XSpanDown[i] = minValue + i * XSpan;
XSpanUp[i] = minValue + (i + 1) * XSpan;
}
//数据在区间数组的数量
SumRang(Data, GroupCount, XSpanDown, XSpanUp, out Yk, out m_Spc_Data_Pareto.YCount);
for (int i = 0; i < GroupCount; i++)
{
if (i == 0)
{
m_Spc_Data_Pareto.AxisX[i] = minValue + XSpan / 2;
}
else
{
m_Spc_Data_Pareto.AxisX[i] = minValue + XSpan;
}
}
}
}
/// <summary>
/// 排列图数据
/// </summary>
public class Spc_Data_Pareto
{
//X轴数据
public double[] AxisX;
//所有数据在X轴各范围内的数量
public double[] YCount;
}

View File

@@ -0,0 +1,225 @@
using System;
using System.Drawing;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using System.Web.UI.DataVisualization.Charting;
using System.Data.SqlClient;
using System.Web.UI.DataVisualization.Charting.Utilities;
/// <summary>
///DrawChart 的摘要说明
/// </summary>
public partial class DrawChart
{
/// <summary>
/// 排列图
/// </summary>
/// <param name="X"></param>
/// <param name="chart1"></param>
public static void ChartQualityData_Pareto(double[] X,Chart chart1)
{
int n=8;
chart1.Series["RawData"].Points.DataBindY(X);
DrawPareto drawPareto = new DrawPareto();
drawPareto.SegmentIntervalNumber = n;
drawPareto.ShowPercentOnSecondaryYAxis = false;
drawPareto.CreatePareto(chart1, "RawData", "Histogram");
drawPareto.MakeParetoChart(chart1, "Histogram", "Pareto");
// Set chart types for output data
chart1.Series["Pareto"].ChartType = SeriesChartType.Line;
// set the markers for each point of the Pareto Line
chart1.Series["Pareto"].IsValueShownAsLabel = true;
chart1.Series["Pareto"].MarkerColor = Color.Red;
chart1.Series["Pareto"].MarkerBorderColor = Color.MidnightBlue;
chart1.Series["Pareto"].MarkerStyle = MarkerStyle.Circle;
chart1.Series["Pareto"].MarkerSize = 6;
chart1.Series["Pareto"].LabelFormat = "0.#"; // format with one decimal and leading zero
// Set Color of line Pareto chart
chart1.Series["Pareto"].Color = Color.FromArgb(252, 180, 65);
}
/// <summary>
/// 直方图
/// </summary>
/// <param name="X"></param>
/// <param name="chart1"></param>
public static void ChartQualityData_Histogram(double[] X, Chart chart1)
{
int n = 8;
chart1.Series["RawData"].Points.DataBindY(X);
// Populate single axis data distribution series. Show Y value of the
// data series as X value and set all Y values to 1.
foreach (DataPoint dataPoint in chart1.Series["RawData"].Points)
{
chart1.Series["DataDistribution"].Points.AddXY(dataPoint.YValues[0], 1);
}
// Create a histogram series
HistogramChartHelper histogramHelper = new HistogramChartHelper();
histogramHelper.SegmentIntervalNumber = n;
histogramHelper.ShowPercentOnSecondaryYAxis = false;
// NOTE: Interval width may be specified instead of interval number
//histogramHelper.SegmentIntervalWidth = 15;
histogramHelper.CreateHistogram(chart1, "RawData", "Histogram");
}
/// <summary>
/// 分析正态分布图
/// </summary>
/// <param name="X">被分析数据组</param>
/// <param name="Usl">理论上限</param>
/// <param name="Lsl">理论下限</param>
/// <param name="chart1"></param>
public static void ChartQualityData_NormalDistribution(double[] X, double Usl, double Lsl, Chart chart1)
{
double x;
double s;
double QU;
double QL;
double cp;
double cpk;
double[] sx;
double[] sy;
double ValueUp = Max(X);
double ValueDown = Min(X);
//计算SPC参数
SpcCaculator.SpcValue(X, ref Usl, ref Lsl, out x, out s, out QU, out QL, out cp, out cpk, out sx, out sy);
//坐标轴
double ValueUpX = Convert.ToDouble(Max(sx).ToString("F4"));
double ValueDownX = Convert.ToDouble(Min(sx).ToString("F4"));
double ValueUpY = Convert.ToDouble(Max(sy).ToString("F4"));
ValueDownX = Math.Min(ValueDownX, Lsl);
ValueDownX = Math.Min(ValueDownX, QL);
ValueUpX = Math.Max(ValueUpX, Usl);
ValueUpX = Math.Max(ValueUpX, QU);
double X1 = (ValueUpX - ValueDownX) / 10;
chart1.ChartAreas["ChartArea1"].AxisX.Minimum = Math.Round(ValueDownX - X1, 4);
chart1.ChartAreas["ChartArea1"].AxisX.Maximum = Math.Round(ValueUpX + X1, 4);
chart1.ChartAreas["ChartArea1"].AxisY.Minimum = 0;
chart1.ChartAreas["ChartArea1"].AxisY.Maximum = Math.Round(ValueUpY + ValueUpY / 10, 4);
//绘图正态分布曲线(共取了11个点)
for (int i = 0; i < sx.Length; i++)
{
chart1.Series[0].Points.AddXY(Math.Round(sx[i], 4), Math.Round(sy[i], 4));
}
chart1.ChartAreas["ChartArea1"].AxisX.StripLines[1].IntervalOffset = sx[5];
chart1.ChartAreas["ChartArea1"].AxisX.StripLines[1].Text = "SL=" + sx[5].ToString("F4");
chart1.ChartAreas["ChartArea1"].AxisX.StripLines[2].IntervalOffset = Usl;
chart1.ChartAreas["ChartArea1"].AxisX.StripLines[2].Text = "USL=" + Usl.ToString("F4");
chart1.ChartAreas["ChartArea1"].AxisX.StripLines[3].IntervalOffset = Lsl;
chart1.ChartAreas["ChartArea1"].AxisX.StripLines[3].Text = "LSL=" + Lsl.ToString("F4");
chart1.ChartAreas["ChartArea1"].AxisX.StripLines[4].IntervalOffset = QL;
chart1.ChartAreas["ChartArea1"].AxisX.StripLines[4].Text = "QL=" + QL.ToString("F4");
chart1.ChartAreas["ChartArea1"].AxisX.StripLines[5].IntervalOffset = QU;
chart1.ChartAreas["ChartArea1"].AxisX.StripLines[5].Text = "QU=" + QU.ToString("F4");
//将CpCpk绘制到图形中
DarwCpCpk(chart1, cp, cpk);
//TextAnnotation annotation3;
//annotation3 = new TextAnnotation();
//annotation3.Text = "Cp=" + cp.ToString("F2");
//annotation3.ForeColor = Color.Black;
//annotation3.Font = new Font("Arial", 11); ;
//annotation3.X = 60;
//annotation3.Y = 90;
//chart1.Annotations.Add(annotation3);
//annotation3 = new TextAnnotation();
//annotation3.Text = "Cpk=" + cpk.ToString("F2");
//annotation3.ForeColor = Color.Black;
//annotation3.Font = new Font("Arial", 11); ;
//annotation3.X = 80;
//annotation3.Y = 90;
//chart1.Annotations.Add(annotation3);
}
/// <summary>
/// SPC分析基本趋势图
/// </summary>
/// <param name="dt"></param>
/// <param name="chart1"></param>
public static void ChartQualityData_TrendPictureBasic_new(DataTable dt, double Usl, double Lsl, Chart chart1)
{
double x;
double s;
double QU;
double QL;
double cp;
double cpk;
double[] sx;
double[] sy;
double[] X;
if (dt.Rows.Count < 3) return;
X = new double[dt.Rows.Count];
for (int i = 0; i < dt.Rows.Count; i++)
{
X[i] = Convert.ToDouble(dt.Rows[i][0]);
}
double ValueUp = Max(X);
double ValueDown = Min(X);
//计算SPC参数
SpcCaculator.SpcValue(X, ref Usl, ref Lsl, out x, out s, out QU, out QL, out cp, out cpk, out sx, out sy);
//坐标轴
double ValueUpX;
double ValueDownX;
ValueDownX = Math.Min(ValueDown, Lsl);
ValueDownX = Math.Min(ValueDownX, QL);
ValueUpX = Math.Max(ValueUp, Usl);
ValueUpX = Math.Max(ValueUpX, QU);
double X1 = (ValueUpX - ValueDownX) / 10;
chart1.ChartAreas["ChartArea1"].AxisY.Minimum = Math.Round(ValueDownX - X1, 4);
chart1.ChartAreas["ChartArea1"].AxisY.Maximum = Math.Round(ValueUpX + X1, 4);
chart1.ChartAreas["ChartArea1"].AxisY.StripLines[1].IntervalOffset = sx[5];
chart1.ChartAreas["ChartArea1"].AxisY.StripLines[1].Text = "SL=" + sx[5].ToString("F4");
chart1.ChartAreas["ChartArea1"].AxisY.StripLines[2].IntervalOffset = Usl;
chart1.ChartAreas["ChartArea1"].AxisY.StripLines[2].Text = "USL=" + Usl.ToString("F4");
chart1.ChartAreas["ChartArea1"].AxisY.StripLines[3].IntervalOffset = Lsl;
chart1.ChartAreas["ChartArea1"].AxisY.StripLines[3].Text = "LSL=" + Lsl.ToString("F4");
chart1.ChartAreas["ChartArea1"].AxisY.StripLines[4].IntervalOffset = QU;
chart1.ChartAreas["ChartArea1"].AxisY.StripLines[4].Text = "QU=" + QU.ToString("F4");
chart1.ChartAreas["ChartArea1"].AxisY.StripLines[5].IntervalOffset = QL;
chart1.ChartAreas["ChartArea1"].AxisY.StripLines[5].Text = "QL=" + QL.ToString("F4");
chart1.Series[0].Points.DataBind(dt.DefaultView, "", "测量值", "Tooltip=ToolTip");
//将CpCpk绘制到图形中
DarwCpCpk(chart1, cp, cpk);
}
/// <summary>
/// 将CpCpk绘制到图形中
/// </summary>
/// <param name="chart1"></param>
/// <param name="cp"></param>
/// <param name="cpk"></param>
static private void DarwCpCpk(Chart chart1,double cp,double cpk)
{
TextAnnotation annotation;
annotation = (TextAnnotation)chart1.Annotations["TextAnnotationCp"];
annotation.Text = "Cp=" + cp.ToString("F2");
annotation = (TextAnnotation)chart1.Annotations["TextAnnotationCpk"];
annotation.Text = "Cpk=" + cpk.ToString("F2");
}
}

View File

@@ -0,0 +1,787 @@
using System;
using System.Drawing;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using System.Web.UI.DataVisualization.Charting;
using System.Data.SqlClient;
/// <summary>
///DrawChart 的摘要说明
/// </summary>
public partial class DrawChart
{
public static void ChartQualityData_Pareto(DataTable dt,int n, Chart chart1)
{
chart1.Series["RawData"].Points.DataBindY(dt.Rows, "测量值");
DrawPareto drawPareto = new DrawPareto();
drawPareto.SegmentIntervalNumber = n;
drawPareto.ShowPercentOnSecondaryYAxis = false;
drawPareto.CreatePareto(chart1, "RawData", "Histogram");
drawPareto.MakeParetoChart(chart1, "Histogram", "Pareto");
// Set chart types for output data
chart1.Series["Pareto"].ChartType = SeriesChartType.Line;
// set the markers for each point of the Pareto Line
chart1.Series["Pareto"].IsValueShownAsLabel = true;
chart1.Series["Pareto"].MarkerColor = Color.Red;
chart1.Series["Pareto"].MarkerBorderColor = Color.MidnightBlue;
chart1.Series["Pareto"].MarkerStyle = MarkerStyle.Circle;
chart1.Series["Pareto"].MarkerSize = 6;
chart1.Series["Pareto"].LabelFormat = "0.#"; // format with one decimal and leading zero
// Set Color of line Pareto chart
chart1.Series["Pareto"].Color = Color.FromArgb(252, 180, 65);
}
/// <summary>
/// SPC分析正态分布图
/// </summary>
/// <param name="X"></param>
/// <param name="n"></param>
/// <param name="chart1"></param>
public static void ChartQualityData_NormalDistribution(double[] X, int n, Chart chart1)
{
double ValueUp = Max(X);
double ValueDown = Min(X);
//绘图数据
ASPNet_Drawing.CSpc_Data_Cpk Spc_Data_Cpk = ASPNet_Drawing.Spc_Data.Cpk(X, n, ValueUp, ValueDown);
//坐标轴
double ValueUpX = Convert.ToDouble(Max(Spc_Data_Cpk.NormalDistributionX).ToString("F2"));
double ValueDownX = Convert.ToDouble(Min(Spc_Data_Cpk.NormalDistributionX).ToString("F2"));
double ValueUpY = Convert.ToDouble(Max(Spc_Data_Cpk.NormalDistributionY).ToString("F2"));
double X1 = (ValueUpX - ValueDownX) / 10;
chart1.ChartAreas["ChartArea1"].AxisX.Minimum = Math.Round(ValueDownX - X1, 2);
chart1.ChartAreas["ChartArea1"].AxisX.Maximum = Math.Round(ValueUpX + X1, 2);
chart1.ChartAreas["ChartArea1"].AxisY.Minimum = 0;
chart1.ChartAreas["ChartArea1"].AxisY.Maximum = Math.Round(ValueUpY + ValueUpY / 10, 2);
//绘图
for (int i = 0; i < Spc_Data_Cpk.NormalDistributionX.Length; i++)
{
chart1.Series[0].Points.AddXY(Math.Round(Spc_Data_Cpk.NormalDistributionX[i], 2), Math.Round(Spc_Data_Cpk.NormalDistributionY[i], 2));
}
// Set Strip line item
//chart1.ChartAreas["ChartArea1"].AxisX.StripLines[0].IntervalOffset = Spc_Data_Cpk.LSL;
//chart1.ChartAreas["ChartArea1"].AxisX.StripLines[0].StripWidth = Spc_Data_Cpk.USL - Spc_Data_Cpk.LSL;
// Set Strip line item
//double SL = (ValueUpX + ValueDownX) / 2;
//double USL = SL + 3 * Spc_Data_Cpk.Singma;
//double LSL = SL - 3 * Spc_Data_Cpk.Singma;
chart1.ChartAreas["ChartArea1"].AxisX.StripLines[1].IntervalOffset = Spc_Data_Cpk.NormalDistributionX[4];
chart1.ChartAreas["ChartArea1"].AxisX.StripLines[1].Text = "SL=" + Spc_Data_Cpk.NormalDistributionX[4].ToString("F2");
chart1.ChartAreas["ChartArea1"].AxisX.StripLines[2].IntervalOffset = Spc_Data_Cpk.NormalDistributionX[1];
chart1.ChartAreas["ChartArea1"].AxisX.StripLines[2].Text = "USL=" + Spc_Data_Cpk.NormalDistributionX[1].ToString("F2");
chart1.ChartAreas["ChartArea1"].AxisX.StripLines[3].IntervalOffset = Spc_Data_Cpk.NormalDistributionX[7];
chart1.ChartAreas["ChartArea1"].AxisX.StripLines[3].Text = "LSL=" + Spc_Data_Cpk.NormalDistributionX[7].ToString("F2");
//TextAnnotation annotation1 = new TextAnnotation();
//annotation1.Text = "Cpk=" + Spc_Data_Cpk.Cpk.ToString("F2");
//annotation1.ForeColor = Color.Black;
//annotation1.Font = new Font("Arial", 11); ;
//annotation1.X = 80;
//annotation1.Y = 8;
//chart1.Annotations.Add(annotation1);
//TextAnnotation annotation2 = new TextAnnotation();
//annotation2.Text = "CPL=" + Spc_Data_Cpk.CPL.ToString("F2");
//annotation2.ForeColor = Color.Black;
//annotation2.Font = new Font("Arial", 11); ;
//annotation2.X = 80;
//annotation2.Y = 13;
//chart1.Annotations.Add(annotation2);
//TextAnnotation annotation3 = new TextAnnotation();
//annotation3.Text = "CPU=" + Spc_Data_Cpk.CPU.ToString("F2");
//annotation3.ForeColor = Color.Black;
//annotation3.Font = new Font("Arial", 11); ;
//annotation3.X = 80;
//annotation3.Y = 18;
//chart1.Annotations.Add(annotation3);
}
/// <summary>
/// SPC分析工序能力图
/// 在均值级差图中
/// </summary>
/// <param name="X"></param>
/// <param name="n"></param>
/// <param name="chart1"></param>
public static void ChartQualityData_Cpk_XR(double[] X, int n, Chart chart1)
{
double ValueUp = Max(X);
double ValueDown = Min(X);
//绘图数据
ASPNet_Drawing.CSpc_Data_Cpk Spc_Data_Cpk = ASPNet_Drawing.Spc_Data.Cpk(X, n, ValueUp, ValueDown);
//坐标轴
double ValueUpX = Convert.ToDouble(Max(Spc_Data_Cpk.NormalDistributionX).ToString("F2"));
double ValueDownX = Convert.ToDouble(Min(Spc_Data_Cpk.NormalDistributionX).ToString("F2"));
double ValueUpY = Convert.ToDouble(Max(Spc_Data_Cpk.NormalDistributionY).ToString("F2"));
double X1 = (ValueUpX - ValueDownX) / 10;
chart1.ChartAreas["ChartArea_Cpk"].AxisX.Minimum = Math.Round(ValueDownX - X1, 2);
chart1.ChartAreas["ChartArea_Cpk"].AxisX.Maximum = Math.Round(ValueUpX + X1, 2);
chart1.ChartAreas["ChartArea_Cpk"].AxisY.Minimum = 0;
chart1.ChartAreas["ChartArea_Cpk"].AxisY.Maximum = Math.Round(ValueUpY + ValueUpY / 10, 2);
//绘图
for (int i = 0; i < Spc_Data_Cpk.NormalDistributionX.Length; i++)
{
chart1.Series["Series_Cpk"].Points.AddXY(Math.Round(Spc_Data_Cpk.NormalDistributionX[i], 2), Math.Round(Spc_Data_Cpk.NormalDistributionY[i], 2));
}
ASPNet_Drawing.CSpc_Data_XR Spc_Data_XR = ASPNet_Drawing.Spc_Data.XR(X, n);
chart1.ChartAreas["ChartArea_Cpk"].AxisX.StripLines[1].IntervalOffset = Spc_Data_Cpk.NormalDistributionX[4];
chart1.ChartAreas["ChartArea_Cpk"].AxisX.StripLines[1].Text = "SL=" + Spc_Data_XR.CL_X.ToString("F2");
chart1.ChartAreas["ChartArea_Cpk"].AxisX.StripLines[2].IntervalOffset = Spc_Data_Cpk.NormalDistributionX[1];
chart1.ChartAreas["ChartArea_Cpk"].AxisX.StripLines[2].Text = "USL=" + Spc_Data_XR.UCL_X.ToString("F2");
chart1.ChartAreas["ChartArea_Cpk"].AxisX.StripLines[3].IntervalOffset = Spc_Data_Cpk.NormalDistributionX[7];
chart1.ChartAreas["ChartArea_Cpk"].AxisX.StripLines[3].Text = "LSL=" + Spc_Data_XR.LCL_X.ToString("F2");
TextAnnotation annotation1 = new TextAnnotation();
annotation1.Text = "Cpk=" + Spc_Data_Cpk.Cpk.ToString("F2");
annotation1.ForeColor = Color.Black;
annotation1.Font = new Font("Arial", 6); ;
annotation1.X = 27;
annotation1.Y = 3.5;
chart1.Annotations.Add(annotation1);
TextAnnotation annotation2 = new TextAnnotation();
annotation2.Text = "CPL=" + Spc_Data_Cpk.CPL.ToString("F2");
annotation2.ForeColor = Color.Black;
annotation2.Font = new Font("Arial", 6); ;
annotation2.X = 27;
annotation2.Y = 5;
chart1.Annotations.Add(annotation2);
TextAnnotation annotation3 = new TextAnnotation();
annotation3.Text = "CPU=" + Spc_Data_Cpk.CPU.ToString("F2");
annotation3.ForeColor = Color.Black;
annotation3.Font = new Font("Arial", 6); ;
annotation3.X = 27;
annotation3.Y = 6.5;
chart1.Annotations.Add(annotation3);
}
/// <summary>
/// SPC分析工序能力图
/// 在均值标准差图中
/// </summary>
/// <param name="X"></param>
/// <param name="n"></param>
/// <param name="chart1"></param>
public static void ChartQualityData_Cpk_XS(double[] X, int n, Chart chart1)
{
double ValueUp = Max(X);
double ValueDown = Min(X);
//绘图数据
ASPNet_Drawing.CSpc_Data_Cpk Spc_Data_Cpk = ASPNet_Drawing.Spc_Data.Cpk(X, n, ValueUp, ValueDown);
//坐标轴
double ValueUpX = Convert.ToDouble(Max(Spc_Data_Cpk.NormalDistributionX).ToString("F2"));
double ValueDownX = Convert.ToDouble(Min(Spc_Data_Cpk.NormalDistributionX).ToString("F2"));
double ValueUpY = Convert.ToDouble(Max(Spc_Data_Cpk.NormalDistributionY).ToString("F2"));
double X1 = (ValueUpX - ValueDownX) / 10;
chart1.ChartAreas["ChartArea_Cpk"].AxisX.Minimum = Math.Round(ValueDownX - X1, 2);
chart1.ChartAreas["ChartArea_Cpk"].AxisX.Maximum = Math.Round(ValueUpX + X1, 2);
chart1.ChartAreas["ChartArea_Cpk"].AxisY.Minimum = 0;
chart1.ChartAreas["ChartArea_Cpk"].AxisY.Maximum = Math.Round(ValueUpY + ValueUpY / 10, 2);
//绘图
for (int i = 0; i < Spc_Data_Cpk.NormalDistributionX.Length; i++)
{
chart1.Series["Series_Cpk"].Points.AddXY(Math.Round(Spc_Data_Cpk.NormalDistributionX[i], 2), Math.Round(Spc_Data_Cpk.NormalDistributionY[i], 2));
}
ASPNet_Drawing.CSpc_Data_XR Spc_Data_XR = ASPNet_Drawing.Spc_Data.XR(X, n);
chart1.ChartAreas["ChartArea_Cpk"].AxisX.StripLines[1].IntervalOffset = Spc_Data_Cpk.NormalDistributionX[4];
chart1.ChartAreas["ChartArea_Cpk"].AxisX.StripLines[1].Text = "SL=" + Spc_Data_XR.CL_X.ToString("F2");
chart1.ChartAreas["ChartArea_Cpk"].AxisX.StripLines[2].IntervalOffset = Spc_Data_Cpk.NormalDistributionX[1];
chart1.ChartAreas["ChartArea_Cpk"].AxisX.StripLines[2].Text = "USL=" + Spc_Data_XR.UCL_X.ToString("F2");
chart1.ChartAreas["ChartArea_Cpk"].AxisX.StripLines[3].IntervalOffset = Spc_Data_Cpk.NormalDistributionX[7];
chart1.ChartAreas["ChartArea_Cpk"].AxisX.StripLines[3].Text = "LSL=" + Spc_Data_XR.LCL_X.ToString("F2");
TextAnnotation annotation1 = new TextAnnotation();
annotation1.Text = "Cpk=" + Spc_Data_Cpk.Cpk.ToString("F2");
annotation1.ForeColor = Color.Black;
annotation1.Font = new Font("Arial", 6); ;
annotation1.X = 27;
annotation1.Y = 3.5;
chart1.Annotations.Add(annotation1);
TextAnnotation annotation2 = new TextAnnotation();
annotation2.Text = "CPL=" + Spc_Data_Cpk.CPL.ToString("F2");
annotation2.ForeColor = Color.Black;
annotation2.Font = new Font("Arial", 6); ;
annotation2.X = 27;
annotation2.Y = 5;
chart1.Annotations.Add(annotation2);
TextAnnotation annotation3 = new TextAnnotation();
annotation3.Text = "CPU=" + Spc_Data_Cpk.CPU.ToString("F2");
annotation3.ForeColor = Color.Black;
annotation3.Font = new Font("Arial", 6); ;
annotation3.X = 27;
annotation3.Y = 6.5;
chart1.Annotations.Add(annotation3);
}
/// <summary>
/// SPC分析工序能力图
/// </summary>
/// <param name="X"></param>
/// <param name="n"></param>
/// <param name="chart1"></param>
public static void ChartQualityData_Cpk(double[] X, int n, Chart chart1)
{
double ValueUp = Max(X);
double ValueDown = Min(X);
//绘图数据
ASPNet_Drawing.CSpc_Data_Cpk Spc_Data_Cpk = ASPNet_Drawing.Spc_Data.Cpk(X, n, ValueUp, ValueDown);
//坐标轴
double ValueUpX = Convert.ToDouble(Max(Spc_Data_Cpk.NormalDistributionX).ToString("F2"));
double ValueDownX = Convert.ToDouble(Min(Spc_Data_Cpk.NormalDistributionX).ToString("F2"));
double ValueUpY = Convert.ToDouble(Max(Spc_Data_Cpk.NormalDistributionY).ToString("F2"));
double X1 = (ValueUpX - ValueDownX) / 10;
chart1.ChartAreas["ChartArea_Cpk"].AxisX.Minimum = Math.Round(ValueDownX - X1, 2);
chart1.ChartAreas["ChartArea_Cpk"].AxisX.Maximum = Math.Round(ValueUpX + X1, 2);
chart1.ChartAreas["ChartArea_Cpk"].AxisY.Minimum = 0;
chart1.ChartAreas["ChartArea_Cpk"].AxisY.Maximum = Math.Round(ValueUpY + ValueUpY / 10, 2);
//绘图
for (int i = 0; i < Spc_Data_Cpk.NormalDistributionX.Length; i++)
{
chart1.Series["Series_Cpk"].Points.AddXY(Math.Round(Spc_Data_Cpk.NormalDistributionX[i], 2), Math.Round(Spc_Data_Cpk.NormalDistributionY[i], 2));
}
// Set Strip line item
//chart1.ChartAreas["ChartArea1"].AxisX.StripLines[0].IntervalOffset = Spc_Data_Cpk.LSL;
//chart1.ChartAreas["ChartArea1"].AxisX.StripLines[0].StripWidth = Spc_Data_Cpk.USL - Spc_Data_Cpk.LSL;
// Set Strip line item
//double SL = (ValueUpX + ValueDownX) / 2;
//double USL = SL + 3 * Spc_Data_Cpk.Singma;
//double LSL = SL - 3 * Spc_Data_Cpk.Singma;
chart1.ChartAreas["ChartArea_Cpk"].AxisX.StripLines[1].IntervalOffset = Spc_Data_Cpk.NormalDistributionX[4];
chart1.ChartAreas["ChartArea_Cpk"].AxisX.StripLines[1].Text = "SL=" + Spc_Data_Cpk.NormalDistributionX[4].ToString("F2");
chart1.ChartAreas["ChartArea_Cpk"].AxisX.StripLines[2].IntervalOffset = Spc_Data_Cpk.NormalDistributionX[1];
chart1.ChartAreas["ChartArea_Cpk"].AxisX.StripLines[2].Text = "USL=" + Spc_Data_Cpk.NormalDistributionX[1].ToString("F2");
chart1.ChartAreas["ChartArea_Cpk"].AxisX.StripLines[3].IntervalOffset = Spc_Data_Cpk.NormalDistributionX[7];
chart1.ChartAreas["ChartArea_Cpk"].AxisX.StripLines[3].Text = "LSL=" + Spc_Data_Cpk.NormalDistributionX[7].ToString("F2");
TextAnnotation annotation1 = new TextAnnotation();
annotation1.Text = "Cpk=" + Spc_Data_Cpk.Cpk.ToString("F2");
annotation1.ForeColor = Color.Black;
annotation1.Font = new Font("Arial", 11); ;
annotation1.X = 80;
annotation1.Y = 8;
chart1.Annotations.Add(annotation1);
TextAnnotation annotation2 = new TextAnnotation();
annotation2.Text = "CPL=" + Spc_Data_Cpk.CPL.ToString("F2");
annotation2.ForeColor = Color.Black;
annotation2.Font = new Font("Arial", 11); ;
annotation2.X = 80;
annotation2.Y = 13;
chart1.Annotations.Add(annotation2);
TextAnnotation annotation3 = new TextAnnotation();
annotation3.Text = "CPU=" + Spc_Data_Cpk.CPU.ToString("F2");
annotation3.ForeColor = Color.Black;
annotation3.Font = new Font("Arial", 11); ;
annotation3.X = 80;
annotation3.Y = 18;
chart1.Annotations.Add(annotation3);
}
/// <summary>
/// 机床报警频次分析
/// </summary>
/// <param name="dt"></param>
/// <param name="chart1"></param>
public static void ChartMachineAlarm(DataTable dt, Chart chart1)
{
if (dt.Rows.Count == 0)
return;
string seriesName = dt.Rows[0]["工位号"].ToString();
chart1.Series.Add(seriesName);
chart1.Series[seriesName].ChartType = SeriesChartType.Column;
chart1.Series[seriesName].BorderWidth = 2;
chart1.Series[seriesName].ToolTip = "报警文本:#VALX \n报警数量#VALY";
chart1.Series[seriesName].Points.DataBindXY(dt.Rows, "报警文本", dt.Rows, "报警数量");
//for (int i = 0; i < 10; i++)
//{
// chart1.Series[seriesName].Points.AddXY(dt.Rows[i]["报警编号"], dt.Rows[i]["报警数量"]);
//}
//chart1.DataBind();
}
///// <summary>
///// 机床状态频次分析
///// </summary>
///// <param name="dt"></param>
///// <param name="chart1"></param>
//public static void ChartMachineStatus(DataTable dt, Chart chart1)
//{
// foreach (DataRow row in dt.Rows)
// {
// // For each Row add a new series
// string seriesName = row["工位号"].ToString();
// chart1.Series.Add(seriesName);
// chart1.Series[seriesName].ChartType = SeriesChartType.StackedBar;
// chart1.Series[seriesName].BorderWidth = 2;
// chart1.Series[seriesName].ToolTip = "工位号:" + seriesName + "\n 频次:= #VALY";
// for (int colIndex = 2; colIndex < dt.Columns.Count; colIndex++)
// {
// // For each column (column 1 and onward) add the value as a point
// string columnName = dt.Columns[colIndex].ColumnName;
// int YVal = (int)row[columnName];
// chart1.Series[seriesName].Points.AddXY(columnName, YVal);
// }
// }
//}
///// <summary>
///// 成海 2012-04-05
///// </summary>
///// <param name="dt"></param>
///// <param name="chart1"></param>
public static void ChartMachineStatus(DataTable dt, Chart chart1)
{
string seriesNameA = "机床上电";
chart1.Series.Add(seriesNameA);
chart1.Series[seriesNameA].ChartType = SeriesChartType.StackedColumn;
chart1.Series[seriesNameA].BorderWidth = 2;
chart1.Series[seriesNameA].ToolTip = "机床状态:" + seriesNameA + "\n 频次:= #VALY";
chart1.Series[seriesNameA].Color = System.Drawing.Color.DeepPink;
string seriesNameB = "循环开始";
chart1.Series.Add(seriesNameB);
chart1.Series[seriesNameB].ChartType = SeriesChartType.StackedColumn;
chart1.Series[seriesNameB].BorderWidth = 2;
chart1.Series[seriesNameB].ToolTip = "机床状态:" + seriesNameB + "\n 频次:= #VALY";
chart1.Series[seriesNameB].Color = System.Drawing.Color.Green;
string seriesNameC = "机床故障";
chart1.Series.Add(seriesNameC);
chart1.Series[seriesNameC].ChartType = SeriesChartType.StackedColumn;
chart1.Series[seriesNameC].BorderWidth = 2;
chart1.Series[seriesNameC].ToolTip = "机床状态:" + seriesNameC + "\n 频次:= #VALY";
chart1.Series[seriesNameC].Color = System.Drawing.Color.Red;
string seriesNameD = "上料无件";
chart1.Series.Add(seriesNameD);
chart1.Series[seriesNameD].ChartType = SeriesChartType.StackedColumn;
chart1.Series[seriesNameD].BorderWidth = 2;
chart1.Series[seriesNameD].ToolTip = "机床状态:" + seriesNameD + "\n 频次:= #VALY";
chart1.Series[seriesNameD].Color = System.Drawing.Color.Blue;
string seriesNameE = "下料堵塞";
chart1.Series.Add(seriesNameE);
chart1.Series[seriesNameE].ChartType = SeriesChartType.StackedColumn;
chart1.Series[seriesNameE].BorderWidth = 2;
chart1.Series[seriesNameE].ToolTip = "机床状态:" + seriesNameE + "\n 频次:= #VALY";
chart1.Series[seriesNameE].Color = System.Drawing.Color.Yellow;
foreach (DataRow row in dt.Rows)
{
string opName = row["工位号"].ToString();
int YValA = (int)row["机床上电"];
chart1.Series[seriesNameA].Points.AddXY(opName, YValA);
int YValB = (int)row["循环开始"];
chart1.Series[seriesNameB].Points.AddXY(opName, YValB);
int YValC = (int)row["机床故障"];
chart1.Series[seriesNameC].Points.AddXY(opName, YValC);
int YValD = (int)row["上料无件"];
chart1.Series[seriesNameD].Points.AddXY(opName, YValD);
int YValE = (int)row["下料堵塞"];
chart1.Series[seriesNameE].Points.AddXY(opName, YValE);
}
}
/// <summary>
/// SPC分析基本趋势图
/// </summary>
/// <param name="dt"></param>
/// <param name="chart1"></param>
public static void ChartQualityData_TrendPictureBasic(DataTable dt, Chart chart1)
{
//string seriesName = "series1";
//chart1.Series.Add(seriesName);
//chart1.Series[seriesName].MarkerStyle = MarkerStyle.Circle;
//chart1.Series[seriesName].MarkerSize = 5;
//chart1.Series[seriesName].MasrkerColor = Color.Magenta;
//chart1.Series[seriesName].ChartType = SeriesChartType.Line;
//chart1.Series[seriesName].BorderWidth = 1;
chart1.Series[0].Points.DataBind(dt.DefaultView, "", "测量值", "Tooltip=ToolTip");
//chart1.DataBinds();
}
/// <summary>
/// 子组平均值的平均值
/// n 子组大小。单个子组观测值的个数
/// </summary>
/// <param name="X">全部测量数据数组</param>
/// <param name="n">子组大小。单个子组观测值的个数</param>
/// <param name="Xk">子组平均值的数组</param>
/// <returns></returns>
static private double Average(double[] X, int n)
{
//k 子组个数
int k;
k = X.Length / n;
double[] Xi = new double[n];
double[] Xk = new double[k];
for (int j = 0; j < k; j++)
{
for (int i = 0; i < n; i++)
{
Xi[i] = X[j * n + i];
}
//子组平均值
Xk[j] = Average(Xi);
}
//子组平均值的平均值
return Average(Xk);
}
/// <summary>
/// 一组观测值的均值
/// </summary>
/// <param name="Xn">子组观测值</param>
/// <returns></returns>
static private double Average(double[] Xn)
{
if (Xn.Length < 1) return 0;
return Sum(Xn) / (double)Xn.Length;
}
/// <summary>
/// 观测值和
/// </summary>
/// <param name="Xn">子组观测值</param>
/// <returns></returns>
static private double Sum(double[] Xn)
{
double temp;
temp = 0;
for (int i = 0; i < Xn.Length; i++)
{
temp = temp + Xn[i];
}
return temp;
}
/// <summary>
/// 观测值最大值
/// </summary>
/// <param name="Xn">子组观测值</param>
/// <returns></returns>
static private double Max(double[] Xn)
{
double temp;
temp = Xn[0];
for (int i = 0; i < Xn.Length; i++)
{
temp = (Xn[i] > temp) ? Xn[i] : temp;
}
return temp;
}
/// <summary>
/// 观测值最小值
/// </summary>
/// <param name="Xn">子组观测值</param>
/// <returns></returns>
static private double Min(double[] Xn)
{
double temp;
temp = Xn[0];
for (int i = 0; i < Xn.Length; i++)
{
temp = (Xn[i] < temp) ? Xn[i] : temp;
}
return temp;
}
/// <summary>
/// 均值极差图
/// </summary>
/// <param name="X"></param>
/// <param name="n"></param>
/// <param name="chart1"></param>
public static void ChartQualityData_XR(double[] X, int n, Chart chart1)
{
//计算XR控制图的数据
ASPNet_Drawing.CSpc_Data_XR Spc_Data_XR = ASPNet_Drawing.Spc_Data.XR(X, n);
for (int i = 0; i < Spc_Data_XR.CL_Xk.Length; i++)
{
//X
chart1.Series["Series_X"].Points.AddXY(i + 1, Spc_Data_XR.CL_Xk[i]);
//R
chart1.Series["Series_R"].Points.AddXY(i + 1, Spc_Data_XR.CL_Rk[i]);
}
chart1.Series["Series_X"].ToolTip = "测量值:= #VALY";
chart1.Series["Series_R"].ToolTip = "测量值:= #VALY";
////均值图Y轴范围
double gapAxis_X = Spc_Data_XR.UCL_X - Spc_Data_XR.LCL_X;
//均值的最大值
double maxXk = Max(Spc_Data_XR.CL_Xk);
//均值的最小值
double minXk = Min(Spc_Data_XR.CL_Xk);
if (maxXk > Spc_Data_XR.UCL_X)
{
chart1.ChartAreas["ChartArea_X"].AxisY.Maximum = Convert.ToDouble((maxXk + gapAxis_X / 8).ToString("F2"));
}
else
{
chart1.ChartAreas["ChartArea_X"].AxisY.Maximum = Convert.ToDouble((Spc_Data_XR.UCL_X + gapAxis_X / 8).ToString("F2"));
}
if (minXk < Spc_Data_XR.LCL_X)
{
chart1.ChartAreas["ChartArea_X"].AxisY.Minimum = Convert.ToDouble((minXk - gapAxis_X / 8).ToString("F2"));
}
else
{
chart1.ChartAreas["ChartArea_X"].AxisY.Minimum = Convert.ToDouble((Spc_Data_XR.LCL_X - gapAxis_X / 8).ToString("F2"));
}
////极差图Y轴范围
double gapAxis_R = Spc_Data_XR.UCL_R - Spc_Data_XR.LCL_R;
//极差最大值
double maxRk = Max(Spc_Data_XR.CL_Rk);
//极差最小值
double minRk = Min(Spc_Data_XR.CL_Rk);
if (maxRk > Spc_Data_XR.UCL_R)
{
chart1.ChartAreas["ChartArea_R"].AxisY.Maximum = Convert.ToDouble((maxRk + gapAxis_R / 8).ToString("F2"));
}
else
{
chart1.ChartAreas["ChartArea_R"].AxisY.Maximum = Convert.ToDouble((Spc_Data_XR.UCL_R + gapAxis_R / 8).ToString("F2"));
}
if (minRk < Spc_Data_XR.LCL_R)
{
chart1.ChartAreas["ChartArea_R"].AxisY.Minimum = Convert.ToDouble((minRk - gapAxis_R / 8).ToString("F2"));
}
else
{
chart1.ChartAreas["ChartArea_R"].AxisY.Minimum = Convert.ToDouble((Spc_Data_XR.LCL_R - gapAxis_R / 8).ToString("F2"));
}
// Set axis title
chart1.ChartAreas["ChartArea_X"].AxisY.Title = "均值图";
chart1.ChartAreas["ChartArea_R"].AxisY.Title = "极差图";
chart1.ChartAreas["ChartArea_X"].AxisY.TitleFont = new Font("Microsoft Sans Serif", 8);
chart1.ChartAreas["ChartArea_R"].AxisY.TitleFont = new Font("Microsoft Sans Serif", 8);
// Set Strip line item
chart1.ChartAreas["ChartArea_X"].AxisY.StripLines[0].IntervalOffset = Spc_Data_XR.LCL_X;
chart1.ChartAreas["ChartArea_X"].AxisY.StripLines[0].StripWidth = Spc_Data_XR.UCL_X - Spc_Data_XR.LCL_X;
// Set Strip line item
chart1.ChartAreas["ChartArea_X"].AxisY.StripLines[1].IntervalOffset = Spc_Data_XR.CL_X;
chart1.ChartAreas["ChartArea_X"].AxisY.StripLines[1].Text = "CL=" + Spc_Data_XR.CL_X.ToString("F2");
chart1.ChartAreas["ChartArea_X"].AxisY.StripLines[2].IntervalOffset = Spc_Data_XR.UCL_X;
chart1.ChartAreas["ChartArea_X"].AxisY.StripLines[2].Text = "UCL=" + Spc_Data_XR.UCL_X.ToString("F2");
chart1.ChartAreas["ChartArea_X"].AxisY.StripLines[3].IntervalOffset = Spc_Data_XR.LCL_X;
chart1.ChartAreas["ChartArea_X"].AxisY.StripLines[3].Text = "LCL=" + Spc_Data_XR.LCL_X.ToString("F2");
// Set Strip line item
chart1.ChartAreas["ChartArea_R"].AxisY.StripLines[0].IntervalOffset = Spc_Data_XR.LCL_R;
chart1.ChartAreas["ChartArea_R"].AxisY.StripLines[0].StripWidth = Spc_Data_XR.UCL_R - Spc_Data_XR.LCL_R;
// Set Strip line item
chart1.ChartAreas["ChartArea_R"].AxisY.StripLines[1].IntervalOffset = Spc_Data_XR.CL_R;
chart1.ChartAreas["ChartArea_R"].AxisY.StripLines[1].Text = "CL=" + Spc_Data_XR.CL_R.ToString("F2");
chart1.ChartAreas["ChartArea_R"].AxisY.StripLines[2].IntervalOffset = Spc_Data_XR.UCL_R;
chart1.ChartAreas["ChartArea_R"].AxisY.StripLines[2].Text = "UCL=" + Spc_Data_XR.UCL_R.ToString("F2");
chart1.ChartAreas["ChartArea_R"].AxisY.StripLines[3].IntervalOffset = Spc_Data_XR.LCL_R;
chart1.ChartAreas["ChartArea_R"].AxisY.StripLines[3].Text = "LCL=" + Spc_Data_XR.LCL_R.ToString("F2");
}
/// <summary>
/// 均值标准差图
/// </summary>
/// <param name="X"></param>
/// <param name="n"></param>
/// <param name="chart1"></param>
public static void ChartQualityData_XS(double[] X, int n, Chart chart1)
{
//计算XS控制图的数据
ASPNet_Drawing.CSpc_Data_XS Spc_Data_XS = ASPNet_Drawing.Spc_Data.XS(X, n);
for (int i = 0; i < Spc_Data_XS.CL_Xk.Length; i++)
{
//X
chart1.Series["Series_X"].Points.AddXY(i + 1, Spc_Data_XS.CL_Xk[i]);
//S
chart1.Series["Series_S"].Points.AddXY(i + 1, Spc_Data_XS.CL_Sk[i]);
}
chart1.Series["Series_X"].ToolTip = "测量值:= #VALY";
chart1.Series["Series_S"].ToolTip = "测量值:= #VALY";
////均值图Y轴范围
double gapAxis_X = Spc_Data_XS.UCL_X - Spc_Data_XS.LCL_X;
//均值的最大值
double maxXk = Max(Spc_Data_XS.CL_Xk);
//均值的最小值
double minXk = Min(Spc_Data_XS.CL_Xk);
if (maxXk > Spc_Data_XS.UCL_X)
{
chart1.ChartAreas["ChartArea_X"].AxisY.Maximum = Convert.ToDouble((maxXk + gapAxis_X / 8).ToString("F2"));
}
else
{
chart1.ChartAreas["ChartArea_X"].AxisY.Maximum = Convert.ToDouble((Spc_Data_XS.UCL_X + gapAxis_X / 8).ToString("F2"));
}
if (minXk < Spc_Data_XS.LCL_X)
{
chart1.ChartAreas["ChartArea_X"].AxisY.Minimum = Convert.ToDouble((minXk - gapAxis_X / 8).ToString("F2"));
}
else
{
chart1.ChartAreas["ChartArea_X"].AxisY.Minimum = Convert.ToDouble((Spc_Data_XS.LCL_X - gapAxis_X / 8).ToString("F2"));
}
////标准差图Y轴范围
double gapAxis_R = Spc_Data_XS.UCL_S - Spc_Data_XS.LCL_S;
//标准差最大值
double maxRk = Max(Spc_Data_XS.CL_Sk);
//标准差最小值
double minRk = Min(Spc_Data_XS.CL_Sk);
if (maxRk > Spc_Data_XS.UCL_S)
{
chart1.ChartAreas["ChartArea_S"].AxisY.Maximum = Convert.ToDouble((maxRk + gapAxis_R / 8).ToString("F2"));
}
else
{
chart1.ChartAreas["ChartArea_S"].AxisY.Maximum = Convert.ToDouble((Spc_Data_XS.UCL_S + gapAxis_R / 8).ToString("F2"));
}
if (minRk < Spc_Data_XS.LCL_S)
{
chart1.ChartAreas["ChartArea_S"].AxisY.Minimum = Convert.ToDouble((minRk - gapAxis_R / 8).ToString("F2"));
}
else
{
chart1.ChartAreas["ChartArea_S"].AxisY.Minimum = Convert.ToDouble((Spc_Data_XS.LCL_S - gapAxis_R / 8).ToString("F2"));
}
// Set axis title
chart1.ChartAreas["ChartArea_X"].AxisY.Title = "均值图";
chart1.ChartAreas["ChartArea_S"].AxisY.Title = "标准差图";
chart1.ChartAreas["ChartArea_X"].AxisY.TitleFont = new Font("Microsoft Sans Serif", 8);
chart1.ChartAreas["ChartArea_S"].AxisY.TitleFont = new Font("Microsoft Sans Serif", 8);
// Set Strip line item
chart1.ChartAreas["ChartArea_X"].AxisY.StripLines[0].IntervalOffset = Spc_Data_XS.LCL_X;
chart1.ChartAreas["ChartArea_X"].AxisY.StripLines[0].StripWidth = Spc_Data_XS.UCL_X - Spc_Data_XS.LCL_X;
// Set Strip line item
chart1.ChartAreas["ChartArea_X"].AxisY.StripLines[1].IntervalOffset = Spc_Data_XS.CL_X;
chart1.ChartAreas["ChartArea_X"].AxisY.StripLines[1].Text = "CL=" + Spc_Data_XS.CL_X.ToString("F2");
chart1.ChartAreas["ChartArea_X"].AxisY.StripLines[2].IntervalOffset = Spc_Data_XS.UCL_X;
chart1.ChartAreas["ChartArea_X"].AxisY.StripLines[2].Text = "UCL=" + Spc_Data_XS.UCL_X.ToString("F2");
chart1.ChartAreas["ChartArea_X"].AxisY.StripLines[3].IntervalOffset = Spc_Data_XS.LCL_X;
chart1.ChartAreas["ChartArea_X"].AxisY.StripLines[3].Text = "LCL=" + Spc_Data_XS.LCL_X.ToString("F2");
// Set Strip line item
chart1.ChartAreas["ChartArea_S"].AxisY.StripLines[0].IntervalOffset = Spc_Data_XS.LCL_S;
chart1.ChartAreas["ChartArea_S"].AxisY.StripLines[0].StripWidth = Spc_Data_XS.UCL_S - Spc_Data_XS.LCL_S;
// Set Strip line item
chart1.ChartAreas["ChartArea_S"].AxisY.StripLines[1].IntervalOffset = Spc_Data_XS.CL_S;
chart1.ChartAreas["ChartArea_S"].AxisY.StripLines[1].Text = "CL=" + Spc_Data_XS.CL_S.ToString("F2");
chart1.ChartAreas["ChartArea_S"].AxisY.StripLines[2].IntervalOffset = Spc_Data_XS.UCL_S;
chart1.ChartAreas["ChartArea_S"].AxisY.StripLines[2].Text = "UCL=" + Spc_Data_XS.UCL_S.ToString("F2");
chart1.ChartAreas["ChartArea_S"].AxisY.StripLines[3].IntervalOffset = Spc_Data_XS.LCL_S;
chart1.ChartAreas["ChartArea_S"].AxisY.StripLines[3].Text = "LCL=" + Spc_Data_XS.LCL_S.ToString("F2");
}
///// <summary>
///// 故障率 lvzhen
///// </summary>
///// <param name="dt"></param>
///// <param name="chart1"></param>
//public static void ChartFaultPercent(DataTable dt, Chart chart1)
//{
// if (dt.Rows.Count == 0)
// return;
// foreach (DataRow row in dt.Rows)
// {
// string seriesName = row["工位号"].ToString();
// chart1.Series.Add(seriesName);
// chart1.Series[seriesName].ChartType = SeriesChartType.Column;
// chart1.Series[seriesName].BorderWidth = 2;
// chart1.Series[seriesName].ToolTip = "工位号:" + row["工位号"].ToString() + "\n运行时间: " + row["运行时间"].ToString() + "\n故障时间: " + row["故障时间"].ToString() + "\n故障率#VALY";
// for (int colIndex = 3; colIndex < dt.Columns.Count; colIndex++)
// {
// // For each column (column 1 and onward) add the value as a point
// string columnName = dt.Columns[colIndex].ColumnName;
// string YVal = row[columnName].ToString();
// chart1.Series[seriesName].Points.AddXY(columnName, YVal);
// }
// //for (int i = 0; i < 10; i++)
// //{
// // chart1.Series[seriesName].Points.AddXY(dt.Rows[i]["报警编号"], dt.Rows[i]["报警数量"]);
// //}
// //chart1.DataBind();
// }
//}
///// <summary>
///// 故障率 lvzhen
///// </summary>
///// <param name="dt"></param>
///// <param name="chart1"></param>
//public static void ChartFaultPercentTrue(DataTable dt, Chart chart1)
//{
// if (dt.Rows.Count == 0)
// return;
// foreach (DataRow row in dt.Rows)
// {
// string seriesName = row["工位号"].ToString();
// chart1.Series.Add(seriesName);
// chart1.Series[seriesName].ChartType = SeriesChartType.Column;
// chart1.Series[seriesName].BorderWidth = 2;
// chart1.Series[seriesName].ToolTip = "工位号:" + row["工位号"].ToString() + " \n故障率#VALY";
// for (int colIndex = 3; colIndex < dt.Columns.Count; colIndex++)
// {
// // For each column (column 1 and onward) add the value as a point
// string columnName = dt.Columns[colIndex].ColumnName;
// string YVal = row[columnName].ToString();
// chart1.Series[seriesName].Points.AddXY(columnName, YVal);
// }
// //for (int i = 0; i < 10; i++)
// //{
// // chart1.Series[seriesName].Points.AddXY(dt.Rows[i]["报警编号"], dt.Rows[i]["报警数量"]);
// //}
// //chart1.DataBind();
// }
//}
///// <summary>
///// 开机率 lvzhen
///// </summary>
///// <param name="dt"></param>
///// <param name="chart1"></param>
//public static void ChartKaijiProportion(DataTable dt, Chart chart1)
//{
// chart1.Series[0].Points.DataBind(dt.DefaultView, "操作日期", "开机率", "Tooltip=ToolTip");
//}
}

View File

@@ -0,0 +1,88 @@
using System;
using System.Drawing;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using System.Web.UI.DataVisualization.Charting;
using System.Data.SqlClient;
/// <summary>
///DrawChart 的摘要说明
/// </summary>
public partial class DrawChart
{
/// <summary>
/// 故障率 lvzhen
/// </summary>
/// <param name="dt"></param>
/// <param name="chart1"></param>
public static void ChartFaultPercent(DataTable dt, Chart chart1)
{
if (dt.Rows.Count == 0)
return;
foreach (DataRow row in dt.Rows)
{
string seriesName = row["工位号"].ToString();
chart1.Series.Add(seriesName);
chart1.Series[seriesName].ChartType = SeriesChartType.Column;
chart1.Series[seriesName].BorderWidth = 2;
chart1.Series[seriesName].ToolTip = "工位号:" + row["工位号"].ToString() + "\n运行时间: " + row["运行时间"].ToString() + "\n故障时间: " + row["故障时间"].ToString() + "\n故障率#VALY";
for (int colIndex = 3; colIndex < dt.Columns.Count; colIndex++)
{
// For each column (column 1 and onward) add the value as a point
string columnName = dt.Columns[colIndex].ColumnName;
string YVal = row[columnName].ToString();
chart1.Series[seriesName].Points.AddXY(columnName, YVal);
}
//for (int i = 0; i < 10; i++)
//{
// chart1.Series[seriesName].Points.AddXY(dt.Rows[i]["报警编号"], dt.Rows[i]["报警数量"]);
//}
//chart1.DataBind();
}
}
/// <summary>
/// 故障率 lvzhen
/// </summary>
/// <param name="dt"></param>
/// <param name="chart1"></param>
public static void ChartFaultPercentTrue(DataTable dt, Chart chart1)
{
if (dt.Rows.Count == 0)
return;
foreach (DataRow row in dt.Rows)
{
string seriesName = row["工位号"].ToString();
chart1.Series.Add(seriesName);
chart1.Series[seriesName].ChartType = SeriesChartType.Column;
chart1.Series[seriesName].BorderWidth = 2;
chart1.Series[seriesName].ToolTip = "工位号:" + row["工位号"].ToString()+" \n故障率#VALY";
for (int colIndex = 3; colIndex < dt.Columns.Count; colIndex++)
{
// For each column (column 1 and onward) add the value as a point
string columnName = dt.Columns[colIndex].ColumnName;
string YVal = row[columnName].ToString();
chart1.Series[seriesName].Points.AddXY(columnName, YVal);
}
//for (int i = 0; i < 10; i++)
//{
// chart1.Series[seriesName].Points.AddXY(dt.Rows[i]["报警编号"], dt.Rows[i]["报警数量"]);
//}
//chart1.DataBind();
}
}
/// <summary>
/// 开机率 lvzhen
/// </summary>
/// <param name="dt"></param>
/// <param name="chart1"></param>
public static void ChartKaijiProportion(DataTable dt, Chart chart1)
{
chart1.Series[0].Points.DataBind(dt.DefaultView, "操作日期", "开机率", "Tooltip=ToolTip");
}
}

View File

@@ -0,0 +1,300 @@
using System;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Web.UI.DataVisualization.Charting;
using System.Collections;
/// <summary>
///DrawPareto 的摘要说明
/// </summary>
public class DrawPareto
{
public DrawPareto()
{
//
//TODO: 在此处添加构造函数逻辑
//
}
/// <summary>
/// Number of class intervals the data range is devided in.
/// This property only has affect when "SegmentIntervalWidth" is
/// set to double.NaN.
/// </summary>
public int SegmentIntervalNumber = 20;
/// <summary>
/// Histogram class interval width. Setting this value to "double.NaN"
/// will result in automatic width calculation based on the data range
/// and number of required interval specified in "SegmentIntervalNumber".
/// </summary>
public double SegmentIntervalWidth = double.NaN;
/// <summary>
/// Indicates that percent frequency should be shown on the right axis
/// </summary>
public bool ShowPercentOnSecondaryYAxis = true;
public void CreatePareto(
Chart chartControl,
string dataSeriesName,
string histogramSeriesName)
{
// Validate input
if (chartControl == null)
{
throw (new ArgumentNullException("chartControl"));
}
if (chartControl.Series.IndexOf(dataSeriesName) < 0)
{
throw (new ArgumentException("Series with name'" + dataSeriesName + "' was not found.", "dataSeriesName"));
}
// Make data series invisible
chartControl.Series[dataSeriesName].Enabled = false;
// Check if histogram series exsists
Series histogramSeries = null;
if (chartControl.Series.IndexOf(histogramSeriesName) < 0)
{
// Add new series
histogramSeries = chartControl.Series.Add(histogramSeriesName);
// Set new series chart type and other attributes
histogramSeries.ChartType = SeriesChartType.Column;
histogramSeries.BorderColor = Color.Black;
histogramSeries.BorderWidth = 1;
histogramSeries.BorderDashStyle = ChartDashStyle.Solid;
}
else
{
histogramSeries = chartControl.Series[histogramSeriesName];
histogramSeries.Points.Clear();
}
// Get data series minimum and maximum values
double minValue = double.MaxValue;
double maxValue = double.MinValue;
int pointCount = 0;
foreach (DataPoint dataPoint in chartControl.Series[dataSeriesName].Points)
{
// Process only non-empty data points
if (!dataPoint.IsEmpty)
{
if (dataPoint.YValues[0] > maxValue)
{
maxValue = dataPoint.YValues[0];
}
if (dataPoint.YValues[0] < minValue)
{
minValue = dataPoint.YValues[0];
}
++pointCount;
}
}
// Calculate interval width if it's not set
if (double.IsNaN(this.SegmentIntervalWidth))
{
this.SegmentIntervalWidth = (maxValue - minValue) / SegmentIntervalNumber;
this.SegmentIntervalWidth = RoundInterval(this.SegmentIntervalWidth);
}
// Round minimum and maximum values
minValue = Math.Floor(minValue / this.SegmentIntervalWidth) * this.SegmentIntervalWidth;
maxValue = Math.Ceiling(maxValue / this.SegmentIntervalWidth) * this.SegmentIntervalWidth;
// Create histogram series points
double currentPosition = minValue;
for (currentPosition = minValue; currentPosition <= maxValue; currentPosition += this.SegmentIntervalWidth)
{
// Count all points from data series that are in current interval
int count = 0;
foreach (DataPoint dataPoint in chartControl.Series[dataSeriesName].Points)
{
if (!dataPoint.IsEmpty)
{
double endPosition = currentPosition + this.SegmentIntervalWidth;
if (dataPoint.YValues[0] >= currentPosition &&
dataPoint.YValues[0] < endPosition)
{
++count;
}
// Last segment includes point values on both segment boundaries
else if (endPosition >= maxValue)
{
if (dataPoint.YValues[0] >= currentPosition &&
dataPoint.YValues[0] <= endPosition)
{
++count;
}
}
}
}
// Add data point into the histogram series
//histogramSeries.Points.AddXY("", count);
histogramSeries.Points.AddY( count);
}
histogramSeries.Sort(PointSortOrder.Descending);
// Adjust series attributes
histogramSeries["PointWidth"] = "1";
// Adjust chart area
ChartArea chartArea = chartControl.ChartAreas[histogramSeries.ChartArea];
chartArea.AxisY.Title = "频数";
//chartArea.AxisX.Minimum = minValue;
//chartArea.AxisX.Maximum = maxValue;
// Set axis interval based on the histogram class interval
// and do not allow more than 10 labels on the axis.
double axisInterval = this.SegmentIntervalWidth;
while ((maxValue - minValue) / axisInterval > 10.0)
{
axisInterval *= 2.0;
}
chartArea.AxisX.Interval = axisInterval;
// Set chart area secondary Y axis
chartArea.AxisY2.Enabled = AxisEnabled.Auto;
if (this.ShowPercentOnSecondaryYAxis)
{
chartArea.RecalculateAxesScale();
chartArea.AxisY2.Enabled = AxisEnabled.True;
chartArea.AxisY2.LabelStyle.Format = "P0";
chartArea.AxisY2.MajorGrid.Enabled = false;
chartArea.AxisY2.Title = "Percent of Total";
chartArea.AxisY2.Minimum = 0;
chartArea.AxisY2.Maximum = chartArea.AxisY.Maximum / (pointCount / 100.0);
double minStep = (chartArea.AxisY2.Maximum > 20.0) ? 5.0 : 1.0;
chartArea.AxisY2.Interval = Math.Ceiling((chartArea.AxisY2.Maximum / 5.0 / minStep)) * minStep;
}
}
/// <summary>
/// Helper method which rounds specified axsi interval.
/// </summary>
/// <param name="interval">Calculated axis interval.</param>
/// <returns>Rounded axis interval.</returns>
public double RoundInterval(double interval)
{
// If the interval is zero return error
if (interval == 0.0)
{
throw (new ArgumentOutOfRangeException("interval", "Interval can not be zero."));
}
// If the real interval is > 1.0
double step = -1;
double tempValue = interval;
while (tempValue > 1.0)
{
step++;
tempValue = tempValue / 10.0;
if (step > 1000)
{
throw (new InvalidOperationException("Auto interval error due to invalid point values or axis minimum/maximum."));
}
}
// If the real interval is < 1.0
tempValue = interval;
if (tempValue < 1.0)
{
step = 0;
}
while (tempValue < 1.0)
{
step--;
tempValue = tempValue * 10.0;
if (step < -1000)
{
throw (new InvalidOperationException("Auto interval error due to invalid point values or axis minimum/maximum."));
}
}
double tempDiff = interval / Math.Pow(10.0, step);
if (tempDiff < 3.0)
{
tempDiff = 2.0;
}
else if (tempDiff < 7.0)
{
tempDiff = 5.0;
}
else
{
tempDiff = 10.0;
}
// Make a correction of the real interval
return tempDiff * Math.Pow(10.0, step);
}
public void MakeParetoChart(Chart chart, string srcSeriesName, string destSeriesName)
{
// get name of the ChartAre of the source series
string strChartArea = chart.Series[srcSeriesName].ChartArea;
// ensure the source series is a column chart type
chart.Series[srcSeriesName].ChartType = SeriesChartType.Column;
// sort the data in the series to be by values in descending order
chart.DataManipulator.Sort(PointSortOrder.Descending, srcSeriesName);
// find the total of all points in the source series
double total = 0.0;
foreach (DataPoint pt in chart.Series[srcSeriesName].Points)
total += pt.YValues[0];
// set the max value on the primary axis to total
chart.ChartAreas[strChartArea].AxisY.Maximum = total;
// create the destination series and add it to the chart
Series destSeries = new Series(destSeriesName);
chart.Series.Add(destSeries);
// ensure the destination series is a Line or Spline chart type
destSeries.ChartType = SeriesChartType.Line;
destSeries.BorderWidth = 3;
// assign the series to the same chart area as the column chart
destSeries.ChartArea = chart.Series[srcSeriesName].ChartArea;
// assign this series to use the secondary axis and set it maximum to be 100%
destSeries.YAxisType = AxisType.Secondary;
chart.ChartAreas[strChartArea].AxisY2.Maximum = 100;
// locale specific percentage format with no decimals
chart.ChartAreas[strChartArea].AxisY2.LabelStyle.Format = "0.#";
// turn off the end point values of the primary X axis
chart.ChartAreas[strChartArea].AxisX.LabelStyle.IsEndLabelVisible = false;
// for each point in the source series find % of total and assign to series
double percentage = 0.0;
foreach (DataPoint pt in chart.Series[srcSeriesName].Points)
{
percentage += (pt.YValues[0] / total * 100.0);
//Chart1.Series["Default"].Points.AddXY(pt.XValue,Math.Round(percentage, 2));
destSeries.Points.Add(Math.Round(percentage, 2));
}
}
}

View File

@@ -0,0 +1,512 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Collections;
using System.Data;
using ASPNet_Drawing;
/// <summary>
///SpcCaculator 的摘要说明
/// </summary>
public class SpcCaculator
{
/// <summary>
/// SPC系数表
///(0)样本大小 (1)A (2)A2 (3)A3 (4)C4 (5)1/C4 (6)B3 (7)B4 (8)B5 (9)B6 (10)d2 (11)1/d2 (12)d3 (13)D1 (14)D2 (15)D3 (16)D4 (17)M3 (18)M3A2
/// </summary>
static public double[,] SPC_coefficient = { {2,2.121,1.880,2.659,0.798,1.253,0,3.267,0,2.606,1.128,0.887,0.853,0,3.686,0,3.267,1.000,1.880},
{3,1.732,1.023,1.954,0.886,1.128,0,2.568,0,2.276,1.693,0.591,0.888,0,4.358,0,2.574,1.160,1.187},
{4,1.500,0.729,1.628,0.921,1.085,0,2.266,0,2.088,2.059,0.486,0.880,0,4.698,0,2.282,1.092,0.796},
{5,1.342,0.572,1.427,0.940,1.064,0,2.089,0,1.964,2.326,0.430,0.864,0,4.918,0,2.114,1.198,0.691},
{6,1.225,0.483,1.287,0.952,1.051,0.030,1.970,0.029,1.874,2.534,0.395,0.848,0,5.078,0,2.004,1.135,0.549},
{7,1.134,0.419,1.182,0.959,1.042,0.118,1.882,0.113,1.806,2.704,0.370,0.833,0.204,5.204,0.076,1.924,1.214,0.509},
{8,1.061,0.373,1.099,0.965,1.036,0.185,1.815,0.179,1.751,2.847,0.351,0.820,0.388,5.306,0.136,1.864,1.160,0.432},
{9,1.00,0.377,1.032,0.969,1.032,0.29,1.761,0.232,1.707,2.970,0.337,0.808,0.547,5.393,0.184,1.816,1.223,0.412},
{10,0.949,0.308,0.975,0.973,1.028,0.284,1.716,0.276,1.669,3.078,0.325,0.797,0.687,5.469,0.223,1.777,1.176,0.363},
{11,0.905,0.285,0.927,0.975,1.025,0.321,1.679,0.313,1.637,3.173,0.315,0.787,0.811,5.535,0.256,1.744,0,0},
{12,0.886,0.266,0.886,0.978,1.023,0.354,1.646,0.346,1.610,3.258,0.307,0.778,0.922,5.594,0.283,1.717,0,0},
{13,0.832,0.249,0.850,0.979,1.021,0.382,1.618,0.374,1.585,3.336,0.300,0.770,1.025,5.647,0.307,1.693,0,0},
{14,0.802,0.235,0.817,0.981,1.019,0.406,1.594,0.399,1.563,3.407,0.294,0.763,1.118,5.696,0.328,1.672,0,0},
{15,0.775,0.223,0.789,0.982,1.018,0.428,1.157,0.421,1.544,3.472,0.288,0.756,1.203,5.741,0.347,1.653,0,0},
{16,0.750,0.212,0.763,0.984,1.017,0.448,1.552,0.440,1.526,3.532,0.283,0.750,1.282,5.782,0.363,1.637,0,0},
{17,0.728,0.203,0.739,0.985,1.016,0.466,1.534,0.458,1.511,3.588,0.279,0.744,1.356,5.820,0.378,1.622,0,0},
{18,0.707,0.194,0.718,0.985,1.015,0.482,1.518,0.475,1.496,3.640,0.275,0.739,1.424,5.856,0.391,1.608,0,0},
{19,0.688,0.187,0.698,0.986,1.014,0.497,1.503,0.490,1.483,3.689,0.271,0.734,1.487,5.891,0.403,1.597,0,0},
{20,0.671,0.180,0.680,0.987,1.013,0.510,1.490,0.504,1.470,3.735,0.268,0.729,1.549,5.921,0.415,1.585,0,0},
{21,0.655,0.173,0.663,0.988,1.013,0.253,1.477,0.516,1.459,3.778,0.265,0.724,1.605,5.951,0.425,1.575,0,0},
{22,0.640,0.167,0.647,0.988,1.012,0.534,1.466,0.528,1.448,3.819,0.262,0.720,1.659,5.979,0.434,1.566,0,0},
{23,0.626,0.126,0.633,0.989,1.011,0.545,1.455,0.539,1.438,3.858,0.259,0.716,1.710,6.006,0.443,1.557,0,0},
{24,0.612,0.157,0.619,0989,1.011,0.555,1.445,0.549,1.429,3.895,0.257,0.712,1.759,6.031,0.451,1.548,0,0},
{25,0.600,0.153,0.606,0.990,1.011,0.565,1.435,0.559,1.420,3.931,0.254,0.708,1.806,6.056,0.459,1.541,0,0} };
static double QU_k = 0.99865;
static double QL_k = 0.00135;
/// <summary>
/// 计算SPC主要参数
/// 输入:"X"被分析数据组Usl理论上限Lsl理论下限。
/// 输出x平均值"s"均方差;"QU"百分比上限;"QL"百分比下限;"cp"工序能力;"cpk"工序能力指数
/// </summary>
/// <param name="X">被分析数据组</param>
/// <param name="Usl">理论上限</param>
/// <param name="Lsl">理论下限</param>
/// <param name="x">平均值</param>
/// <param name="s">均方差</param>
/// <param name="QU">百分比上限</param>
/// <param name="QL">百分比下限</param>
/// <param name="cp">工序能力</param>
/// <param name="cpk">工序能力指数</param>
public static void SpcValue(double[] X, ref double Usl, ref double Lsl, out double x, out double s,
out double QU, out double QL, out double cp, out double cpk, out double[] sx, out double[] sy)
{
x = AVERAGE(X);
s = STDEV(X);
if (Usl == Lsl)
{
Usl = x + 4.0 * s;
Lsl = x - 4.0 * s;
}
QU_QL(X, out QU, out QL);
cp = Cp(QU, QL, Usl, Lsl);
cpk = Cpk(x, QU, QL, Usl, Lsl);
sxy(s, x, out sx, out sy);
}
/// <summary>
/// 计算SPC主要参数
/// 输入:"X"被分析数据组Usl理论上限Lsl理论下限。
/// 输出x平均值"s"均方差;"QU"百分比上限;"QL"百分比下限;"cp"工序能力;"cpk"工序能力指数
/// </summary>
/// <param name="X">被分析数据组</param>
/// <param name="Usl">理论上限</param>
/// <param name="Lsl">理论下限</param>
/// <param name="x">平均值</param>
/// <param name="s">均方差</param>
/// <param name="QU">百分比上限</param>
/// <param name="QL">百分比下限</param>
/// <param name="cp">工序能力</param>
/// <param name="cpk">工序能力指数</param>
public static void SpcValue(int n,double[] X, ref double Usl, ref double Lsl, out double x, out double s,
out double QU, out double QL, out double cp, out double cpk, out double[] sx, out double[] sy)
{
x = AVERAGE(X);
s = STDEV(X);
if (Usl == Lsl)
{
Usl = x + 4.0 * s;
Lsl = x - 4.0 * s;
}
QU_QL(X, out QU, out QL);
cp = Cp(QU, QL, Usl, Lsl);
cpk = Cpk(x, QU, QL, Usl, Lsl);
sxy(s, x, out sx, out sy);
double X2 = Spc_Data.Average(X, n);
double S2 = Spc_Data.StandardDeviation_S2(X, n);
double R2 = Spc_Data.Range_R2(X, n);
double xiGamaC4;
double xiGamaD2;
double c4 = (double)Spc_Data.Spc_Param.Tables[Xml_Spc_Param.Table_Name].Rows[n - 2][Xml_Spc_Param.Param_C4];
double d2 = (double)Spc_Data.Spc_Param.Tables[Xml_Spc_Param.Table_Name].Rows[n - 2][Xml_Spc_Param.Param_L_D1];
xiGamaC4 = S2 / c4;
xiGamaD2 = R2 / d2;
double USL = Usl;
double LSL = Lsl;
double T = USL - LSL;
double CP = T / (6 * xiGamaD2);
double M = (USL + LSL) / 2.0;
double M1 = M - X2;
M1 = Math.Abs(M1);
double CPK = CP - M1 / (3 * xiGamaD2);
cp = CP;
cpk = CPK;
}
/// <summary>
/// 均方差
/// </summary>
/// <param name="X">被分析数据组</param>
/// <returns>均方差</returns>
public static double STDEV(double[] X)
{
if (X.Length < 2)
return 0;
double s = 0;
//平均值
double x;
x = AVERAGE(X);
for (int i = 0; i < X.Length; i++)
{
s = s + (X[i] - x) * (X[i] - x);
}
s = Math.Sqrt(s / (double)(X.Length - 1));
return s;
}
/// <summary>
/// 平均值
/// </summary>
/// <param name="X">被分析数据组</param>
/// <returns>平均值</returns>
public static double AVERAGE(double[] X)
{
return X.Average();
}
/// <summary>
/// 排序
/// </summary>
/// <param name="X"></param>
/// <returns></returns>
public static double[] Sort(double[] X)
{
ArrayList temp = new ArrayList(X);
temp.Sort();
return X = (double[])temp.ToArray(typeof(double));
}
/// <summary>
/// 已知表格行数为m各行的数值分别记为 ,其中 表示第 行的数值,
/// 将这 个数值由小到大排列,记排列后的数值为 ,其中 表示 个数值经排列之后第k个数值。
/// 给定上下标线数值0.99865和0.00135。计算Q上和Q下的方法为
///a = m - 1* 0.99865
///取a的整数部分为i小数部分为j。
///Q上 = 1 j* xi+1+ j * xi+2
///同理:
///b = m - 1* 0.00135
///取b的整数部分为i小数部分为j。
///Q下 = 1 j* xi+1+ j * xi+2
/// </summary>
/// <param name="X">被分析数据组</param>
/// <param name="QU">百分比上限</param>
/// <param name="QL">百分比下限</param>
public static void QU_QL(double[] X, out double QU, out double QL)
{
QU = 0;
QL = 0;
double QU_n;
int QU_n_i;
double QU_n_j;
double QL_n;
int QL_n_i;
double QL_n_j;
X = Sort(X);
QU_n = (double)(X.Length - 1) * QU_k;
QU_n_i = (int)QU_n;
QU_n_j = QU_n - QU_n_i;
//Q上 = 1 j* xi+1+ j * xi+2
QU = (1 - QU_n_j) * X[QU_n_i] + QU_n_j * X[QU_n_i + 1];
QL_n = (double)(X.Length - 1) * QL_k;
QL_n_i = (int)QL_n;
QL_n_j = QL_n - QL_n_i;
//Q下 = 1 j* xi+1+ j * xi+2
QL = (1 - QL_n_j) * X[QL_n_i] + QL_n_j * X[QL_n_i + 1];
return;
}
/// <summary>
/// 工序能力
/// </summary>
/// <param name="X">被分析数据组</param>
/// <param name="Usl">理论上限</param>
/// <param name="Lsl">理论下限</param>
/// <returns>工序能力</returns>
public static double Cp(double[] X, double Usl, double Lsl)
{
double QU;
double QL;
double cp = 0;
QU_QL(X, out QU, out QL);
cp = (Usl - Lsl) / (QU - QL);
return cp;
}
/// <summary>
/// 工序能力
/// </summary>
/// <param name="QU">百分比上限</param>
/// <param name="QL">百分比下限</param>
/// <param name="Usl">理论上限</param>
/// <param name="Lsl">理论下限</param>
/// <returns></returns>
public static double Cp(double QU, double QL, double Usl, double Lsl)
{
double cp = 0;
cp = (Usl - Lsl) / (QU - QL);
return cp;
}
/// <summary>
/// 工序能力指数
/// </summary>
/// <param name="[] X">被分析数据组</param>
/// <param name="Usl">理论上限</param>
/// <param name="Lsl">理论下限</param>
/// <returns></returns>
public static double Cpk(double[] X, double Usl, double Lsl)
{
double cpk;
double cpkU;
double cpkL;
double QU;
double QL;
double cp = 0;
//均方差
double s;
//均值
double x;
x = AVERAGE(X);
QU_QL(X, out QU, out QL);
cp = (Usl - Lsl) / (QU - QL);
cpkU = (Usl - x) / (QU - x);
cpkL = (Lsl - x) / (QL - x);
cpk = Math.Min(cpkU, cpkL);
return cpk;
}
/// <summary>
/// 工序能力指数
/// </summary>
/// <param name="x">平均值</param>
/// <param name="QU">百分比上限</param>
/// <param name="QL">百分比下限</param>
/// <param name="Usl">理论上限</param>
/// <param name="Lsl">理论下限</param>
/// <returns></returns>
public static double Cpk(double x, double QU, double QL, double Usl, double Lsl)
{
double cpk;
double cpkU;
double cpkL;
double cp = 0;
cp = Cp(QU, QL, Usl, Lsl);
cpkU = (Usl - x) / (QU - x);
cpkL = (x - Lsl) / (x - QL);
cpk = Math.Min(cpkU, cpkL);
return cpk;
}
/// <summary>
/// 计算正态分布的x坐标y坐标
/// </summary>
/// <param name="s">均方差</param>
/// <param name="x">平均值</param>
public static void sxy(double s, double x, out double[] sx, out double[] sy)
{
double S2;
double X2;
X2 = x;
S2 = s;
sx = new double[11];
sy = new double[11];
double tempmaxdouble = 1.0 / (s * Math.Sqrt(2.0 * Math.PI));
sx[0] = X2 - 4.0 * S2;
sx[1] = X2 - 3.0 * S2;
sx[2] = X2 - 2.0 * S2;
sx[3] = X2 - 1.0 * S2;
sx[4] = X2 - 0.5 * S2;
sx[5] = X2;
sx[6] = X2 + 0.5 * S2;
sx[7] = X2 + 1.0 * S2;
sx[8] = X2 + 2.0 * S2;
sx[9] = X2 + 3.0 * S2;
sx[10] = X2 + 4.0 * S2;
sy[0] = tempmaxdouble * Math.Exp(-16.0F / 2.0F);
sy[1] = tempmaxdouble * Math.Exp(-9.0F / 2.0F);
sy[2] = tempmaxdouble * Math.Exp(-4.0F / 2.0F);
sy[3] = tempmaxdouble * Math.Exp(-1.0F / 2.0F);
sy[4] = tempmaxdouble * Math.Exp(-0.25F / 2.0F);
sy[5] = tempmaxdouble;
sy[6] = tempmaxdouble * Math.Exp(-0.25F / 2.0F);
sy[7] = tempmaxdouble * Math.Exp(-1.0F / 2.0F);
sy[8] = tempmaxdouble * Math.Exp(-4.0F / 2.0F);
sy[9] = tempmaxdouble * Math.Exp(-9.0F / 2.0F);
sy[10] = tempmaxdouble * Math.Exp(-16.0F / 2.0F);
double sy_sum = 0;
for (int i = 0; i < sy.Length; i++)
{
sy_sum = sy_sum + sy[i];
}
for (int i = 0; i < sy.Length; i++)
{
sy[i] = sy[i] / sy_sum;
}
}
/// <summary>
/// 根据查询的数据,获得理论上限,理论下限
/// </summary>
/// <param name="dl"></param>
/// <param name="Usl">理论上限</param>
/// <param name="Lsl">理论下限</param>
public static void GetUslLsl(DataTable dt, out double Usl, out double Lsl)
{
Usl = 0;
Lsl = 0;
if (dt != null)
{
if (dt.Rows.Count > 0)
{
try
{
//Usl = Convert.ToDouble(dt.Rows[0]["上限值"]);
//Lsl = Convert.ToDouble(dt.Rows[0]["下限值"]);
Usl = 100;
Lsl = 100;
}
catch
{
Usl = 0;
Lsl = 0;
}
}
}
}
}
/// <summary>
/// 测试数据
/// </summary>
public class Spc_Data_TestData
{
/// <summary>
/// 子组大小。单个子组观测值的个数
/// </summary>
static public int n = 5;
/// <summary>
/// 子组个数
/// </summary>
static public int k = 30;
/// <summary>
/// 特征值上限
/// </summary>
static public double USL = 1.7;
/// <summary>
/// 特征值下限
/// </summary>
static public double LSL = 1.5;
/// <summary>
/// 特征值上限
/// </summary>
static public double USL1 = 1.0;
/// <summary>
/// 特征值下限
/// </summary>
static public double LSL1 = 0.9;
/// <summary>
/// 特征值上限
/// </summary>
static public double USL2 = 1.15;
/// <summary>
/// 特征值下限
/// </summary>
static public double LSL2 = 1.10;
/// <summary>
/// 特征值上限
/// </summary>
static public double USL3 = 129.01;
/// <summary>
/// 特征值下限
/// </summary>
static public double LSL3 = 129;
static public double[] X3 =
{
129.006,129.006,129.006,129.005,129.006,
129.006,129.005,129.005,129.005,129.005,
129.005,129.006,129.007,129.006,129.005,
129.005,129.005,129.006,129.005,129.006,
129.006,129.006,129.007,129.006,129.005,
129.007,129.006,129.005,129.005,129.006,
129.006,129.007,129.005,129.005,129.005,
129.007,129.006,129.006,129.007,129.005,
129.007,129.005,129.005,129.006,129.007,
129.006,129.007,129.005,129.005,129.006
};
static public double[] X2 =
{
1.141,1.130,1.131,1.127,1.137,
1.140,1.137,1.130,1.135,1.125,
1.133,1.133,1.131,1.128,1.127,
1.122,1.131,1.131,1.125,1.123,
1.131,1.128,1.117,1.133,1.136,
1.123,1.128,1.135,1.127,1.130,
1.138,1.126,1.130,1.133,1.133,
1.130,1.127,1.128,1.127,1.128,
1.122,1.142,1.128,1.135,1.133,
1.142,1.127,1.133,1.135,1.135
};
static public double[] X1 =
{ 0.941,0.942,0.947,0.939,0.942,0.943,
0.942,0.950,0.943,0.948,0.941,0.953,
0.944,0.943,0.941,0.933,0.942,0.941,
0.942,0.942,0.942,0.947,0.938,0.941,
0.947,0.943,0.943,0.948,0.938,0.946,
0.946,0.943,0.945,0.946,0.942,0.951,
0.951,0.938,0.938,0.952,0.947,0.945,
0.951,0.948,0.946,0.947,0.947,0.947,
0.953,0.956
};
static public double[] X =
{ 1.55,1.58,1.61,1.60,1.60,//1
1.58,1.63,1.63,1.62,1.63,//2
1.62,1.63,1.62,1.59,1.58,//3
1.58,1.60,1.61,1.62,1.63,//4
1.58,1.64,1.63,1.62,1.62,//5
1.62,1.62,1.63,1.61,1.57,//6
1.64,1.62,1.61,1.60,1.58,//7
1.57,1.59,1.61,1.62,1.63,//8
1.58,1.61,1.60,1.62,1.63,//9
1.60,1.61,1.64,1.64,1.63,//10
1.58,1.60,1.62,1.63,1.65,//11
1.62,1.58,1.59,1.57,1.58,//12
1.57,1.57,1.58,1.59,1.64,//13
1.61,1.64,1.62,1.60,1.59,//14
1.65,1.62,1.62,1.60,1.58,//15
1.57,1.59,1.57,1.59,1.62,//16
1.56,1.57,1.57,1.61,1.62,//17
1.56,1.58,1.59,1.60,1.62,//18
1.58,1.60,1.60,1.62,1.63,//19
1.58,1.59,1.60,1.63,1.62,//20
1.58,1.59,1.62,1.63,1.64,//21
1.58,1.59,1.62,1.63,1.61,//22
1.58,1.59,1.60,1.61,1.63,//23
1.57,1.59,1.61,1.61,1.62,//24
1.58,1.58,1.60,1.61,1.63,//25
1.62,1.58,1.58,1.58,1.57,//26
1.63,1.59,1.57,1.58,1.57,//27
1.58,1.62,1.61,1.63,1.61,//28
1.58,1.57,1.59,1.60,1.62,//29
1.62,1.60,1.60,1.57,1.57 //30
};
}

View File

Binary file not shown.

BIN
App_code/vssver2.scc Normal file

Binary file not shown.

167
App_code/webChatClient.cs Normal file
View File

@@ -0,0 +1,167 @@
using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using MES_SPC;
namespace ChatClient
{
public static class webChatClient
{
private static bool stopFlag;
/// <summary>
/// 服务器是否反馈
/// </summary>
public static bool ServersResponse = false;
/// <summary>
/// 命令状态
/// </summary>
public static bool commandstatus = false;
/// <summary>
/// 是否正忙
/// </summary>
public static bool isworking = false;
//与服务器的连接
static TcpClient tcpClient= new TcpClient();
//与服务器数据交互的流通道
private static NetworkStream Stream;
////客户端的状态
//private static string CLOSED = "closed";
//private static string CONNECTED = "connected";
//private static string state = CLOSED;
////private static bool stopFlag;
static bool connect()
{
string HostName = ApplicationConfiguration.GPRSDataHost; ;
//IPHostEntry dnstoip = new IPHostEntry();
//dnstoip = Dns.GetHostEntry(HostName);
//string HostIP = dnstoip.AddressList[0].ToString();
string Port = ApplicationConfiguration.GPRSDataPort;
return connect(HostName, Port);
}
private static bool connect(string HostName, string Port)
{
try
{
if (!tcpClient.Connected)
{
tcpClient = new TcpClient();
tcpClient = TcpClientConnector.Connect(HostName, Int32.Parse(Port), 1000);
Stream = tcpClient.GetStream();
//Thread thread = new Thread(new ThreadStart(ServerResponse));
//thread.Start();
string cmd = "CONN|" + "WEB" + "|!";
Byte[] outbytes = System.Text.Encoding.Default.GetBytes(
cmd.ToCharArray());
Stream.Write(outbytes, 0, outbytes.Length);
}
return true;
}
catch (Exception ex)
{
return false;
}
}
//当单击“离开”按钮时便进入了btnExit_Click 处理程序。
//在btnExit_Click 处理程序中,
//将“EXIT”命令发送给服务器此命令格式要与服务器端的命令格式一致
private static void EXIT()
{
try
{
if (tcpClient.Connected)
{
string message = "EXIT|" + "WEB" + "|!";
//将字符串转化为字符数组
Byte[] outbytes = System.Text.Encoding.Default.GetBytes(
message.ToCharArray());
Stream.Write(outbytes, 0, outbytes.Length);
tcpClient.Close();
}
}
catch { }
}
private static void ServerResponse()
{
//定义一个byte数组用于接收从服务器端发送来的数据
//每次所能接收的数据包的最大长度为1024个字节
byte[] buff = new byte[1024];
string msg;
int len;
try
{
if (!Stream.CanRead)
{
//return "不可读";
return;
}
stopFlag = false;
while (!stopFlag)
{
//从流中得到数据并存入到buff字符数组中
len = Stream.Read(buff, 0, buff.Length);
if (len < 1)
{
Thread.Sleep(200);
continue;
}
ServersResponse = true;
}
tcpClient.Close();
//关闭连接
}
catch
{
//return "网络发生错误";
}
}
static string command = "";
//当点击“发送”按钮时便会进入btnSend_Click处理程序。
//在btnSend_Click处理程序中如果不是私聊
//将“CHAT”命令发送给服务器
//否则为私聊将“PRIV”命令发送给服务器
//注意命令格式一定要与服务器端的命令格式一致
public static void sentmessage(string GPRScommand)
{
if (isworking)
{
return;
}
isworking = true;
try
{
command = GPRScommand;
commandstatus = false;
if (connect())
{
byte[] outbytes = System.Text.Encoding.ASCII.GetBytes(command.ToCharArray());
Stream.Write(outbytes, 0, outbytes.Length);
commandstatus = true;
}
else
{
commandstatus = false;
}
}
catch (Exception err)
{
tcpClient.Close();
commandstatus = false;
}
isworking = false;
}
}
}

BIN
Bin/ASPNet_Drawing.dll Normal file

Binary file not shown.

8722
Bin/ASPNet_Drawing.xml Normal file

File diff suppressed because it is too large Load Diff

BIN
Bin/Aspose.Cells.dll Normal file

Binary file not shown.

BIN
Bin/BasicData.dll Normal file

Binary file not shown.

BIN
Bin/DataLinkMesWork.dll Normal file

Binary file not shown.

4511
Bin/DataLinkMesWork.xml Normal file

File diff suppressed because it is too large Load Diff

Binary file not shown.

File diff suppressed because it is too large Load Diff

BIN
Bin/MES_SPC.dll Normal file

Binary file not shown.

BIN
Bin/NPOI.OOXML.dll Normal file

Binary file not shown.

9621
Bin/NPOI.OOXML.xml Normal file

File diff suppressed because it is too large Load Diff

BIN
Bin/NPOI.OpenXml4Net.dll Normal file

Binary file not shown.

3019
Bin/NPOI.OpenXml4Net.xml Normal file

File diff suppressed because it is too large Load Diff

BIN
Bin/NPOI.OpenXmlFormats.dll Normal file

Binary file not shown.

BIN
Bin/NPOI.dll Normal file

Binary file not shown.

43613
Bin/NPOI.xml Normal file

File diff suppressed because it is too large Load Diff

BIN
Bin/Newtonsoft.Json.dll Normal file

Binary file not shown.

Binary file not shown.

BIN
Bin/Spire.License.dll Normal file

Binary file not shown.

BIN
Bin/Spire.Pdf.dll Normal file

Binary file not shown.

BIN
Bin/Spire.XLS.dll Normal file

Binary file not shown.

BIN
Bin/WriteExcelNPOI.dll Normal file

Binary file not shown.

1265
Bin/WriteExcelNPOI.xml Normal file

File diff suppressed because it is too large Load Diff

0
Bin/_system~.ini Normal file
View File

0
JS/_system~.ini Normal file
View File

4
JS/jquery-3.2.1.min.js vendored Normal file

File diff suppressed because one or more lines are too long

63
MES_Manage.sln Normal file
View File

@@ -0,0 +1,63 @@
Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 16
VisualStudioVersion = 16.0.30002.166
MinimumVisualStudioVersion = 10.0.40219.1
Project("{E24C65DC-7377-472B-9ABA-BC803B73C61A}") = "MES_Manage", ".", "{4F66CC1F-BFDE-4EEA-B800-7CF049E5176A}"
ProjectSection(WebsiteProperties) = preProject
TargetFrameworkMoniker = ".NETFramework,Version%3Dv4.0"
ProjectReferences = "{97127b87-d43d-457c-9894-5f2244e4d2e7}|DataLinkMesWork.dll;{d7e149c7-a7e2-41c7-a3d3-af5d2efc9af8}|WriteExcelNPOI.dll;"
Debug.AspNetCompiler.VirtualPath = "/localhost_57966"
Debug.AspNetCompiler.PhysicalPath = "..\MES_Manage\"
Debug.AspNetCompiler.TargetPath = "PrecompiledWeb\localhost_57966\"
Debug.AspNetCompiler.Updateable = "true"
Debug.AspNetCompiler.ForceOverwrite = "true"
Debug.AspNetCompiler.FixedNames = "false"
Debug.AspNetCompiler.Debug = "True"
Release.AspNetCompiler.VirtualPath = "/localhost_57966"
Release.AspNetCompiler.PhysicalPath = "..\MES_Manage\"
Release.AspNetCompiler.TargetPath = "PrecompiledWeb\localhost_57966\"
Release.AspNetCompiler.Updateable = "true"
Release.AspNetCompiler.ForceOverwrite = "true"
Release.AspNetCompiler.FixedNames = "false"
Release.AspNetCompiler.Debug = "False"
VWDPort = "57966"
SlnRelativePath = "..\MES_Manage\"
EndProjectSection
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "03.WriteExcelNPOI", "..\03.WriteExcelNPOI\03.WriteExcelNPOI.csproj", "{D7E149C7-A7E2-41C7-A3D3-AF5D2EFC9AF8}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "02DataLinkMesWork", "..\02DataLinkMesWork\02DataLinkMesWork.csproj", "{97127B87-D43D-457C-9894-5F2244E4D2E7}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "07_WinformApiApp", "..\WinformApiApp\07_WinformApiApp.csproj", "{802E9943-6998-4BBF-B901-FF79FFB53584}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{4F66CC1F-BFDE-4EEA-B800-7CF049E5176A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{4F66CC1F-BFDE-4EEA-B800-7CF049E5176A}.Debug|Any CPU.Build.0 = Debug|Any CPU
{4F66CC1F-BFDE-4EEA-B800-7CF049E5176A}.Release|Any CPU.ActiveCfg = Debug|Any CPU
{4F66CC1F-BFDE-4EEA-B800-7CF049E5176A}.Release|Any CPU.Build.0 = Debug|Any CPU
{D7E149C7-A7E2-41C7-A3D3-AF5D2EFC9AF8}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{D7E149C7-A7E2-41C7-A3D3-AF5D2EFC9AF8}.Debug|Any CPU.Build.0 = Debug|Any CPU
{D7E149C7-A7E2-41C7-A3D3-AF5D2EFC9AF8}.Release|Any CPU.ActiveCfg = Release|Any CPU
{D7E149C7-A7E2-41C7-A3D3-AF5D2EFC9AF8}.Release|Any CPU.Build.0 = Release|Any CPU
{97127B87-D43D-457C-9894-5F2244E4D2E7}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{97127B87-D43D-457C-9894-5F2244E4D2E7}.Debug|Any CPU.Build.0 = Debug|Any CPU
{97127B87-D43D-457C-9894-5F2244E4D2E7}.Release|Any CPU.ActiveCfg = Release|Any CPU
{97127B87-D43D-457C-9894-5F2244E4D2E7}.Release|Any CPU.Build.0 = Release|Any CPU
{802E9943-6998-4BBF-B901-FF79FFB53584}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{802E9943-6998-4BBF-B901-FF79FFB53584}.Debug|Any CPU.Build.0 = Debug|Any CPU
{802E9943-6998-4BBF-B901-FF79FFB53584}.Release|Any CPU.ActiveCfg = Release|Any CPU
{802E9943-6998-4BBF-B901-FF79FFB53584}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {1F054BAF-3BFA-42C6-BF56-4717FA1418A2}
EndGlobalSection
EndGlobal

BIN
TemplateMES.xls Normal file

Binary file not shown.

174
Web.config Normal file
View File

@@ -0,0 +1,174 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
有关如何配置 ASP.NET 应用程序的详细信息,请访问
http://go.microsoft.com/fwlink/?LinkId=169433
-->
<configuration>
<appSettings>
<!--<add key="ERP_ConnectionString" value="server=192.168.137.1;database=MacroinfBasicDB_JF;uid=sa;pwd=126.com;Connection Reset=FALSE;Max Pool Size = 1000"/>-->
<!--<add key="ConnectionString" value="server=.;database=MW-MES20180331;uid=sa;pwd=126.com;Connection Reset=FALSE;Max Pool Size = 1000" />-->
<!--<add key="ConnectionString" value="server=.;database=ERPTOOL_HPP;uid=sa;pwd=126.com;Connection Reset=FALSE;Max Pool Size = 1000" />-->
<!--<add key="ConnectionString" value="server=.,1333;database=MESBasicDB_HL;uid=sa;pwd=126.com;Connection Reset=FALSE;Max Pool Size = 1000" />-->
<add key="ConnectionString" value="server=.;database=WC_WP12T_13L;uid=sa;pwd=126.com;Connection Reset=FALSE;Max Pool Size = 1000" />
<!--<add key="ConnectionString" value="server=.\MSSQLSERVER2012;database=MES_ManagerTest;uid=sa;pwd=126.com;Connection Reset=FALSE;Max Pool Size = 1000" />-->
<!--<add key="ConnectionString" value="server=120.26.210.14\SQL2012,1433;database=SL;uid=sa;pwd=126.com;Connection Reset=FALSE;Max Pool Size = 1000" />-->
<add key="ConnectionString01" value="server=119.45.113.185\DB01;database=EMS;uid=sa;pwd=126.com;Connection Reset=FALSE;Max Pool Size = 1000" />
<add key="ConnectionString02" value="server=119.45.113.185\DB02;database=DB02;uid=sa;pwd=126.com;Connection Reset=FALSE;Max Pool Size = 1000" />
<add key="ConnectionString03" value="server=119.45.113.185\DB03;database=DB03;uid=sa;pwd=126.com;Connection Reset=FALSE;Max Pool Size = 1000" />
<add key="ConnectionString04" value="server=119.45.113.185\DB04;database=DB04;uid=sa;pwd=126.com;Connection Reset=FALSE;Max Pool Size = 1000" />
<add key="ConnectionString05" value="server=119.45.113.185\DB05;database=DB05;uid=sa;pwd=126.com;Connection Reset=FALSE;Max Pool Size = 1000" />
<add key="ConnectionString06" value="server=119.45.113.185\DB06;database=DB06;uid=sa;pwd=126.com;Connection Reset=FALSE;Max Pool Size = 1000" />
<add key="ConnectionString07" value="server=119.45.113.185\DB07;database=DB07;uid=sa;pwd=126.com;Connection Reset=FALSE;Max Pool Size = 1000" />
<add key="ConnectionString08" value="server=119.45.113.185\DB08;database=DB08;uid=sa;pwd=126.com;Connection Reset=FALSE;Max Pool Size = 1000" />
<add key="ConnectionString09" value="server=119.45.113.185\DB09;database=DB09;uid=sa;pwd=126.com;Connection Reset=FALSE;Max Pool Size = 1000" />
<add key="ConnectionString10" value="server=119.45.113.185\DB10;database=DB10;uid=sa;pwd=126.com;Connection Reset=FALSE;Max Pool Size = 1000" />
<!--<add key="ConnectionString" value="server=123.56.95.229;database=ERPTOOL_GJ;uid=sa;pwd=126.com;Connection Reset=FALSE;Max Pool Size = 1000" />-->
<!--<add key="ConnectionString" value="server=192.168.1.171;database=海洋;uid=sa;pwd=126.com;Connection Reset=FALSE;Max Pool Size = 1000" />-->
<!--<add key="ConnectionString" value="server=.;database=ERPTOOL_GJ;uid=sa;pwd=126.com;Connection Reset=FALSE;Max Pool Size = 1000" />-->
<add key="SN" value="WEBa1a524c0" />
<add key="MESWORKSN" value="C:\meswork.sn" />
<add key="connectionStringL2" value="max pool size=512;server=192.168.1.212;database=AMSReport_L2;uid=sa;pwd=ea211"/>
<add key="TempPath" value="Temp"/>
<add key="TimeOut" value="600"/>
<!--生产线名:一线 or 二线 -->
<!--<add key="LineName" value="一线"/>-->
<add key="LineName" value="二线"/>
<add key="OpNumber1" value="39,40,41,54,55,135,225,258,382,60,84"/>
<add key="DataLen1" value="46"/>
<!--<add key="OpNumber1" value="39,40,41,54,55,135,225,382,60,84"/>
<add key="DataLen1" value="43"/>-->
<!--不含op258-->
<add key="OpNumber2" value="72,73,74,96,97,147,273,480,664,432"/>
<add key="DataLen2" value="45"/>
<add key="IsBakup" value="0" />
<add key="IsBakup01" value="0" />
<add key="IsBakup02" value="0" />
<add key="IsBakup03" value="0" />
<add key="IsBakup04" value="0" />
<add key="IsBakup05" value="0" />
<add key="IsBakup06" value="0" />
<add key="IsBakup07" value="0" />
<add key="IsBakup08" value="0" />
<add key="IsBakup09" value="0" />
<add key="IsBakup10" value="0" />
<add key="ConnectionStringBakup" value="server=.\BAK00;database=BAK00;uid=sa;pwd=126.com;Connection Reset=FALSE;Max Pool Size = 1000" />
<add key="ConnectionStringBakup01" value="server=.\BAK01;database=BAK01;uid=sa;pwd=126.com;Connection Reset=FALSE;Max Pool Size = 1000" />
<add key="ConnectionStringBakup02" value="server=.\BAK02;database=BAK02;uid=sa;pwd=126.com;Connection Reset=FALSE;Max Pool Size = 1000" />
<add key="ConnectionStringBakup03" value="server=.\BAK03;database=BAK03;uid=sa;pwd=126.com;Connection Reset=FALSE;Max Pool Size = 1000" />
<add key="ConnectionStringBakup04" value="server=.\BAK04;database=BAK04;uid=sa;pwd=126.com;Connection Reset=FALSE;Max Pool Size = 1000" />
<add key="ConnectionStringBakup05" value="server=.\BAK05;database=BAK05;uid=sa;pwd=126.com;Connection Reset=FALSE;Max Pool Size = 1000" />
<add key="ConnectionStringBakup06" value="server=.\BAK06;database=BAK06;uid=sa;pwd=126.com;Connection Reset=FALSE;Max Pool Size = 1000" />
<add key="ConnectionStringBakup07" value="server=.\BAK07;database=BAK07;uid=sa;pwd=126.com;Connection Reset=FALSE;Max Pool Size = 1000" />
<add key="ConnectionStringBakup08" value="server=.\BAK08;database=BAK08;uid=sa;pwd=126.com;Connection Reset=FALSE;Max Pool Size = 1000" />
<add key="ConnectionStringBakup09" value="server=.\BAK09;database=BAK09;uid=sa;pwd=126.com;Connection Reset=FALSE;Max Pool Size = 1000" />
<add key="ConnectionStringBakup10" value="server=.\BAK10;database=BAK10;uid=sa;pwd=126.com;Connection Reset=FALSE;Max Pool Size = 1000" />
<add key="GPRSDataHost" value="61.51.183.90" />
<add key="GPRSDataPort" value="41101" />
<add key="TracingTraceFile" value="~/TracingTraceFile.txt" />
<add key="reportTempDir" value="C:\报表程序\excel模版" />
<add key="reportDir" value="C:\报表程序\excel输出" />
<add key="reportTempFileName" value="导入数据标准模块.xls" />
<add key="CollectorreportTempFileName" value="更换采集器导入模板 .xls" />
<add key="ChartImageHandler" value="storage=file;timeout=20;dir=F:\TempImageFiles\;" />
<add key="FilePath_exl" value="E:\研发规划\00MES平台\MES_Manage(20170318)\MES_Manage" />
<add key="vs:EnableBrowserLink" value="false" />
</appSettings>
<!--<connectionStrings>
<appSettings>
-->
<!--<add key="ERP_ConnectionString" value="server=GYF;database=ERPTOOL;uid=sa;pwd=sa;Connection Reset=FALSE;Max Pool Size = 1000"/>-->
<!--
-->
<!--<add key="ERP_ConnectionString" value="server=LIJIALIN;database=ERPTOOL_HPP;uid=sa;pwd=sa;Connection Reset=FALSE;Max Pool Size = 1000"/>-->
<!--
-->
<!--<add key="ERP_ConnectionString" value="server=work1;database=ERPTOOL20110111;uid=sa;pwd=sa;Connection Reset=FALSE;Max Pool Size = 1000"/>-->
<!--
<add key="ERP_ConnectionString" value="server=PUHUI;database=HeatManageSystem;uid=sa;pwd=126.com;Connection Reset=FALSE;Max Pool Size = 1000"/>
-->
<!--<add key="ERP_ConnectionString" value="server=GX;database=ERPTOOL20130117;uid=sa;pwd=126.com;Connection Reset=FALSE;Max Pool Size = 1000"/>-->
<!--
-->
<!-- -->
<!--
-->
<!-- 报表模版文件路径 -->
<!--
<add key="reportTempDir" value="C:\报表程序\excel模版"/>
-->
<!-- 报表文件输出路径 -->
<!--
<add key="reportDir" value="C:\报表程序\excel输出"/>
-->
<!-- 报表模版文件 -->
<!--
<add key="reportTempFileName" value="报表模版.XLS"/>
</appSettings>
<add name="ApplicationServices" connectionString="data source=.\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\aspnetdb.mdf;User Instance=true" providerName="System.Data.SqlClient"/>
</connectionStrings>-->
<system.web>
<httpRuntime executionTimeout="90" maxRequestLength="40960" useFullyQualifiedRedirectUrl="false" minFreeThreads="8" minLocalRequestFreeThreads="4" appRequestQueueLimit="100" />
<httpHandlers>
<add path="ChartImg.axd" verb="GET,HEAD,POST" type="System.Web.UI.DataVisualization.Charting.ChartHttpHandler, System.Web.DataVisualization, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" validate="false" />
</httpHandlers>
<pages>
<controls>
<add tagPrefix="asp" namespace="System.Web.UI.DataVisualization.Charting" assembly="System.Web.DataVisualization, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />
</controls>
</pages>
<compilation debug="true" targetFramework="4.0">
<assemblies>
<add assembly="System.Web.DataVisualization, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
</assemblies>
</compilation>
<authentication mode="Forms">
<forms loginUrl="~/Account/Login.aspx" timeout="2880" />
</authentication>
<membership>
<providers>
<clear />
<add name="AspNetSqlMembershipProvider" type="System.Web.Security.SqlMembershipProvider" connectionStringName="ApplicationServices" enablePasswordRetrieval="false" enablePasswordReset="true" requiresQuestionAndAnswer="false" requiresUniqueEmail="false" maxInvalidPasswordAttempts="5" minRequiredPasswordLength="6" minRequiredNonalphanumericCharacters="0" passwordAttemptWindow="10" applicationName="/" />
</providers>
</membership>
<profile>
<providers>
<clear />
<add name="AspNetSqlProfileProvider" type="System.Web.Profile.SqlProfileProvider" connectionStringName="ApplicationServices" applicationName="/" />
</providers>
</profile>
<roleManager enabled="false">
<providers>
<clear />
<add name="AspNetSqlRoleProvider" type="System.Web.Security.SqlRoleProvider" connectionStringName="ApplicationServices" applicationName="/" />
<add name="AspNetWindowsTokenRoleProvider" type="System.Web.Security.WindowsTokenRoleProvider" applicationName="/" />
</providers>
</roleManager>
</system.web>
<system.webServer>
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*" />
<add name="Access-Control-Allow-Headers" value="Content-Type" />
<add name="Access-Control-Allow-Methods" value="GET, POST, PUT, DELETE, OPTIONS" />
</customHeaders>
</httpProtocol>
<modules runAllManagedModulesForAllRequests="true" />
<handlers>
<remove name="ChartImageHandler" />
<add name="ChartImageHandler" preCondition="integratedMode" verb="GET,HEAD,POST" path="ChartImg.axd" type="System.Web.UI.DataVisualization.Charting.ChartHttpHandler, System.Web.DataVisualization, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />
</handlers>
<defaultDocument>
<files>
<add value="login.htm" />
</files>
</defaultDocument>
<validation validateIntegratedModeConfiguration="false" />
<directoryBrowse enabled="true" />
</system.webServer>
</configuration>

0
_system~.ini Normal file
View File

View File

View File

57
localhost_10020.sln Normal file
View File

@@ -0,0 +1,57 @@
Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 16
VisualStudioVersion = 16.0.33027.164
MinimumVisualStudioVersion = 10.0.40219.1
Project("{E24C65DC-7377-472B-9ABA-BC803B73C61A}") = "http://localhost:10020", "http://localhost:10020", "{8885E35C-E781-4514-BE5F-2B269779D632}"
ProjectSection(WebsiteProperties) = preProject
UseIISExpress = "false"
TargetFrameworkMoniker = ".NETFramework,Version%3Dv4.0"
ProjectReferences = "{97127b87-d43d-457c-9894-5f2244e4d2e7}|DataLinkMesWork.dll;"
Debug.AspNetCompiler.VirtualPath = "/localhost_10020"
Debug.AspNetCompiler.PhysicalPath = "D:\项目管理\18.迈思\公司项目代码\getSql\通讯服务器20220629wdq\通讯服务器20220629\MES_Manage\"
Debug.AspNetCompiler.TargetPath = "PrecompiledWeb\localhost_10020\"
Debug.AspNetCompiler.Updateable = "true"
Debug.AspNetCompiler.ForceOverwrite = "true"
Debug.AspNetCompiler.FixedNames = "false"
Debug.AspNetCompiler.Debug = "True"
Release.AspNetCompiler.VirtualPath = "/localhost_10020"
Release.AspNetCompiler.PhysicalPath = "D:\项目管理\18.迈思\公司项目代码\getSql\通讯服务器20220629wdq\通讯服务器20220629\MES_Manage\"
Release.AspNetCompiler.TargetPath = "PrecompiledWeb\localhost_10020\"
Release.AspNetCompiler.Updateable = "true"
Release.AspNetCompiler.ForceOverwrite = "true"
Release.AspNetCompiler.FixedNames = "false"
Release.AspNetCompiler.Debug = "False"
SlnRelativePath = "D:\项目管理\18.迈思\公司项目代码\getSql\通讯服务器20220629wdq\通讯服务器20220629\MES_Manage\"
EndProjectSection
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "02DataLinkMesWork", "..\02DataLinkMesWork\02DataLinkMesWork.csproj", "{97127B87-D43D-457C-9894-5F2244E4D2E7}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "03.WriteExcelNPOI", "..\03.WriteExcelNPOI\03.WriteExcelNPOI.csproj", "{D7E149C7-A7E2-41C7-A3D3-AF5D2EFC9AF8}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{8885E35C-E781-4514-BE5F-2B269779D632}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{8885E35C-E781-4514-BE5F-2B269779D632}.Debug|Any CPU.Build.0 = Debug|Any CPU
{8885E35C-E781-4514-BE5F-2B269779D632}.Release|Any CPU.ActiveCfg = Debug|Any CPU
{8885E35C-E781-4514-BE5F-2B269779D632}.Release|Any CPU.Build.0 = Debug|Any CPU
{97127B87-D43D-457C-9894-5F2244E4D2E7}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{97127B87-D43D-457C-9894-5F2244E4D2E7}.Debug|Any CPU.Build.0 = Debug|Any CPU
{97127B87-D43D-457C-9894-5F2244E4D2E7}.Release|Any CPU.ActiveCfg = Release|Any CPU
{97127B87-D43D-457C-9894-5F2244E4D2E7}.Release|Any CPU.Build.0 = Release|Any CPU
{D7E149C7-A7E2-41C7-A3D3-AF5D2EFC9AF8}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{D7E149C7-A7E2-41C7-A3D3-AF5D2EFC9AF8}.Debug|Any CPU.Build.0 = Debug|Any CPU
{D7E149C7-A7E2-41C7-A3D3-AF5D2EFC9AF8}.Release|Any CPU.ActiveCfg = Release|Any CPU
{D7E149C7-A7E2-41C7-A3D3-AF5D2EFC9AF8}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {2E15E713-0BF7-49DB-B842-15146A7B5EF6}
EndGlobalSection
EndGlobal

19
submit/Handler111.ashx Normal file
View File

@@ -0,0 +1,19 @@
<%@ WebHandler Language="C#" Class="Handler111" %>
using System;
using System.Web;
public class Handler111 : IHttpHandler {
public void ProcessRequest (HttpContext context) {
context.Response.ContentType = "text/plain";
context.Response.Write("Hello World");
}
public bool IsReusable {
get {
return false;
}
}
}

View File

@@ -0,0 +1,231 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Runtime.Serialization.Json;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using System.Web.Script.Serialization;
using System.Data;
public class JsonHelper
{
#region 序列化和反序列化
// 序列化
public static string JsonSerializer<T>(T t)
{
// 使用 DataContractJsonSerializer 将 T 对象序列化为内存流。
DataContractJsonSerializer jsonSerializer = new DataContractJsonSerializer(typeof(T));
MemoryStream ms = new MemoryStream();
// 使用 WriteObject 方法将 JSON 数据写入到流中。
jsonSerializer.WriteObject(ms, t);
// 流转字符串
string jsonString = Encoding.UTF8.GetString(ms.ToArray());
ms.Close();
//替换Json的Date字符串
string p = @"\\/Date\((\d+)\+\d+\)\\/";
MatchEvaluator matchEvaluator = new MatchEvaluator(ConvertJsonDateToDateString);
Regex reg = new Regex(p);
jsonString = reg.Replace(jsonString, matchEvaluator);
return jsonString;
}
public static T JsonDeserialize<T>(string jsonString)
{
//将"yyyy-MM-dd HH:mm:ss"格式的字符串转为"\/Date(1294499956278+0800)\/"格式
string p = @"\d{4}-\d{2}-\d{2}\s\d{2}:\d{2}:\d{2}";
MatchEvaluator matchEvaluator = new MatchEvaluator(ConvertDateStringToJsonDate);
Regex reg = new Regex(p);
jsonString = reg.Replace(jsonString, matchEvaluator);
DataContractJsonSerializer jsonSerializer = new DataContractJsonSerializer(typeof(T));
// 字符串转流
MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(jsonString));
// 通过使用 DataContractJsonSerializer 的 ReadObject 方法,将 JSON 编码数据反序列化为T
T obj = (T)jsonSerializer.ReadObject(ms);
return obj;
}
public static string ConvertJsonDateToDateString(Match match)
{
string result = string.Empty;
DateTime dateTime = new DateTime(1970, 1, 1);
dateTime = dateTime.AddMilliseconds(long.Parse(match.Groups[1].Value));
dateTime = dateTime.ToLocalTime();
result = dateTime.ToString("yyyy-MM-dd HH:mm:ss");
return result;
}
private static string ConvertDateStringToJsonDate(Match m)
{
string result = string.Empty;
DateTime dt = DateTime.Parse(m.Groups[0].Value);
dt = dt.ToUniversalTime();
TimeSpan ts = dt - DateTime.Parse("1970-01-01");
result = string.Format("\\/Date({0}+0800)\\/", ts.TotalMilliseconds);
return result;
}
#endregion
// 对象转换为Json
public static string ObjectToJson(object obj)
{
JavaScriptSerializer js = new JavaScriptSerializer();
try
{
return js.Serialize(obj);
}
catch (Exception exception)
{
throw new Exception(exception.Message);
}
}
// 数据表转化为集合
public static List<Dictionary<string, object>> DataTableToList(DataTable dt)
{
List<Dictionary<string, object>> list = new List<Dictionary<string, object>>();
foreach (DataRow dataRow in dt.Rows)
{
Dictionary<string, object> dic = new Dictionary<string, object>();
foreach (DataColumn dc in dt.Columns)
{
dic.Add(dc.ColumnName, dataRow[dc.ColumnName]);
}
list.Add(dic);
}
return list;
}
// 表转换为Json
public static string DataTableToJson(DataTable dt)
{
return ObjectToJson(DataTableToList(dt));
}
/// <summary>
/// 将DataTable中的数据转换成JSON格式
/// </summary>
/// <param name="dt">数据源DataTable</param>
/// <param name="displayCount">是否输出数据总条数</param>
/// <param name="totalcount">JSON中显示的数据总条数</param>
/// <returns></returns>
public static string CreateJsonParameters(DataTable dt, bool displayCount, int totalcount)
{
StringBuilder JsonString = new StringBuilder();
//Exception Handling
if (dt != null)
{
JsonString.Append("{ ");
JsonString.Append("\"rows\":[ ");
for (int i = 0; i < dt.Rows.Count; i++)
{
JsonString.Append("{ ");
for (int j = 0; j < dt.Columns.Count; j++)
{
if (j < dt.Columns.Count - 1)
{
//if (dt.Rows[i][j] == DBNull.Value) continue;
if (dt.Columns[j].DataType == typeof(bool))
{
JsonString.Append("\"JSON_" + dt.Columns[j].ColumnName.ToLower() + "\":" +
dt.Rows[i][j].ToString().ToLower() + ",");
}
else if (dt.Columns[j].DataType == typeof(string))
{
JsonString.Append("\"JSON_" + dt.Columns[j].ColumnName.ToLower() + "\":" + "\"" +
dt.Rows[i][j].ToString().Replace("\"", "\\\"") + "\",");
}
else
{
JsonString.Append("\"JSON_" + dt.Columns[j].ColumnName.ToLower() + "\":" + "\"" + dt.Rows[i][j] + "\",");
}
}
else if (j == dt.Columns.Count - 1)
{
//if (dt.Rows[i][j] == DBNull.Value) continue;
if (dt.Columns[j].DataType == typeof(bool))
{
JsonString.Append("\"JSON_" + dt.Columns[j].ColumnName.ToLower() + "\":" +
dt.Rows[i][j].ToString().ToLower());
}
else if (dt.Columns[j].DataType == typeof(string))
{
JsonString.Append("\"JSON_" + dt.Columns[j].ColumnName.ToLower() + "\":" + "\"" +
dt.Rows[i][j].ToString().Replace("\"", "\\\"") + "\"");
}
else
{
JsonString.Append("\"JSON_" + dt.Columns[j].ColumnName.ToLower() + "\":" + "\"" + dt.Rows[i][j] + "\"");
}
}
}
/*end Of String*/
if (i == dt.Rows.Count - 1)
{
JsonString.Append("} ");
}
else
{
JsonString.Append("}, ");
}
}
JsonString.Append("]");
if (displayCount)
{
JsonString.Append(",");
JsonString.Append("\"total\":");
JsonString.Append(totalcount);
}
JsonString.Append("}");
return JsonString.ToString().Replace("\n", "");
}
else
{
return null;
}
}
StringBuilder result = new StringBuilder();
StringBuilder sb = new StringBuilder();
/// <summary>
/// 根据DataTable生成EasyUI Tree Json树结构
/// </summary>
/// <param name="tabel">数据源</param>
/// <param name="idCol">ID列</param>
/// <param name="txtCol">Text列</param>
/// <param name="url">节点Url</param>
/// <param name="rela">关系字段</param>
/// <param name="pId">父ID</param>
public string GetTreeJsonByTable(DataTable tabel, string idCol, string txtCol, string url, string rela, object pId)
{
result.Append(sb.ToString());
sb.Clear();
if (tabel.Rows.Count > 0)
{
sb.Append("[");
string filer = string.Format("{0}='{1}'", rela, pId);
DataRow[] rows = tabel.Select(filer);
if (rows.Length > 0)
{
foreach (DataRow row in rows)
{
sb.Append("{\"id\":\"" + row[idCol] + "\",\"text\":\"" + row[txtCol] + "\",\"attributes\":\"" + row[url] + "\",\"state\":\"open\"");
if (tabel.Select(string.Format("{0}='{1}'", rela, row[idCol])).Length > 0)
{
sb.Append(",\"children\":");
GetTreeJsonByTable(tabel, idCol, txtCol, url, rela, row[idCol]);
result.Append(sb.ToString());
sb.Clear();
}
result.Append(sb.ToString());
sb.Clear();
sb.Append("},");
}
sb = sb.Remove(sb.Length - 1, 1);
}
sb.Append("]");
result.Append(sb.ToString());
sb.Clear();
}
return result.ToString();
}
}

1216
submit/MESCommonBase.ashx Normal file

File diff suppressed because it is too large Load Diff

267
submit/MESCommonBase01.ashx Normal file
View File

@@ -0,0 +1,267 @@
<%@ WebHandler Language="C#" Class="MESCommonBase01" %>
using System;
using System.Web;
using System.Text;
using System.Linq;
using System.Collections.Generic;
using System.IO;
using System.Web.Script.Serialization;
using System.Data;
//using BizDataAccess;
using System.Data.SqlClient;//<a href="uploadInvoiceScan.ashx">uploadInvoiceScan.ashx</a>
//using DbCallData;
using BasicData;
//using LitJson;
using DataLinkMesWork;
using System.Text.RegularExpressions;
public class MESCommonBase01 : IHttpHandler
{
public bool IsReusable
{
get
{
return false;
}
}
public void ProcessRequest(HttpContext context)
{
string connType = "01";
context.Response.ContentType = "application/json";
var data = context.Request;
var stream = new StreamReader(data.InputStream).ReadToEnd();
string InvoiceNum;
//JsonData jsonData;
string responseText = "NULL";
byte[] bytes = null;
string fileName = "test.xsl";
try
{
JsonData jsonData=null;
try
{
jsonData = JsonMapper.ToObject(stream);
}
catch(Exception err)
{ }
int type=0;
try
{
if(jsonData!=null)
{
if(jsonData.ContainsKey("Type"))
{
type = Int32.Parse( jsonData["Type"].ToString());
}else if(jsonData.ContainsKey("type"))
{
type = Int32.Parse( jsonData["type"].ToString());
}
}
}
catch
{
}
jsonobj dataobj=null;
try
{
dataobj = new JavaScriptSerializer().Deserialize<jsonobj>(stream);
if(dataobj!=null)
{
type = Int32.Parse(dataobj.Type);
}
}
catch(Exception err)
{
dataobj = null;
}
if(dataobj==null)
{
try
{
InvoiceNum = HttpContext.Current.Request["param"];
if(InvoiceNum!=null)
{
jsonData = JsonMapper.ToObject(InvoiceNum);
if(jsonData.ContainsKey("Type"))
{
type = Int32.Parse( jsonData["Type"].ToString());
}else if(jsonData.ContainsKey("type"))
{
type = Int32.Parse( jsonData["type"].ToString());
}
}
}
catch
{
jsonData = null;
}
}
string fileExtension="";
HttpFileCollection files;
string suffix;
string name;
switch(type)
{
case 2001:
//DataLink.LogJsonData(jsonData);
MESDownloadExcel.ExcelWebCall.ExcelFile(jsonData,out bytes,out fileName,ref fileExtension);
fileName = fileName + "."+fileExtension;
HttpContext.Current.Response.ContentType = "application/octet-stream";
//HttpContext.Current.Response.ContentType = getContentType(extension);
//通知浏览器下载文件而不是打开
HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode(fileName, System.Text.Encoding.UTF8));
HttpContext.Current.Response.AddHeader("Access-Control-Expose-Headers", "Content-Disposition");
HttpContext.Current.Response.BinaryWrite(bytes);
HttpContext.Current.Response.Flush();
HttpContext.Current.Response.End();
break;
case 2002:
//DataLink.LogJsonData(jsonData);
MESDownloadExcel.ExcelWebCall.ExcelFilePdf(jsonData,out bytes,out fileName,out fileExtension);
fileName = fileName + "."+fileExtension;
HttpContext.Current.Response.ContentType = "application/octet-stream";
//HttpContext.Current.Response.ContentType = getContentType(extension);
//通知浏览器下载文件而不是打开
HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode(fileName, System.Text.Encoding.UTF8));
HttpContext.Current.Response.AddHeader("Access-Control-Expose-Headers", "Content-Disposition");
HttpContext.Current.Response.BinaryWrite(bytes);
HttpContext.Current.Response.Flush();
HttpContext.Current.Response.End();
break;
case 2003:// 合成excel图片下载
string[] dataimg;
if(context.Request.Form.Keys.Count>0)
{
dataimg = data.Form.GetValues(0);
MESDownloadExcel.ExcelWebCall.ExcelFile(jsonData,out bytes,out fileName,ref dataimg[0]);
if (bytes == null) return;
fileName = fileName + "."+dataimg[0];
HttpContext.Current.Response.ContentType = "application/octet-stream";
//HttpContext.Current.Response.ContentType = getContentType(extension);
//通知浏览器下载文件而不是打开
HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode(fileName, System.Text.Encoding.UTF8));
HttpContext.Current.Response.AddHeader("Access-Control-Expose-Headers", "Content-Disposition");
HttpContext.Current.Response.BinaryWrite(bytes);
HttpContext.Current.Response.Flush();
HttpContext.Current.Response.End();
//if(DataLinkMesWork.DataLink.isBakup=="1")
//{
// DataLinkMesWork.DataLink.ExePROCEDURE_Type16_Bakup(jsonData, out bytes, out fileName, out suffix);
//}
}
break;
case 2004:
//DataLink.LogJsonData(jsonData);
DataLinkMesWork.DataLink.ExePROCEDURE_Type2004(connType,jsonData, out bytes, out fileName, out fileExtension);
//MESDownloadExcel.ExcelWebCall.ExcelFile(jsonData,out bytes,out fileName,ref fileExtension);
fileName = fileName + "."+fileExtension;
HttpContext.Current.Response.ContentType = "application/octet-stream";
//HttpContext.Current.Response.ContentType = getContentType(extension);
//通知浏览器下载文件而不是打开
HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode(fileName, System.Text.Encoding.UTF8));
HttpContext.Current.Response.AddHeader("Access-Control-Expose-Headers", "Content-Disposition");
HttpContext.Current.Response.BinaryWrite(bytes);
HttpContext.Current.Response.Flush();
HttpContext.Current.Response.End();
break;
case 15://上传文件
files = context.Request.Files;
if (files.Count > 0)
{
fileName = files[0].FileName;
bytes = new byte[files[0].InputStream.Length];
files[0].InputStream.Read(bytes, 0, bytes.Length);
suffix = fileName.Substring(fileName.LastIndexOf(".")+1);
name = fileName.Substring(0,fileName.LastIndexOf("."));
responseText = DataLinkMesWork.DataLink.ExePROCEDURE_Type15(connType,jsonData, name, suffix, bytes);
context.Response.Write(responseText);
//if(DataLinkMesWork.DataLink.isBakup=="1")
//{
// DataLinkMesWork.DataLink.ExePROCEDURE_Type15_Bakup(jsonData, name, suffix, bytes);
//}
}
else
{
fileName = "";
bytes = new byte[1];
suffix = "";
name = "";
responseText = DataLinkMesWork.DataLink.ExePROCEDURE_Type15(connType,jsonData, name, suffix, bytes);
context.Response.Write(responseText);
//if(DataLinkMesWork.DataLink.isBakup=="1")
//{
// DataLinkMesWork.DataLink.ExePROCEDURE_Type15_Bakup(jsonData, name, suffix, bytes);
//}
}
break;
case 16://上传文件
DataLink.LogJsonData(jsonData);
DataLinkMesWork.DataLink.ExePROCEDURE_Type16(connType,jsonData, out bytes, out fileName, out suffix);
if (bytes == null) return;
fileName = fileName + "."+suffix;
HttpContext.Current.Response.ContentType = "application/octet-stream";
//HttpContext.Current.Response.ContentType = getContentType(extension);
//通知浏览器下载文件而不是打开
HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode(fileName, System.Text.Encoding.UTF8));
HttpContext.Current.Response.AddHeader("Access-Control-Expose-Headers", "Content-Disposition");
HttpContext.Current.Response.BinaryWrite(bytes);
HttpContext.Current.Response.Flush();
HttpContext.Current.Response.End();
//if(DataLinkMesWork.DataLink.isBakup=="1")
//{
// DataLinkMesWork.DataLink.ExePROCEDURE_Type16_Bakup(jsonData, out bytes, out fileName, out suffix);
//}
break;
default:
//DataLink.LogJsonData(jsonData);
responseText = DataLinkMesWork.DataLink.SqlWebCall(connType,type,jsonData,dataobj);//.SqlWebCall(stream);
context.Response.Write(responseText);
//if(DataLinkMesWork.DataLink.isBakup=="1")
//{
// DataLinkMesWork.DataLink.SqlWebCall_Bakup(type,jsonData,dataobj);
//}
break;
}
}
catch(Exception err)
{
context.Response.Write(responseText);
}
}
}

257
submit/MESCommonBase02.ashx Normal file
View File

@@ -0,0 +1,257 @@
<%@ WebHandler Language="C#" Class="MESCommonBase02" %>
using System;
using System.Web;
using System.IO;
using System.Web.Script.Serialization;
using BasicData;
using DataLinkMesWork;
public class MESCommonBase02 : IHttpHandler
{
public bool IsReusable
{
get
{
return false;
}
}
public void ProcessRequest(HttpContext context)
{
string connType = "01";
context.Response.ContentType = "application/json";
var data = context.Request;
var stream = new StreamReader(data.InputStream).ReadToEnd();
string InvoiceNum;
//JsonData jsonData;
string responseText = "NULL";
byte[] bytes = null;
string fileName = "test.xsl";
try
{
JsonData jsonData=null;
try
{
jsonData = JsonMapper.ToObject(stream);
}
catch(Exception err)
{ }
int type=0;
try
{
if(jsonData!=null)
{
if(jsonData.ContainsKey("Type"))
{
type = Int32.Parse( jsonData["Type"].ToString());
}else if(jsonData.ContainsKey("type"))
{
type = Int32.Parse( jsonData["type"].ToString());
}
}
}
catch
{
}
jsonobj dataobj=null;
try
{
dataobj = new JavaScriptSerializer().Deserialize<jsonobj>(stream);
if(dataobj!=null)
{
type = Int32.Parse(dataobj.Type);
}
}
catch(Exception err)
{
dataobj = null;
}
if(dataobj==null)
{
try
{
InvoiceNum = HttpContext.Current.Request["param"];
if(InvoiceNum!=null)
{
jsonData = JsonMapper.ToObject(InvoiceNum);
if(jsonData.ContainsKey("Type"))
{
type = Int32.Parse( jsonData["Type"].ToString());
}else if(jsonData.ContainsKey("type"))
{
type = Int32.Parse( jsonData["type"].ToString());
}
}
}
catch
{
jsonData = null;
}
}
string fileExtension="";
HttpFileCollection files;
string suffix;
string name;
switch(type)
{
case 2001:
//DataLink.LogJsonData(jsonData);
MESDownloadExcel.ExcelWebCall.ExcelFile(jsonData,out bytes,out fileName,ref fileExtension);
fileName = fileName + "."+fileExtension;
HttpContext.Current.Response.ContentType = "application/octet-stream";
//HttpContext.Current.Response.ContentType = getContentType(extension);
//通知浏览器下载文件而不是打开
HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode(fileName, System.Text.Encoding.UTF8));
HttpContext.Current.Response.AddHeader("Access-Control-Expose-Headers", "Content-Disposition");
HttpContext.Current.Response.BinaryWrite(bytes);
HttpContext.Current.Response.Flush();
HttpContext.Current.Response.End();
break;
case 2002:
//DataLink.LogJsonData(jsonData);
MESDownloadExcel.ExcelWebCall.ExcelFilePdf(jsonData,out bytes,out fileName,out fileExtension);
fileName = fileName + "."+fileExtension;
HttpContext.Current.Response.ContentType = "application/octet-stream";
//HttpContext.Current.Response.ContentType = getContentType(extension);
//通知浏览器下载文件而不是打开
HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode(fileName, System.Text.Encoding.UTF8));
HttpContext.Current.Response.AddHeader("Access-Control-Expose-Headers", "Content-Disposition");
HttpContext.Current.Response.BinaryWrite(bytes);
HttpContext.Current.Response.Flush();
HttpContext.Current.Response.End();
break;
case 2003:// 合成excel图片下载
string[] dataimg;
if(context.Request.Form.Keys.Count>0)
{
dataimg = data.Form.GetValues(0);
MESDownloadExcel.ExcelWebCall.ExcelFile(jsonData,out bytes,out fileName,ref dataimg[0]);
if (bytes == null) return;
fileName = fileName + "."+dataimg[0];
HttpContext.Current.Response.ContentType = "application/octet-stream";
//HttpContext.Current.Response.ContentType = getContentType(extension);
//通知浏览器下载文件而不是打开
HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode(fileName, System.Text.Encoding.UTF8));
HttpContext.Current.Response.AddHeader("Access-Control-Expose-Headers", "Content-Disposition");
HttpContext.Current.Response.BinaryWrite(bytes);
HttpContext.Current.Response.Flush();
HttpContext.Current.Response.End();
//if(DataLinkMesWork.DataLink.isBakup=="1")
//{
// DataLinkMesWork.DataLink.ExePROCEDURE_Type16_Bakup(jsonData, out bytes, out fileName, out suffix);
//}
}
break;
case 2004:
//DataLink.LogJsonData(jsonData);
DataLinkMesWork.DataLink.ExePROCEDURE_Type2004(connType,jsonData, out bytes, out fileName, out fileExtension);
//MESDownloadExcel.ExcelWebCall.ExcelFile(jsonData,out bytes,out fileName,ref fileExtension);
fileName = fileName + "."+fileExtension;
HttpContext.Current.Response.ContentType = "application/octet-stream";
//HttpContext.Current.Response.ContentType = getContentType(extension);
//通知浏览器下载文件而不是打开
HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode(fileName, System.Text.Encoding.UTF8));
HttpContext.Current.Response.AddHeader("Access-Control-Expose-Headers", "Content-Disposition");
HttpContext.Current.Response.BinaryWrite(bytes);
HttpContext.Current.Response.Flush();
HttpContext.Current.Response.End();
break;
case 15://上传文件
files = context.Request.Files;
if (files.Count > 0)
{
fileName = files[0].FileName;
bytes = new byte[files[0].InputStream.Length];
files[0].InputStream.Read(bytes, 0, bytes.Length);
suffix = fileName.Substring(fileName.LastIndexOf(".")+1);
name = fileName.Substring(0,fileName.LastIndexOf("."));
responseText = DataLinkMesWork.DataLink.ExePROCEDURE_Type15(connType,jsonData, name, suffix, bytes);
context.Response.Write(responseText);
//if(DataLinkMesWork.DataLink.isBakup=="1")
//{
// DataLinkMesWork.DataLink.ExePROCEDURE_Type15_Bakup(jsonData, name, suffix, bytes);
//}
}
else
{
fileName = "";
bytes = new byte[1];
suffix = "";
name = "";
responseText = DataLinkMesWork.DataLink.ExePROCEDURE_Type15(connType,jsonData, name, suffix, bytes);
context.Response.Write(responseText);
//if(DataLinkMesWork.DataLink.isBakup=="1")
//{
// DataLinkMesWork.DataLink.ExePROCEDURE_Type15_Bakup(jsonData, name, suffix, bytes);
//}
}
break;
case 16://上传文件
DataLink.LogJsonData(jsonData);
DataLinkMesWork.DataLink.ExePROCEDURE_Type16(connType,jsonData, out bytes, out fileName, out suffix);
if (bytes == null) return;
fileName = fileName + "."+suffix;
HttpContext.Current.Response.ContentType = "application/octet-stream";
//HttpContext.Current.Response.ContentType = getContentType(extension);
//通知浏览器下载文件而不是打开
HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode(fileName, System.Text.Encoding.UTF8));
HttpContext.Current.Response.AddHeader("Access-Control-Expose-Headers", "Content-Disposition");
HttpContext.Current.Response.BinaryWrite(bytes);
HttpContext.Current.Response.Flush();
HttpContext.Current.Response.End();
//if(DataLinkMesWork.DataLink.isBakup=="1")
//{
// DataLinkMesWork.DataLink.ExePROCEDURE_Type16_Bakup(jsonData, out bytes, out fileName, out suffix);
//}
break;
default:
//DataLink.LogJsonData(jsonData);
responseText = DataLinkMesWork.DataLink.SqlWebCall(connType,type,jsonData,dataobj);//.SqlWebCall(stream);
context.Response.Write(responseText);
//if(DataLinkMesWork.DataLink.isBakup=="1")
//{
// DataLinkMesWork.DataLink.SqlWebCall_Bakup(type,jsonData,dataobj);
//}
break;
}
}
catch(Exception err)
{
context.Response.Write(responseText);
}
}
}

253
submit/MESCommonBase03.ashx Normal file
View File

@@ -0,0 +1,253 @@
<%@ WebHandler Language="C#" Class="MESCommonBase03" %>
using System;
using System.Web;
using System.IO;
using System.Web.Script.Serialization;
using BasicData;
using DataLinkMesWork;
public class MESCommonBase03 : IHttpHandler
{
public bool IsReusable
{
get
{
return false;
}
}
public void ProcessRequest(HttpContext context)
{
string connType = "03";
context.Response.ContentType = "application/json";
var data = context.Request;
var stream = new StreamReader(data.InputStream).ReadToEnd();
string InvoiceNum;
//JsonData jsonData;
string responseText = "NULL";
byte[] bytes = null;
string fileName = "test.xsl";
try
{
JsonData jsonData=null;
try
{
jsonData = JsonMapper.ToObject(stream);
}
catch(Exception err)
{ }
int type=0;
try
{
if(jsonData!=null)
{
if(jsonData.ContainsKey("Type"))
{
type = Int32.Parse( jsonData["Type"].ToString());
}else if(jsonData.ContainsKey("type"))
{
type = Int32.Parse( jsonData["type"].ToString());
}
}
}
catch
{
}
jsonobj dataobj=null;
try
{
dataobj = new JavaScriptSerializer().Deserialize<jsonobj>(stream);
if(dataobj!=null)
{
type = Int32.Parse(dataobj.Type);
}
}
catch(Exception err)
{
dataobj = null;
}
if(dataobj==null)
{
try
{
InvoiceNum = HttpContext.Current.Request["param"];
if(InvoiceNum!=null)
{
jsonData = JsonMapper.ToObject(InvoiceNum);
if(jsonData.ContainsKey("Type"))
{
type = Int32.Parse( jsonData["Type"].ToString());
}else if(jsonData.ContainsKey("type"))
{
type = Int32.Parse( jsonData["type"].ToString());
}
}
}
catch
{
jsonData = null;
}
}
string fileExtension="";
HttpFileCollection files;
string suffix;
string name;
switch(type)
{
case 2001:
//DataLink.LogJsonData(jsonData);
MESDownloadExcel.ExcelWebCall.ExcelFile(jsonData,out bytes,out fileName,ref fileExtension);
fileName = fileName + "."+fileExtension;
HttpContext.Current.Response.ContentType = "application/octet-stream";
//HttpContext.Current.Response.ContentType = getContentType(extension);
//通知浏览器下载文件而不是打开
HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode(fileName, System.Text.Encoding.UTF8));
HttpContext.Current.Response.AddHeader("Access-Control-Expose-Headers", "Content-Disposition");
HttpContext.Current.Response.BinaryWrite(bytes);
HttpContext.Current.Response.Flush();
HttpContext.Current.Response.End();
break;
case 2002:
//DataLink.LogJsonData(jsonData);
MESDownloadExcel.ExcelWebCall.ExcelFilePdf(jsonData,out bytes,out fileName,out fileExtension);
fileName = fileName + "."+fileExtension;
HttpContext.Current.Response.ContentType = "application/octet-stream";
//HttpContext.Current.Response.ContentType = getContentType(extension);
//通知浏览器下载文件而不是打开
HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode(fileName, System.Text.Encoding.UTF8));
HttpContext.Current.Response.AddHeader("Access-Control-Expose-Headers", "Content-Disposition");
HttpContext.Current.Response.BinaryWrite(bytes);
HttpContext.Current.Response.Flush();
HttpContext.Current.Response.End();
break;
case 2003:// 合成excel图片下载
string[] dataimg;
if(context.Request.Form.Keys.Count>0)
{
dataimg = data.Form.GetValues(0);
MESDownloadExcel.ExcelWebCall.ExcelFile(jsonData,out bytes,out fileName,ref dataimg[0]);
if (bytes == null) return;
fileName = fileName + "."+dataimg[0];
HttpContext.Current.Response.ContentType = "application/octet-stream";
//HttpContext.Current.Response.ContentType = getContentType(extension);
//通知浏览器下载文件而不是打开
HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode(fileName, System.Text.Encoding.UTF8));
HttpContext.Current.Response.AddHeader("Access-Control-Expose-Headers", "Content-Disposition");
HttpContext.Current.Response.BinaryWrite(bytes);
HttpContext.Current.Response.Flush();
HttpContext.Current.Response.End();
//if(DataLinkMesWork.DataLink.isBakup=="1")
//{
// DataLinkMesWork.DataLink.ExePROCEDURE_Type16_Bakup(jsonData, out bytes, out fileName, out suffix);
//}
}
break;
case 2004:
//DataLink.LogJsonData(jsonData);
DataLinkMesWork.DataLink.ExePROCEDURE_Type2004(connType,jsonData, out bytes, out fileName, out fileExtension);
//MESDownloadExcel.ExcelWebCall.ExcelFile(jsonData,out bytes,out fileName,ref fileExtension);
fileName = fileName + "."+fileExtension;
HttpContext.Current.Response.ContentType = "application/octet-stream";
//HttpContext.Current.Response.ContentType = getContentType(extension);
//通知浏览器下载文件而不是打开
HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode(fileName, System.Text.Encoding.UTF8));
HttpContext.Current.Response.AddHeader("Access-Control-Expose-Headers", "Content-Disposition");
HttpContext.Current.Response.BinaryWrite(bytes);
HttpContext.Current.Response.Flush();
HttpContext.Current.Response.End();
break;
case 15://上传文件
files = context.Request.Files;
if (files.Count > 0)
{
fileName = files[0].FileName;
bytes = new byte[files[0].InputStream.Length];
files[0].InputStream.Read(bytes, 0, bytes.Length);
suffix = fileName.Substring(fileName.LastIndexOf(".")+1);
name = fileName.Substring(0,fileName.LastIndexOf("."));
responseText = DataLinkMesWork.DataLink.ExePROCEDURE_Type15(connType,jsonData, name, suffix, bytes);
context.Response.Write(responseText);
//if(DataLinkMesWork.DataLink.isBakup=="1")
//{
// DataLinkMesWork.DataLink.ExePROCEDURE_Type15_Bakup(jsonData, name, suffix, bytes);
//}
}
else
{
fileName = "";
bytes = new byte[1];
suffix = "";
name = "";
responseText = DataLinkMesWork.DataLink.ExePROCEDURE_Type15(connType,jsonData, name, suffix, bytes);
context.Response.Write(responseText);
//if(DataLinkMesWork.DataLink.isBakup=="1")
//{
// DataLinkMesWork.DataLink.ExePROCEDURE_Type15_Bakup(jsonData, name, suffix, bytes);
//}
}
break;
case 16://上传文件
DataLink.LogJsonData(jsonData);
DataLinkMesWork.DataLink.ExePROCEDURE_Type16(connType,jsonData, out bytes, out fileName, out suffix);
if (bytes == null) return;
fileName = fileName + "."+suffix;
HttpContext.Current.Response.ContentType = "application/octet-stream";
//HttpContext.Current.Response.ContentType = getContentType(extension);
//通知浏览器下载文件而不是打开
HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode(fileName, System.Text.Encoding.UTF8));
HttpContext.Current.Response.AddHeader("Access-Control-Expose-Headers", "Content-Disposition");
HttpContext.Current.Response.BinaryWrite(bytes);
HttpContext.Current.Response.Flush();
HttpContext.Current.Response.End();
//if(DataLinkMesWork.DataLink.isBakup=="1")
//{
// DataLinkMesWork.DataLink.ExePROCEDURE_Type16_Bakup(jsonData, out bytes, out fileName, out suffix);
//}
break;
default:
//DataLink.LogJsonData(jsonData);
responseText = DataLinkMesWork.DataLink.SqlWebCall(connType,type,jsonData,dataobj);//.SqlWebCall(stream);
context.Response.Write(responseText);
//if(DataLinkMesWork.DataLink.isBakup=="1")
//{
// DataLinkMesWork.DataLink.SqlWebCall_Bakup(type,jsonData,dataobj);
//}
break;
}
}
catch(Exception err)
{
context.Response.Write(responseText);
}
}
}

View File

@@ -0,0 +1,22 @@
<%@ WebHandler Language="C#" Class="MESCommonBase04" %>
using System.Web;
public class MESCommonBase04 : IHttpHandler
{
public bool IsReusable
{
get
{
return false;
}
}
public void ProcessRequest(HttpContext context)
{
string connType = "04";
//ProcessRequestHttpContext.ProcessRequestServer.ProcessRequestHttpContext(connType, context);
}
}

209
submit/MESCommonBase05.ashx Normal file
View File

@@ -0,0 +1,209 @@
<%@ WebHandler Language="C#" Class="MESCommonBase05" %>
using System.Web;
public class MESCommonBase05 : IHttpHandler
{
public bool IsReusable
{
get
{
return false;
}
}
public void ProcessRequest(HttpContext context)
{
string connType = "05";
//ProcessRequestHttpContext.ProcessRequestServer.ProcessRequestHttpContext(connType, context);
}
//public void ProcessRequestHttpContext(string connType,HttpContext context)
//{
// context.Response.ContentType = "application/json";
// var data = context.Request;
// var stream = new StreamReader(data.InputStream).ReadToEnd();
// string InvoiceNum;
// //JsonData jsonData;
// string responseText = "NULL";
// byte[] bytes = null;
// string fileName = "test.xsl";
// try
// {
// JsonData jsonData=null;
// try
// {
// jsonData = JsonMapper.ToObject(stream);
// }
// catch(Exception err)
// { }
// int type=0;
// try
// {
// if(jsonData!=null)
// {
// if(jsonData.ContainsKey("Type"))
// {
// type = Int32.Parse( jsonData["Type"].ToString());
// }else if(jsonData.ContainsKey("type"))
// {
// type = Int32.Parse( jsonData["type"].ToString());
// }
// }
// }
// catch
// {
// }
// jsonobj dataobj=null;
// try
// {
// dataobj = new JavaScriptSerializer().Deserialize<jsonobj>(stream);
// if(dataobj!=null)
// {
// type = Int32.Parse(dataobj.Type);
// }
// }
// catch(Exception err)
// {
// dataobj = null;
// }
// if(dataobj==null)
// {
// try
// {
// InvoiceNum = HttpContext.Current.Request["param"];
// if(InvoiceNum!=null)
// {
// jsonData = JsonMapper.ToObject(InvoiceNum);
// if(jsonData.ContainsKey("Type"))
// {
// type = Int32.Parse( jsonData["Type"].ToString());
// }else if(jsonData.ContainsKey("type"))
// {
// type = Int32.Parse( jsonData["type"].ToString());
// }
// }
// }
// catch
// {
// jsonData = null;
// }
// }
// string fileExtension;
// HttpFileCollection files;
// string suffix;
// string name;
// switch(type)
// {
// case 2001:
// DataLink.LogJsonData(connType,jsonData);
// MESDownloadExcel.ExcelWebCall.ExcelFile(connType,jsonData,out bytes,out fileName,out fileExtension);
// fileName = fileName + "."+fileExtension;
// HttpContext.Current.Response.ContentType = "application/octet-stream";
// //HttpContext.Current.Response.ContentType = getContentType(extension);
// //通知浏览器下载文件而不是打开
// HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode(fileName, System.Text.Encoding.UTF8));
// HttpContext.Current.Response.AddHeader("Access-Control-Expose-Headers", "Content-Disposition");
// HttpContext.Current.Response.BinaryWrite(bytes);
// HttpContext.Current.Response.Flush();
// HttpContext.Current.Response.End();
// break;
// case 2002:
// DataLink.LogJsonData(connType,jsonData);
// MESDownloadExcel.ExcelWebCall.ExcelFilePdf(connType,jsonData,out bytes,out fileName,out fileExtension);
// fileName = fileName + "."+fileExtension;
// HttpContext.Current.Response.ContentType = "application/octet-stream";
// //HttpContext.Current.Response.ContentType = getContentType(extension);
// //通知浏览器下载文件而不是打开
// HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode(fileName, System.Text.Encoding.UTF8));
// HttpContext.Current.Response.AddHeader("Access-Control-Expose-Headers", "Content-Disposition");
// HttpContext.Current.Response.BinaryWrite(bytes);
// HttpContext.Current.Response.Flush();
// HttpContext.Current.Response.End();
// break;
// case 15://上传文件
// files = context.Request.Files;
// if (files.Count > 0)
// {
// fileName = files[0].FileName;
// bytes = new byte[files[0].InputStream.Length];
// files[0].InputStream.Read(bytes, 0, bytes.Length);
// suffix = fileName.Split(new Char[] { '.' })[1];
// name = fileName.Split(new Char[] { '.' })[0];
// DataLinkMesWork.DataLink.ExePROCEDURE_Type15(connType,jsonData, name, suffix, bytes);
// if(DataLinkMesWork.DataLink.isBakup=="1")
// {
// DataLinkMesWork.DataLink.ExePROCEDURE_Type15_Bakup(connType,jsonData, name, suffix, bytes);
// }
// }
// else
// {
// fileName = "";
// bytes = new byte[1];
// suffix = "";
// name = "";
// DataLinkMesWork.DataLink.ExePROCEDURE_Type15(connType,jsonData, name, suffix, bytes);
// if(DataLinkMesWork.DataLink.isBakup=="1")
// {
// DataLinkMesWork.DataLink.ExePROCEDURE_Type15_Bakup(connType,jsonData, name, suffix, bytes);
// }
// }
// break;
// case 16://上传文件
// DataLink.LogJsonData(jsonData);
// DataLinkMesWork.DataLink.ExePROCEDURE_Type16(connType,jsonData, out bytes, out fileName, out suffix);
// if (bytes == null) return;
// fileName = fileName + "."+suffix;
// HttpContext.Current.Response.ContentType = "application/octet-stream";
// //HttpContext.Current.Response.ContentType = getContentType(extension);
// //通知浏览器下载文件而不是打开
// HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode(fileName, System.Text.Encoding.UTF8));
// HttpContext.Current.Response.AddHeader("Access-Control-Expose-Headers", "Content-Disposition");
// HttpContext.Current.Response.BinaryWrite(bytes);
// HttpContext.Current.Response.Flush();
// HttpContext.Current.Response.End();
// if(DataLinkMesWork.DataLink.isBakup=="1")
// {
// DataLinkMesWork.DataLink.ExePROCEDURE_Type16_Bakup(connType,jsonData, out bytes, out fileName, out suffix);
// }
// break;
// default:
// DataLink.LogJsonData(jsonData);
// responseText = DataLinkMesWork.DataLink.SqlWebCall(connType,type,jsonData,dataobj);//.SqlWebCall(stream);
// context.Response.Write(responseText);
// string isBakup= DataLinkMesWork.DataLink.GetIsBakupByConnType(connType);
// if(isBakup=="1")
// {
// DataLinkMesWork.DataLink.SqlWebCall_Bakup(connType,type,jsonData,dataobj);
// }
// break;
// }
// }
// catch(Exception err)
// {
// context.Response.Write(responseText);
// }
//}
}

254
submit/MESCommonBase06.ashx Normal file
View File

@@ -0,0 +1,254 @@
<%@ WebHandler Language="C#" Class="MESCommonBase06" %>
using System;
using System.Web;
using System.IO;
using System.Web.Script.Serialization;
using BasicData;
using DataLinkMesWork;
public class MESCommonBase06 : IHttpHandler
{
public bool IsReusable
{
get
{
return false;
}
}
public void ProcessRequest(HttpContext context)
{
string connType = "06";
context.Response.ContentType = "application/json";
var data = context.Request;
var stream = new StreamReader(data.InputStream).ReadToEnd();
string InvoiceNum;
//JsonData jsonData;
string responseText = "NULL";
byte[] bytes = null;
string fileName = "test.xsl";
try
{
JsonData jsonData=null;
try
{
jsonData = JsonMapper.ToObject(stream);
}
catch(Exception err)
{ }
int type=0;
try
{
if(jsonData!=null)
{
if(jsonData.ContainsKey("Type"))
{
type = Int32.Parse( jsonData["Type"].ToString());
}else if(jsonData.ContainsKey("type"))
{
type = Int32.Parse( jsonData["type"].ToString());
}
}
}
catch
{
}
jsonobj dataobj=null;
try
{
dataobj = new JavaScriptSerializer().Deserialize<jsonobj>(stream);
if(dataobj!=null)
{
type = Int32.Parse(dataobj.Type);
}
}
catch(Exception err)
{
dataobj = null;
}
if(dataobj==null)
{
try
{
InvoiceNum = HttpContext.Current.Request["param"];
if(InvoiceNum!=null)
{
jsonData = JsonMapper.ToObject(InvoiceNum);
if(jsonData.ContainsKey("Type"))
{
type = Int32.Parse( jsonData["Type"].ToString());
}else if(jsonData.ContainsKey("type"))
{
type = Int32.Parse( jsonData["type"].ToString());
}
}
}
catch
{
jsonData = null;
}
}
string fileExtension="";
HttpFileCollection files;
string suffix;
string name;
switch(type)
{
case 2001:
//DataLink.LogJsonData(jsonData);
MESDownloadExcel.ExcelWebCall.ExcelFile(jsonData,out bytes,out fileName,ref fileExtension);
fileName = fileName + "."+fileExtension;
HttpContext.Current.Response.ContentType = "application/octet-stream";
//HttpContext.Current.Response.ContentType = getContentType(extension);
//通知浏览器下载文件而不是打开
HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode(fileName, System.Text.Encoding.UTF8));
HttpContext.Current.Response.AddHeader("Access-Control-Expose-Headers", "Content-Disposition");
HttpContext.Current.Response.BinaryWrite(bytes);
HttpContext.Current.Response.Flush();
HttpContext.Current.Response.End();
break;
case 2002:
//DataLink.LogJsonData(jsonData);
MESDownloadExcel.ExcelWebCall.ExcelFilePdf(jsonData,out bytes,out fileName,out fileExtension);
fileName = fileName + "."+fileExtension;
HttpContext.Current.Response.ContentType = "application/octet-stream";
//HttpContext.Current.Response.ContentType = getContentType(extension);
//通知浏览器下载文件而不是打开
HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode(fileName, System.Text.Encoding.UTF8));
HttpContext.Current.Response.AddHeader("Access-Control-Expose-Headers", "Content-Disposition");
HttpContext.Current.Response.BinaryWrite(bytes);
HttpContext.Current.Response.Flush();
HttpContext.Current.Response.End();
break;
case 2003:// 合成excel图片下载
string[] dataimg;
if(context.Request.Form.Keys.Count>0)
{
dataimg = data.Form.GetValues(0);
MESDownloadExcel.ExcelWebCall.ExcelFile(jsonData,out bytes,out fileName,ref dataimg[0]);
if (bytes == null) return;
fileName = fileName + "."+dataimg[0];
HttpContext.Current.Response.ContentType = "application/octet-stream";
//HttpContext.Current.Response.ContentType = getContentType(extension);
//通知浏览器下载文件而不是打开
HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode(fileName, System.Text.Encoding.UTF8));
HttpContext.Current.Response.AddHeader("Access-Control-Expose-Headers", "Content-Disposition");
HttpContext.Current.Response.BinaryWrite(bytes);
HttpContext.Current.Response.Flush();
HttpContext.Current.Response.End();
//if(DataLinkMesWork.DataLink.isBakup=="1")
//{
// DataLinkMesWork.DataLink.ExePROCEDURE_Type16_Bakup(jsonData, out bytes, out fileName, out suffix);
//}
}
break;
case 2004:
//DataLink.LogJsonData(jsonData);
DataLinkMesWork.DataLink.ExePROCEDURE_Type2004(connType,jsonData, out bytes, out fileName, out fileExtension);
//MESDownloadExcel.ExcelWebCall.ExcelFile(jsonData,out bytes,out fileName,ref fileExtension);
fileName = fileName + "."+fileExtension;
HttpContext.Current.Response.ContentType = "application/octet-stream";
//HttpContext.Current.Response.ContentType = getContentType(extension);
//通知浏览器下载文件而不是打开
HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode(fileName, System.Text.Encoding.UTF8));
HttpContext.Current.Response.AddHeader("Access-Control-Expose-Headers", "Content-Disposition");
HttpContext.Current.Response.BinaryWrite(bytes);
HttpContext.Current.Response.Flush();
HttpContext.Current.Response.End();
break;
case 15://上传文件
files = context.Request.Files;
if (files.Count > 0)
{
fileName = files[0].FileName;
bytes = new byte[files[0].InputStream.Length];
files[0].InputStream.Read(bytes, 0, bytes.Length);
suffix = fileName.Substring(fileName.LastIndexOf(".")+1);
name = fileName.Substring(0,fileName.LastIndexOf("."));
responseText = DataLinkMesWork.DataLink.ExePROCEDURE_Type15(connType,jsonData, name, suffix, bytes);
context.Response.Write(responseText);
//if(DataLinkMesWork.DataLink.isBakup=="1")
//{
// DataLinkMesWork.DataLink.ExePROCEDURE_Type15_Bakup(jsonData, name, suffix, bytes);
//}
}
else
{
fileName = "";
bytes = new byte[1];
suffix = "";
name = "";
responseText = DataLinkMesWork.DataLink.ExePROCEDURE_Type15(connType,jsonData, name, suffix, bytes);
context.Response.Write(responseText);
//if(DataLinkMesWork.DataLink.isBakup=="1")
//{
// DataLinkMesWork.DataLink.ExePROCEDURE_Type15_Bakup(jsonData, name, suffix, bytes);
//}
}
break;
case 16://上传文件
DataLink.LogJsonData(jsonData);
DataLinkMesWork.DataLink.ExePROCEDURE_Type16(connType,jsonData, out bytes, out fileName, out suffix);
if (bytes == null) return;
fileName = fileName + "."+suffix;
HttpContext.Current.Response.ContentType = "application/octet-stream";
//HttpContext.Current.Response.ContentType = getContentType(extension);
//通知浏览器下载文件而不是打开
HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode(fileName, System.Text.Encoding.UTF8));
HttpContext.Current.Response.AddHeader("Access-Control-Expose-Headers", "Content-Disposition");
HttpContext.Current.Response.BinaryWrite(bytes);
HttpContext.Current.Response.Flush();
HttpContext.Current.Response.End();
//if(DataLinkMesWork.DataLink.isBakup=="1")
//{
// DataLinkMesWork.DataLink.ExePROCEDURE_Type16_Bakup(jsonData, out bytes, out fileName, out suffix);
//}
break;
default:
//DataLink.LogJsonData(jsonData);
responseText = DataLinkMesWork.DataLink.SqlWebCall(connType,type,jsonData,dataobj);//.SqlWebCall(stream);
context.Response.Write(responseText);
//if(DataLinkMesWork.DataLink.isBakup=="1")
//{
// DataLinkMesWork.DataLink.SqlWebCall_Bakup(type,jsonData,dataobj);
//}
break;
}
}
catch(Exception err)
{
context.Response.Write(responseText);
}
}
}

254
submit/MESCommonBase07.ashx Normal file
View File

@@ -0,0 +1,254 @@
<%@ WebHandler Language="C#" Class="MESCommonBase07" %>
using System;
using System.Web;
using System.IO;
using System.Web.Script.Serialization;
using BasicData;
using DataLinkMesWork;
public class MESCommonBase07 : IHttpHandler
{
public bool IsReusable
{
get
{
return false;
}
}
public void ProcessRequest(HttpContext context)
{
string connType = "07";
context.Response.ContentType = "application/json";
var data = context.Request;
var stream = new StreamReader(data.InputStream).ReadToEnd();
string InvoiceNum;
//JsonData jsonData;
string responseText = "NULL";
byte[] bytes = null;
string fileName = "test.xsl";
try
{
JsonData jsonData=null;
try
{
jsonData = JsonMapper.ToObject(stream);
}
catch(Exception err)
{ }
int type=0;
try
{
if(jsonData!=null)
{
if(jsonData.ContainsKey("Type"))
{
type = Int32.Parse( jsonData["Type"].ToString());
}else if(jsonData.ContainsKey("type"))
{
type = Int32.Parse( jsonData["type"].ToString());
}
}
}
catch
{
}
jsonobj dataobj=null;
try
{
dataobj = new JavaScriptSerializer().Deserialize<jsonobj>(stream);
if(dataobj!=null)
{
type = Int32.Parse(dataobj.Type);
}
}
catch(Exception err)
{
dataobj = null;
}
if(dataobj==null)
{
try
{
InvoiceNum = HttpContext.Current.Request["param"];
if(InvoiceNum!=null)
{
jsonData = JsonMapper.ToObject(InvoiceNum);
if(jsonData.ContainsKey("Type"))
{
type = Int32.Parse( jsonData["Type"].ToString());
}else if(jsonData.ContainsKey("type"))
{
type = Int32.Parse( jsonData["type"].ToString());
}
}
}
catch
{
jsonData = null;
}
}
string fileExtension="";
HttpFileCollection files;
string suffix;
string name;
switch(type)
{
case 2001:
//DataLink.LogJsonData(jsonData);
MESDownloadExcel.ExcelWebCall.ExcelFile(jsonData,out bytes,out fileName,ref fileExtension);
fileName = fileName + "."+fileExtension;
HttpContext.Current.Response.ContentType = "application/octet-stream";
//HttpContext.Current.Response.ContentType = getContentType(extension);
//通知浏览器下载文件而不是打开
HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode(fileName, System.Text.Encoding.UTF8));
HttpContext.Current.Response.AddHeader("Access-Control-Expose-Headers", "Content-Disposition");
HttpContext.Current.Response.BinaryWrite(bytes);
HttpContext.Current.Response.Flush();
HttpContext.Current.Response.End();
break;
case 2002:
//DataLink.LogJsonData(jsonData);
MESDownloadExcel.ExcelWebCall.ExcelFilePdf(jsonData,out bytes,out fileName,out fileExtension);
fileName = fileName + "."+fileExtension;
HttpContext.Current.Response.ContentType = "application/octet-stream";
//HttpContext.Current.Response.ContentType = getContentType(extension);
//通知浏览器下载文件而不是打开
HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode(fileName, System.Text.Encoding.UTF8));
HttpContext.Current.Response.AddHeader("Access-Control-Expose-Headers", "Content-Disposition");
HttpContext.Current.Response.BinaryWrite(bytes);
HttpContext.Current.Response.Flush();
HttpContext.Current.Response.End();
break;
case 2003:// 合成excel图片下载
string[] dataimg;
if(context.Request.Form.Keys.Count>0)
{
dataimg = data.Form.GetValues(0);
MESDownloadExcel.ExcelWebCall.ExcelFile(jsonData,out bytes,out fileName,ref dataimg[0]);
if (bytes == null) return;
fileName = fileName + "."+dataimg[0];
HttpContext.Current.Response.ContentType = "application/octet-stream";
//HttpContext.Current.Response.ContentType = getContentType(extension);
//通知浏览器下载文件而不是打开
HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode(fileName, System.Text.Encoding.UTF8));
HttpContext.Current.Response.AddHeader("Access-Control-Expose-Headers", "Content-Disposition");
HttpContext.Current.Response.BinaryWrite(bytes);
HttpContext.Current.Response.Flush();
HttpContext.Current.Response.End();
//if(DataLinkMesWork.DataLink.isBakup=="1")
//{
// DataLinkMesWork.DataLink.ExePROCEDURE_Type16_Bakup(jsonData, out bytes, out fileName, out suffix);
//}
}
break;
case 2004:
//DataLink.LogJsonData(jsonData);
DataLinkMesWork.DataLink.ExePROCEDURE_Type2004(connType,jsonData, out bytes, out fileName, out fileExtension);
//MESDownloadExcel.ExcelWebCall.ExcelFile(jsonData,out bytes,out fileName,ref fileExtension);
fileName = fileName + "."+fileExtension;
HttpContext.Current.Response.ContentType = "application/octet-stream";
//HttpContext.Current.Response.ContentType = getContentType(extension);
//通知浏览器下载文件而不是打开
HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode(fileName, System.Text.Encoding.UTF8));
HttpContext.Current.Response.AddHeader("Access-Control-Expose-Headers", "Content-Disposition");
HttpContext.Current.Response.BinaryWrite(bytes);
HttpContext.Current.Response.Flush();
HttpContext.Current.Response.End();
break;
case 15://上传文件
files = context.Request.Files;
if (files.Count > 0)
{
fileName = files[0].FileName;
bytes = new byte[files[0].InputStream.Length];
files[0].InputStream.Read(bytes, 0, bytes.Length);
suffix = fileName.Substring(fileName.LastIndexOf(".")+1);
name = fileName.Substring(0,fileName.LastIndexOf("."));
responseText = DataLinkMesWork.DataLink.ExePROCEDURE_Type15(connType,jsonData, name, suffix, bytes);
context.Response.Write(responseText);
//if(DataLinkMesWork.DataLink.isBakup=="1")
//{
// DataLinkMesWork.DataLink.ExePROCEDURE_Type15_Bakup(jsonData, name, suffix, bytes);
//}
}
else
{
fileName = "";
bytes = new byte[1];
suffix = "";
name = "";
responseText = DataLinkMesWork.DataLink.ExePROCEDURE_Type15(connType,jsonData, name, suffix, bytes);
context.Response.Write(responseText);
//if(DataLinkMesWork.DataLink.isBakup=="1")
//{
// DataLinkMesWork.DataLink.ExePROCEDURE_Type15_Bakup(jsonData, name, suffix, bytes);
//}
}
break;
case 16://上传文件
DataLink.LogJsonData(jsonData);
DataLinkMesWork.DataLink.ExePROCEDURE_Type16(connType,jsonData, out bytes, out fileName, out suffix);
if (bytes == null) return;
fileName = fileName + "."+suffix;
HttpContext.Current.Response.ContentType = "application/octet-stream";
//HttpContext.Current.Response.ContentType = getContentType(extension);
//通知浏览器下载文件而不是打开
HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode(fileName, System.Text.Encoding.UTF8));
HttpContext.Current.Response.AddHeader("Access-Control-Expose-Headers", "Content-Disposition");
HttpContext.Current.Response.BinaryWrite(bytes);
HttpContext.Current.Response.Flush();
HttpContext.Current.Response.End();
//if(DataLinkMesWork.DataLink.isBakup=="1")
//{
// DataLinkMesWork.DataLink.ExePROCEDURE_Type16_Bakup(jsonData, out bytes, out fileName, out suffix);
//}
break;
default:
//DataLink.LogJsonData(jsonData);
responseText = DataLinkMesWork.DataLink.SqlWebCall(connType,type,jsonData,dataobj);//.SqlWebCall(stream);
context.Response.Write(responseText);
//if(DataLinkMesWork.DataLink.isBakup=="1")
//{
// DataLinkMesWork.DataLink.SqlWebCall_Bakup(type,jsonData,dataobj);
//}
break;
}
}
catch(Exception err)
{
context.Response.Write(responseText);
} }
}

View File

@@ -0,0 +1,21 @@
<%@ WebHandler Language="C#" Class="MESCommonBase08" %>
using System.Web;
public class MESCommonBase08 : IHttpHandler
{
public bool IsReusable
{
get
{
return false;
}
}
public void ProcessRequest(HttpContext context)
{
string connType = "08";
//ProcessRequestHttpContext.ProcessRequestServer.ProcessRequestHttpContext(connType, context);
}
}

View File

@@ -0,0 +1,21 @@
<%@ WebHandler Language="C#" Class="MESCommonBase09" %>
using System.Web;
public class MESCommonBase09 : IHttpHandler
{
public bool IsReusable
{
get
{
return false;
}
}
public void ProcessRequest(HttpContext context)
{
string connType = "09";
//ProcessRequestHttpContext.ProcessRequestServer.ProcessRequestHttpContext(connType, context);
}
}

View File

@@ -0,0 +1,21 @@
<%@ WebHandler Language="C#" Class="MESCommonBase10" %>
using System.Web;
public class MESCommonBase10 : IHttpHandler
{
public bool IsReusable
{
get
{
return false;
}
}
public void ProcessRequest(HttpContext context)
{
string connType = "10";
//ProcessRequestHttpContext.ProcessRequestServer.ProcessRequestHttpContext(connType, context);
}
}

View File

@@ -0,0 +1,117 @@
<%@ WebHandler Language="C#" Class="DownloadHandler" %>
using System;
using System.Web;
using System.Data;
using System.Collections.Generic;
using System.Linq;
using System.Web.Script.Serialization;
using System.IO;
using System.Net;
using System.Web.Services;
using System.Text;
using BasicData;
using DataLinkMesWork;
using MESDownloadExcel;
public class DownloadHandler : IHttpHandler
{
/// <summary>
/// 00 标准DataTable
/// 01 计划工时模板
/// 02 外协加工任务单
/// 03 外购备料请款
/// 04 自家项目报表
/// 05 材料清单
/// </summary>
/// <param name="context"></param>
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "application/json";
var data = context.Request;
var stream = new StreamReader(data.InputStream).ReadToEnd();
//JsonData jsonData;
//string responseText = "NULL";
byte[] bytes = null;
string fileName = "test.xsl";
try
{
string InvoiceNum = HttpContext.Current.Request["param"];
JsonData jsonData = JsonMapper.ToObject(InvoiceNum);
DataLink.LogJsonData(jsonData);
MESDownloadExcel.ExcelWebCall.ExcelFile(jsonData,out bytes,out fileName);
fileName = fileName + ".xls";
HttpContext.Current.Response.ContentType = "application/octet-stream";
//HttpContext.Current.Response.ContentType = getContentType(extension);
//通知浏览器下载文件而不是打开
HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode(fileName, System.Text.Encoding.UTF8));
HttpContext.Current.Response.AddHeader("Access-Control-Expose-Headers", "Content-Disposition");
HttpContext.Current.Response.BinaryWrite(bytes);
HttpContext.Current.Response.Flush();
HttpContext.Current.Response.End();
return;
}
catch (Exception ex)
{
return;
}
}
///// <summary>
///// Unicode编码(汉字转换为\uxxx)
///// </summary>
///// <param name="str"></param>
///// <returns></returns>
//public static string EnUnicode(string str)
//{
// StringBuilder strResult = new StringBuilder();
// if (!string.IsNullOrEmpty(str))
// {
// for (int i = 0; i < str.Length; i++)
// {
// strResult.Append("\\u");
// strResult.Append(((int)str[i]).ToString("x"));
// }
// }
// return strResult.ToString();
//}
///// <summary>
///// Unicode解码\uxxxx转换为汉字
///// </summary>
///// <param name="str"></param>
///// <returns></returns>
//public static string DeUnicode(string str)
//{
// //最直接的方法Regex.Unescape(str);
// Regex reg = new Regex(@"(?i)\\[uU]([0-9a-f]{4})");
// return reg.Replace(str, delegate(Match m) { return ((char)Convert.ToInt32(m.Groups[1].Value, 16)).ToString(); });
//}
// /// <summary>
///// Unicode解码
///// </summary>
///// <param name="str"></param>
///// <returns></returns>
//public static string DeUnicode(string str)
//{
// //最直接的方法Regex.Unescape(str);
// Regex reg = new Regex(@"(?i)\\[uU]([0-9a-f]{4})");
// return reg.Replace(str, delegate (Match m) { return ((char)Convert.ToInt32(m.Groups[1].Value, 16)).ToString(); });
//}
public bool IsReusable
{
get
{
return false;
}
}
}

View File

@@ -0,0 +1,117 @@
<%@ WebHandler Language="C#" Class="DownloadHandler" %>
using System;
using System.Web;
using System.Data;
using System.Collections.Generic;
using System.Linq;
using System.Web.Script.Serialization;
using System.IO;
using System.Net;
using System.Web.Services;
using System.Text;
using BasicData;
using DataLinkMesWork;
using MESDownloadExcel;
public class DownloadHandler : IHttpHandler
{
/// <summary>
/// 00 标准DataTable
/// 01 计划工时模板
/// 02 外协加工任务单
/// 03 外购备料请款
/// 04 自家项目报表
/// 05 材料清单
/// </summary>
/// <param name="context"></param>
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "application/json";
var data = context.Request;
var stream = new StreamReader(data.InputStream).ReadToEnd();
//JsonData jsonData;
//string responseText = "NULL";
byte[] bytes = null;
string fileName = "test.xsl";
try
{
string InvoiceNum = HttpContext.Current.Request["param"];
JsonData jsonData = JsonMapper.ToObject(InvoiceNum);
DataLink.LogJsonData(jsonData);
MESDownloadExcel.ExcelWebCallDemo.ExcelFile(jsonData,out bytes,out fileName);
fileName = fileName + ".xls";
HttpContext.Current.Response.ContentType = "application/octet-stream";
//HttpContext.Current.Response.ContentType = getContentType(extension);
//通知浏览器下载文件而不是打开
HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode(fileName, System.Text.Encoding.UTF8));
HttpContext.Current.Response.AddHeader("Access-Control-Expose-Headers", "Content-Disposition");
HttpContext.Current.Response.BinaryWrite(bytes);
HttpContext.Current.Response.Flush();
HttpContext.Current.Response.End();
return;
}
catch (Exception ex)
{
return;
}
}
///// <summary>
///// Unicode编码(汉字转换为\uxxx)
///// </summary>
///// <param name="str"></param>
///// <returns></returns>
//public static string EnUnicode(string str)
//{
// StringBuilder strResult = new StringBuilder();
// if (!string.IsNullOrEmpty(str))
// {
// for (int i = 0; i < str.Length; i++)
// {
// strResult.Append("\\u");
// strResult.Append(((int)str[i]).ToString("x"));
// }
// }
// return strResult.ToString();
//}
///// <summary>
///// Unicode解码\uxxxx转换为汉字
///// </summary>
///// <param name="str"></param>
///// <returns></returns>
//public static string DeUnicode(string str)
//{
// //最直接的方法Regex.Unescape(str);
// Regex reg = new Regex(@"(?i)\\[uU]([0-9a-f]{4})");
// return reg.Replace(str, delegate(Match m) { return ((char)Convert.ToInt32(m.Groups[1].Value, 16)).ToString(); });
//}
// /// <summary>
///// Unicode解码
///// </summary>
///// <param name="str"></param>
///// <returns></returns>
//public static string DeUnicode(string str)
//{
// //最直接的方法Regex.Unescape(str);
// Regex reg = new Regex(@"(?i)\\[uU]([0-9a-f]{4})");
// return reg.Replace(str, delegate (Match m) { return ((char)Convert.ToInt32(m.Groups[1].Value, 16)).ToString(); });
//}
public bool IsReusable
{
get
{
return false;
}
}
}

View File

@@ -0,0 +1,52 @@
<%@ WebHandler Language="C#" Class="DownloadHandler" %>
using System;
using System.Web;
using System.Data;
using System.Collections.Generic;
using System.Linq;
//using BizDataAccess;
using System.IO;
using System.Net;
using System.Web.Services;
using System.Text;
public class DownloadHandler : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/plain";
string filePath = "../webpage/part";
filePath = HttpContext.Current.Server.MapPath(filePath);
string id = HttpContext.Current.Request["id"];
filePath = filePath + "/" + id;
string name = HttpContext.Current.Request["name"];
try
{
System.IO.FileStream fs = new System.IO.FileStream(filePath, System.IO.FileMode.Open);
byte[] bytes = new byte[(int)fs.Length];
fs.Read(bytes, 0, bytes.Length);
fs.Close();
HttpContext.Current.Response.ContentType = "application/octet-stream";
//HttpContext.Current.Response.ContentType = getContentType(extension);
//通知浏览器下载文件而不是打开
HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode(name, System.Text.Encoding.UTF8));
HttpContext.Current.Response.BinaryWrite(bytes);
HttpContext.Current.Response.Flush();
HttpContext.Current.Response.End();
return;
}
catch (Exception ex)
{
return;
}
}
public bool IsReusable
{
get
{
return false;
}
}
}

View File

@@ -0,0 +1,76 @@
<%@ WebHandler Language="C#" Class="MESCommonBase" %>
using System;
using System.Web;
using System.Text;
using System.Linq;
using System.Collections.Generic;
using System.IO;
using System.Web.Script.Serialization;
using System.Data;
//using BizDataAccess;
using System.Data.SqlClient;
//using DbCallData;
//using BasicData;
using System.Net.Mail;
using System.Net.Mime;
using System.Timers;
using System.Xml;
using System.Net;
public class MESCommonBase : IHttpHandler
{
public bool IsReusable
{
get
{
return false;
}
}
public int message;
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/plain";
string Uid = HttpContext.Current.Request["Uid"];
string Key = HttpContext.Current.Request["Key"];
string smsMob = HttpContext.Current.Request["smsMob"];
string smsText = HttpContext.Current.Request["smsText"];
try
{
string url = "http://utf8.api.smschinese.cn/?Uid=" + Uid + "&Key=" + Key + "&smsMob=" + smsMob + "&smsText=" + smsText;
string relust = GetHtmlFromUrl(url);
context.Response.Write(Convert.ToInt16(relust));
}
catch (Exception ex)
{
return;
}
}
public string GetHtmlFromUrl(string url)
{
string strRet = null;
if(url==null || url.Trim().ToString()=="")
{
return strRet;
}
string targeturl = url.Trim().ToString();
try
{
HttpWebRequest hr = (HttpWebRequest)WebRequest.Create(targeturl);
hr.UserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)";
hr.Method = "GET";
hr.Timeout = 30 * 60 * 1000;
WebResponse hs = hr.GetResponse();
Stream sr = hs.GetResponseStream();
StreamReader ser = new StreamReader(sr, Encoding.Default);
strRet = ser.ReadToEnd();
}
catch (Exception ex)
{
strRet = null;
}
return strRet;
}
}

157
submit/MESUpload.ashx Normal file
View File

@@ -0,0 +1,157 @@
<%@ WebHandler Language="C#" Class="UploadHandler" %>
using System;
using System.Web;
using System.Data;
using System.Collections.Generic;
using System.Linq;
using System.IO;
using System.Net;
using System.Web.Services;
using System.Text;
using DataLinkMesWork;
using System.Data.SqlClient;
public class UploadHandler : IHttpHandler
{
private static string connectionString = System.Configuration.ConfigurationManager.AppSettings.GetValues("ConnectionString")[0].ToString();
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/plain";
string filePath = "../webpage/part";
filePath = HttpContext.Current.Server.MapPath(filePath);
string num = HttpContext.Current.Request["num"];
string tableName = HttpContext.Current.Request["tableName"];
string result = "";
bool isOK;
var stream = new StreamReader(context.Request.InputStream).ReadToEnd();
JsonData jsonData = JsonMapper.ToObject(stream);
//DataLink.LogJsonData(jsonData);
try
{
Guid guid = Guid.NewGuid();
string uid = guid.ToString().Replace("-", "").ToUpper();
HttpFileCollection files = context.Request.Files;
if (files.Count > 0)
{
for (int i = 0; i < files.Count; i++)
{
HttpPostedFile hpFile = files[0];
if (hpFile.ContentLength > 0)
{
string fileName = System.IO.Path.GetFileName(hpFile.FileName);
string suffix = fileName.Split(new Char[] { '.' })[1];
string name = fileName.Split(new Char[] { '.' })[0];
string sql = "insert into " + tableName + " (num, uid, name, suffix, 是否启用) values(" + num + ",'" + uid + "','" + name + "','" + suffix + "'," + '1' + ")";
isOK =DataLinkMesWork.DataLink.ExecuteNonQuery(sql);
//--业务代码 1
//-- 1 发货管理_附件
//-- 2 合同信息管理_履约保证金_履约保函
//-- 3 合同管理_文件路径
//-- 4 PDM_机床总图_文件列表
//-- 5 采购管理_采购发票_附件
//-- 6 车间采购管理_发票结算申请单
//-- 7 设备管理_设备监控_图片
//-- 8 车间生产管理_质检管理
//-- 9 人员管理_图片
//--10 tableName
//SET ANSI_NULLS ON
//GO
//SET QUOTED_IDENTIFIER ON
//GO
//ALTER PROCEDURE [dbo].[_文件存储_高精_增加]
// @业务代码 int,
// @文件标识 int,
// @文件名称 nvarchar(150),
// @文件后缀 nvarchar(50),
// @文件内容 varbinary(max)
// as
//SET NOCOUNT ON;
//INSERT INTO [dbo].[_文件存储_高精](业务代码,[文件标识],[文件名称],[文件后缀],[文件内容])
// VALUES(@业务代码,@文件标识,@文件名称,@文件后缀,@文件内容)
//isOK = SQLCommon.ExecuteNonQuery(sql, connectionString, out result);
//isOK = SQLCommon.ExecuteNonQuery(sql, connectionString, out result);
if (isOK)
{
try
{
filePath = filePath + "/" + uid + "." + suffix;
hpFile.SaveAs(filePath);
result = "[{ \"result\":\"1\"}]";
}
catch
{
}
}
else
{
result = "[{ \"result\":\"0\"}]";
}
try
{
//增加文件保存到数据库的功能
byte[]bytes = new byte[files[0].InputStream.Length];
files[0].InputStream.Read(bytes, 0, bytes.Length);
string procedureName = "_文件存储_高精_增加";
string errorMessage;
SqlParameter []thisParms = new SqlParameter[5];
thisParms[0] = new SqlParameter("@业务代码", 10);
thisParms[1] = new SqlParameter("@文件标识", uid);
thisParms[2] = new SqlParameter("@文件名称", name);
thisParms[3] = new SqlParameter("@文件后缀", suffix);
thisParms[4] = new SqlParameter("@文件内容", bytes);
DataLinkMesWork.DataLink.ExecuteStoredProcedure(procedureName, ref thisParms, out errorMessage);
if(DataLinkMesWork.DataLink.isBakup=="1")
{
DataLinkMesWork.DataLink.ExecuteNonQuery_Bakup(sql);
DataLinkMesWork.DataLink.ExecuteStoredProcedure_Bakup(procedureName, ref thisParms, out errorMessage);
}
}
catch
{
}
}
else
{
context.Response.Write(result);
}
}
}
}
catch (Exception ex)
{
result = "[{ \"result\":\"0\"}]";
}
context.Response.Write(result);
}
public bool IsReusable
{
get
{
return false;
}
}
}

103
submit/MESUploadFile.ashx Normal file
View File

@@ -0,0 +1,103 @@
<%@ WebHandler Language="C#" Class="UploadHandler" %>
using System;
using System.Web;
using System.Data;
using System.Collections.Generic;
using System.Linq;
using System.IO;
using System.Net;
using System.Web.Services;
using System.Text;
using DataLinkMesWork;
using System.Data.SqlClient;
public class UploadHandler : IHttpHandler
{
private static string connectionString = System.Configuration.ConfigurationManager.AppSettings.GetValues("ConnectionString")[0].ToString();
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/plain";
string filePath = "../webpage/part";
filePath = HttpContext.Current.Server.MapPath(filePath);
string num = HttpContext.Current.Request["num"];
string tableName = HttpContext.Current.Request["tableName"];
string result = "";
bool isOK;
try
{
Guid guid = Guid.NewGuid();
string uid = guid.ToString().Replace("-", "").ToUpper();
HttpFileCollection files = context.Request.Files;
if (files.Count > 0)
{
for (int i = 0; i < files.Count; i++)
{
HttpPostedFile hpFile = files[0];
if (hpFile.ContentLength > 0)
{
string fileName = System.IO.Path.GetFileName(hpFile.FileName);
string suffix = fileName.Split(new Char[] { '.' })[1];
string name = fileName.Split(new Char[] { '.' })[0];
string sql = "insert into " + tableName + " (num, uid, name, suffix, 是否启用) values(" + num + ",'" + uid + "','" + name + "','" + suffix + "'," + '1' + ")";
isOK = DataLinkMesWork.DataLink.ExecuteNonQuery(sql);
//isOK = SQLCommon.ExecuteNonQuery(sql, connectionString, out result);
if (isOK)
{
filePath = filePath + "/" + uid + "." + suffix;
hpFile.SaveAs(filePath);
result = "[{ \"result\":\"1\"}]";
}
else
{
result = "[{ \"result\":\"0\"}]";
}
try
{
//增加文件保存到数据库的功能
byte[]bytes = new byte[files[0].InputStream.Length];
files[0].InputStream.Read(bytes, 0, bytes.Length);
string procedureName = "_文件存储_高精_增加";
string errorMessage;
SqlParameter []thisParms = new SqlParameter[5];
thisParms[0] = new SqlParameter("@业务代码", 10);
thisParms[1] = new SqlParameter("@文件标识", uid);
thisParms[2] = new SqlParameter("@文件名称", name);
thisParms[3] = new SqlParameter("@文件后缀", suffix);
thisParms[4] = new SqlParameter("@文件内容", bytes);
DataLinkMesWork.DataLink.ExecuteStoredProcedure(procedureName, ref thisParms, out errorMessage);
if(DataLinkMesWork.DataLink.isBakup=="1")
{
DataLinkMesWork.DataLink.ExecuteNonQuery_Bakup(sql);
}
}
catch
{
}
}
else
{
context.Response.Write(result);
}
}
}
}
catch (Exception ex)
{
result = "[{ \"result\":\"0\"}]";
}
context.Response.Write(result);
}
public bool IsReusable
{
get
{
return false;
}
}
}

Some files were not shown because too many files have changed in this diff Show More