Asp. NET micro-letter public Number Customer Service Interface _ practical skills

Source: Internet
Author: User
Tags datetime int size numeric value openid read ini file readline trim

This example for you to share the ASP.net micro-letter customer service interface of the specific code for your reference, the specific content as follows

Kf_account.cs Code:

 Public partial class Kf_account:form {private readonly datatable Adt_user = new DataTable ();

  Private readonly String as_inifile = Application.startuppath + "\\user.ini";
  Public Kf_account () {binduser (); private void Binduser () {if (!
    File.exists (As_inifile)) {var str = new StringBuilder (); Str.
    Append ("; content is generated automatically by program, please do not modify this file content \ r \ n"); Str.
    Append ("[total]\r\n"); Str.
    Append ("total=\r\n"); Str.
    Append ("[count]\r\n"); Str.
    Append ("count=\r\n"); Str.
    Append ("[user]\r\n");
    StreamWriter SW = Default (StreamWriter);
    SW = File.createtext (ls_inifile); Sw. WriteLine (str.
    ToString ()); Sw.
    Close (); File.writealltext (As_inifile, str.
    ToString (), Encoding.unicode);
   File.setattributes (As_inifile, Fileattributes.hidden);
   } Checkforillegalcrossthreadcalls = false;
   InitializeComponent ();
   Icon = Resource1.ico; Lkl_num.
   Text = Inifile.contentvalue ("Total", "total", as_inifile); Lkl_num_c.text = Inifile.contenTValue ("Count", "Count", as_inifile);
   Picturebox1.visible = true;
   var sr = new StreamReader (As_inifile, Encoding.unicode);
   String Line;
   int li_count = 0; Adt_user.
   Columns.clear (); Adt_user.
   Columns.Add ("username", Type.GetType ("System.String")); Adt_user.
   Columns.Add ("OpenID", Type.GetType ("System.String")); while (line = Sr.
    ReadLine ())!= null) {li_count++;
     if (Li_count > 6) {line = SYSVISITOR.CURRENT.GETFORMATSTR (line);
     DataRow NewRow; NewRow = Adt_user.
     NewRow (); newrow["username"] = line. Substring (0, line.
     LastIndexOf (' = ')); newrow["OpenID"] = line. Substring (line.
     LastIndexOf (' = ') + 1); Adt_user.
    Rows.Add (NewRow); }} Sr.
   Close ();
   Datagridview1.autogeneratecolumns = false;
   Datagridview1.datasource = Adt_user;
   Datagridview1.autosizecolumnsmode = System.Windows.Forms.DataGridViewAutoSizeColumnsMode.DisplayedCells; Lbl_count.
   Text = "Total" + (li_count-6) + "line";
  Picturebox1.visible = false; }

  private void Btn_getuser_click (object sender, EventArgs e) {if (MessageBox.Show) the speed at which user information is pulled depends on your attention and network speed, and may take a few
Clock even longer.
Using this feature will consume a large number of user management interface quotas. Do you want to continue with this operation?
   "," Hint: ", messageboxbuttons.yesno) = = dialogresult.no) {return;
   var thr = new Thread (get_user_list); Thr.
  Start ();
   private void Get_user_list () {file.delete (as_inifile);
   var str = new StringBuilder (); Str.
   Append ("; content is generated automatically by program, please do not modify this file content \ r \ n"); Str.
   Append ("[total]\r\n"); Str.
   Append ("total=\r\n"); Str.
   Append ("[count]\r\n"); Str.
   Append ("count=\r\n"); Str.
   Append ("[user]\r\n"); File.writealltext (As_inifile, str.
   ToString (), Encoding.unicode);

   File.setattributes (As_inifile, Fileattributes.hidden);
   String ls_appid = Inifile.contentvalue ("Weixin", "AppID");
   String ls_secret = Inifile.contentvalue ("Weixin", "Appsecret");
   String access_token = "";
   String menu = ""; if (ls_appid. Length!= 18 | | Ls_secret. Length!=) {MessageBox.Show ("your AppID or Appsecret is not right, please checkAfter the operation ");
   Return
   } Access_token = SysVisitor.Current.Get_Access_token (Ls_appid, Ls_secret);
    if (Access_token = = "") {MessageBox.Show ("AppID or appsecret wrong, please check and then operate");
   Return
   } menu = SysVisitor.Current.GetPageInfo ("https://api.weixin.qq.com/cgi-bin/user/get?access_token=" + Access_token); if (menu).
   Substring (2, 7) = = "Errcode") {MessageBox.Show ("Pull failed, return message: \ r \ n" + menu);
   } jobject JSON = Jobject.parse (menu); Lkl_num. Text = json["Total"].
   ToString (); Inifile.setinistring ("Total", "total", lkl_num.
   Text, As_inifile); Lkl_num_c.text = json["Count"].
   ToString ();
   Inifile.setinistring ("Count", "Count", Lkl_num_c.text, As_inifile); int li_count = Int. Parse (json["Count").
   ToString ());
   btn_getuser.enabled = false;
   Picturebox1.visible = true;
   FileStream fs = null;
   Encoding encoder = Encoding.unicode;
    for (int i = 0; i < Li_count i++) {string OpenID, username; OpenID = Get_username (json["Data"] ["OpenID"][i]. Tostring ()); Username = json["Data" ["OpenID"][i].
    ToString ();
    Inifile.setinistring ("User", OpenID, username, as_inifile); byte[] bytes = encoder.
    GetBytes (OpenID + "=" + username + "\ r \ n");
    FS = File.openwrite (As_inifile); Set the start position of the writing as the end of the file FS. Position = fs.
    Length; Appends the pending content to the end of the file FS. Write (bytes, 0, bytes.
    Length); Fs.
    Close (); Lab_nums.
   Text = "pulled" + i + "one, remaining" + (Li_count-i) + ", please be patient"; } lab_nums.
   Text = "";
   Binduser ();
   Btn_getuser.enabled = true;
   Picturebox1.visible = false;
  MessageBox.Show ("All pulled out, please reopen the window");
  ///<summary>///Get user details, return to JSON///</summary>///<param name= "As_openid" ></param>
   private string Get_user (String as_openid) {string ls_json = "";
   String access_token = "";
   Access_token = SysVisitor.Current.Get_Access_token (); Ls_json = SysVisitor.Current.GetPageInfo ("https://api.weixin.qq.com/cgi-bin/user/info?access_token=" + Access_ Token + "&openid="+ As_openid +" &LANG=ZH_CN ");
  return Ls_json; ///<summary>///Get user user's nickname///</summary> private String Get_username (string as_openid) {St
   Ring Ls_json = "";
   Ls_json = Get_user (As_openid);
   String username = "";
   Jobject json = Jobject.parse (Ls_json); Username = json["nickname"].
   ToString ();
   Username = SysVisitor.Current.GetFormatStr (username);
  return username; private void Btn_search_click (object sender, EventArgs e) {string username = Txt_search.
   Text.trim (); if (string.
   Isnullorwhitespace (username)) {return; } datarow[] DataRows = Adt_user.

   Select ("username like '%" + username + "%");
   var Ldt = new DataTable (); Ldt.
   Columns.clear (); Ldt.
   Columns.Add ("username", Type.GetType ("System.String")); Ldt.
   Columns.Add ("OpenID", Type.GetType ("System.String"));
   LDT = todatatable (DataRows); try {Lbl_count. Text = Ldt.
   Rows.Count.ToString (); The catch {} Datagridview1.autogeneraTecolumns = false;
  Datagridview1.datasource = LDT; Public DataTable todatatable (datarow[] Rows {if rows = null | | rows.
   Length = = 0) return null; DataTable tmp = rows[0]. Table.clone (); Copy DataRow table structure foreach (DataRow row in rows) tmp. Rows.Add (row. ItemArray);
  Add DataRow to the DataTable return TMP; } private void Datagridview1_cellmouseclick (object sender, DataGridViewCellMouseEventArgs e) {try {Sysvis Itor. Current.wx_openid = Datagridview1.rows[datagridview1.currentcell.rowindex]. CELLS[1].
    Value.tostring (); SysVisitor.Current.Wx_username = Datagridview1.rows[datagridview1.currentcell.rowindex]. Cells[0].
    Value.tostring ();
    MessageBox.Show (str); Grb_chat.
    Enabled = true; Grb_chat.
   Text = SysVisitor.Current.Wx_username; The catch {} webbrowser_msg.
   DocumentText = ""; String url = string. Format ("https://api.weixin.qq.com/cgi-bin/customservice/getrecord?access_token={0}", SYSVISITOR.CURRENT.GET_ACCEss_token ());
   String ls_text = @ "{"; Ls_text + = "\" starttime\ ":" + DateTime.Now.AddDays (-3).
   Ticks + ",";
   Ls_text + + "endtime\": "+ DateTime.Now.Ticks +";
   Ls_text + + "openid\": \ "" + SysVisitor.Current.Wx_openid + "\";
   Ls_text + + "pagesize\": 1000, ";
   Ls_text + + "pageindex\": 1, ";
   Ls_text + = "}";
   String ls_history = SysVisitor.Current.PostPage (URL, ls_text); Webbrowser_msg.
  DocumentText = ls_history; private void Btn_send_click (object sender, EventArgs e) {string ls_msg = richtextbox_msg.
   Text;
   String ls_text = @ "{";
   Ls_text + + "Touser\": \ "" + SysVisitor.Current.Wx_openid + "\";
   Ls_text + + "msgtype\": \ "Text\";
   Ls_text + + "text\": ";
   Ls_text + = "{";
   Ls_text + + "content\": \ "" + Ls_msg + "" ";
   Ls_text + = "}";
   Ls_text + = "}"; String url = string. Format ("https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token={0}", SysVisitor.Current.Get_Access_
   Token ()); String ls_isright = SysvisItor.

   Current.postpage (URL, ls_text); Webbrowser_msg.
  DocumentText + = "<p align=right><font size=3>" + ls_isright + "</FONT></P>"; private void Btn_addkf_click (object sender, EventArgs e) {string url = string. Format ("https://api.weixin.qq.com/customservice/kfaccount/add?access_token={0}", SysVisitor.Current.Get_Access_
   Token ());
   Customer account Settings xxx@ Your public number is the correct format.
   String ls_text = "{";
   Ls_text + + "kf_account\": Test2@gz-sisosoft, ";
   Ls_text + + "nickname\": \ "Customer service 2\", ";
   Ls_text + + "password\": \ "12345\";
   Ls_text + = "}";
      String LS_KF = @ "{' Kf_account ': ' Test1@gz-sisosoft ', ' nickname ': ' Customer service 1 ', ' Password ': ' 123456 ',
   }";
   String ls_isok = SysVisitor.Current.PostPage (URL, ls_text);
  MessageBox.Show (Ls_isok);

 } private void Kf_account_load (object sender, EventArgs e) {}}

SysVisitor.cs Code:

 Class Sysvisitor {private static sysvisitor visit = NULL;

    public static Sysvisitor Current {get {if (visit = = null) visit = new Sysvisitor ();
   return visit; }///<summary>///get access_token///</summary>///<param name= "AppID" >appid</param&gt
  ; <param name= "Secret" >appsecret</param>///<returns></returns> public string get_access_t
   Oken (String AppID, String appsecret) {string secondappid = Inifile.contentvalue ("Weixin", "secondappid"); if (AppID. ToLower () = = Secondappid.
    ToLower ()) {string ls_time = Inifile.contentvalue ("Weixin", "gettime");
    Decimal Ldt;
     try {Ldt = Convert.todecimal (ls_time); if (DateTime.Now.ToString ("YYYYMMDDHHMMSS"))-Ldt < 7100)//refresh once every two hours {return Inifile.con convert.todecimal
     Tentvalue ("Weixin", "Access_token"); The Catch {}} string ls_appid = AppID.
   Replace ("", ""); String LS_SECRET = Appsecret.
   Replace ("", "");
   String access_token = ""; String url = string. Format ("Https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={0}&secret={1}", Ls_
   AppID, Ls_secret);
   String json_access_token = GetPageInfo (URL);
   DataTable dt = json.jsontodatatable (Json_access_token);
   DataTable dt = jsonhelper.jsontodatatable (Json_access_token); try {access_token = dt. rows[0]["Access_token"].
   ToString ();
   Catch {return "";
   } inifile.setinistring ("Weixin", "GetTime", DateTime.Now.ToString ("Yyyymmddhhmmss"));
   Inifile.setinistring ("Weixin", "Access_token", Access_token);

   Inifile.setinistring ("Weixin", "Secondappid", ls_appid);
  return access_token; ///<summary>///Get access_token///</summary> public string Get_access_token () {string ls_a
   Ppid = Inifile.contentvalue ("Weixin", "Appid");
   String ls_secret = Inifile.contentvalue ("Weixin", "Appsecret"); Return Get_access_token(Ls_appid, Ls_secret); The///<summary>///get method requests the URL and receives the return message///</summary>///<param name= "strURL" >url address </PARAM&G
  T <returns></returns> public string getpageinfo (string url) {HttpWebRequest request = (httpwebreques
   t) httpwebrequest.create (URL); HttpWebResponse response = (HttpWebResponse) request.

   GetResponse (); string ret = string.
   Empty;
   Stream s;
   String strdate = "";

   string strvalue = ""; if (response. StatusCode = = Httpstatuscode.ok) {s = response.
    GetResponseStream ();

    Here processing the returned text StreamReader Reader = new StreamReader (s, Encoding.UTF8);
    while ((strdate = Reader.readline ())!= null) {strvalue + = strdate + "\ r \ n";
   }//strvalue = Reader.readtoend ();
  return strvalue; ///<summary>///Post method///</summary>///<param name= "PostURL" >URL</param>/// ;p Aram Name= "PostData" >post data </param>///<returns></reTurns> public string Postpage (string PostURL, String postdata) {Stream outstream = null;
   Stream instream = null;
   StreamReader sr = null;
   HttpWebResponse response = null;
   HttpWebRequest request = null;
   Encoding Encoding = Encoding.UTF8; byte[] data = encoding.
   GetBytes (PostData);
    Prepare request ... try {//Set parameter request = WebRequest.Create (PostURL) as HttpWebRequest;
    Cookiecontainer Cookiecontainer = new Cookiecontainer (); Request.
    Cookiecontainer = Cookiecontainer; Request.
    AllowAutoRedirect = true; Request.
    method = "POST"; Request.
    ContentType = "application/x-www-form-urlencoded"; Request. ContentLength = data.
    Length; OutStream = Request.
    GetRequestStream (); OutStream. Write (data, 0, data.
    Length); OutStream.
    Close (); Send request and get corresponding response data response = Request.
    GetResponse () as HttpWebResponse; Until request. The GetResponse () program only starts sending post requests to the target Web page instream = response.
    GetResponseStream (); sr = new StreamReader (instream, encoding); Returns the resulting web page (HTML) code string content = Sr.
    ReadToEnd (); string err = string.
    Empty;
   return content; The catch (Exception ex) {string err = ex.
    message; return string.
   Empty; }///<summary>///format string///</summary>///<param name= "str" ></param>///<re
   Turns></returns> public string Getformatstr (String str) {if ("= = str") return ""; else {str = str.
    Trim (); str = str.
    Replace ("'", "" "); str = str.
    Replace ("", "<"); str = str.
    Replace ("", ">"); str = str.
    Replace (",", ",");
   return str;
  } String ls_username = "";
   <summary>///User name///</summary> public string Wx_username {get {return ls_username;
   } set {ls_username = value;
  } String Ls_openid = "";
   <summary>///Openid///</summary> public string Wx_openid {get {return ls_openid; } set {
    Ls_openid = value;

 }
  }
 }

INIFile.cs Code:

 Class INIFile {/////<summary>/////set INI file parameters/////</summary>/////<param name= "section" > INI file </param>/////<param name= "key" >ini file keywords </param>/////<param name= "val" > INI file keywords value </param>/////<param name= "FilePath" >ini file full path and name </param>/////<returns> </returns>//[dllimport ("kernel32")]//private static extern long WritePrivateProfileString (//String section

  , string key, String val, string filePath); <summary>/////get ini file parameter/////</summary>/////<param name= The paragraph name in the "section" >ini file </param >/////<param name= "key" >ini file keyword </param>/////<param name= "def" > Default values when unreadable </param >/////<param name= "RetVal" > Reading value </param>/////<param name= "Size" > Numeric value </param>/////&L T;param name= "FilePath" >ini full path and name of file </param>//[dllimport ("kernel32")]//private static extern int GetpriVateprofilestring (//String section, String key, String Def, StringBuilder retVal, int size, string filePath);

  static string gs_filename = System.AppDomain.CurrentDomain.BaseDirectory + "Config.ini"; <summary>/////get ini file parameter/////</summary>/////<param name= "as_section" >ini file paragraph name </pa ram>/////<param name= "as_key" >ini file keywords </param>/////<param name= "As_filename" >
  INI file full path and name </param>//public static string getinistring (String as_section, String As_key, String as_filename)
  {//StringBuilder temp = new StringBuilder (255);
  int i = getprivateprofilestring (as_section, As_key, "", temp, 255, as_filename); Return temp.
  ToString (); /////<summary>/////Gets the name of the paragraph in the ini file parameter/////</summary>/////<param name= "as_section" >ini file lt;/param>/////<param name= "as_key" >ini file keywords </param>/////<param name= "As_filename" >
  The full path and name of the INI file </param>public static string Getinistring (String as_section, String as_key)//{//Return getinistring (As_section, As_key, G
  S_filename); /////<summary>/////Set INI file parameters/////</summary>/////<param name= "as_section" >ini file paragraphs &L t;/param>/////<param name= "as_key" >ini file keywords </param>/////<param name= "As_value" > INI file value of keywords </param>/////<param name= "as_filename" >ini file full path and name </param>//public static Long Set Inistring (String as_section, String As_key, String as_value, String as_filename)//{//Return Writeprivateprofilestri
  Ng (As_section, As_key, As_value, as_filename); /////<summary>/////Set INI file parameters/////</summary>/////<param name= "as_section" >ini file paragraphs ;/param>/////<param name= "as_key" >ini file keywords </param>/////<param name= "As_value" > INI file the value of the keyword </param>//public static long setinistring (string as_section, String As_key, String As_vAlue)//{//Return setinistring (As_section, As_key, As_value, gs_filename); ///<summary>///Write INI file///</summary>///<param name= "section" > node name [such as [Typename]]</par am>///<param name= "key" > Key </param>///<param name= "val" > Value </param>///<param name= "f  Ilepath "> File path </param>///<returns></returns> [DllImport (" kernel32 ")] public static extern long
  WritePrivateProfileString (string section, string key, String val, string filepath); [DllImport ("kernel32.dll")] public extern static int Getprivateprofilesectionnamesa (byte[] buffer, int ilen, string file
  Name); <summary>///Write INI file (section: node name key: Key val: value)///</summary>///<param name= "section" > Node name & lt;/param>///<param name= "key" > Key </param>///<param name= "val" > Value </param>///<return s></returns> public static long Setinistring (string section, string key, StrinG val, string as_filepath = "") {if (As_filepath = = "") {return (WritePrivateProfileString, Key, Val
   , strFilePath)); 
   else {return (writeprivateprofilestring (section, Key, Val, As_filepath)); }///<summary>///read INI file///</summary>///<param name= "section" > Node name </param>// /<param name= "key" > Key </param>///<param name= "def" > Value </param>///<param name= "RetVal" >s Tringbulider objects </param>///<param name= "Size" > Byte size </param>///<param name= "FilePath" > File path & Lt;/param>///<returns></returns> [DllImport ("kernel32")] public static extern int Getprivateprofile
  String (string section, String key, String Def, StringBuilder retval, int size, string filePath); public static String strFilePath = Application.startuppath + "\\Config.ini";//Get INI file default path public static string strsec =

  ""; INI filename///<summary>///Read the content method in the INI file (Section node name, key key)///</summary>///<param name= "" section > Node name </param>///<param "Key" > Key </param>///<returns></returns> public static string Contentvalue (string section, string key,
   String as_filepath = "") {StringBuilder temp = new StringBuilder (1024);
   if (As_filepath = = "") {getprivateprofilestring (section, Key, "", temp, 1024, strFilePath); 
   else {getprivateprofilestring (section, Key, "", temp, 1024, as_filepath); Return to temp.
  ToString (); ///<summary>///Gets a list of all the item names and values in the specified subsection///</summary>///<param name= "section" > Segment for the section to be obtained. Note that this string is case-insensitive </param>///<param name= the "buffer" > Buffer returns a binary string that is separated by "a" between the strings </param>///<param Name= "nsize" > Buffer size </param>///<param name= "FilePath" > Initialization file name.
  If you do not specify a full pathname, Windows finds files in the Windows directory </param>///<returns></returns> [DllImport ("kernel32")] public static EXtern int Getprivateprofilesection (string section, byte[] buffer, int nsize, string filePath); <summary>///gets all key value pairs in the specified segment section to return each key of the collection such as "Key=value"///</summary>///<param name= "section" > Specified paragraph </param>///<param name= "filePath" >ini file absolute path </param>///<returns></returns > public static list<string> readkeyvalues (String, String as_filepath = "") {byte[] buffer = new
   BYTE[32767];
   list<string> list = new list<string> ();
   int length = 0; if (As_filepath = = "") {length = getprivateprofilesection (section, buffer, buffer.)
   GetUpperBound (0), strFilePath); else {length = getprivateprofilesection (section, buffer, buffer.) 
   GetUpperBound (0), As_filepath);
   A string temp;
   int postion = 0; for (int i = 0; i < length; i++) {if (buffer[i] = = 0x00)//Is delimited by ' i ' {temp = System.Text.ASCIIEncodi Ng. default.getstring (buffer, postion, i-postion).Trim ();
     postion = i + 1; if (temp. Length > 0) {list.
     ADD (temp);
  }} return list; }///<summary>///Delete the specified key///</summary>///<param name= "section" > The paragraph name to be written </param>// /<param name= "key" > the key to be deleted </param>///<param name= "filename" >ini file full path and filename </param> public St atic void Delkey (string section, string key, String as_filepath = "") {if (As_filepath = = "") {Writeprivatep
   Rofilestring (section, key, NULL, strFilePath);
   else {writeprivateprofilestring (section, key, NULL, As_filepath);
  }///<summary>///Returns a collection of all the section names in the profile///</summary> public static ArrayList readsections ()
   {byte[] buffer = new byte[65535]; int rel = Getprivateprofilesectionnamesa (buffer, buffer. 
   GetUpperBound (0), strFilePath);
   int icnt, IPos;
   ArrayList ArrayList = new ArrayList ();
   string tmp;
  if (Rel > 0) {icnt = 0; iPos = 0;  for (icnt = 0; icnt < rel; icnt++) {if (buffer[icnt] = = 0x00) {tmp = System.Text.ASCIIEncoding. UTF8. GetString (buffer, IPos, Icnt-ipos).
      Trim ();
      IPos = icnt + 1;
     if (tmp!= "") Arraylist.add (TMP);
  }} return arrayList;

 } 
 }

Run Result:

This article has been sorted out to the ASP. NET micro-Credit Development tutorial Summary, you are welcome to learn to read.

The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.