C# 发EDM

原创 2016年08月30日 15:29:40

最近公司需要写了一个EDM,基本功能可以,暂时还没有优化。压缩的还没测试。

#region 发EDM
        #region 创建CSV文件
        public static void CreateCSV(DataTable dt, string fileName)
        {
            FileStream fs = new FileStream(fileName, System.IO.FileMode.Create, System.IO.FileAccess.Write);
            StreamWriter sw = new StreamWriter(fs, System.Text.Encoding.Default);
            string data = "";
            //写出列名称
            for (int i = 0; i < dt.Columns.Count; i++)
            {
                data += dt.Columns[i].ColumnName.ToString();
                if (i < dt.Columns.Count - 1)
                    data += ",";
            }
            sw.WriteLine(data);

            //写出各行数据
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                data = "";
                for (int j = 0; j < dt.Columns.Count; j++)
                {
                    data += dt.Rows[i][j].ToString();
                    if (j < dt.Columns.Count - 1)
                        data += ",";
                }
                sw.WriteLine(data);
            }
            sw.Close();
            fs.Close();
            fs.Dispose();
        }
        #endregion

        #region 压缩CSV文件
        /// <summary>  
        /// 压缩单个文件  
        /// </summary>  
        /// <param name="fileToZip">要压缩的文件</param>  
        /// <param name="zipedFile">压缩后的文件全名</param>  
        /// <param name="compressionLevel">压缩程度,范围0-9,数值越大,压缩程序越高</param>  
        /// <param name="blockSize">分块大小</param>  
        public static void ZipFile(string fileToZip, string zipedFile, int compressionLevel, int blockSize)
        {
            FileStream streamToZip = new FileStream(fileToZip, FileMode.Open, FileAccess.Read);
            FileStream zipFile = File.Create(zipedFile);
            ZipOutputStream zipStream = new ZipOutputStream(zipFile);
            ZipEntry zipEntry = new ZipEntry(fileToZip);
            zipStream.PutNextEntry(zipEntry);
            zipStream.SetLevel(compressionLevel);
            byte[] buffer = new byte[blockSize];
            int size = streamToZip.Read(buffer, 0, buffer.Length);
            zipStream.Write(buffer, 0, size);
            try
            {
                while (size < streamToZip.Length)
                {
                    int sizeRead = streamToZip.Read(buffer, 0, buffer.Length);
                    zipStream.Write(buffer, 0, sizeRead);
                    size += sizeRead;
                }
            }
            catch (Exception ex)
            {
                GC.Collect();
                throw ex;
            }

            zipStream.Finish();
            zipStream.Close();
            streamToZip.Close();
            GC.Collect();
        }
        #endregion

        #region 发送csv文件
        public static string UpLoadFile(string filePath)
        {
            string url = "接口url";
            string fileName = Path.GetFileName(filePath);
            string responseContent;
            var memStream = new MemoryStream();
            // 边界符
            var boundary = "---------------" + DateTime.Now.Ticks.ToString("x");
            // 开始边界符
            var beginBoundary = Encoding.ASCII.GetBytes("--" + boundary + "\r\n");
            // 最后的结束符
            var endBoundary = Encoding.ASCII.GetBytes("--" + boundary + "--\r\n");
            //文件流
            var fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read);

            // WebRequest设置属性
            var webRequest = (HttpWebRequest)WebRequest.Create(url);
            webRequest.Method = "POST";
            webRequest.ContentType = "multipart/form-data; boundary=" + boundary;
            //写入开始符           
            memStream.Write(beginBoundary, 0, beginBoundary.Length);

            // 写入文件标题
            const string filePartHeader =
                "Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\n" +
                "Content-Type: application/vnd.ms-excel\r\n\r\n";
            var header = string.Format(filePartHeader, "customerFile", fileName);
            var headerbytes = Encoding.UTF8.GetBytes(header);
            memStream.Write(headerbytes, 0, headerbytes.Length);

            //写入文件流
            var buffer = new byte[1024];
            int bytesRead; // =0
            while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)
            {
                memStream.Write(buffer, 0, bytesRead);
            }
            // 写入最后的结束边界符                 
            memStream.Write(endBoundary, 0, endBoundary.Length);
            webRequest.ContentLength = memStream.Length;
            var requestStream = webRequest.GetRequestStream();
            memStream.Position = 0;
            var tempBuffer = new byte[memStream.Length];
            memStream.Read(tempBuffer, 0, tempBuffer.Length);
            memStream.Close();
            requestStream.Write(tempBuffer, 0, tempBuffer.Length);
            requestStream.Close();
            var httpWebResponse = (HttpWebResponse)webRequest.GetResponse();
            using (var httpStreamReader = new StreamReader(httpWebResponse.GetResponseStream(), Encoding.GetEncoding("utf-8")))
            {
                responseContent = httpStreamReader.ReadToEnd();
            }
            fileStream.Close();
            httpWebResponse.Close();
            webRequest.Abort();

            JObject jo = JObject.Parse(responseContent);
            string[] values = jo.Properties().Select(item => item.Value.ToString()).ToArray();
            return values[0];
        }
        #endregion

        #region csv文件转服务器数据库
        public static string csvToDataBase(string csvPath)
        {
            string postDataStr = GetpostDataStr(csvPath);
            string url = "接口url";
            string jobid = GetRadicaData(url, postDataStr);
            return jobid;
        }

        public static string GetpostDataStr(string csvPathpar)
        {
            DataTable dtmapping = new DataTable();
            dtmapping.Columns.Add("column", typeof(string));
            dtmapping.Columns.Add("propId", typeof(string));
            DataRow dr;
            dr = dtmapping.NewRow();
            dr["column"] = 0;
            dr["propId"] = "客户提供";
            dtmapping.Rows.Add(dr);

            dr = dtmapping.NewRow();
            dr["column"] = 1;
            dr["propId"] = "客户提供ID";
            dtmapping.Rows.Add(dr);

            dr = dtmapping.NewRow();
            dr["column"] = 2;
            dr["propId"] = "客户提供ID";
            dtmapping.Rows.Add(dr);

            dr = dtmapping.NewRow();
            dr["column"] = 3;
            dr["propId"] = "57a29bb147b8842f2cea6920";
            dtmapping.Rows.Add(dr);

            dr = dtmapping.NewRow();
            dr["column"] = 4;
            dr["propId"] = "客户提供ID";
            dtmapping.Rows.Add(dr);
            string[] arrtagids = new string[] { };
            string[] arrtagnames = new string[] { "test123456" };
            CSVObjecrt csvobject = new CSVObjecrt
            {
                path = csvPathpar,
                operation = "replace",
                tagids = arrtagids,
                tagNames = arrtagnames,
                fieldMapping = dtmapping
            };

            var json = JsonConvert.SerializeObject(csvobject);
            return json.ToString();
        }
        #endregion
      

        #region 调用接口返回json字符串
        public static string GetData(string url, string postData)
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            request.Method = "POST";
            request.ContentType = "application/json";
            //request.ContentLength = Encoding.UTF8.GetByteCount(postDataStr);
            Stream myRequestStream = request.GetRequestStream();
            StreamWriter myStreamWriter = new StreamWriter(myRequestStream, Encoding.GetEncoding("utf-8"));
            myStreamWriter.Write(postData);
            myStreamWriter.Close();
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            Stream myResponseStream = response.GetResponseStream();
            StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding("utf-8"));
            string retString = myStreamReader.ReadToEnd();
            myStreamReader.Close();
            myResponseStream.Close();
            JObject jo = JObject.Parse(retString);
            string[] values = jo.Properties().Select(item => item.Value.ToString()).ToArray();
            return values[0];
        }
        #endregion

        #region 发短信
        /// <summary>
        /// 调用短信接口
        /// </summary>
        public static void sendSMSTask(DataTable dtcampaign)
        {
            int result = sendSMSt("手机号", "短信内容", "ID", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));  
        }
        /// <summary>
        /// 发送短信
        /// </summary>
        /// <param name="mobile">收短信人手机</param>
        /// <param name="content">短信内容</param>
        /// <param name="misc"></param>
        /// <param name="time"></param>
        /// <returns></returns>
        public static int sendSMSt(String mobile, String content, String misc, String time)
        {
            int iR = 1;
            string url = "接口url";
            string postStrTpl = "username={0}&password={1}&content={2}&mobile={3}&batchID={4}&senddate={5}";
            string username = "用户名";
            string pwd = "密码";
            UTF8Encoding encoding = new UTF8Encoding();
            //统一任务下的ID一样
            byte[] postData = encoding.GetBytes(string.Format(postStrTpl, username, pwd, content, mobile, misc, time));

            HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(url);
            myRequest.Method = "POST";
            myRequest.ContentType = "application/x-www-form-urlencoded";
            myRequest.ContentLength = postData.Length;

            Stream newStream = myRequest.GetRequestStream();
            // Send the data.
            newStream.Write(postData, 0, postData.Length);
            newStream.Flush();
            newStream.Close();

            HttpWebResponse myResponse = (HttpWebResponse)myRequest.GetResponse();
            if (myResponse.StatusCode == HttpStatusCode.OK)
            {
                StreamReader reader = new StreamReader(myResponse.GetResponseStream(), Encoding.UTF8);
                string tmp = reader.ReadToEnd();
                if (tmp == "0")
                    iR = 0;
            }
            else
            {
                //访问失败
            }
            return iR;
        }
        #endregion
        #endregion



版权声明:本文为博主原创文章,未经博主允许不得转载。

相关文章推荐

EDM邮件群发常见问题误区总结

如何用EDM邮件群发进行正确的营销呢?企业一般使用在线邮件群发来实现广告送达,但由于使用操作中存在问题,导致营销效果无法达到预期目标。   很多企业认为只要把想发送的内容通过邮件传播出去就万...

EDM营销之会员邮件群发攻略

EDM营销基于采用许可式会员营销的方式为前提,从邮件发送量的关注转移到邮件的质,不是发送更多的电子邮件,而是发送更好的电子邮件,与更多用户产生共鸣。   自然的个性化   个性化服务不仅在...

EDM邮件群发A/B测试的操作方法

很多人知道A/B测试功能却不了解如何操作,更多企业看重的是某些数据的增长,其实EDM邮件群发首要任务是增加销量提升转化,并加深用户对品牌的认知,那么,EDM发送过程中A/B测试应该如何操作才最有效呢。...

EDM5月份数据分析

  • 2012-07-01 17:32
  • 814KB
  • 下载

三品EDM产品功能

  • 2013-01-09 14:35
  • 34KB
  • 下载

responsive EDM HTML的编写注意事项

1.无DOCTYPE,电子邮件会自动删除代码中的doctype声明; 2.bgcolor可以不需要"#"; 3.table的cellpadding,cellspacing指的是单元格的padding ...

EDM放电加工英文课件

  • 2010-01-10 02:08
  • 423KB
  • 下载

EDM(Email Direct Marketing)HTML制作要点

我们打开邮箱邮件,经常发现类似这样的网页: 上图为京东发送的商用邮件,我们即称之为EDM,中文名电子邮箱营销。在网页中嵌入的京东推荐中,我们点击商品链接或者图片就可实现跳转等功能。 我们可以思考一下...

数据仓库 EDM 3.0

  • 2010-08-20 20:35
  • 3.32MB
  • 下载
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:深度学习:神经网络中的前向传播和反向传播算法推导
举报原因:
原因补充:

(最多只允许输入30个字)