public void AddSecurity(string security, DataFactory dataFactoryObject) { if (security.Trim().Length > 0) { _securities.Add(security, dataFactoryObject); } }
public void Constructor_IfTheDataFactoryParameterIsNotNull_ShouldSetTheDataFactoryProperty() { using(ShimsContext.Create()) { ShimDataFactory.StaticConstructor = () => { }; DataFactory dataFactory = new DataFactory(); Assert.AreEqual(dataFactory, new DataFactoryWrapper(dataFactory, Mock.Of<IPageDataCaster>(), Mock.Of<IPermanentLinkMapper>()).DataFactory); } }
protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { string uId = Page.User.Identity.Name.ToString(); string name = new DataFactory().getAData("select [username] from [managerinfo] where [manageId]=" + uId, "username"); this.lb_account.Text = name; this.lb_serverTime.Text = DateTime.Now.ToLocalTime().ToString(); } }
//--- Methods --- protected override Yield Start(XDoc config, Result result) { yield return Coroutine.Invoke(base.Start, config, new Result()); // read configuration settings _factory = new DataFactory(MySql.Data.MySqlClient.MySqlClientFactory.Instance, "?"); _catalog = new DataCatalog(_factory, config); _domain = (config["openid-suffix"].AsText ?? string.Empty).ToLowerInvariant(); // test database connection try { _catalog.TestConnection(); } catch(Exception) { throw new Exception(string.Format("Unable to connect to Deki Social instance with connectionString: {0}", _catalog.ConnectionString)); } result.Return(); }
//--- Methods --- protected override Yield Start(XDoc config, Result result) { yield return Coroutine.Invoke(base.Start, config, new Result()); // read configuration settings _factory = new DataFactory(MySql.Data.MySqlClient.MySqlClientFactory.Instance, "?"); _catalog = new DataCatalog(_factory, config); _tablePrefix = config["db-tableprefix"].AsText ?? string.Empty; // test database connection try { _catalog.TestConnection(); } catch(Exception) { throw new Exception(string.Format("Unable to connect to vBulletin instance with connection string: {0}", _catalog.ConnectionString)); } result.Return(); }
/// <summary> /// 添加或修改车辆信息 /// </summary> /// <param name="ht"></param> /// <param name="_key"></param> /// <returns></returns> public bool AddOrEditVehicleInfo(Hashtable ht, string _key) { return(DataFactory.SqlDataBase().Submit_AddOrEdit("YR_Vehicles", "ID", _key, ht)); }
/// <summary> /// 车辆操控日志 /// </summary> /// <param name="operate_type">操作类型:01开车,02锁车,03寻车,04开座锁</param> /// <param name="gpsID">车辆gps编号</param> /// <param name="result">操控返回结果:0失败,1成功</param> /// <returns></returns> public bool VehicleOperateLog(string operate_type, string vehicleid, bool result, string returnResult) { string gpsNum = ""; string longitude = ""; string latitude = ""; string speed = "0"; string power = "0"; string lockState = ""; Hashtable vehicle_ht = GetVehicleInfoByID(vehicleid); if (vehicle_ht != null) { gpsNum = SiteHelper.GetHashTableValueByKey(vehicle_ht, "VehicleGPSNum"); longitude = SiteHelper.GetHashTableValueByKey(vehicle_ht, "Longitude"); latitude = SiteHelper.GetHashTableValueByKey(vehicle_ht, "Latitude"); speed = SiteHelper.GetHashTableValueByKey(vehicle_ht, "CurrentSpeed"); power = SiteHelper.GetHashTableValueByKey(vehicle_ht, "Electricity"); lockState = SiteHelper.GetHashTableValueByKey(vehicle_ht, "LockState"); } List <StringBuilder> sqls = new List <StringBuilder>(); List <object> objs = new List <object>(); //StringBuilder sbAddLog = new StringBuilder(); //sbAddLog.Append("INSERT INTO YR_VehicleDriveLog(ID,VehicleID,OrderID,GPSNum,Longitude,Latitude,Address,Direction,Speed,Power,LockState,LightState,RecordTime,DriveStyle,IsStart,IsEnd,OprResult,ReturnResult) " + // "SELECT convert(varchar(50),newid()),YR_Vehicles.ID,YR_Orders.ID,VehicleGPSNum,Longitude,Latitude,null,null,CurrentSpeed,Electricity,LockState,LightState,getdate(),@DriveStyle,null,null,@OprResult,@ReturnResult " + // "FROM YR_Vehicles left join YR_Orders on YR_Vehicles.ID=YR_Orders.VehicleID and OrderState=1 where YR_Vehicles.DeleteMark=1 and YR_Vehicles.ID=@ID"); StringBuilder sbAddLog = new StringBuilder(); sbAddLog.Append("INSERT INTO YR_VehicleDriveLog(ID,VehicleID,GPSNum,Longitude,Latitude,Speed,Power,LockState,RecordTime,DriveStyle,IsStart,IsEnd,OprResult,ReturnResult) VALUES(convert(varchar(50),newid()),@VehicleID,@GPSNum,@Longitude,@Latitude,@Speed,@Power,@LockState,getdate(),@DriveStyle,null,null,@OprResult,@ReturnResult)"); SqlParam[] parmAddLog = new SqlParam[] { new SqlParam("@VehicleID", vehicleid), new SqlParam("@GPSNum", gpsNum), new SqlParam("@Longitude", longitude), new SqlParam("@Latitude", latitude), new SqlParam("@Speed", speed), new SqlParam("@Power", power), new SqlParam("@LockState", lockState), new SqlParam("@DriveStyle", operate_type), new SqlParam("@OprResult", result?1:0), new SqlParam("@ReturnResult", returnResult), new SqlParam("@ID", vehicleid) }; sqls.Add(sbAddLog); objs.Add(parmAddLog); if (result) { if (operate_type == "01") { //开车 StringBuilder sbUpdateVehicle = new StringBuilder(); sbUpdateVehicle.Append("UPDATE YR_Vehicles SET LockState='unlock' WHERE ID=@ID"); SqlParam[] parmUpdateVehicle = new SqlParam[] { new SqlParam("@ID", vehicleid) }; sqls.Add(sbUpdateVehicle); objs.Add(parmUpdateVehicle); } else if (operate_type == "02") { //锁车 StringBuilder sbUpdateVehicle = new StringBuilder(); sbUpdateVehicle.Append("UPDATE YR_Vehicles SET LockState='lock' WHERE ID=@ID"); SqlParam[] parmUpdateVehicle = new SqlParam[] { new SqlParam("@ID", vehicleid) }; sqls.Add(sbUpdateVehicle); objs.Add(parmUpdateVehicle); } else if (operate_type == "03") { //寻车 } else if (operate_type == "04") { //开座锁 } else { //其它... } } return(DataFactory.SqlDataBase().BatchExecuteBySqlWithTrans(sqls.ToArray(), objs.ToArray()) ? true : false); }
/// <summary> /// 保存事件 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> protected void Save_Click(object sender, EventArgs e) { string guid = CommonHelper.GetGuid; Hashtable ht = new Hashtable(); ht["User_Code"] = User_Code.Value; ht["User_Name"] = User_Name.Value; ht["User_Account"] = User_Account.Value; ht["User_Pwd"] = Md5Helper.MD5(User_Pwd.Value, 32); //Md5Helper.MD5(pwd, 32) ht["User_Sex"] = User_Sex.Value; ht["Email"] = Email.Value; //ht["Title"] = Title.Value; ht["User_Remark"] = User_Remark.Value; ht["birthday"] = birthday.Text; ht["Sage_b"] = Sage_b.Value; ht["join_date"] = join_date.Text; ht["out_date"] = out_date.Text; ht["work_flag"] = work_flag.Value; ht["Boss_id"] = GetIDFromName(Boss_id.Value); ht["Boss_Flag"] = Boss_Flag.Value; ht["ATS_Code"] = ATS_Code.Value; if (HR.Value != strHRtemp) { string strsql = "update Base_UserInfo set HR=0"; StringBuilder sbsql = new StringBuilder(strsql); DataTable dtsql = DataFactory.SqlDataBase().GetDataTableBySQL(sbsql); } ht["HR"] = HR.Value; if (work_flag.Value == "0") { ht["DeleteMark"] = 2; } else { ht["DeleteMark"] = 1; } if (!string.IsNullOrEmpty(_key)) { guid = _key; ht["ModifyDate"] = DateTime.Now; if (User_Pwd.Value == "*************") { ht.Remove("User_Pwd"); } ht["ModifyUserId"] = RequestSession.GetSessionUser().UserId; ht["ModifyUserName"] = RequestSession.GetSessionUser().UserName; } else { ht["User_ID"] = guid; ht["CreateUserId"] = RequestSession.GetSessionUser().UserId; ht["CreateUserName"] = RequestSession.GetSessionUser().UserName; } bool IsOk = DataFactory.SqlDataBase().Submit_AddOrEdit("Base_UserInfo", "User_ID", _key, ht); if (IsOk) { IsOk = systemidao.Add_AppendPropertyInstance(guid, AppendProperty_value.Value.Split(';')); if (IsOk) { IsOk = this.add_ItemForm(checkbox_value.Value.Split(','), guid); } } if (IsOk) { string strsql = "insert into Base_LeaveConsole(EmpID) select USER_ID from Base_UserInfo where USER_ID not in (select empid from Base_LeaveConsole)"; StringBuilder sbsql = new StringBuilder(strsql); DataFactory.SqlDataBase().ExecuteBySql(sbsql); ShowMsgHelper.ParmAlertMsg("Success!"); } else { ShowMsgHelper.Alert_Error("Error!"); } }
public GiftAidDeclarationController(DataFactory dataFactory) { _GiftAidDeclarationWorker = (GiftAidDeclarationWorker)dataFactory.GetDataFactory <GiftAidDeclaration>(); }
public void GetPage_WithTwoParameters_ShouldCallGetPageWithTwoParametersOfTheWrappedDataFactory() { using(ShimsContext.Create()) { bool getPageIsCalled = false; PageReference pageLinkValue = null; ILanguageSelector selectorValue = null; PageData pageData = new PageData(); ShimDataFactory.StaticConstructor = () => { }; DataFactory dataFactory = new DataFactory(); new ShimDataFactory(dataFactory).GetPagePageReferenceILanguageSelector = delegate(PageReference pageLink, ILanguageSelector selector) { getPageIsCalled = true; pageLinkValue = pageLink; selectorValue = selector; return pageData; }; PageReference pageLinkParameter = new PageReference(); ILanguageSelector selectorParameter = Mock.Of<ILanguageSelector>(); Assert.IsFalse(getPageIsCalled); Assert.AreEqual(pageData, new DataFactoryWrapper(dataFactory, Mock.Of<IPageDataCaster>(), Mock.Of<IPermanentLinkMapper>()).GetPage(pageLinkParameter, selectorParameter)); Assert.IsTrue(getPageIsCalled); Assert.AreEqual(pageLinkParameter, pageLinkValue); Assert.AreEqual(selectorParameter, selectorValue); } }
/// <summary> /// Verifies the extension rule. /// </summary> /// <param name="context">The Interop service context</param> /// <param name="info">out parameter to return violation information when rule does not pass</param> /// <returns>true if rule passes; false otherwise</returns> public override bool?Verify(ServiceContext context, out ExtensionRuleViolationInfo info) { if (context == null) { throw new ArgumentNullException("context"); } bool?passed = null; info = null; ServiceStatus serviceStatus = ServiceStatus.GetInstance(); DataFactory dFactory = DataFactory.Instance(); var detail = new ExtensionRuleResultDetail(this.Name, serviceStatus.RootURL, HttpMethod.Post, string.Empty); List <string> keyPropertyTypes = new List <string>() { "Edm.Int32", "Edm.Int16", "Edm.Int64", "Edm.Guid", "Edm.String" }; List <EntityTypeElement> entityTypeElements = MetadataHelper.GetEntityTypes(serviceStatus.MetadataDocument, 1, keyPropertyTypes, null, NavigationRoughType.None).ToList(); if (null == entityTypeElements || 0 == entityTypeElements.Count()) { detail.ErrorMessage = "To verify this rule it expects an entity type with Int32/Int64/Int16/Guid/String key property, but there is no this entity type in metadata so can not verify this rule."; info = new ExtensionRuleViolationInfo(new Uri(serviceStatus.RootURL), serviceStatus.ServiceDocument, detail); return(passed); } EntityTypeElement eTypeElement = new EntityTypeElement(); Dictionary <string, string> entityAndpaths = MetadataHelper.StreamPropertyEntities(serviceStatus.MetadataDocument); string relativePath = string.Empty; foreach (var en in entityTypeElements) { if (entityAndpaths.Keys.Contains(en.EntityTypeShortName) && string.IsNullOrEmpty(en.EntitySetName)) { eTypeElement = en; relativePath = entityAndpaths[en.EntityTypeShortName]; break; } } if (eTypeElement.EntityTypeShortName == null) { detail.ErrorMessage = "Cannot find the appropriate entity-set to verify this rule."; info = new ExtensionRuleViolationInfo(new Uri(serviceStatus.RootURL), serviceStatus.ServiceDocument, detail); return(passed); } string url = serviceStatus.RootURL.TrimEnd('/') + @"/" + eTypeElement.EntitySetName; var additionalInfos = new List <AdditionalInfo>(); var reqData = dFactory.ConstructInsertedEntityData(eTypeElement.EntitySetName, eTypeElement.EntityTypeShortName, null, out additionalInfos); string reqDataStr = reqData.ToString(); bool isMediaType = !string.IsNullOrEmpty(additionalInfos.Last().ODataMediaEtag); var resp = WebHelper.CreateEntity(url, context.RequestHeaders, reqData, isMediaType, ref additionalInfos); detail = new ExtensionRuleResultDetail(this.Name, url, HttpMethod.Post, string.Empty, resp, string.Empty, reqDataStr); if (HttpStatusCode.Created == resp.StatusCode || HttpStatusCode.NoContent == resp.StatusCode) { url = additionalInfos.Last().EntityId.TrimEnd('/') + "/" + relativePath.TrimEnd('/'); if (!Uri.IsWellFormedUriString(url, UriKind.RelativeOrAbsolute)) { detail.ErrorMessage = string.Format("Fail to find the stream property read and edit URL.", resp.StatusCode); // Restore the service. var resps = WebHelper.DeleteEntities(context.RequestHeaders, additionalInfos); return(passed); } resp = WebHelper.Get(new Uri(url), null, RuleEngineSetting.Instance().DefaultMaximumPayloadSize, null); detail = new ExtensionRuleResultDetail(this.Name, url, HttpMethod.Get, StringHelper.MergeHeaders(Constants.V4AcceptHeaderJsonFullMetadata, serviceStatus.DefaultHeaders), resp); if ((resp.StatusCode.HasValue && HttpStatusCode.OK == resp.StatusCode) || HttpStatusCode.NoContent == resp.StatusCode) { resp = WebHelper.UpdateMediaTypeEntity(url, context.RequestHeaders, additionalInfos.Last().HasEtag); detail = new ExtensionRuleResultDetail(this.Name, url, HttpMethod.Put, string.Empty, resp, string.Empty, "Successfully updated the stream of the image."); if (null != resp && (HttpStatusCode.NoContent == resp.StatusCode || resp.StatusCode == HttpStatusCode.OK)) { passed = true; } else { passed = false; detail.ErrorMessage = string.Format("HTTP PUT to update the stream property failed with the error {0}.", resp.StatusCode); } } else { detail.ErrorMessage = "Get stream property failed from above URI."; } // Restore the service. WebHelper.DeleteEntities(context.RequestHeaders, additionalInfos); } else { detail.ErrorMessage = "Created the new entity failed for above URI."; } var details = new List <ExtensionRuleResultDetail>() { detail }; info = new ExtensionRuleViolationInfo(new Uri(url), serviceStatus.ServiceDocument, details); return(passed); }
/// <summary> /// Verifies the extension rule. /// </summary> /// <param name="context">The Interop service context</param> /// <param name="info">out parameter to return violation information when rule does not pass</param> /// <returns>true if rule passes; false otherwise</returns> public override bool?Verify(ServiceContext context, out ExtensionRuleViolationInfo info) { if (context == null) { throw new ArgumentNullException("context"); } bool?passed = null; info = null; var termDocs = TermDocuments.GetInstance(); var serviceStatus = ServiceStatus.GetInstance(); var dFactory = DataFactory.Instance(); var detail1 = new ExtensionRuleResultDetail(this.Name); var detail2 = new ExtensionRuleResultDetail(this.Name); List <string> keyPropertyTypes = new List <string>() { "Edm.Int32", "Edm.Int16", "Edm.Int64", "Edm.Guid", "Edm.String" }; List <string> norPropertyTypes = new List <string>() { "Edm.String" }; List <EntityTypeElement> entityTypeElements = MetadataHelper.GetEntityTypes(serviceStatus.MetadataDocument, 1, keyPropertyTypes, norPropertyTypes, NavigationRoughType.None).ToList(); if (null == entityTypeElements || 0 == entityTypeElements.Count) { detail1.ErrorMessage = "To verify this rule it expects an entity type with Int32/Int64/Int16/Guid/String key property and a normal property with string type, but there is not this entity type in metadata, so can not verify this rule."; info = new ExtensionRuleViolationInfo(new Uri(serviceStatus.RootURL), serviceStatus.ServiceDocument, detail1); return(passed); } EntityTypeElement entityType = null; foreach (var ele in entityTypeElements) { if (ele.EntityTypeShortName.IsMediaType()) { continue; } var funcs = new List <Func <string, string, string, List <NormalProperty>, List <NavigProperty>, bool> >() { AnnotationsHelper.GetInsertRestrictions, AnnotationsHelper.GetUpdateRestrictions, AnnotationsHelper.GetDeleteRestrictions }; var methods = new List <Func <string, string, List <string>, bool?> >() { SupportiveFeatureHelper.IsSupportBatchOperation }; var restrictions = ele.EntitySetName.GetRestrictions(serviceStatus.MetadataDocument, termDocs.VocCapabilitiesDoc, funcs, null, NavigationRoughType.None, methods); if (!string.IsNullOrEmpty(restrictions.Item1) && null != restrictions.Item2 && restrictions.Item2.Any()) { entityType = ele; break; } } if (null == entityType || string.IsNullOrEmpty(entityType.EntitySetName)) { detail1.ErrorMessage = "The service does not support batch operation."; info = new ExtensionRuleViolationInfo(new Uri(serviceStatus.RootURL), serviceStatus.ServiceDocument, detail1); return(passed); } string entitySetUrl = entityType.EntitySetName.MapEntitySetNameToEntitySetURL(); if (string.IsNullOrEmpty(entitySetUrl)) { detail1.ErrorMessage = string.Format("Cannot find the entity-set URL which is matched with {0}", entityType.EntityTypeShortName); info = new ExtensionRuleViolationInfo(new Uri(serviceStatus.RootURL), serviceStatus.ServiceDocument, detail1); return(passed); } string url = serviceStatus.RootURL.TrimEnd('/') + @"/" + entitySetUrl; var additionalInfos = new List <AdditionalInfo>(); var reqData = dFactory.ConstructInsertedEntityData(entityType.EntitySetName, entityType.EntityTypeShortName, null, out additionalInfos); string reqDataStr = reqData.ToString(); var resp = WebHelper.CreateEntity(url, context.RequestHeaders, reqData, false, ref additionalInfos); detail1 = new ExtensionRuleResultDetail(this.Name, url, HttpMethod.Post, string.Empty, resp, string.Empty, reqDataStr); if (HttpStatusCode.Created == resp.StatusCode) { string entityId = additionalInfos.Last().EntityId; bool hasEtag = additionalInfos.Last().HasEtag; resp = WebHelper.GetEntity(entityId); if (HttpStatusCode.OK == resp.StatusCode) { JObject entity = JObject.Parse(resp.ResponsePayload); List <string> norPropertyNames = entityType.NormalProperties.Where(norProp => norPropertyTypes.Contains(norProp.PropertyType)).Select(norProp => norProp.PropertyName).ToList(); reqDataStr = dFactory.ConstructUpdatedEntityData(entity, norPropertyNames).ToString(); string boundary = "batch_4e1a76dc-b738-4aa4-9f93-df661d0a4c9f"; string batchReqData = string.Format( @" --batch_4e1a76dc-b738-4aa4-9f93-df661d0a4c9f Content-Type: multipart/mixed; boundary=changeset_77162fcd-b8da-41ac-a9f8-9357efbbd621 --changeset_77162fcd-b8da-41ac-a9f8-9357efbbd621 Content-Type: application/http Content-Transfer-Encoding: binary Content-ID: 1 PATCH {0} HTTP/1.1 " + (hasEtag ? "If-Match: *" : string.Empty) + @" {1} --changeset_77162fcd-b8da-41ac-a9f8-9357efbbd621-- --batch_4e1a76dc-b738-4aa4-9f93-df661d0a4c9f-- ", entityId, reqDataStr); resp = WebHelper.BatchOperation(serviceStatus.RootURL, batchReqData, boundary); detail2 = new ExtensionRuleResultDetail(this.Name, serviceStatus.RootURL + "/$batch", HttpMethod.Post, string.Empty, resp, string.Empty, batchReqData); if (HttpStatusCode.OK == resp.StatusCode) { string expectedData = @"Content-Type: application/http Content-Transfer-Encoding: binary Content-ID: 1 HTTP/1.1 204 No Content "; int index = resp.ResponsePayload.IndexOf("--changesetresponse"); string payload = resp.ResponsePayload.Remove(0, index + 1); if (expectedData == payload.Filtration(new List <string>() { "\nContent-Type:", "\nContent-Transfer-Encoding:", "\nContent-ID:", "\nHTTP/1.1 " })) { passed = true; } else { passed = false; detail2.ErrorMessage = string.Format("The response payload does not accord with the expected pattern as follows:\r\n{0}", expectedData); } } else { passed = false; detail2.ErrorMessage = "The OData service does not return a 200 OK HTTP status code."; } // Restore the service. var resps = WebHelper.DeleteEntities(context.RequestHeaders, additionalInfos); } } else { passed = false; detail1.ErrorMessage = string.Format("Created the new entity failed for above URI with entity data {0}.", reqDataStr); } var details = new List <ExtensionRuleResultDetail>() { detail1, detail2 }.RemoveNullableDetails(); info = new ExtensionRuleViolationInfo(new Uri(serviceStatus.RootURL), serviceStatus.ServiceDocument, details); return(passed); }
private static MktSummaryEvent PrepareMktSummaryEvent(DataFactory factory, MktSummaryEvent mktSummary, TickData tick) { switch (tick.Type) { case Type.Ask: if (mktSummary.Ask == null) { mktSummary.Ask = tick; if (tick.TimeStamp > mktSummary.EventTime) mktSummary.EventTime = tick.TimeStamp; mktSummary = CheckForSyntheticTradeCondition(factory, mktSummary); } break; case Type.Bid: if (mktSummary.Bid == null) { mktSummary.Bid = tick; if (tick.TimeStamp > mktSummary.EventTime) mktSummary.EventTime = tick.TimeStamp; mktSummary = CheckForSyntheticTradeCondition(factory, mktSummary); } break; case Type.Trade: if (mktSummary.Trade == null) { mktSummary.Trade = tick; if (tick.TimeStamp > mktSummary.EventTime) mktSummary.EventTime = tick.TimeStamp; mktSummary = CheckForSyntheticTradeCondition(factory, mktSummary); } break; } if ((mktSummary.Ask != null) && (mktSummary.Bid != null) && mktSummary.Trade != null) { mktSummary.Complete = true; Console.WriteLine("Mkt summary {0} {1} ask {2} bid {3} trade {4}", tick.Security, mktSummary.EventTime.ToLongTimeString(), mktSummary.Ask.Price, mktSummary.Bid.Price, mktSummary.Trade.Price); } return mktSummary; }
/// <summary> /// Verifies the extension rule. /// </summary> /// <param name="context">The Interop service context</param> /// <param name="info">out parameter to return violation information when rule does not pass</param> /// <returns>true if rule passes; false otherwise</returns> public override bool?Verify(ServiceContext context, out ExtensionRuleViolationInfo info) { if (context == null) { throw new ArgumentNullException("context"); } bool?passed = null; info = null; ServiceStatus serviceStatus = ServiceStatus.GetInstance(); TermDocuments termDocs = TermDocuments.GetInstance(); DataFactory dFactory = DataFactory.Instance(); var detail1 = new ExtensionRuleResultDetail(this.Name); var detail2 = new ExtensionRuleResultDetail(this.Name); var detail3 = new ExtensionRuleResultDetail(this.Name); var detail4 = new ExtensionRuleResultDetail(this.Name); List <string> keyPropertyTypes = new List <string>() { "Edm.Int32", "Edm.Int16", "Edm.Int64", "Edm.Guid", "Edm.String" }; List <EntityTypeElement> entityTypeElements = MetadataHelper.GetEntityTypes(serviceStatus.MetadataDocument, 1, keyPropertyTypes, null, NavigationRoughType.SingleValued).ToList(); if (null == entityTypeElements || 0 == entityTypeElements.Count()) { detail1.ErrorMessage = "To verify this rule it expects an entity type with Int32/Int64/Int16/Guid/String key property, but there is no this entity type in metadata so can not verify this rule."; info = new ExtensionRuleViolationInfo(new Uri(serviceStatus.RootURL), serviceStatus.ServiceDocument, detail1); return(passed); } EntityTypeElement entityType = null; foreach (var en in entityTypeElements) { var matchEntity = en.EntitySetName.GetRestrictions(serviceStatus.MetadataDocument, termDocs.VocCapabilitiesDoc, new List <Func <string, string, string, List <NormalProperty>, List <NavigProperty>, bool> >() { AnnotationsHelper.GetDeleteRestrictions, AnnotationsHelper.GetInsertRestrictions, AnnotationsHelper.GetUpdateRestrictions }); if (!string.IsNullOrEmpty(matchEntity.Item1) && matchEntity.Item2 != null && matchEntity.Item2.Any() && matchEntity.Item3 != null && matchEntity.Item3.Any()) { entityType = en; break; } } string entitySetUrl = entityType.EntitySetName.MapEntitySetNameToEntitySetURL(); if (string.IsNullOrEmpty(entitySetUrl)) { detail1.ErrorMessage = string.Format("Cannot find the entity-set URL which is matched with {0}", entityType.EntityTypeShortName); info = new ExtensionRuleViolationInfo(new Uri(serviceStatus.RootURL), serviceStatus.ServiceDocument, detail1); return(passed); } // Create a entity string url = serviceStatus.RootURL.TrimEnd('/') + @"/" + entitySetUrl; var keyNames = entityType.KeyProperties; string keyName = keyNames.First().PropertyName; var additionalInfos = new List <AdditionalInfo>(); var reqData = dFactory.ConstructInsertedEntityData(entityType.EntitySetName, entityType.EntityTypeShortName, null, out additionalInfos); string reqDataStr = reqData.ToString(); bool isMediaType = !string.IsNullOrEmpty(additionalInfos.Last().ODataMediaEtag); var resp = WebHelper.CreateEntity(url, context.RequestHeaders, reqData, isMediaType, ref additionalInfos); detail1 = new ExtensionRuleResultDetail(this.Name, url, HttpMethod.Post, string.Empty, resp, string.Empty, reqDataStr); if (resp.StatusCode == HttpStatusCode.Created) { var entityId = additionalInfos.Last().EntityId; var hasEtag = additionalInfos.Last().HasEtag; // Get a individual property except key property string toUpdatePropertyName = string.Empty; List <string> properties = MetadataHelper.GetSortedPropertiesOfEntity(serviceStatus.MetadataDocument, entityType.EntityTypeShortName); foreach (string name in properties) { if (!string.Equals(name.Split(',')[0], keyName)) { if (name.Split(',')[1].Equals("Edm.String")) { toUpdatePropertyName = name.Split(',')[0]; break; } } } string individualProUrl = entityId + @"/" + toUpdatePropertyName; resp = WebHelper.Get(new Uri(individualProUrl), Constants.AcceptHeaderJson, RuleEngineSetting.Instance().DefaultMaximumPayloadSize, serviceStatus.DefaultHeaders); detail2 = new ExtensionRuleResultDetail(this.Name, individualProUrl, HttpMethod.Get, StringHelper.MergeHeaders(Constants.AcceptHeaderJson, serviceStatus.DefaultHeaders), resp); if (resp.StatusCode == HttpStatusCode.OK) { JObject jo; resp.ResponsePayload.TryToJObject(out jo); string valueOfIndividualProperty = jo[Constants.Value].ToString(); string newValue = valueOfIndividualProperty + "ToUpdate"; jo[Constants.Value] = newValue; // Update the individual property resp = WebHelper.UpdateEntity(individualProUrl, jo.ToString(), HttpMethod.Put); detail3 = new ExtensionRuleResultDetail(this.Name, individualProUrl, HttpMethod.Put, string.Empty, resp, string.Empty, jo.ToString()); if (resp.StatusCode == HttpStatusCode.NoContent) { // Check whether the individual property is updated to new value if (WebHelper.GetContent(individualProUrl, context.RequestHeaders, out resp)) { detail4 = new ExtensionRuleResultDetail(this.Name, individualProUrl, HttpMethod.Get, string.Empty, resp); resp.ResponsePayload.TryToJObject(out jo); if (jo != null && jo[Constants.Value] != null && jo[Constants.Value].Value <string>().Equals(newValue)) { passed = true; } else if (jo == null) { passed = false; detail4.ErrorMessage = "Can not get individual property after PUT to it."; } else if (jo != null && jo[Constants.Value] == null) { passed = false; detail4.ErrorMessage = "Can not get the value of individual property."; } else if (jo != null && jo[Constants.Value] != null && !jo[Constants.Value].Value <string>().Equals(newValue)) { passed = false; detail4.ErrorMessage = "The value of individual property is not updated."; } } } else { passed = false; detail3.ErrorMessage = "Update individual property from the created entity failed."; } } else { passed = false; detail2.ErrorMessage = "Get individual property from the created entity failed."; } // Delete the entity var resps = WebHelper.DeleteEntities(context.RequestHeaders, additionalInfos); } else { passed = false; detail1.ErrorMessage = "Created the new entity failed for above URI."; } var details = new List <ExtensionRuleResultDetail>() { detail1, detail2, detail3, detail4 }.RemoveNullableDetails(); info = new ExtensionRuleViolationInfo(this.ErrorMessage, new Uri(serviceStatus.RootURL), serviceStatus.ServiceDocument, details); return(passed); }
protected void btnSave_Click(object sender, EventArgs e) { //if (string.IsNullOrEmpty(txtContainer.Text)) //{ // div_bottom.Html = "<p class=\"error\">Status : Save failed, Container can't for empty .</p>"; // txtContainer.Focus(); // return; //} DataFactory dal = new DataFactory(); DataTable dt = dal.FactoryDAL(PageHelper.ConnectionStrings, "FW_OceanImport_Container_SP", new List <IFields>() { dal.CreateIFields().Append("Option", "Update") .Append("oc_CtnrNo", txtContainer.Text.ToUpper().Trim()) .Append("oc_CtnrSize", CmbSize.Value) .Append("oc_SealNo", txtSeal.Text.Trim().ToUpper()) .Append("oc_Servicemode", CmbSerMode.Value) .Append("oc_SONo", txtSO.Text.Trim().ToUpper()) .Append("oc_GWT", string.IsNullOrEmpty(txtGWT.Text)?DBNull.Value:(object)txtGWT.Text) .Append("oc_CBM", string.IsNullOrEmpty(txtCBM.Text)?DBNull.Value:(object)txtCBM.Text) .Append("oc_Piece", string.IsNullOrEmpty(txtPiece.Text)?DBNull.Value:(object)txtPiece.Text) .Append("oc_Unit", CmbUnit.Value) .Append("oc_OrderMarks", txtMarks1.Text.ToUpper().Replace("\r\n", "\n")) .Append("oc_OrderNoOfPackage", txtmarks3.Text.ToUpper().Replace("\r\n", "\n")) .Append("oc_OrderDescription", txtMarks2.Text.ToUpper().Replace("\r\n", "\n")) .Append("oc_Remark", txtRemark.Text.ToUpper().Replace("\r\n", "\n")) .Append("oc_STAT", FSecurityHelper.CurrentUserDataGET()[12]) .Append("oc_SYS", SYS) .Append("oc_User", FSecurityHelper.CurrentUserDataGET()[0]) .Append("oc_ToHBL", hidHBL.Text) .Append("oc_ROWID", hidID.Text) }).GetTable(); if (dt != null) { string rowID = dt.Rows[0][0].ToString(); string flag = dt.Rows[0][1].ToString(); ControlBinder.pageTitleMsg(true, "OI-C:" + txtContainer.Text, "<p class=\"success\">Status : Record Saved with <span>" + txtContainer.Text + " </span> </p>", div_bottom); if (b) { b = false; X.Redirect("Container.aspx?HBL=" + Request["HBL"]); return; } if (flag.Trim() == "Insert") { //X.Msg.Alert("status", " Saved successfully").Show(); X.Redirect("Container.aspx?ID=" + rowID + "&HBL=" + Request["HBL"]); } lblPiece.Text = txtPiece.Text; lblUnit.Text = CmbUnit.Value; } else { ControlBinder.pageTitleMsg(false, "OI-C:" + txtContainer.Text, "<p class=\"error\">Status : Save failed, please check the data . </p>", div_bottom); } }
/// <summary> /// 权限授权提交事件 /// </summary> /// <param name="ModuleId">访问权限值</param> /// <param name="ModuleButtonId">操作权限值</param> /// <param name="ViewDetailId">视图权限值</param> /// <param name="ObjectId">对象ID</param> /// <param name="Category">分类</param> /// <returns></returns> public ActionResult AuthorizedSubmit(string ModuleId, string ModuleButtonId, string ViewDetailId, string ObjectId, string Category) { IDatabase database = DataFactory.Database(); DbTransaction isOpenTrans = database.BeginTrans(); try { List <DbParameter> parameter = new List <DbParameter> { DbFactory.CreateDbParameter("@ObjectId", ObjectId), DbFactory.CreateDbParameter("@Category", Category) }; #region 访问 string[] arrayModuleId = ModuleId.Split(','); StringBuilder sbDelete_Module = new StringBuilder("delete from BaseModulePermission where ObjectId = @ObjectId AND Category=@Category"); database.ExecuteBySql(sbDelete_Module, parameter.ToArray(), isOpenTrans); int index = 1; foreach (var item in arrayModuleId) { if (item.Length > 0) { BaseModulePermission entity = new BaseModulePermission(); entity.ModulePermissionId = CommonHelper.GetGuid; entity.ObjectId = ObjectId; entity.Category = Category; entity.ModuleId = item; entity.SortCode = index; entity.Create(); database.Insert(entity, isOpenTrans); index++; } } #endregion #region 操作 string[] arrayModuleButtonId = ModuleButtonId.Split(','); StringBuilder sbDelete_Button = new StringBuilder("delete from BaseButtonPermission where ObjectId = @ObjectId AND Category=@Category"); database.ExecuteBySql(sbDelete_Button, parameter.ToArray(), isOpenTrans); index = 1; foreach (var item in arrayModuleButtonId) { if (item.Length > 0) { string[] stritem = item.Split('|'); BaseButtonPermission entity = new BaseButtonPermission(); entity.ButtonPermissionId = CommonHelper.GetGuid; entity.ObjectId = ObjectId; entity.Category = Category; entity.ModuleButtonId = stritem[0]; entity.ModuleId = stritem[0]; entity.SortCode = index; entity.Create(); database.Insert(entity, isOpenTrans); index++; } } #endregion #region 视图 string[] arrayViewDetailId = ViewDetailId.Split(','); StringBuilder sbDelete_View = new StringBuilder("delete from BaseViewPermission where ObjectId = @ObjectId AND Category=@Category"); database.ExecuteBySql(sbDelete_View, parameter.ToArray(), isOpenTrans); index = 1; foreach (var item in arrayViewDetailId) { if (item.Length > 0) { string[] stritem = item.Split('|'); BaseViewPermission entity = new BaseViewPermission(); entity.ViewPermissionId = CommonHelper.GetGuid; entity.ObjectId = ObjectId; entity.Category = Category; entity.ViewId = stritem[0]; entity.ModuleId = stritem[1]; entity.SortCode = index; entity.Create(); database.Insert(entity, isOpenTrans); index++; } } #endregion database.Commit(); return(Content(new JsonMessage { Success = true, Code = "1", Message = "操作成功。" }.ToString())); } catch (Exception ex) { database.Rollback(); return(Content(new JsonMessage { Success = false, Code = "-1", Message = "操作失败,错误:" + ex.Message }.ToString())); } }
public SmsManager() : this(DataFactory.Get <IOutboundSmsRepository>()) { }
private static void setEntityId(IDbCommand cmd, EntityPropertyInfo info, Object paramVal) { int id = ((IEntity)paramVal).Id; DataFactory.SetParameter(cmd, info.ColumnName, id); }
public Hashtable GetVehicleInfoByLicenseNumber(string licenseNumber) { return(DataFactory.SqlDataBase().GetHashtableById("YR_Vehicles", "LicenseNumber", licenseNumber)); }
/// <summary> /// 更改提现状态 /// </summary> /// <returns></returns> public ActionResult PayToBank(string KeyValue, int Status, string StatusStr) { IDatabase database = DataFactory.Database(); DbTransaction isOpenTrans = database.BeginTrans(); try { Am_UserGetMoneyToBank entity = repositoryfactory.Repository().FindEntity(KeyValue); if (entity == null || string.IsNullOrEmpty(entity.Number)) { return(Content(new JsonMessage { Success = false, Code = "-1", Message = "数据异常" }.ToString())); } if (entity.Status != 0) { return(Content(new JsonMessage { Success = false, Code = "-1", Message = "提现状态不正常" }.ToString())); } entity.Modify(KeyValue); entity.Status = Status; entity.StatusStr = StatusStr; entity.PayTime = DateTime.Now; int IsOk = database.Update(entity, isOpenTrans); //更新提现状态 Base_SysLogBll.Instance.WriteLog(KeyValue, OperationType.Update, IsOk > 0 ? "成功" : "失败", "提现操作"); //更新用户信息表的押金金额 var usermodel = database.FindEntity <Ho_PartnerUser>(entity.U_Number); if (usermodel == null || string.IsNullOrEmpty(usermodel.Number)) { database.Rollback(); return(Content(new JsonMessage { Success = false, Code = "-1", Message = "数据异常" }.ToString())); } if (Status == 9) //退还 { usermodel.Money += entity.Money; usermodel.Modify(usermodel.Number); database.Update(usermodel, isOpenTrans); //更新用户信息表 //添加押金返还记录1 var recordModel = new Am_MoneyDetail() { CreateTime = DateTime.Now, CurrMoney = usermodel.Money, CreateUserId = ManageProvider.Provider.Current().UserId, CreateUserName = ManageProvider.Provider.Current().UserName, OperateType = 6, OperateTypeStr = "提现取消", Money = entity.Money, UserName = entity.UserName, U_Name = entity.U_Name, U_Number = entity.U_Number }; recordModel.Create(); database.Insert(recordModel, isOpenTrans); //添加返还记录1 } else //提现成功 { if (usermodel.FreezeMoney > 0) //首先要有押金 { var money = entity.BankCharge; //如果返还的金额大于 if (entity.BankCharge > usermodel.FreezeMoney) { money = usermodel.FreezeMoney; } usermodel.FreezeMoney -= money; //扣除手续费1:1返还 usermodel.Money += money; usermodel.Modify(usermodel.Number); database.Update(usermodel, isOpenTrans); //更新用户信息表 //添加押金返还记录 var recordModel = new Am_AmDepositDetail() { CreateTime = DateTime.Now, CurrMoney = usermodel.FreezeMoney, Mark = "押金1:1返还", Money = money, UserName = entity.UserName, U_Name = entity.U_Name, U_Number = entity.U_Number }; recordModel.Create(); database.Insert(recordModel, isOpenTrans); //添加返还记录 } } database.Commit(); return(Content(new JsonMessage { Success = true, Code = "1", Message = "操作成功" }.ToString())); } catch (Exception ex) { database.Rollback(); return(Content(new JsonMessage { Success = false, Code = "-1", Message = "操作失败:" + ex.Message }.ToString())); } }
private void LoadDbConfig() { _dbConfig = XDocFactory.LoadFrom(_dbConfigFile, MimeType.XML); _factory = new MindTouch.Data.DataFactory(MySql.Data.MySqlClient.MySqlClientFactory.Instance, "?"); _catalog = new DataCatalog(_factory, _dbConfig); }
/// <summary> /// Verifies the extension rule. /// </summary> /// <param name="context">The Interop service context</param> /// <param name="info">out parameter to return violation information when rule does not pass</param> /// <returns>true if rule passes; false otherwise</returns> public override bool?Verify(ServiceContext context, out ExtensionRuleViolationInfo info) { if (context == null) { throw new ArgumentNullException("context"); } bool?passed = null; info = null; ServiceStatus serviceStatus = ServiceStatus.GetInstance(); DataFactory dFactory = DataFactory.Instance(); var detail = new ExtensionRuleResultDetail(this.Name, serviceStatus.RootURL, HttpMethod.Post, string.Empty); string updateUrl = serviceStatus.RootURL; List <string> keyPropertyTypes = new List <string>() { "Edm.Int32", "Edm.Int16", "Edm.Int64", "Edm.Guid", "Edm.String" }; List <string> norPropertyTypes = new List <string>() { "Edm.String" }; List <EntityTypeElement> entityTypeElements = MetadataHelper.GetEntityTypes(serviceStatus.MetadataDocument, 1, keyPropertyTypes, null, NavigationRoughType.None).ToList(); if (null == entityTypeElements || 0 == entityTypeElements.Count) { detail.ErrorMessage = "To verify this rule it expects an entity type with Int32/Int64/Int16/Guid/String key property and a string type normal property, but there is no this entity type in metadata so can not verify this rule."; info = new ExtensionRuleViolationInfo(new Uri(serviceStatus.RootURL), serviceStatus.ServiceDocument, detail); return(passed); } EntityTypeElement entityType = null; Dictionary <string, Dictionary <KeyValuePair <string, string>, List <string> > > entityTypeInfo = new Dictionary <string, Dictionary <KeyValuePair <string, string>, List <string> > >(); bool foundEntity = MetadataHelper.GetEntityTypesWithComplexProperty(serviceStatus.MetadataDocument, "Edm.String", out entityTypeInfo); if (foundEntity) { foreach (var en in entityTypeElements) { if (entityTypeInfo.Keys.Contains(en.EntityTypeShortName) && !string.IsNullOrEmpty(en.EntitySetName)) { entityType = en; break; } } } else { detail.ErrorMessage = "To verify this rule it expects an entity type with complex type normal property, but there is no this entity type in metadata so can not verify this rule."; info = new ExtensionRuleViolationInfo(new Uri(serviceStatus.RootURL), serviceStatus.ServiceDocument, detail); return(passed); } if (entityType == null) { detail.ErrorMessage = "To verify this rule it expects an entity type with complex type normal property, but there is no this entity type in metadata so can not verify this rule."; info = new ExtensionRuleViolationInfo(new Uri(serviceStatus.RootURL), serviceStatus.ServiceDocument, detail); return(passed); } Dictionary <KeyValuePair <string, string>, List <string> > complexProps = entityTypeInfo[entityType.EntityTypeShortName]; KeyValuePair <KeyValuePair <string, string>, List <string> > complexPop = complexProps.First(); string complexPropName = complexPop.Key.Key; string entitySetUrl = entityType.EntitySetName.MapEntitySetNameToEntitySetURL(); updateUrl = entitySetUrl; string url = serviceStatus.RootURL.TrimEnd('/') + @"/" + entitySetUrl; updateUrl = url; var additionalInfos = new List <AdditionalInfo>(); JObject reqData = dFactory.ConstructInsertedEntityData(entityType.EntitySetName, entityType.EntityTypeShortName, null, out additionalInfos); if (!dFactory.CheckOrAddTheMissingPropertyData(entityType.EntitySetName, complexPropName, ref reqData)) { detail.ErrorMessage = "The property to update does not exist, and cannot be updated."; info = new ExtensionRuleViolationInfo(new Uri(serviceStatus.RootURL), serviceStatus.ServiceDocument, detail); return(passed); } string reqDataStr = reqData.ToString(); bool isMediaType = !string.IsNullOrEmpty(additionalInfos.Last().ODataMediaEtag); var resp = WebHelper.CreateEntity(url, context.RequestHeaders, reqData, isMediaType, ref additionalInfos); detail = new ExtensionRuleResultDetail(this.Name, url, HttpMethod.Post, string.Empty, resp, string.Empty, reqDataStr); if (HttpStatusCode.Created == resp.StatusCode) { string entityId = additionalInfos.Last().EntityId; updateUrl = entityId.TrimEnd('/') + "/" + complexPropName; bool hasEtag = additionalInfos.Last().HasEtag; resp = WebHelper.GetPropertyValue(updateUrl); detail = new ExtensionRuleResultDetail(this.Name, entityId, HttpMethod.Get, string.Empty, resp); if (HttpStatusCode.OK == resp.StatusCode || HttpStatusCode.NoContent == resp.StatusCode) { JProperty complexPropContent = null; foreach (JProperty prop in reqData.Children <JProperty>()) { if (prop.Name.Equals(complexPropName)) { complexPropContent = prop; break; } } resp = WebHelper.UpdateComplexProperty(updateUrl, context.RequestHeaders, complexPropContent, hasEtag, complexPop.Value); detail = new ExtensionRuleResultDetail(this.Name, updateUrl, HttpMethod.Patch, string.Empty, resp, string.Empty, reqDataStr); if (HttpStatusCode.NoContent == resp.StatusCode) { resp = WebHelper.GetPropertyValue(updateUrl); detail = new ExtensionRuleResultDetail(this.Name, updateUrl, HttpMethod.Get, string.Empty, resp, string.Empty, reqDataStr); if (HttpStatusCode.OK == resp.StatusCode) { JObject value; resp.ResponsePayload.TryToJObject(out value); bool updated = true; if (value != null && value.Type == JTokenType.Object) { foreach (var prop in value.Children <JProperty>()) { if (complexPop.Value.Contains(prop.Name)) { updated = prop.Value.ToString().Equals(Constants.UpdateData); } if (!updated) { passed = false; detail.ErrorMessage = string.Format("The compelex property in request fails in HTTP patch updating."); break; } } if (updated) { passed = true; } } } else { passed = false; detail.ErrorMessage = "Can not get the updated entity."; } } else { passed = false; detail.ErrorMessage = "HTTP Patch the complex property failed."; } } else { detail.ErrorMessage = "Can not get the created entity from above URI."; } // Restore the service. var resps = WebHelper.DeleteEntities(context.RequestHeaders, additionalInfos); } else { detail.ErrorMessage = "Created the new entity failed for above URI."; } var details = new List <ExtensionRuleResultDetail>() { detail }; info = new ExtensionRuleViolationInfo(new Uri(updateUrl), serviceStatus.ServiceDocument, details); return(passed); }
public void GetChildren_WithOneParameter_ShouldCallGetChildrenWithOneParameterOfTheWrappedDataFactory() { using(ShimsContext.Create()) { bool getChildrenIsCalled = false; PageReference pageLinkValue = null; PageDataCollection pageDataCollection = new PageDataCollection(); ShimDataFactory.StaticConstructor = () => { }; DataFactory dataFactory = new DataFactory(); new ShimDataFactory(dataFactory).GetChildrenPageReference = delegate(PageReference pageLink) { getChildrenIsCalled = true; pageLinkValue = pageLink; return pageDataCollection; }; PageReference pageLinkParameter = new PageReference(); Assert.IsFalse(getChildrenIsCalled); Assert.AreEqual(pageDataCollection, new DataFactoryWrapper(dataFactory, Mock.Of<IPageDataCaster>(), Mock.Of<IPermanentLinkMapper>()).GetChildren(pageLinkParameter)); Assert.IsTrue(getChildrenIsCalled); Assert.AreEqual(pageLinkParameter, pageLinkValue); } }
public bool AddOrEditInfo(Hashtable ht, string _key) { return(DataFactory.SqlDataBase().Submit_AddOrEdit("YR_ServiceArea", "ID", _key, ht)); }
public void AddSecurity(DataFactory dataFactoryObject) { _securities.Add(dataFactoryObject.SecurityName, dataFactoryObject); }
public int DeleteByID(Hashtable ht, string _key) { return(DataFactory.SqlDataBase().UpdateByHashtable("YR_ServiceArea", "ID", _key, ht)); }
private static ISnmpMessage ParseMessage(int first, Stream stream, UserRegistry registry) { var array = DataFactory.CreateSnmpData(first, stream); if (array == null) { return(null); } if (array.TypeCode != SnmpType.Sequence) { throw new SnmpException("not an SNMP message"); } var body = (Sequence)array; if (body.Length != 3 && body.Length != 4) { throw new SnmpException("not an SNMP message"); } var version = (VersionCode)((Integer32)body[0]).ToInt32(); Header header; SecurityParameters parameters; IPrivacyProvider privacy; Scope scope; if (body.Length == 3) { header = Header.Empty; parameters = SecurityParameters.Create((OctetString)body[1]); privacy = DefaultPrivacyProvider.DefaultPair; scope = new Scope((ISnmpPdu)body[2]); } else { header = new Header(body[1]); parameters = new SecurityParameters((OctetString)body[2]); privacy = registry.Find(parameters.UserName); if (privacy == null) { // handle decryption exception. return(new MalformedMessage(header.MessageId, parameters.UserName)); } var code = body[3].TypeCode; if (code == SnmpType.Sequence) { // v3 not encrypted scope = new Scope((Sequence)body[3]); } else if (code == SnmpType.OctetString) { // v3 encrypted try { scope = new Scope((Sequence)privacy.Decrypt(body[3], parameters)); } catch (DecryptionException) { // handle decryption exception. return(new MalformedMessage(header.MessageId, parameters.UserName)); } } else { throw new SnmpException(string.Format(CultureInfo.InvariantCulture, "invalid v3 packets scoped data: {0}", code)); } if (!privacy.AuthenticationProvider.VerifyHash(stream, parameters.AuthenticationParameters, parameters.EngineId)) { throw new SnmpException("invalid v3 packet data hash detected"); } } var scopeCode = scope.Pdu.TypeCode; switch (scopeCode) { case SnmpType.TrapV1Pdu: return(new TrapV1Message(body)); case SnmpType.TrapV2Pdu: return(new TrapV2Message(version, header, parameters, scope, privacy)); case SnmpType.GetRequestPdu: return(new GetRequestMessage(version, header, parameters, scope, privacy)); case SnmpType.ResponsePdu: return(new ResponseMessage(version, header, parameters, scope, privacy, false)); case SnmpType.SetRequestPdu: return(new SetRequestMessage(version, header, parameters, scope, privacy)); case SnmpType.GetNextRequestPdu: return(new GetNextRequestMessage(version, header, parameters, scope, privacy)); case SnmpType.GetBulkRequestPdu: return(new GetBulkRequestMessage(version, header, parameters, scope, privacy)); case SnmpType.ReportPdu: return(new ReportMessage(version, header, parameters, scope, privacy)); case SnmpType.InformRequestPdu: return(new InformRequestMessage(version, header, parameters, scope, privacy)); default: throw new SnmpException(string.Format(CultureInfo.InvariantCulture, "unsupported pdu: {0}", scopeCode)); } }
public Hashtable GetInfoByID(string areaID) { return(DataFactory.SqlDataBase().GetHashtableById("YR_ServiceArea", "ID", areaID)); }
/// <summary> /// 批量新增所属,部门,角色,工作组,用户权限 /// </summary> /// <param name="item_value">对象主键</param> /// <param name="user_id">用户主键</param> /// <returns></returns> public bool add_ItemForm(string[] item_value, string user_id) { try { int index = 0; string key; string type; StringBuilder[] sqls = new StringBuilder[item_value.Length + 4]; object[] objs = new object[item_value.Length + 4]; StringBuilder sbDelete_org = new StringBuilder(); sbDelete_org.Append("Delete From Base_StaffOrganize Where User_ID =@User_ID"); SqlParam[] parm_org = new SqlParam[] { new SqlParam("@User_ID", user_id) }; sqls[0] = sbDelete_org; objs[0] = parm_org; StringBuilder sbDelete_Role = new StringBuilder(); sbDelete_Role.Append("Delete From Base_UserRole Where User_ID =@User_ID"); SqlParam[] parm_Role = new SqlParam[] { new SqlParam("@User_ID", user_id) }; sqls[1] = sbDelete_Role; objs[1] = parm_Role; StringBuilder sbDelete_UserGroup = new StringBuilder(); sbDelete_UserGroup.Append("Delete From Base_UserInfoUserGroup Where User_ID =@User_ID"); SqlParam[] parm_UserGroup = new SqlParam[] { new SqlParam("@User_ID", user_id) }; sqls[2] = sbDelete_UserGroup; objs[2] = parm_UserGroup; StringBuilder sbDelete_Right = new StringBuilder(); sbDelete_Right.Append("Delete From Base_UserRight Where User_ID =@User_ID"); SqlParam[] parm_Right = new SqlParam[] { new SqlParam("@User_ID", user_id) }; sqls[3] = sbDelete_Right; objs[3] = parm_Right; index = 4; foreach (var item in item_value) { if (item.Length > 0) { string[] str_item = item.Split('|'); key = str_item[0]; type = str_item[1]; if (type == "所属部门") { StringBuilder sbadd = new StringBuilder(); sbadd.Append("Insert into Base_StaffOrganize("); sbadd.Append("StaffOrganize_Id,Organization_ID,User_ID,CreateUserId,CreateUserName"); sbadd.Append(")Values("); sbadd.Append("@StaffOrganize_Id,@Organization_ID,@User_ID,@CreateUserId,@CreateUserName)"); SqlParam[] parmAdd = new SqlParam[] { new SqlParam("@StaffOrganize_Id", CommonHelper.GetGuid), new SqlParam("@Organization_ID", key), new SqlParam("@User_ID", user_id), new SqlParam("@CreateUserId", RequestSession.GetSessionUser().UserId), new SqlParam("@CreateUserName", RequestSession.GetSessionUser().UserName) }; sqls[index] = sbadd; objs[index] = parmAdd; } else if (type == "所属角色") { StringBuilder sbadd = new StringBuilder(); sbadd.Append("Insert into Base_UserRole("); sbadd.Append("UserRole_ID,User_ID,Roles_ID,CreateUserId,CreateUserName"); sbadd.Append(")Values("); sbadd.Append("@UserRole_ID,@User_ID,@Roles_ID,@CreateUserId,@CreateUserName)"); SqlParam[] parmAdd = new SqlParam[] { new SqlParam("@UserRole_ID", CommonHelper.GetGuid), new SqlParam("@User_ID", user_id), new SqlParam("@Roles_ID", key), new SqlParam("@CreateUserId", RequestSession.GetSessionUser().UserId), new SqlParam("@CreateUserName", RequestSession.GetSessionUser().UserName) }; sqls[index] = sbadd; objs[index] = parmAdd; } else if (type == "用户工作组") { StringBuilder sbadd = new StringBuilder(); sbadd.Append("Insert into Base_UserInfoUserGroup("); sbadd.Append("UserInfoUserGroup_ID,User_ID,UserGroup_ID,CreateUserId,CreateUserName"); sbadd.Append(")Values("); sbadd.Append("@UserInfoUserGroup_ID,@User_ID,@UserGroup_ID,@CreateUserId,@CreateUserName)"); SqlParam[] parmAdd = new SqlParam[] { new SqlParam("@UserInfoUserGroup_ID", CommonHelper.GetGuid), new SqlParam("@User_ID", user_id), new SqlParam("@UserGroup_ID", key), new SqlParam("@CreateUserId", RequestSession.GetSessionUser().UserId), new SqlParam("@CreateUserName", RequestSession.GetSessionUser().UserName) }; sqls[index] = sbadd; objs[index] = parmAdd; } else if (type == "用户权限") { StringBuilder sbadd = new StringBuilder(); sbadd.Append("Insert into Base_UserRight("); sbadd.Append("UserRight_ID,User_ID,Menu_Id,CreateUserId,CreateUserName"); sbadd.Append(")Values("); sbadd.Append("@UserRight_ID,@User_ID,@Menu_Id,@CreateUserId,@CreateUserName)"); SqlParam[] parmAdd = new SqlParam[] { new SqlParam("@UserRight_ID", CommonHelper.GetGuid), new SqlParam("@User_ID", user_id), new SqlParam("@Menu_Id", key), new SqlParam("@CreateUserId", RequestSession.GetSessionUser().UserId), new SqlParam("@CreateUserName", RequestSession.GetSessionUser().UserName) }; sqls[index] = sbadd; objs[index] = parmAdd; } index++; } } return(DataFactory.SqlDataBase().BatchExecuteBySql(sqls, objs) >= 0 ? true : false); } catch { return(false); } }
public ConfigSettingsController(IConfiguration config) { _config = config; _listSettings = DataFactory.GetSettingList(); }
public void ProcessRequest(HttpContext context) { string Action = context.Request["action"]; //提交动作 switch (Action) { case "login": PwdLogin(context); break; case "code_login": CodeLogin(context); break; case "retrieve_pwd": Retrieve_Pwd(context); break; case "sms_code": SmsCode(context); break; case "jizhumima": string str = "0"; HttpCookie cookie = context.Request.Cookies["USER_COOKIE"]; if (cookie != null) { str = cookie["UserName"] + "&" + cookie["PassWord"] + "&" + cookie["DLAdminHotelid"]; } context.Response.Write(str); break; case "Menu": RM_System_IDAO sys_idao = new RM_System_Dal(); string UserId = RequestSession.GetSessionUser().UserId.ToString();//用户ID string strMenus = JsonHelper.DataTableToJson(sys_idao.GetMenuHtml(UserId), "MENU"); context.Response.Write(strMenus); break; case "CheckSqlIsOpen": try { //数据库连接状态 if (DataFactory.CheckSqlIsOpen(RequestSession.GetSessionUser().AdminHotelid.ToString(), Convert.ToInt32(RequestSession.GetSessionUser().Hotelid))) { StringBuilder sql = new StringBuilder(); sql.AppendFormat("SELECT id,ErrorNum FROM dbo.Set_Association WHERE hotelid={0} ", RequestSession.GetSessionUser().Hotelid); DataTable dt = DataFactory.SqlDataBase().GetDataTableBySQL(sql); if (dt != null && dt.Rows.Count > 0) { if (Convert.ToInt32(dt.Rows[0]["ErrorNum"]) > 0) { Hashtable ht = new Hashtable(); ht["ErrorNum"] = 0; DataFactory.SqlDataBase().UpdateByHashtable("Set_Association", "id", dt.Rows[0]["id"].ToString(), ht); } } context.Response.Write("1"); } else { context.Response.Write("0"); } } catch { } break; default: break; } }
public bool Delete <T>(T entity) where T : class, new() { var tt = DataFactory.DeleteEntity <T>(entity, null, null); return(true); }
/// <summary> /// 通过主键ID删除车辆信息(逻辑删除) /// </summary> /// <param name="ht"></param> /// <param name="_key"></param> /// <returns></returns> public int DelVehicleInfoByID(Hashtable ht, string _key) { return(DataFactory.SqlDataBase().UpdateByHashtable("YR_Vehicles", "ID", _key, ht)); }
/// <summary> /// Verifies the extension rule. /// </summary> /// <param name="context">The Interop service context</param> /// <param name="info">out parameter to return violation information when rule does not pass</param> /// <returns>true if rule passes; false otherwise</returns> public override bool?Verify(ServiceContext context, out ExtensionRuleViolationInfo info) { if (context == null) { throw new ArgumentNullException("context"); } bool?passed = null; info = null; ServiceStatus serviceStatus = ServiceStatus.GetInstance(); TermDocuments termDocs = TermDocuments.GetInstance(); DataFactory dFactory = DataFactory.Instance(); var detail1 = new ExtensionRuleResultDetail(this.Name); var detail2 = new ExtensionRuleResultDetail(this.Name); var detail3 = new ExtensionRuleResultDetail(this.Name); var detail4 = new ExtensionRuleResultDetail(this.Name); List <string> keyPropertyTypes = new List <string>() { "Edm.Int32", "Edm.Int16", "Edm.Int64", "Edm.Guid", "Edm.String" }; List <EntityTypeElement> entityTypeElements = MetadataHelper.GetEntityTypes(serviceStatus.MetadataDocument, 1, keyPropertyTypes, null, NavigationRoughType.None).ToList(); if (null == entityTypeElements || 0 == entityTypeElements.Count()) { detail1.ErrorMessage = "To verify this rule it expects an entity type with Int32/Int64/Int16/Guid/String key property, but there is no this entity type in metadata so can not verify this rule."; info = new ExtensionRuleViolationInfo(new Uri(serviceStatus.RootURL), serviceStatus.ServiceDocument, detail1); return(passed); } EntityTypeElement entityType = null; foreach (var en in entityTypeElements) { var matchEntity = en.EntitySetName.GetRestrictions(serviceStatus.MetadataDocument, termDocs.VocCapabilitiesDoc, new List <Func <string, string, string, List <NormalProperty>, List <NavigProperty>, bool> >() { AnnotationsHelper.GetDeleteRestrictions, AnnotationsHelper.GetInsertRestrictions, AnnotationsHelper.GetUpdateRestrictions }); if (!string.IsNullOrEmpty(matchEntity.Item1) && matchEntity.Item2 != null && matchEntity.Item2.Any() && matchEntity.Item3 != null && matchEntity.Item3.Any()) { entityType = en; break; } } string entitySetUrl = entityType.EntitySetName.MapEntitySetNameToEntitySetURL(); if (string.IsNullOrEmpty(entitySetUrl)) { detail1.ErrorMessage = string.Format("Cannot find the entity-set URL which is matched with {0}", entityType.EntityTypeShortName); info = new ExtensionRuleViolationInfo(new Uri(serviceStatus.RootURL), serviceStatus.ServiceDocument, detail1); return(passed); } // Create a entity string url = serviceStatus.RootURL.TrimEnd('/') + @"/" + entitySetUrl; var additionalInfos = new List <AdditionalInfo>(); var reqData = dFactory.ConstructInsertedEntityData(entityType.EntitySetName, entityType.EntityTypeShortName, null, out additionalInfos); string reqDataStr = reqData.ToString(); bool isMediaType = !string.IsNullOrEmpty(additionalInfos.Last().ODataMediaEtag); var resp = WebHelper.CreateEntity(url, context.RequestHeaders, reqData, isMediaType, ref additionalInfos); detail1 = new ExtensionRuleResultDetail(this.Name, url, HttpMethod.Post, string.Empty, resp, string.Empty, reqDataStr); if (HttpStatusCode.Created == resp.StatusCode) { var entityId = additionalInfos.Last().EntityId; var hasEtag = additionalInfos.Last().HasEtag; resp = WebHelper.DeleteEntity(entityId, context.RequestHeaders, hasEtag); detail2 = new ExtensionRuleResultDetail(this.Name, entityId, HttpMethod.Delete, string.Empty, resp); if (HttpStatusCode.NoContent == resp.StatusCode) { var header = new KeyValuePair <string, string>("If-None-Match", "*"); var headers = new List <KeyValuePair <string, string> >() { header }; resp = WebHelper.UpsertEntity(entityId, reqDataStr, HttpMethod.Put, hasEtag ? headers : null); detail3 = new ExtensionRuleResultDetail(this.Name, url, HttpMethod.Put, string.Empty, resp, string.Empty, reqDataStr); if (HttpStatusCode.Created == resp.StatusCode) { resp = WebHelper.GetEntity(entityId); detail4 = new ExtensionRuleResultDetail(this.Name, entityId, HttpMethod.Get, string.Empty, resp); if (HttpStatusCode.OK == resp.StatusCode) { passed = true; } else { passed = false; detail4.ErrorMessage = "Can not the Upserted entity from above URI."; } // Restore the service. var resps = WebHelper.DeleteEntities(context.RequestHeaders, additionalInfos); } else { passed = false; detail3.ErrorMessage = "Upsert the entity failed."; } } else { passed = false; detail2.ErrorMessage = "Delete the entity failed."; } } else { passed = false; detail1.ErrorMessage = "Created the new entity failed for above URI."; } var details = new List <ExtensionRuleResultDetail>() { detail1, detail2, detail3, detail4 }.RemoveNullableDetails(); info = new ExtensionRuleViolationInfo(new Uri(serviceStatus.RootURL), serviceStatus.ServiceDocument, details); return(passed); }
/// <summary> /// 通过车辆ID获取车辆信息 /// </summary> /// <param name="vehicleID">车辆ID</param> /// <returns></returns> public Hashtable GetVehicleInfoByID(string vehicleID) { return(DataFactory.SqlDataBase().GetHashtableById("YR_Vehicles", "ID", vehicleID)); }
/// <summary> /// Verifies the extension rule. /// </summary> /// <param name="context">The Interop service context</param> /// <param name="info">out parameter to return violation information when rule does not pass</param> /// <returns>true if rule passes; false otherwise</returns> public override bool?Verify(ServiceContext context, out ExtensionRuleViolationInfo info) { if (context == null) { throw new ArgumentNullException("context"); } bool?passed = null; info = null; ServiceStatus serviceStatus = ServiceStatus.GetInstance(); TermDocuments termDocs = TermDocuments.GetInstance(); DataFactory dFactory = DataFactory.Instance(); var detail1 = new ExtensionRuleResultDetail(this.Name); var detail2 = new ExtensionRuleResultDetail(this.Name); var detail3 = new ExtensionRuleResultDetail(this.Name); var detail4 = new ExtensionRuleResultDetail(this.Name); List <string> keyPropertyTypes = new List <string>() { "Edm.Int32", "Edm.Int16", "Edm.Int64", "Edm.Guid", "Edm.String" }; List <string> norPropertyTypes = new List <string>() { "Edm.String" }; List <EntityTypeElement> entityTypeElements = MetadataHelper.GetEntityTypes(serviceStatus.MetadataDocument, 1, keyPropertyTypes, norPropertyTypes, NavigationRoughType.CollectionValued).ToList(); if (null == entityTypeElements || 0 == entityTypeElements.Count()) { detail1.ErrorMessage = "It expects an entity type with Int32 key property and containing a string property to Patch/Post, but there is no this entity type in metadata so can not verify this rule."; info = new ExtensionRuleViolationInfo(new Uri(serviceStatus.RootURL), serviceStatus.ServiceDocument, detail1); return(passed); } foreach (var et in entityTypeElements) { string navigPropName = null; string navigPropRelatedEntitySetUrl = null; string navigPropRelatedEntityTypeKeyName = null; var matchEntity = et.EntitySetName.GetRestrictions(serviceStatus.MetadataDocument, termDocs.VocCapabilitiesDoc, new List <Func <string, string, string, List <NormalProperty>, List <NavigProperty>, bool> >() { AnnotationsHelper.GetDeleteRestrictions, AnnotationsHelper.GetInsertRestrictions, AnnotationsHelper.GetUpdateRestrictions }); if (string.IsNullOrEmpty(matchEntity.Item1) || matchEntity.Item2 == null || !matchEntity.Item2.Any() || matchEntity.Item3 == null || !matchEntity.Item3.Any()) { continue; } foreach (var np in matchEntity.Item3) { navigPropName = np.NavigationPropertyName; string navigEntityTypeShortName = np.NavigationPropertyType.RemoveCollectionFlag().GetLastSegment(); List <NormalProperty> navigKeyProps = MetadataHelper.GetKeyProperties(serviceStatus.MetadataDocument, navigEntityTypeShortName).ToList(); if (navigKeyProps.Count == 1 && keyPropertyTypes.Contains(navigKeyProps[0].PropertyType)) { navigPropRelatedEntitySetUrl = navigEntityTypeShortName.MapEntityTypeShortNameToEntitySetURL(); navigPropRelatedEntityTypeKeyName = navigKeyProps[0].PropertyName; break; } } if (!string.IsNullOrEmpty(navigPropRelatedEntityTypeKeyName) && !string.IsNullOrEmpty(navigPropRelatedEntitySetUrl)) { string entitySetUrl = et.EntitySetName.MapEntitySetNameToEntitySetURL(); string url = serviceStatus.RootURL.TrimEnd('/') + @"/" + entitySetUrl; var additionalInfos = new List <AdditionalInfo>(); var reqData = dFactory.ConstructInsertedEntityData(et.EntitySetName, et.EntityTypeShortName, null, out additionalInfos); string reqDataStr = reqData.ToString(); bool isMediaType = !string.IsNullOrEmpty(additionalInfos.Last().ODataMediaEtag); var resp = WebHelper.CreateEntity(url, context.RequestHeaders, reqData, isMediaType, ref additionalInfos); detail1 = new ExtensionRuleResultDetail(this.Name, url, HttpMethod.Post, string.Empty, resp, string.Empty, reqDataStr); if (null != resp && HttpStatusCode.Created == resp.StatusCode) { string entityId = additionalInfos.Last().EntityId; bool hasEtag = additionalInfos.Last().HasEtag; JObject newEntity = JObject.Parse(resp.ResponsePayload); url = serviceStatus.RootURL.TrimEnd('/') + @"/" + navigPropRelatedEntitySetUrl; resp = WebHelper.Get(new Uri(url), Constants.V4AcceptHeaderJsonFullMetadata, RuleEngineSetting.Instance().DefaultMaximumPayloadSize, serviceStatus.DefaultHeaders); detail2 = new ExtensionRuleResultDetail(this.Name, url, HttpMethod.Get, StringHelper.MergeHeaders(Constants.V4AcceptHeaderJsonFullMetadata, serviceStatus.DefaultHeaders), resp); if (resp.StatusCode == HttpStatusCode.OK) { JObject feed; resp.ResponsePayload.TryToJObject(out feed); var entities = JsonParserHelper.GetEntries(feed); if (entities.Count > 0 && entities[0][Constants.V4OdataId] != null) { reqDataStr = @"{""" + Constants.V4OdataId + @""" : """ + entities[0][Constants.V4OdataId].ToString() + @"""}"; url = string.Format("{0}/{1}/$ref", entityId, navigPropName); // Verify to send a POST Http request and response with a 204 No Content status code. resp = WebHelper.CreateEntity(url, reqDataStr); detail3 = new ExtensionRuleResultDetail(this.Name, url, HttpMethod.Post, string.Empty, resp, string.Empty, reqDataStr); if (null != resp && resp.StatusCode == HttpStatusCode.NoContent) { if (resp.ResponseHeaders.Contains("OData-EntityId")) { // Verify to send a PATCH Http request and response with a 204 No Content status code. List <string> norPropertyNames = et.NormalProperties .Where(np => norPropertyTypes.Contains(np.PropertyType) && !np.IsKey) .Select(np => np.PropertyName).ToList(); if (!norPropertyNames.Any()) { detail3.ErrorMessage = "The entity-type does not contain any properties can be updated."; info = new ExtensionRuleViolationInfo(new Uri(url), resp.ResponsePayload, detail3); return(passed); } reqData = dFactory.ConstructUpdatedEntityData(newEntity, norPropertyNames); resp = WebHelper.UpdateEntity(entityId, context.RequestHeaders, reqDataStr, HttpMethod.Patch, hasEtag); detail4 = new ExtensionRuleResultDetail(this.Name, url, HttpMethod.Patch, string.Empty, resp, string.Empty, reqDataStr); if (HttpStatusCode.NoContent == resp.StatusCode) { if (resp.ResponseHeaders.Contains("OData-EntityId")) { passed = true; } else { passed = false; detail4.ErrorMessage = "The response headers does not contain OData-EntityId header for above patch request."; } } else { passed = false; detail4.ErrorMessage = "Patch HTTP request failed."; } } else { passed = false; detail3.ErrorMessage = "The response headers does not contain OData-EntityId header for above POST request."; } } else { passed = false; detail3.ErrorMessage = "POST HTTP request failed for above URI."; } } } // Restore the service. var resps = WebHelper.DeleteEntities(context.RequestHeaders, additionalInfos); } else { passed = false; detail1.ErrorMessage = "Created the new entity failed for above URI."; } break; } } var details = new List <ExtensionRuleResultDetail>() { detail1, detail2, detail3, detail4 }.RemoveNullableDetails(); info = new ExtensionRuleViolationInfo(new Uri(serviceStatus.RootURL), serviceStatus.ServiceDocument, details); return(passed); }
private void initializeDataHandler() { _markets = new MarketAggregator(); //const string dsPath = "TickData.qbd"; //_histFeed = new HistoricalDataHandler(dsPath); //_histFeed.AddDataInterval(new DateTime(2013, 3, 4, 23, 59, 50), new DateTime(2013, 3, 5, 0, 1, 0)); //_histFeed.AddDataInterval(new DateTime(2013, 3, 5, 23, 59, 44), new DateTime(2013, 3, 6, 0, 1, 0)); //var NKH3 = new DataFactory(new Security("NKM3 Index", 13, Security.SecurityType.IndexFuture)); //_histFeed.AddSecurity(NKH3); //_markets.AddSecurity(NKH3); //NKH3.AddReferenceToMarkets(_markets); //var NOH3 = new DataFactory(new Security("NOH3 Index", 17, Security.SecurityType.IndexFuture)); //_histFeed.AddSecurity(NOH3); //_markets.AddSecurity(NOH3); //NOH3.AddReferenceToMarkets(_markets); //var NIH3 = new DataFactory(new Security("NIH3 Index", 21, Security.SecurityType.IndexFuture)); //_histFeed.AddSecurity(NIH3); //_markets.AddSecurity(NIH3); //NIH3.AddReferenceToMarkets(_markets); //NIH3.LogEachTick = true; //var TPH3 = new DataFactory(new Security("TPH3 Index", 26, Security.SecurityType.IndexFuture)); //_histFeed.AddSecurity(TPH3); //_markets.AddSecurity(TPH3); //TPH3.AddReferenceToMarkets(_markets); //var JBH3 = new DataFactory(new Security("JBH3 Comdty", 31, Security.SecurityType.IndexFuture)); //_histFeed.AddSecurity(JBH3); //_markets.AddSecurity(JBH3); //JBH3.AddReferenceToMarkets(_markets); //var JPY = new DataFactory(new Security("JPY Curncy", 9, Security.SecurityType.IndexFuture)); //_histFeed.AddSecurity(JPY); //_markets.AddSecurity(JPY); //JPY.AddReferenceToMarkets(_markets); //_histFeed.LoadHistoricalData(); //DateTime start = DateTime.Now; //_histFeed.PlayBackData(); //TimeSpan time = DateTime.Now - start; //Console.WriteLine("Playback time {0} seconds", time.Seconds.ToString()); //const string filePath = @"C:\Users\Andre\Documents\BBDataSource\Market Aggregator OutPut\"; //_markets.BatchWriteOutData(MarketAggregator.OutPutType.FlatFile, MarketAggregator.OutPutMktMode.BothMkts, filePath, 11); var NKM3 = new DataFactory(new Security("NKM3 Index", 13, Security.SecurityType.IndexFuture)); _markets.AddSecurity(NKM3); _blbgFeed.AddSecurity(NKM3, NKM3.SecurityName); NKM3.SubscribeToDataFeedEvents(_blbgFeed); NKM3.AddReferenceToMarkets(_markets); NKM3.LogEachTick = true; //var NOM3 = new DataFactory(new Security("NOM3 Index", 18, Security.SecurityType.IndexFuture)); //_markets.AddSecurity(NOM3); //_blbgFeed.AddSecurity(NOM3); //NOM3.SubscribeToDataFeedEvents(_blbgFeed); //NOM3.AddReferenceToMarkets(_markets); //NOM3.LogEachTick = true; //var JPY = new DataFactory(new Security("JPY Curncy", 9, Security.SecurityType.Curncy)); //_markets.AddSecurity(JPY); //_blbgFeed.AddSecurity(JPY.Security, JPY); //JPY.SubscribeToDataFeedEvents(_blbgFeed); //JPY.AddReferenceToMarkets(_markets); //JPY.LogEachTick = true; ////var NIM3 = new DataFactory(new Security("NIM3 Index", 22, Security.SecurityType.IndexFuture)); ////_markets.AddSecurity(NIM3); ////_blbgFeed.AddSecurity(NIM3); ////NIM3.SubscribeToDataFeedEvents(_blbgFeed); ////NIM3.AddReferenceToMarkets(_markets); ////NIM3.LogEachTick = true; //var JBM3 = new DataFactory(new Security("JBM3 Comdty", 32, Security.SecurityType.IndexFuture)); //_markets.AddSecurity(JBM3); //_blbgFeed.AddSecurity(JBM3); //JBM3.SubscribeToDataFeedEvents(_blbgFeed); //JBM3.AddReferenceToMarkets(_markets); //JBM3.LogEachTick = true; _blbgFeed.Subscribe(); }
/// <summary> /// Verifies the extension rule. /// </summary> /// <param name="context">The Interop service context</param> /// <param name="info">out parameter to return violation information when rule does not pass</param> /// <returns>true if rule passes; false otherwise</returns> public override bool?Verify(ServiceContext context, out ExtensionRuleViolationInfo info) { if (context == null) { throw new ArgumentNullException("context"); } bool?passed = null; info = null; ServiceStatus serviceStatus = ServiceStatus.GetInstance(); TermDocuments termDocs = TermDocuments.GetInstance(); DataFactory dFactory = DataFactory.Instance(); var detail1 = new ExtensionRuleResultDetail(this.Name); var detail2 = new ExtensionRuleResultDetail(this.Name); var detail3 = new ExtensionRuleResultDetail(this.Name); var detail4 = new ExtensionRuleResultDetail(this.Name); List <string> keyPropertyTypes = new List <string>() { "Edm.Int32", "Edm.Int16", "Edm.Int64", "Edm.Guid", "Edm.String" }; List <string> norPropertyTypes = new List <string>() { "Edm.String" }; List <EntityTypeElement> entityTypeElements = MetadataHelper.GetEntityTypes(serviceStatus.MetadataDocument, 1, keyPropertyTypes, null, NavigationRoughType.CollectionValued).ToList(); if (null == entityTypeElements || 0 == entityTypeElements.Count) { detail1.ErrorMessage = "To verify this rule it expects an entity type with Int32/Int64/Int16/Guid/String key property and a string type normal property, but there is no this entity type in metadata so can not verify this rule."; info = new ExtensionRuleViolationInfo(new Uri(serviceStatus.RootURL), serviceStatus.ServiceDocument, detail1); return(passed); } EntityTypeElement entityType = null; foreach (var en in entityTypeElements) { var matchEntity = en.EntitySetName.GetRestrictions(serviceStatus.MetadataDocument, termDocs.VocCapabilitiesDoc, new List <Func <string, string, string, List <NormalProperty>, List <NavigProperty>, bool> >() { AnnotationsHelper.GetDeleteRestrictions, AnnotationsHelper.GetInsertRestrictions, AnnotationsHelper.GetUpdateRestrictions }); if (!string.IsNullOrEmpty(matchEntity.Item1) && matchEntity.Item2 != null && matchEntity.Item2.Any() && matchEntity.Item3 != null && matchEntity.Item3.Any()) { entityType = en; break; } } string entitySetUrl = entityType.EntitySetName.MapEntitySetNameToEntitySetURL(); if (string.IsNullOrEmpty(entitySetUrl)) { detail1.ErrorMessage = string.Format("Cannot find the entity-set URL which is matched with {0}", entityType.EntityTypeShortName); info = new ExtensionRuleViolationInfo(new Uri(serviceStatus.RootURL), serviceStatus.ServiceDocument, detail1); return(passed); } string url = serviceStatus.RootURL.TrimEnd('/') + @"/" + entitySetUrl; var additionalInfos = new List <AdditionalInfo>(); var reqData = dFactory.ConstructInsertedEntityData(entityType.EntitySetName, entityType.EntityTypeShortName, null, out additionalInfos); string reqDataStr = reqData.ToString(); bool isMediaType = !string.IsNullOrEmpty(additionalInfos.Last().ODataMediaEtag); var resp = WebHelper.CreateEntity(url, context.RequestHeaders, reqData, isMediaType, ref additionalInfos); detail1 = new ExtensionRuleResultDetail(this.Name, url, HttpMethod.Post, string.Empty, resp, string.Empty, reqDataStr); if (HttpStatusCode.Created == resp.StatusCode) { string entityId = additionalInfos.Last().EntityId; bool hasEtag = additionalInfos.Last().HasEtag; resp = WebHelper.GetEntity(entityId); detail2 = new ExtensionRuleResultDetail(this.Name, entityId, HttpMethod.Get, string.Empty, resp); if (HttpStatusCode.OK == resp.StatusCode) { JObject entity = JObject.Parse(resp.ResponsePayload); List <string> norPropertyNames = entityType.NormalProperties .Where(norProp => norPropertyTypes.Contains(norProp.PropertyType) && !norProp.IsKey) .Select(norProp => norProp.PropertyName) .ToList(); reqDataStr = dFactory.ConstructUpdatedEntityData(entity, norPropertyNames).ToString(); resp = WebHelper.UpdateEntity(entityId, context.RequestHeaders, reqDataStr, HttpMethod.Patch, hasEtag); detail3 = new ExtensionRuleResultDetail(this.Name, url, HttpMethod.Patch, string.Empty, resp, string.Empty, reqDataStr); if (HttpStatusCode.NoContent == resp.StatusCode) { resp = WebHelper.GetEntity(entityId); detail4 = new ExtensionRuleResultDetail(this.Name, entityId, HttpMethod.Get, string.Empty, resp, string.Empty, reqDataStr); if (HttpStatusCode.OK == resp.StatusCode) { entity = JObject.Parse(resp.ResponsePayload); var jProps = entity.Children <JProperty>(); int counter = 0; foreach (var jP in jProps) { if (norPropertyNames.Contains(jP.Name) && Constants.UpdateData == jP.Value.ToString()) { counter++; } } if (norPropertyNames.Count == counter) { passed = true; } else { passed = false; detail4.ErrorMessage = string.Format("Not all properties in request are updated, there are {0} properties in request to be updated but {1} properties are updated. ", norPropertyNames.Count, counter); } } else { passed = false; detail4.ErrorMessage = "Can not get the updated entity."; } } else { passed = false; detail3.ErrorMessage = "Patch the entity failed."; } } else { passed = false; detail2.ErrorMessage = "Can not get the created entity from above URI."; } // Restore the service. var resps = WebHelper.DeleteEntities(context.RequestHeaders, additionalInfos); } else { passed = false; detail1.ErrorMessage = "Created the new entity failed for above URI."; } var details = new List <ExtensionRuleResultDetail>() { detail1, detail2, detail3, detail4 }.RemoveNullableDetails(); info = new ExtensionRuleViolationInfo(new Uri(serviceStatus.RootURL), serviceStatus.ServiceDocument, details); return(passed); }
private void AddHistDataToCache(DataFactory factory, TickData tick) { if (!CachedTickData.ContainsKey(tick.TimeStamp)) CachedTickData.Add(tick.TimeStamp, new Dictionary<DataFactory, List<TickData>>()); Dictionary<DataFactory, List<TickData>> timeInterval = CachedTickData[tick.TimeStamp]; if (!timeInterval.ContainsKey(factory)) timeInterval.Add(factory, new List<TickData>()); List<TickData> tickData = timeInterval[factory]; tickData.Add(tick); }
//--- Constructors --- /// <summary> /// Create a new instance. /// </summary> /// <param name="factory">Factory to use for command construction and query execution.</param> /// <param name="connectionString">Database connection string.</param> /// <param name="slowSqlWarningEnabled">A value indicating whether the slow SQL warning is enabled.</param> public DataCatalog(DataFactory factory, string connectionString, bool slowSqlWarningEnabled = true) { if(factory == null) { throw new ArgumentNullException("factory"); } if(connectionString == null) { throw new ArgumentNullException("connectionString"); } this._factory = factory; _connection = connectionString; _slowSqlWarningEnabled = slowSqlWarningEnabled; }
public void GetChildren_WithFourParameters_ShouldCallGetChildrenWithFourParametersOfTheWrappedDataFactory() { using(ShimsContext.Create()) { bool getChildrenIsCalled = false; PageReference pageLinkValue = null; ILanguageSelector selectorValue = null; int? startIndexValue = null; int? maxRowsValue = null; PageDataCollection pageDataCollection = new PageDataCollection(); ShimDataFactory.StaticConstructor = () => { }; DataFactory dataFactory = new DataFactory(); new ShimDataFactory(dataFactory).GetChildrenPageReferenceILanguageSelectorInt32Int32 = delegate(PageReference pageLink, ILanguageSelector selector, int startIndex, int maxRows) { getChildrenIsCalled = true; pageLinkValue = pageLink; selectorValue = selector; startIndexValue = startIndex; maxRowsValue = maxRows; return pageDataCollection; }; PageReference pageLinkParameter = new PageReference(); ILanguageSelector selectorParameter = Mock.Of<ILanguageSelector>(); int startIndexParameter = DateTime.Now.Second; int maxRowsParameter = DateTime.Now.Millisecond; Assert.IsFalse(getChildrenIsCalled); Assert.AreEqual(pageDataCollection, new DataFactoryWrapper(dataFactory, Mock.Of<IPageDataCaster>(), Mock.Of<IPermanentLinkMapper>()).GetChildren(pageLinkParameter, selectorParameter, startIndexParameter, maxRowsParameter)); Assert.IsTrue(getChildrenIsCalled); Assert.AreEqual(pageLinkParameter, pageLinkValue); Assert.AreEqual(selectorParameter, selectorValue); Assert.AreEqual(startIndexValue.Value, startIndexParameter); Assert.AreEqual(maxRowsValue.Value, maxRowsParameter); } }
public DataCatalog(DataFactory factory, XDoc config) { if(factory == null) { throw new ArgumentNullException("factory"); } if(config == null) { throw new ArgumentNullException("config"); } _factory = factory; // compose connection string from config document string server = config["db-server"].AsText ?? "localhost"; int port = config["db-port"].AsInt ?? 3306; string catalog = config["db-catalog"].AsText; string user = config["db-user"].AsText; string password = config["db-password"].AsText ?? string.Empty; string options = config["db-options"].AsText; if(string.IsNullOrEmpty(catalog)) { throw new ArgumentNullException("config/catalog"); } if(string.IsNullOrEmpty(user)) { throw new ArgumentNullException("config/user"); } _connection = string.Format("Server={0};Port={1};Database={2};Uid={3};Pwd={4};{5}", server, port, catalog, user, password, options); // compose read-only connection string string readonly_server = config["db-readonly-server"].AsText ?? server; int readonly_port = config["db-readonly-port"].AsInt ?? port; string readonly_catalog = config["db-readonly-catalog"].AsText ?? catalog; string readonly_user = config["db-readonly-user"].AsText ?? user; string readonly_password = config["db-readonly-password"].AsText ?? password; string readonly_options = config["db-readonly-options"].AsText ?? options; _readonlyconnection = string.Format("Server={0};Port={1};Database={2};Uid={3};Pwd={4};{5}", readonly_server, readonly_port, readonly_catalog, readonly_user, readonly_password, readonly_options); }
public void GetDescendents_ShouldCallGetDescendentsOfTheWrappedDataFactoryAndReturnAConvertedResult() { using(ShimsContext.Create()) { bool getDescendentsIsCalled = false; PageReference pageLinkValue = null; IList<PageReference> pageReferenceList = new List<PageReference>(new[] {new PageReference(1), new PageReference(2), new PageReference(3)}); ShimDataFactory.StaticConstructor = () => { }; DataFactory dataFactory = new DataFactory(); new ShimDataFactory(dataFactory).GetDescendentsPageReference = delegate(PageReference pageLink) { getDescendentsIsCalled = true; pageLinkValue = pageLink; return pageReferenceList; }; ContentReference contentLinkParameter = new ContentReference(DateTime.Now.Second); Assert.IsFalse(getDescendentsIsCalled); IEnumerable<ContentReference> descendents = new DataFactoryWrapper(dataFactory, Mock.Of<IPageDataCaster>(), Mock.Of<IPermanentLinkMapper>()).GetDescendents(contentLinkParameter); Assert.IsTrue(getDescendentsIsCalled); Assert.AreEqual(pageLinkValue, contentLinkParameter); Assert.AreEqual(pageLinkValue.ID, contentLinkParameter.ID); // ReSharper disable PossibleMultipleEnumeration Assert.AreEqual(3, descendents.Count()); Assert.AreEqual(1, descendents.ElementAt(0).ID); Assert.AreEqual(2, descendents.ElementAt(1).ID); Assert.AreEqual(3, descendents.ElementAt(2).ID); // ReSharper restore PossibleMultipleEnumeration } }
private static TickData DataRowToTickData(DataFactory factory, DataRow row) { Type type; DateTime timeStamp; Double price; uint size; Dictionary<string, string> codes = null; TickData tick = null; // try parse dataRow for tick data values if (Enum.TryParse(row[0].ToString(), out type)) if (DateTime.TryParse(row[1].ToString(), out timeStamp)) if (Double.TryParse(row[2].ToString(), out price)) if (uint.TryParse(row[3].ToString(), out size)) { if ((price > 0) || (price < 0)) { // if there are any codes, add to the tickData event if ((row[4].ToString() != String.Empty) || (row[5].ToString() != String.Empty)) { codes = GetCodes(row[4].ToString(), row[5].ToString(), type); } // create a new tick data event tick = new TickData { Type = type, TimeStamp = timeStamp, Price = price, Size = size, Codes = codes, Security = factory.SecurityObj.Name, SecurityObj = factory.SecurityObj, SecurityID = factory.SecurityObj.Id }; //Console.WriteLine(tick.ToString()); } } return tick; }
private void InitData() { ModelState = new ModelStateDictionary(); _service = DataFactory.getManagerService(ModelState, Information.PersistanceStrategy); }
private void ParseDataTable(DataFactory factory, DataTable dt) { Console.WriteLine("Parsing {0} DataTable({1} rows)", factory.SecurityName, dt.Rows.Count.ToString()); if (!_mktSummaryEvents.ContainsKey(factory)) _mktSummaryEvents.Add(factory, new MktSummaryEvent {Complete = false}); MktSummaryEvent mktSummary = _mktSummaryEvents[factory]; foreach (DataRow row in dt.Rows) { TickData tick = DataRowToTickData(factory, row); if (tick != null) { if (!mktSummary.Complete) { mktSummary = PrepareMktSummaryEvent(factory, mktSummary, tick); _mktSummaryEvents[factory] = mktSummary; } else { AddHistDataToCache(factory, tick); } } } }
//--- Constructors --- /// <summary> /// Create a new instance. /// </summary> /// <param name="factory">Factory to use for command construction and query execution.</param> /// <param name="connectionString">Database connection string.</param> public DataCatalog(DataFactory factory, string connectionString) { if(factory == null) { throw new ArgumentNullException("factory"); } if(connectionString == null) { throw new ArgumentNullException("connectionString"); } this._factory = factory; _connection = connectionString; }
public static void Init() { HandlerFactory.Add(new GenericHandler()); DataFactory.Add(new SqlDataAccess()); }
/// <summary> /// Verifies the extension rule. /// </summary> /// <param name="context">The Interop service context</param> /// <param name="info">out parameter to return violation information when rule does not pass</param> /// <returns>true if rule passes; false otherwise</returns> public override bool?Verify(ServiceContext context, out ExtensionRuleViolationInfo info) { if (context == null) { throw new ArgumentNullException("context"); } bool?passed = null; info = null; ServiceStatus serviceStatus = ServiceStatus.GetInstance(); TermDocuments termDocs = TermDocuments.GetInstance(); DataFactory dFactory = DataFactory.Instance(); ExtensionRuleResultDetail detail1 = new ExtensionRuleResultDetail(this.Name); ExtensionRuleResultDetail detail2 = new ExtensionRuleResultDetail(this.Name); List <string> keyPropertyTypes = new List <string>() { "Edm.Int32", "Edm.Int16", "Edm.Int64", "Edm.Guid", "Edm.String" }; List <EntityTypeElement> entityTypeElements = MetadataHelper.GetEntityTypes(serviceStatus.MetadataDocument, 1, keyPropertyTypes, null, NavigationRoughType.None).ToList(); if (null == entityTypeElements || 0 == entityTypeElements.Count()) { detail1.ErrorMessage = "To verify this rule it expects an entity type with Int32/Int64/Int16/Guid/String key property, but there is no this entity type in metadata so can not verify this rule."; info = new ExtensionRuleViolationInfo(new Uri(serviceStatus.RootURL), serviceStatus.ServiceDocument, detail1); return(passed); } // To get test entity which is deleteable and insertable EntityTypeElement entityType = null; foreach (var entityEle in entityTypeElements) { var matchEntity = entityEle.EntitySetName.GetRestrictions(serviceStatus.MetadataDocument, termDocs.VocCapabilitiesDoc, new List <Func <string, string, string, List <NormalProperty>, List <NavigProperty>, bool> >() { AnnotationsHelper.GetInsertRestrictions, AnnotationsHelper.GetDeleteRestrictions }); if (!string.IsNullOrEmpty(matchEntity.Item1) && matchEntity.Item2 != null && matchEntity.Item2.Any() && matchEntity.Item3 != null && matchEntity.Item3.Any()) { entityType = entityEle; break; } } if (null == entityType) { detail1.ErrorMessage = "To verify this rule it expects an entity type with deleteable and insertable restrictions, but there is no entity type in metadata which is insertable and deleteable."; info = new ExtensionRuleViolationInfo(new Uri(serviceStatus.RootURL), serviceStatus.ServiceDocument, detail1); return(passed); } string entitySetUrl = entityType.EntitySetName.MapEntitySetNameToEntitySetURL(); if (string.IsNullOrEmpty(entitySetUrl)) { detail1.ErrorMessage = string.Format("Cannot find the entity-set URL which is matched with {0}.", entityType.EntityTypeShortName); info = new ExtensionRuleViolationInfo(new Uri(serviceStatus.RootURL), serviceStatus.ServiceDocument, detail1); return(passed); } string url = serviceStatus.RootURL.TrimEnd('/') + @"/" + entitySetUrl; var additionalInfos = new List <AdditionalInfo>(); var reqData = dFactory.ConstructInsertedEntityData(entityType.EntitySetName, entityType.EntityTypeShortName, null, out additionalInfos); string reqDataStr = reqData.ToString(); bool isMediaType = !string.IsNullOrEmpty(additionalInfos.Last().ODataMediaEtag); var resp = WebHelper.CreateEntity(url, context.RequestHeaders, reqData, isMediaType, ref additionalInfos); detail1 = new ExtensionRuleResultDetail(this.Name, url, HttpMethod.Post, string.Empty, resp, string.Empty, reqDataStr); // If create successfully, the resource is updatable and deletable. if (resp.StatusCode.HasValue && resp.StatusCode == HttpStatusCode.Created) { // Get feed response. resp = WebHelper.Get(new Uri(url), Constants.V4AcceptHeaderJsonFullMetadata, RuleEngineSetting.Instance().DefaultMaximumPayloadSize, serviceStatus.DefaultHeaders); detail2 = new ExtensionRuleResultDetail(this.Name, url, HttpMethod.Get, StringHelper.MergeHeaders(Constants.V4AcceptHeaderJsonFullMetadata, serviceStatus.DefaultHeaders), resp); if (resp.StatusCode.HasValue && resp.StatusCode == HttpStatusCode.OK) { JObject jo; resp.ResponsePayload.TryToJObject(out jo); var entries = JsonParserHelper.GetEntries(jo); foreach (JObject entry in entries) { if (entry[Constants.V4OdataEditLink] == null) { passed = false; detail2.ErrorMessage = "Not all entities from above URI contain edit links."; break; } } if (passed == null) { passed = true; } } else { passed = false; detail2.ErrorMessage = "Get feed resource failed from above URI."; } // Restore the service. var resps = WebHelper.DeleteEntities(context.RequestHeaders, additionalInfos); } else { passed = null; detail1.ErrorMessage = "Created new entity failed, it is not an updatable resource and can not verify this rule."; } var details = new List <ExtensionRuleResultDetail>() { detail1, detail2 }.RemoveNullableDetails(); info = new ExtensionRuleViolationInfo(new Uri(serviceStatus.RootURL), serviceStatus.ServiceDocument, details); return(passed); }
private static MktSummaryEvent CheckForSyntheticTradeCondition(DataFactory factory, MktSummaryEvent mktSummary) { if ((mktSummary.Ask != null) && (mktSummary.Bid != null)) { mktSummary.Trade = new TickData { Type = Type.Trade, TimeStamp = mktSummary.EventTime, Price = (mktSummary.Bid.Price + mktSummary.Ask.Price) / 2, Size = 0, Codes = null, Security = factory.SecurityObj.Name, SecurityObj = factory.SecurityObj, SecurityID = factory.SecurityObj.Id }; } return mktSummary; }