public override bool AfterSave() { if (IsDoctorRelated == null || !Convert.ToBoolean(IsDoctorRelated)) { return(true); } if (DoctorID == null) { MessageToView = "You should choose the Doctor"; return(false); } Doctor_Diagnosis_cu bridge = DBCommon.CreateNewDBEntity <Doctor_Diagnosis_cu>(); bridge.Diagnosis_CU_ID = ((Diagnosis_cu)ActiveCollector.ActiveDBItem).ID; bridge.Doctor_CU_ID = Convert.ToInt32(DoctorID); if (UserID != null) { bridge.InsertedBy = Convert.ToInt32(UserID); } bridge.IsOnDuty = true; switch (((IDiagnosis_Viewer)ActiveCollector.ActiveViewer).CommonTransactionType) { case DB_CommonTransactionType.DeleteExisting: bridge.IsOnDuty = false; break; } bridge.IsMerkInsertion = false; return(bridge.SaveChanges()); }
public Drawing CreateDefaultDrawingWithFileName() { try { Drawing d = DBCommon.CreateDefaultDrawing(); d.FileName = _db.Filename; try { d.Number = Path.GetFileNameWithoutExtension(d.FileName); while (DBCommon.DrawingComboExists(d.Number, d.Sheet)) { PromptStringOptions pso = new PromptStringOptions(string.Format("Drawing {0} sheet {1} already exists. Please enter a new sheet number:", d.Number, d.Sheet)); string str = _ed.DoPrompt(pso).StringResult; _ed.WriteMessage(str + Environment.NewLine); if (str == "") { return(null); } d.Sheet = str; } } catch (Exception ex) { _ed.WriteMessage(ex.ToString()); } return(d); } catch { return(null); } }
public static int UserLoginByExternalGate(int ObjectTypeId, int ObjectId, string GUID, string Email) { int UserId = DBUser.GetUserByEmail(Email, true); string DBGUID = DBCommon.GetGateGuid(ObjectTypeId, ObjectId, UserId); if (0 != string.Compare(DBGUID, GUID, true)) { // Audit if (PortalConfig.AuditWebLogin) { HttpRequest request = HttpContext.Current.Request; string referrer = ""; if (request.UrlReferrer != null) { referrer = String.Concat(request.UrlReferrer.Host, request.UrlReferrer.PathAndQuery); } string message = String.Format(CultureInfo.InvariantCulture, "Failed IBN portal external login.\r\n\r\nEmail: {0}\r\nGate:{1}\r\nIP: {2}\r\nReferrer: {3}", Email, GUID, request.UserHostAddress, referrer); Log.WriteEntry(message, System.Diagnostics.EventLogEntryType.FailureAudit); } // throw new AccessDeniedException(); } return(UserId); }
/// <summary> /// Load the list of recently used templates, and add the default template /// </summary> public AddTemplateDrawingViewModel() { //load the default template Drawing d = DBCommon.CreateDefaultDrawing(); _recentTemplates = new ObservableCollection <TemplateDrawingModel>(); _recentTemplates.Add(new TemplateDrawingModel("(default)", d)); //read the recent templates, and attempt to load them string[] templates = Properties.Settings.Default.RecentTemplates.Split(new char[] { ';' }); foreach (string file in templates) { try { if (!File.Exists(file)) { continue; } _recentTemplates.Add(new TemplateDrawingModel(file)); } //if we have a problem then just ignore it and continue //TODO: perhaps log these errors somewhere catch { } } }
public static AccountingJournalEntryTransaction CreateAccountingJournalEntryTransaction( object accountingJournalTransaction_ID, object amount, object serial, object chartOfAccount_CU_ID, object isDebit, object description) { if (amount == null || serial == null || accountingJournalTransaction_ID == null || chartOfAccount_CU_ID == null || isDebit == null) { return(null); } AccountingJournalEntryTransaction accountingJournalEntryTransaction = DBCommon.CreateNewDBEntity <AccountingJournalEntryTransaction>(); accountingJournalEntryTransaction.Amount = Convert.ToDouble(amount); accountingJournalEntryTransaction.Serial = serial.ToString(); accountingJournalEntryTransaction.AccountingJournalTransaction_ID = Convert.ToInt32(accountingJournalTransaction_ID); accountingJournalEntryTransaction.ChartOfAccount_CU_ID = Convert.ToInt32(chartOfAccount_CU_ID); accountingJournalEntryTransaction.IsDebit = Convert.ToBoolean(isDebit); if (description != null) { accountingJournalEntryTransaction.Description = description.ToString(); } return(accountingJournalEntryTransaction); }
private void AddTemplateExecute() { Drawing d = DBCommon.CreateDefaultDrawing(); d.Number = ""; _recentTemplates.Add(new TemplateDrawingModel("[new template]", d)); }
public ActionResult UserActivity(string userID) { DBCommon commObj = new DBCommon(); var result = commObj.UserActivity(userID, "Vmrx"); return(Json(result, JsonRequestBehavior.AllowGet)); }
public static CashBoxInOutTransaction CreateCashBoxInOutTransaction(object transactionDate, object cashBoxTransactionType_P_ID, object chartOfAccount_CU_ID, object generalChartOfAccountType_CU_ID, object transactionAmount, object paymentType_P_ID, object cashBox_CU_ID, object bank_CU_ID, object bankAccount_CU_ID, object currency_CU_ID, object currencyExchangeRate, object transcationSerial, object description) { if (transactionDate == null || cashBoxTransactionType_P_ID == null || chartOfAccount_CU_ID == null || generalChartOfAccountType_CU_ID == null || transactionAmount == null || paymentType_P_ID == null || currency_CU_ID == null) { return(null); } CashBoxInOutTransaction cashBoxInOutTransaction = DBCommon.CreateNewDBEntity <CashBoxInOutTransaction>(); cashBoxInOutTransaction.TranscationDate = Convert.ToDateTime(transactionDate); cashBoxInOutTransaction.CashBoxTransactionType_P_ID = Convert.ToInt32(cashBoxTransactionType_P_ID); cashBoxInOutTransaction.ChartOfAccount_CU_ID = Convert.ToInt32(chartOfAccount_CU_ID); cashBoxInOutTransaction.GeneralChartOfAccountType_CU_ID = Convert.ToInt32(generalChartOfAccountType_CU_ID); cashBoxInOutTransaction.TransactionAmount = Convert.ToDouble(transactionAmount); cashBoxInOutTransaction.PaymentType_P_ID = Convert.ToInt32(paymentType_P_ID); cashBoxInOutTransaction.Currency_CU_ID = Convert.ToInt32(currency_CU_ID); if (currencyExchangeRate != null) { cashBoxInOutTransaction.CurrencyExchangeRate = Convert.ToDouble(currencyExchangeRate); } if (transcationSerial != null) { cashBoxInOutTransaction.TranscationSerial = transcationSerial.ToString(); } cashBoxInOutTransaction.IsCancelled = false; return(cashBoxInOutTransaction); }
public override IEnumerable <TEntity> GetItemsList() { List <InsuranceCarrier_InsuranceLevel_cu> list = DBCommon.GetItemsList <InsuranceCarrier_InsuranceLevel_cu>().ToList().ToList(); return((IEnumerable <TEntity>)list); }
private static void ValidateSqlServerVesion() { // SQL Server 2005: 9.00.1399.06 // SQL Server 2000 SP4: 8.00.2039 // SQL Server 2000 SP3: 8.00.760 bool success = false; string productVesion = DBCommon.GetSqlServerVersion(); try { int firstDotPos = productVesion.IndexOf("."); int lastDotPos = productVesion.LastIndexOf("."); int majorVersion = int.Parse(productVesion.Substring(0, firstDotPos)); int build = int.Parse(productVesion.Substring(lastDotPos + 1)); if (majorVersion > 8 || (majorVersion == 8 && build >= 760)) { success = true; } } catch { } if (!success) { throw new UnsupportedSqlServerVersionException(); } }
private void Button_Click(object sender, RoutedEventArgs e) { btnSave.Focus();//prop grid wont save unless it loses focus (which it wont if we press enter instead of click the button) if (propGrid.IsReadOnly) { propGrid.IsReadOnly = false; btnSave.Content = "Save and Close"; lblEditMessage.Visibility = System.Windows.Visibility.Visible; } else { if (DBCommon.DrawingComboExists(_d.Number, _d.Sheet, _d.Id)) { MessageBox.Show("A drawing with the specified number and sheet number already exists."); } else { try { _dc.SubmitChanges(); } catch (Exception ex) { MessageBox.Show("An error has occured while trying to commit changes to the database. A data concurrency exception may have occured, please refresh the data by re-searching." + Environment.NewLine + Environment.NewLine + ex.Message); } this.Close(); } } }
/// <summary> /// Fills a title blocks drawing number with the next available number, then saves it to the database /// (so a subsequent call to this function will give the next number, not the same one) /// </summary> public void AutoNumberBlockThenSave() { Transaction tr = _db.TransactionManager.StartTransaction(); try { IEnumerable <BlockReference> blocks = PromptForBlock(tr); foreach (BlockReference blkRef in blocks) { Dictionary <string, AttributeReference> attribs = GetBlockAttributes(blkRef, tr); attribs["DRAWING-NUMBER"].TextString = DBCommon.GetNextDrawingNumber(); if (!BlockToDatabase(blkRef, tr)) { _ed.WriteMessage("Could not save drawing to database, returning drawing number to the pool \n"); attribs["DRAWING-NUMBER"].TextString = ""; } } tr.Commit(); } catch (Exception ex) { _ed.WriteMessage(ex.Message + "\n"); } finally { tr.Dispose(); } }
public static void UpdateTimeline(int taskId, DateTime startDate, DateTime finishDate) { string title; string description; int priorityId; bool isMilestone; int activationType; int completionType; bool mustBeConfirmed; int phaseId; int taskTime; using (IDataReader TaskReader = Task.GetTask(taskId)) { if (TaskReader.Read()) { title = (string)TaskReader["Title"]; description = TaskReader["Description"].GetType() == typeof(DBNull) ? null: (string)TaskReader["Description"]; isMilestone = (bool)TaskReader["IsMilestone"]; priorityId = (int)TaskReader["PriorityId"]; completionType = (int)TaskReader["CompletionTypeId"]; activationType = (int)TaskReader["ActivationTypeId"]; mustBeConfirmed = (bool)TaskReader["MustBeConfirmed"]; phaseId = DBCommon.NullToInt32(TaskReader["PhaseId"]); taskTime = (int)TaskReader["TaskTime"]; } else { throw new Exception("Task not found"); } } ArrayList categories = new ArrayList(); using (IDataReader reader = DBCommon.GetListCategoriesByObject((int)OBJECT_TYPE, taskId)) { while (reader.Read()) { int categoryId = (int)reader["CategoryId"]; categories.Add(categoryId); } } Task.Update( taskId , title , description , startDate , finishDate , priorityId , isMilestone , activationType , completionType , mustBeConfirmed , categories , phaseId , taskTime ); }
public List <TicketExceptions> GetTicket_VoidnExpired(Tickets oTickets, List <string> lstPositions) { string strTicketInException = string.Empty; List <TicketExceptions> lstTickets = null; TicketExceptions excep = null; try { DataTable dtTickets = cashdeskmanagerDataAccess.GetTickets(oTickets); if (dtTickets == null && dtTickets.Rows.Count < 0) { } else { lstTickets = new List <TicketExceptions>(); foreach (DataRow row in dtTickets.Rows) { excep = new TicketExceptions(); excep.SEGM = row["PrintDevice"].ToString(); excep.Machine = cashdeskmanagerDataAccess.GetBarPositionFromAsset(row["PrintDevice"].ToString()); excep.currValue = (float)Convert.ToDouble(row["iAmount"]) / 100; if (DBCommon.CheckPositionToDisplay(excep.Machine, lstPositions)) { excep.Position = cashdeskmanagerDataAccess.GetBarPositionFromAsset(row["PrintDevice"].ToString()); excep.TransactionType = "Voucher"; excep.Zone = "n/a"; System.Threading.Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("en-GB"); DateTime dt = DateTime.Parse(row["dtPrinted"].ToString(), System.Threading.Thread.CurrentThread.CurrentCulture.DateTimeFormat); excep.Asset = row["Asset"].ToString(); // excep.PrintDate = row["dtPrinted"].ToString().ReadDateTimeWithSeconds().ToString(); excep.PrintDate = Convert.ToDateTime(row["dtPrinted"]).ToString("dd MMM yyyy HH:mm:ss").ReadDateTimeWithSeconds().ToString(); excep.PayDate = Convert.ToDateTime(row["dtExpire"]).ToString("dd MMM yyyy HH:mm:ss").ReadDateTimeWithSeconds().ToString(); excep.Value = Convert.ToDouble(row["iAmount"]) / 100; //excep.Amount = (Convert.ToDouble().ToString("###0.#0") +")"; excep.Amount = CurrencySymbol + " " + (Convert.ToDecimal(row["iAmount"]) / 100).GetUniversalCurrencyFormat(); excep.Status = (row["StrVoucherStatus"].ToString().Trim().ToUpper() == "NA" ? "Auto Cancelled" : row["StrVoucherStatus"].ToString().Trim().ToUpper() == "VD" ? "Void" : row["StrVoucherStatus"].ToString().Trim().ToUpper() == "EXP" ? "Expired" : "Expired"); excep.cExceptionsTotal += excep.currValue; } lstTickets.Add(excep); } } } catch (Exception ex) { LogManager.WriteLog(ex.Message, LogManager.enumLogLevel.Info); ExceptionManager.Publish(ex); } return(lstTickets); }
public ActionResult UpdatePendingInvoiceNotifications() { DBCommon commObj = new DBCommon(); var result = commObj.GetNumwithQuery("SendInvoiceNotif", "", getUserId()); string displayMsg = result > 0 ? DBQueries.msgUpPendingNotifSuccess : DBQueries.msgUpPendingNotifFailed; return(Json(displayMsg, JsonRequestBehavior.AllowGet)); }
public static DataTable GetSystemEventsDT(DateTime StartDate, DateTime EndDate) { int TimeZoneId = Security.CurrentUser.TimeZoneId; StartDate = DBCommon.GetUTCDate(TimeZoneId, StartDate); EndDate = DBCommon.GetUTCDate(TimeZoneId, EndDate); return(DBSystemEvents.GetSystemEventsDT(Security.CurrentUser.UserID, StartDate, EndDate, TimeZoneId)); }
public ActionResult UpdateResendInvNotif(InvNotifications ResendNotifications) { DBCommon commObj = new DBCommon(); DBQueries dbQueries = new DBQueries(); string query = string.Format(dbQueries.sqlUpdateResendInvoiceNotif, ResendNotifications.PharmacyCode, ResendNotifications.FacilityCode, ResendNotifications.Email, getUserId()); int result = commObj.GetNumwithQuery("UpdateResend", query, getUserId()); return(Json(result, JsonRequestBehavior.AllowGet)); }
/// <summary> /// Reader returns fields: /// GroupId, GroupName, HasChildren /// </summary> public static IDataReader GetListGroupsBySubstring(string SubString) { // O.R. [2008-08-21]: Wildcard chars replacing SubString = DBCommon.ReplaceSqlWildcard(SubString); // return(DbHelper2.RunSpDataReader("GroupsSearch", DbHelper2.mp("@SubString", SqlDbType.NVarChar, 50, @SubString))); }
string getManager(string id) { CoreClass.DBCommon db = new DBCommon(); string sql = "select chuliren from Bank_tixian where id =" + id; DataTable dt = db.GetDataTableBySql(sql); string temp = dt.Rows[0][0].ToString(); return(temp); }
private void btnAddToList_Click(object sender, EventArgs e) { if (spnAmount.EditValue == null || Math.Abs(Convert.ToDouble(spnAmount.EditValue)) < 0.0001) { return; } if (CashBoxInOutTransactionsList == null) { CashBoxInOutTransactionsList = new List <CashBoxInOutTransaction>(); } CashBoxInOutTransaction cashBoxInOutTransaction = DBCommon.CreateNewDBEntity <CashBoxInOutTransaction>(); if (CashBoxTransactionType_P_ID != null) { cashBoxInOutTransaction.CashBoxTransactionType_P_ID = Convert.ToInt32(CashBoxTransactionType_P_ID); } if (TransactionAmount != null) { cashBoxInOutTransaction.TransactionAmount = chkExpenses.Checked || chkReverseRevenue.Checked ? Convert.ToDouble(TransactionAmount) * -1 : Convert.ToDouble(TransactionAmount); } if (TranscationSerial != null) { cashBoxInOutTransaction.TranscationSerial = TranscationSerial.ToString(); } if (Description != null) { cashBoxInOutTransaction.Description = Description.ToString(); } if (TranscationDate != null) { cashBoxInOutTransaction.TranscationDate = Convert.ToDateTime(TranscationDate); } if (ApplicationStaticConfiguration.ActiveCashBox != null) { cashBoxInOutTransaction.CashBox_CU_ID = ApplicationStaticConfiguration.ActiveCashBox.ID; } cashBoxInOutTransaction.AddedType = AddedType.NewelyAdded; CashBoxInOutTransactionsList.Add(cashBoxInOutTransaction); listToBeViewedOnly.Clear(); listToBeViewedOnly.AddRange(CashBoxInOutTransaction.ItemsList.FindAll(item => !Convert.ToInt32(item.AddedType).Equals(Convert.ToInt32(AddedType.Removed)))); listToBeViewedOnly.AddRange(CashBoxInOutTransactionsList.FindAll(item => !Convert.ToInt32(item.AddedType).Equals(Convert.ToInt32(AddedType.Removed)))); grdCashBoxInOutTransactions.DataSource = listToBeViewedOnly.OrderByDescending(item => item.TranscationDate); grdCashBoxInOutTransactions.RefreshDataSource(); gridView7.SelectRow(-1); ClearControls(); }
public override bool CreateNew() { if (ActiveDBItem == null) { ActiveDBItem = DBCommon.CreateNewDBEntity <InventoryItem_UnitMeasurment_cu>(); ((IInventoryItem_UnitMeasurment_Viewer)ActiveCollector.ActiveViewer).CommonTransactionType = DB_CommonTransactionType.SaveNew; return(true); } return(false); }
public override bool CreateNew() { if (ActiveDBItem == null) { ActiveDBItem = DBCommon.CreateNewDBEntity <InPatientRoomBed_cu>(); ((IInPatientRoomBedViewer)ActiveCollector.ActiveViewer).CommonTransactionType = DB_CommonTransactionType.SaveNew; return(true); } return(false); }
public override bool CreateNew() { if (ActiveDBItem == null) { ActiveDBItem = DBCommon.CreateNewDBEntity <InsuranceCarrier_InsuranceLevel_cu>(); ((IInsurancePolicyViewer)ActiveCollector.ActiveViewer).CommonTransactionType = DB_CommonTransactionType.SaveNew; return(true); } return(false); }
// Internal #region Load(IDataReader reader) internal void Load(IDataReader reader) { FieldId = (int)reader["FieldId"]; BitField = (bool)reader["BitField"]; IbnName = reader["IbnName"].ToString(); LdapName = reader["LdapName"].ToString(); BitMask = DBCommon.NullToInt32(reader["BitMask"]); Equal = (bool)DBCommon.NullToObject(reader["Equal"], true); CompareTo = DBCommon.NullToInt32(reader["CompareTo"]); }
string getCpUser() { string uid = Request.Cookies["userid"].Value; string sql = "select * from z8 where id = " + uid; CoreClass.DBCommon db = new DBCommon(); DataTable dt = db.GetDataTableBySql(sql); return(dt.Rows[0]["name"].ToString()); }
public override bool CreateNew() { if (ActiveDBItem == null) { ActiveDBItem = DBCommon.CreateNewDBEntity <User_UserGroup_cu>(); ((IUser_UserGroup_Viewer)ActiveCollector.ActiveViewer).CommonTransactionType = DB_CommonTransactionType.SaveNew; return(true); } return(false); }
/// <summary> /// Reader returns fields: /// GroupId, GroupName, HasChildren /// </summary> public static IDataReader GetListGroupsBySubstringForPartner(string SubString, int UserId) { // O.R. [2008-08-21]: Wildcard chars replacing SubString = DBCommon.ReplaceSqlWildcard(SubString); // return(DbHelper2.RunSpDataReader("GroupsSearchForPartner", DbHelper2.mp("@SubString", SqlDbType.NVarChar, 50, @SubString), DbHelper2.mp("@PrincipalId", SqlDbType.Int, UserId))); }
public override bool CreateNew() { if (ActiveDBItem == null) { ActiveDBItem = DBCommon.CreateNewDBEntity <FinanceInvoice>(); ((IFinanceInvoiceCreation)ActiveCollector.ActiveViewer).CommonTransactionType = DB_CommonTransactionType.SaveNew; return(true); } return(false); }
protected override int CreateSystemRow(FillDataMode mode, params object[] item) { if (mode == FillDataMode.Update) { throw new NotSupportedException("Update is not supported for Incident import"); } string Description = ""; string Resolution = ""; string Workaround = ""; string Title = "Imported incident " + DateTime.Now.ToString("d"); DateTime CreationDate = DateTime.UtcNow; int PriorityId = int.Parse(PortalConfig.IncidentDefaultValuePriorityField); int TypeId = int.Parse(PortalConfig.IncidentDefaultValueTypeField); int SeverityId = int.Parse(PortalConfig.IncidentDefaultValueSeverityField);; if (item[0] != null) { Title = (string)item[0]; } if (item[2] != null) { CreationDate = DBCommon.GetUTCDate(Security.CurrentUser.TimeZoneId, (DateTime)item[2]); } if (item[1] != null) { Description = (string)item[1]; } if (item[6] != null) { Resolution = (string)item[6]; } if (item[7] != null) { Workaround = item[7].ToString(); } if (item[3] != null) { PriorityId = GetPriorityId((string)item[3]); } if (item[4] != null) { TypeId = GetTypeId((string)item[4]); } if (item[5] != null) { SeverityId = GetSeverityId((string)item[5]); } int IncidentId = Incident.Create(Title, Description, TypeId, PriorityId, SeverityId, Security.CurrentUser.UserID, CreationDate); //Issue2.UpdateResolutionInfo(IncidentId, Resolution, Workaround); return(IncidentId); }
private void mnuRemovePlugin2015_Click(object sender, RoutedEventArgs e) { try { DBCommon.RemovePlugin(AcadVersion.ACAD2015); } catch (Exception ex) { MessageBox.Show(ex.Message); } }
/// <summary> /// 进行 Token 请求,将值存储在静态类中 /// </summary> public static void RequestServiceToken() { //表示 请求 成功与否 bool flag = false; //1.请求 Token string url = "https://api.weixin.qq.com/cgi-bin/token"; //2.带参数 var dnmXML = XMLHelper.LoadConfigXML("SystemConfigXML"); var par = new { grant_type = "client_credential", appid = dnmXML.SystemConfig.AppID, secret = dnmXML.SystemConfig.AppSecret }; RequestHelper _requestHelper = new RequestHelper(); string strPar = _requestHelper.JoinArguments(par); //接收准备 string s_access_token = string.Empty; string s_expires_in = string.Empty; //3.请求 using (HttpClient htpClt = new HttpClient()) { string rqtResult = htpClt.GetStringAsync(new Uri(url + strPar)).Result; dynamic dnm = JsonConvert.DeserializeObject(rqtResult); if (dnm.errorcode != null) { flag = false; //失败 } else { flag = true; //成功 s_access_token = dnm.access_token; s_expires_in = dnm.expires_in; } } if (flag) { //4.给静态对象赋值 TokenEntity.Token = s_access_token; TokenEntity.DateLength = int.Parse(s_expires_in); TokenEntity.ExpiresDate = DateTime.Now.AddSeconds(TokenEntity.DateLength); } }
/// <summary> /// 注册按钮 - 需要将按钮配置信息存入XML中 /// </summary> /// <returns></returns> public ActionResult RegisterMenu() { //将菜单信息配置到XML中 List<object> buttonList = new List<object>(); //第一顺序菜单 buttonList.Add( new { type = "click", name = "精彩推荐", key = "zzsc_BestArticle" } ); //第二顺序菜单 buttonList.Add( new { type = "view", name = "智种商城", url = "http://inovoseed.com/WeShop/Main" } ); //第三顺序菜单 buttonList.Add( new { name = "了解我们", sub_button = new List<object>() { new { type = "view",name = "公司简介",url = "http://123.56.205.75:8123/zzwIntro.html"}, new { type = "click",name = "联系我们",key = "zzsc_Contect"} } } ); var objMenu = new { button = buttonList }; return Content(RequestRegisterMenu(objMenu)); }
/// <summary> /// 获取所有素材? /// </summary> /// <param name="par1">从全部素材的该偏移位置开始返回,0表示从第一个素材返回</param> /// <param name="par2">返回素材的数量,取值在1到20之间</param> /// <returns></returns> public ActionResult RequestMaterialList(string par1, string par2) { string strResult = "请求失败!"; if (string.IsNullOrEmpty(par1) || string.IsNullOrEmpty(par2)) { //都为空 return Content(strResult); } //参数准备 string offset = par1; string count = par2; string token = tokenOpe.GetToken(); string url = "https://api.weixin.qq.com/cgi-bin/material/batchget_material?access_token="; object param = new { type = "news", offset = offset, count = count }; //请求 using (WebClient wc = new WebClient()) { Encoding enc = Encoding.UTF8; strResult = enc.GetString(wc.UploadData(new Uri(url + token), enc.GetBytes(JsonConvert.SerializeObject(param)))); } return Content(strResult); }
/// <summary> /// 自定义菜单创建接口 /// </summary> /// <returns></returns> public ActionResult RequestCreateMenu() { string strResult = string.Empty; //1.获取 Token string token = tokenOpe.GetToken(); //2.api地址 string url = "https://api.weixin.qq.com/cgi-bin/menu/create?access_token="; //3.准备发送信息 List<object> buttonList = new List<object>(); #region 按照顺序添加菜单 //第一顺序菜单 buttonList.Add( new { name = "公司概况", sub_button = new List<object>() { new { type = "view",name = "公司简介",url = "http://101.200.140.102:8123/"}, new { type = "click",name = "经典回顾",key = "xrhf_BestArticle"} } } ); //第二顺序菜单 buttonList.Add( new { type = "view", name = "智种商城", url = "http://101.200.140.102:8123/zzwIntro.html" } ); //第三顺序菜单 buttonList.Add( new { type = "click", name = "联系我们", key = "xrhf_Contect" } ); var postParam = new { button = buttonList }; #endregion string strJson = JsonConvert.SerializeObject(postParam); //4.发送请求 using (WebClient wc = new WebClient()) { Encoding enc = Encoding.UTF8; strResult = enc.GetString(wc.UploadData(new Uri(url + token), enc.GetBytes(strJson))); } return Content(strResult); }
/// <summary> /// 获取openid /// Remark:校验code /// </summary> public Tuple<bool, string> GetOpenidAndAccessToken(HttpContextBase _base) { if (!string.IsNullOrEmpty(_base.Request["code"])) { //获取code码,以获取openid和access_token string code = _base.Request["code"]; GetOpenidAndAccessTokenFromCode(_base, code); return new Tuple<bool, string>(true, string.Empty); } else { //构造网页授权获取code的URL string url = "https://open.weixin.qq.com/connect/oauth2/authorize"; string host = _base.Request.Url.Host; string path = _base.Request.Path; string redirect_uri = HttpUtility.UrlEncode("http://" + host + path); var par = new { appid = ZZSCResource.DnmSystemConfig.SystemConfig.AppID, redirect_uri = redirect_uri, response_type = "code", scope = ZZSCResource.DnmSystemConfig.SystemConfig.scope, state = "STATE" + "#wechat_redirect" }; //Log string strPar = new RequestHelper().JoinArguments(par); //跳转 return new Tuple<bool, string>(false, url + strPar); } }
/// <summary> /// 注册 自定义菜单事件 /// </summary> /// <param name="id">token</param> /// <returns></returns> public ActionResult RegisterSelfMenu() { string strResult = "注册失败"; string token = tokenOpe.GetToken(); //请求的路径 string url = "https://api.weixin.qq.com/cgi-bin/menu/create?access_token="; //提交的内容 List<object> buttonList = new List<object>(); #region 按照顺序添加菜单 //第一顺序菜单 buttonList.Add( new { name = "了解我们", sub_button = new List<object>() { new { type = "view",name = "公司简介",url = "http://101.200.140.102:8123/"}, new { type = "click",name = "经典回顾",key = "xrhf_BestArticle"} } } ); //第二顺序菜单 buttonList.Add( new { type = "view", name = "智种商城", url = "http://101.200.140.102:8123/zzwIntro.html" } ); //第三顺序菜单 buttonList.Add( new { type = "click", name = "联系我们", key = "xrhf_Contect" } ); var registerValue = new { button = buttonList }; #endregion //请求 using (WebClient wc = new WebClient()) { Encoding enc = Encoding.UTF8; strResult = enc.GetString(wc.UploadData(new Uri(url + token), enc.GetBytes(JsonConvert.SerializeObject(registerValue)))); dynamic dnm = JsonConvert.DeserializeObject(strResult); if (dnm.errmsg == "ok" && dnm.errcode == "0") { strResult = "注册成功!"; } else { strResult = dnm.ToString(); } } return Content(strResult); }
/// <summary> /// 根据Code取出 access_token、openid 值 /// Remark:存储到Session中 /// </summary> /// <param name="code"></param> public void GetOpenidAndAccessTokenFromCode(HttpContextBase _base, string code) { //Result Data string access_token = string.Empty; string openid = string.Empty; //Init Data bool flag = false; string url = "https://api.weixin.qq.com/sns/oauth2/access_token"; var par = new { appid = ZZSCResource.DnmSystemConfig.SystemConfig.AppID, secret = ZZSCResource.DnmSystemConfig.SystemConfig.AppSecret, code = code, grant_type = "authorization_code" }; string strPar = new RequestHelper().JoinArguments(par); //Request using (HttpClient htpClt = new HttpClient()) { string rqtResult = htpClt.GetStringAsync(new Uri(url + strPar)).Result; dynamic dnm = JsonConvert.DeserializeObject(rqtResult); if (dnm.errorcode != null) { flag = false; //失败 } else { flag = true; //成功 access_token = dnm.access_token; openid = dnm.openid; _base.Session["access_token"] = access_token; _base.Session["openid"] = openid; } } }
/// <summary> /// 根据 MediaID 请求素材 /// </summary> /// <param name="mediaID"></param> /// <returns></returns> public static string RequestArticleItemByID(string mediaID) { //Result Data string strResult = string.Empty; //Init Data string token = new TokenOpe().GetToken(); string url = "https://api.weixin.qq.com/cgi-bin/material/get_material?access_token="; //Post Data object param = new { media_id = mediaID }; //请求 using (WebClient wc = new WebClient()) { Encoding enc = Encoding.UTF8; strResult = enc.GetString(wc.UploadData(new Uri(url + token), enc.GetBytes(JsonConvert.SerializeObject(param)))); } return strResult; }
/// <summary> /// 根据 起始时间 + 结束时间 查询图文总分析结果 /// </summary> /// <param name="par1">起始时间</param> /// <param name="par2">截止时间</param> /// <param name="par3">查询接口类型 推荐:1</param> /// <returns></returns> public ActionResult RequestArticleUserRead(string par1, string par2, string par3) { DateTime startDate; DateTime endDate; DateTime.TryParse(par1, out startDate); DateTime.TryParse(par2, out endDate); string token = tokenOpe.GetToken(); string strResult = string.Empty; //测试 - 接口类别 string type = par3; //请求的路径 string url = ""; switch (type) { case "": url = "https://api.weixin.qq.com/datacube/getarticlesummary?access_token="; break; case "1": url = "https://api.weixin.qq.com/datacube/getarticlesummary?access_token="; break; case "2": url = "https://api.weixin.qq.com/datacube/getarticletotal?access_token="; break; case "3": url = "https://api.weixin.qq.com/datacube/getuserread?access_token="; break; case "4": url = "https://api.weixin.qq.com/datacube/getuserreadhour?access_token="; break; case "5": url = "https://api.weixin.qq.com/datacube/getusershare?access_token="; break; case "6": url = "https://api.weixin.qq.com/datacube/getusersharehour?access_token="; break; default: break; } //提交的内容 var postParam = new { begin_date = startDate, end_date = endDate }; //请求 using (WebClient wc = new WebClient()) { Encoding enc = Encoding.UTF8; strResult = enc.GetString(wc.UploadData(new Uri(url + token), enc.GetBytes(JsonConvert.SerializeObject(postParam)))); } return Content(strResult); }
/// <summary> /// 用地址信息 /// </summary> /// <returns></returns> public string GetEditAddressParameters(HttpContextBase _base) { string parameter = ""; try { string host = _base.Request.Url.Host; string path = _base.Request.Path; string queryString = _base.Request.Url.Query; //这个地方要注意,参与签名的是网页授权获取用户信息时微信后台回传的完整url string url = "http://" + host + path + queryString; //构造需要用SHA1算法加密的数据 var par = new { accesstoken = _base.Session["access_token"], appid = ZZSCResource.DnmSystemConfig.SystemConfig.AppID, noncestr = TokenHelper.GenerateNonceStr(), timestamp = TokenHelper.GenerateTimeStamp(), url = url }; string param = new RequestHelper().JoinArguments(par); //Log.Debug(this.GetType().ToString(), "SHA1 encrypt param : " + param); //SHA1加密 string addrSign = FormsAuthentication.HashPasswordForStoringInConfigFile(param.TrimStart('?'), "SHA1"); //Log.Debug(this.GetType().ToString(), "SHA1 encrypt result : " + addrSign); //获取收货地址js函数入口参数 var parNa = new { addrSign = addrSign, appId = ZZSCResource.DnmSystemConfig.SystemConfig.AppID, noncestr = TokenHelper.GenerateNonceStr(), timestamp = TokenHelper.GenerateTimeStamp(), scope = "jsapi_address", signType = "sha1" }; SortedDictionary<string, object> dicPar = new SortedDictionary<string, object>(); dicPar.Add("addrSign", addrSign); dicPar.Add("appId", ZZSCResource.DnmSystemConfig.SystemConfig.AppID); dicPar.Add("noncestr", TokenHelper.GenerateNonceStr()); dicPar.Add("timestamp", TokenHelper.GenerateTimeStamp()); dicPar.Add("scope", "jsapi_address"); dicPar.Add("signType", "sha1"); //转为json格式 parameter = JsonConvert.SerializeObject(parNa); //parameter = JsonMapper.ToJson(dicPar); //Log.Debug(this.GetType().ToString(), "Get EditAddressParam : " + parameter); } catch (Exception ex) { //Log.Error(this.GetType().ToString(), ex.ToString()); DBCommon.LogFileHelper.WriteLogByTxt(string.Format("GetEditAddressParameters方法异常:{0}", ex.ToString())); throw new Exception(ex.ToString()); } return parameter; }