public bool PosTest3() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest3: Verify dispose interface is implemented in customer class..."); try { int i = TestLibrary.Generator.GetInt32(-55); IntPtr ip = new IntPtr(i); MyResource myRes = new MyResource(ip); myRes.Dispose(); if (myRes.handle != IntPtr.Zero) { TestLibrary.TestFramework.LogError("004", "The handle should be IntPtr.zero!"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("005", "Unexpected exception occurs: " + e); retVal = false; } return(retVal); }
/// <summary> /// 删除单条数据 /// </summary> /// <param name="entity"></param> /// <returns></returns> public virtual bool Delete(MyResource entity, int id) { string sql = string.Format("delete from ResourcesInfo where id=@Id; delete from ResourcesInfo where '|'+code+'|' like '%|" + id + "|%'"); SqlParameter pms = new SqlParameter("@Id", id); return SQLHelp.ExecuteNonQuery(sql, CommandType.Text, pms) > 0; }
public object GetDeserializedObject(object obj, Type targetType) { if (obj.GetType() == typeof(Dictionary <string, object>) && targetType == typeof(MyResource)) { Dictionary <string, object> dict = (Dictionary <string, object>)obj; MyResource mr = new MyResource(); foreach (PropertyInfo prop in GetInterestingProperties(typeof(MyResource))) { DataMemberAttribute att = prop.GetCustomAttribute <DataMemberAttribute>(); object value; if (dict.TryGetValue(att.Name, out value)) { prop.SetValue(mr, value); dict.Remove(prop.Name); } } // should only be one property left in the dictionary if (dict.Count > 0) { var kvp = dict.First(); mr.SpecialName = kvp.Key; mr.SpecialValue = (string)kvp.Value; } return(mr); } return(obj); }
/// <summary> /// 修改文件夹(文件夹)名称 /// </summary> /// <param name="context"></param> private void reName(HttpContext context) { string result = ""; JsonModel jsonModel = null; JavaScriptSerializer jss = new System.Web.Script.Serialization.JavaScriptSerializer(); MyResource modol = new MyResource(); string Name = context.Request["NewName"].SafeToString(); string FileUrl = context.Request["FileUrl"].SafeToString(); string oldName = context.Request["oldname"].SafeToString(); int LastLen = FileUrl.LastIndexOf("/"); string LastName = FileUrl.Substring(LastLen, FileUrl.Length - LastLen); string newUrl = FileUrl.Substring(0, LastLen) + LastName.Replace(oldName, Name); if (LastName.IndexOf('.') > 0) { FileHelper.Move(context.Server.MapPath(FileUrl), context.Server.MapPath(newUrl)); } else { Directory.Move(context.Server.MapPath(FileUrl), context.Server.MapPath(newUrl)); } modol.ID = Convert.ToInt32(context.Request["ID"]); if (Name.IndexOf(".") > 0) { Name = Name.Split('.')[0]; } modol.FileUrl = newUrl; modol.Name = Name; modol.EditTime = DateTime.Now; jsonModel = Bll.Update(modol); result = "{\"result\":" + jss.Serialize(jsonModel) + "}"; context.Response.Write(result); context.Response.End(); }
public static void Main() { // Insert code here to create // and use the MyResource object. MyResource mr = new MyResource(IntPtr.Zero); //GC.Collect(); }
static void Main(string[] args) { using (MyResource resource = new MyResource()) { Console.WriteLine("Using my resource"); } Console.WriteLine("Finished"); }
/// <summary> /// 文件下载 /// </summary> /// <returns></returns> private void Down(HttpContext context) { ZipHelper zip = new ZipHelper(); JsonModel jsonModel = null; JavaScriptSerializer jss = new System.Web.Script.Serialization.JavaScriptSerializer(); string ids = context.Request.Form["DownID"].SafeToString(); string ZipUrl = context.Server.MapPath(ConfigHelper.GetConfigString("ZipUrl")) + "/" + DateTime.Now.Ticks; string DownUrl = ConfigHelper.GetConfigString("DownUrl"); string result = "0"; try { string[] idarry = ids.TrimEnd(',').Split(','); FileHelper.CreateDirectory(ZipUrl); for (int i = 0; i < idarry.Length; i++) { #region 文件移动 JsonModel model = Bll.GetEntityById(int.Parse(idarry[i])); MyResource resource = (MyResource)(model.retData); string FileUrl = resource.FileUrl; if (resource.postfix == "") { FileHelper.CopyFolder(context.Server.MapPath(FileUrl), ZipUrl); } else { FileHelper.CopyTo(context.Server.MapPath(FileUrl), ZipUrl + FileUrl.Substring(FileUrl.LastIndexOf("/"))); } #endregion } string ZipName = "/下载文件" + DateTime.Now.Ticks + ".rar"; //文件打包 SharpZip.PackFiles(context.Server.MapPath(ConfigHelper.GetConfigString("ZipUrl")) + ZipName, ZipUrl); jsonModel = new JsonModel() { errNum = 0, errMsg = "", retData = DownUrl + "\\" + ZipName //+ ".rar" }; } catch (Exception ex) { jsonModel = new JsonModel() { errNum = 400, errMsg = ex.Message, retData = "" }; LogService.WriteErrorLog(ex.Message); } result = "{\"result\":" + jss.Serialize(jsonModel) + "}"; context.Response.Write(result); context.Response.End(); }
/// <summary> /// 获取分页数据 /// </summary> /// <param name="context"></param> private void GetPage(HttpContext context) { string result = ""; JsonModel jsonModel = null; JavaScriptSerializer jss = new System.Web.Script.Serialization.JavaScriptSerializer(); try { MyResource resource = new MyResource(); Hashtable ht = new Hashtable(); ht.Add("PageIndex", context.Request["PageIndex"].SafeToString()); ht.Add("PageSize", context.Request["PageSize"].SafeToString()); ht.Add("TableName", "MyResource"); ht.Add("Pid", context.Request["Pid"].SafeToString()); ht.Add("DocName", context.Request["DocName"].SafeToString()); ht.Add("Postfixs", context.Request["Postfixs"].SafeToString()); ht.Add("CreateUID", context.Request["CreateUID"].SafeToString()); DateTime datetime = DateTime.Now; string Time = context.Request["CreateTime"].SafeToString(); switch (Time) { case "Week": datetime = datetime.AddDays(-7); break; case "Month": datetime = datetime.AddMonths(-1); break; case "Year": datetime = datetime.AddMonths(-6); break; default: datetime = datetime.AddYears(-1); break; } ht.Add("CreateTime", datetime); jsonModel = Bll.GetPage(ht); result = "{\"result\":" + jss.Serialize(jsonModel) + "}"; } catch (Exception ex) { jsonModel = new JsonModel() { errNum = 400, errMsg = ex.Message, retData = "" }; LogService.WriteErrorLog(ex.Message); } result = "{\"result\":" + jss.Serialize(jsonModel) + "}"; context.Response.Write(result); context.Response.End(); }
public static void Main() { var handle = new IntPtr(5); using (var myResource = new MyResource(handle)) { Console.WriteLine("Hello"); } Console.Read(); }
public void AddLoad(string path, MyResource.Progress call) { if (path.Length <= 0) { return; } MyResource mres = new MyResource(); mres.request = Resources.LoadAsync(path); mres.call = call; MyRes[Count] = mres; Count++; }
/// <summary> /// 文件删除 /// </summary> /// <returns></returns> private void Del(HttpContext context) { JsonModel jsonModel = null; JavaScriptSerializer jss = new System.Web.Script.Serialization.JavaScriptSerializer(); string ids = context.Request.Form["DelID"].SafeToString(); string result = "0"; try { string[] idarry = ids.TrimEnd(',').Split(','); for (int i = 0; i < idarry.Length; i++) { #region 文件删除 JsonModel model = Bll.GetEntityById(int.Parse(idarry[i])); MyResource resource = (MyResource)(model.retData); string FileUrl = resource.FileUrl; if (resource.postfix == "") { FileHelper.DeleteDirectory(context.Server.MapPath(FileUrl)); } else { FileHelper.DeleteFile(context.Server.MapPath(FileUrl)); } #endregion //数据删除 jsonModel = Bll.Delete(int.Parse(idarry[i])); } } catch (Exception ex) { jsonModel = new JsonModel() { errNum = 400, errMsg = ex.Message, retData = "" }; LogService.WriteErrorLog(ex.Message); } result = "{\"result\":" + jss.Serialize(jsonModel) + "}"; context.Response.Write(result); context.Response.End(); }
public object GetObjectToSerialize(object obj, Type targetType) { if (obj.GetType() == typeof(MyResource) && targetType == typeof(Dictionary <string, object>)) { MyResource mr = (MyResource)obj; Dictionary <string, object> dict = new Dictionary <string, object>(); dict.Add(mr.SpecialName, mr.SpecialValue); foreach (PropertyInfo prop in GetInterestingProperties(typeof(MyResource))) { DataMemberAttribute att = prop.GetCustomAttribute <DataMemberAttribute>(); dict.Add(att.Name, prop.GetValue(mr)); } return(dict); } return(obj); }
public ParallelLoopResult Microsoft() => Parallel.For(0, Count, _ => { MyResource res = null; string str; try { res = _microsoftObjectPool.Get(); str = res.Value; } finally { if (res != null) { _microsoftObjectPool.Return(res); } } });
public string Microsoft() { MyResource res = null; string str; try { res = _microsoftObjectPool.Get(); str = res.Value; } finally { if (res != null) { _microsoftObjectPool.Return(res); } } return(str); }
public void CanSerializeAtomLinksToCorrectFormat() { // Arrange string correctXml = @"<link href=""http://dr.dk/"" rel=""test"" type=""text/html"" title=""DR"" xmlns=""http://www.w3.org/2005/Atom"" />"; XmlSerializer serializer = new XmlSerializer(typeof(MyResource)); MyResource r = new MyResource(); r.Links.Add(new AtomLink(new Uri("http://dr.dk"), "http://dr.dk", "test", "text/html", "DR")); // Act using (StringWriter w = new StringWriter()) { serializer.Serialize(w, r); string xml = w.ToString(); Console.Write(xml); Assert.IsTrue(xml.Contains(correctXml)); } }
public void TestImmediateResource() { var env = new Environment(); var res = new MyResource(env, capacity: 1); Assert.AreEqual(0, res.InUse); Assert.AreEqual(1, res.Remaining); Assert.AreEqual(0, res.RequestQueueLength); Assert.AreEqual(0, res.ReleaseQueueLength); var req1 = res.Request(); Assert.IsTrue(req1.IsTriggered); Assert.AreEqual(1, res.InUse); Assert.AreEqual(0, res.Remaining); Assert.AreEqual(0, res.RequestQueueLength); Assert.AreEqual(0, res.ReleaseQueueLength); var req2 = res.Request(); Assert.IsFalse(req2.IsTriggered); Assert.AreEqual(1, res.InUse); Assert.AreEqual(0, res.Remaining); Assert.AreEqual(1, res.RequestQueueLength); Assert.AreEqual(0, res.ReleaseQueueLength); req1.Dispose(); Assert.IsFalse(req2.IsTriggered); Assert.AreEqual(0, res.InUse); Assert.AreEqual(1, res.Remaining); Assert.AreEqual(1, res.RequestQueueLength); Assert.AreEqual(0, res.ReleaseQueueLength); var req3 = res.Request(); Assert.IsTrue(req2.IsTriggered); Assert.IsFalse(req3.IsTriggered); Assert.AreEqual(1, res.InUse); Assert.AreEqual(0, res.Remaining); Assert.AreEqual(1, res.RequestQueueLength); Assert.AreEqual(0, res.ReleaseQueueLength); }
public void CanSerializeAtomLinksWithMissingMediaTypeToCorrectFormat() { // Arrange string correctXml = @"<link href=""http://dr.dk/"" rel=""test"" title=""DR"" xmlns=""http://www.w3.org/2005/Atom"" />"; XmlSerializer serializer = new XmlSerializer(typeof(MyResource)); MyResource r = new MyResource(); r.Links.Add(new AtomLink(new Uri("http://dr.dk"), "http://dr.dk", "test", null, "DR")); // Act using (StringWriter w = new StringWriter()) { serializer.Serialize(w, r); string xml = w.ToString(); Console.Write(xml); Assert.IsTrue(xml.Contains(correctXml)); } }
static void Main(string[] args) { //we need better examples here. Or: I need better understanding of GC! var res1 = new MyResource(); res1 = null; // we forget to Dispose here! GC.Collect(); // example taken from https://msdn.microsoft.com/en-us/library/ms244737.aspx using (var res2 = new MyResource()) { //nothing happens here GC.Collect(); } //it should be Disposed now GC.Collect(); }
public static void DemoDispose() { using (var res = new MyResource()) { Console.WriteLine("Verwende MyResource"); } // Gleichbedeutend zu: MyResource res2 = new MyResource(); try { Console.WriteLine("Verwende MyResource"); } finally { if (res2 != null) { res2.Dispose(); } } }
static void Main(string[] args) { string json = @" { ""12345"": ""text string"", ""rel"": ""myResource"" }"; var settings = new DataContractJsonSerializerSettings(); settings.DataContractSurrogate = new MyDataContractSurrogate(); settings.KnownTypes = new List <Type> { typeof(Dictionary <string, object>) }; settings.UseSimpleDictionaryFormat = true; MyResource mr = Deserialize <MyResource>(json, settings); Console.WriteLine("Special name: " + mr.SpecialName); Console.WriteLine("Special value: " + mr.SpecialValue); Console.WriteLine("Rel: " + mr.Rel); Console.WriteLine(); json = Serialize(mr, settings); Console.WriteLine(json); }
/// <summary> /// 文件删除 /// </summary> /// <returns></returns> private void MoveTo(HttpContext context) { JsonModel jsonModel = null; JavaScriptSerializer jss = new System.Web.Script.Serialization.JavaScriptSerializer(); string ids = context.Request.Form["MoveIDs"].SafeToString(); string url = context.Request.Form["Url"]; string code = context.Request.Form["code"]; string pid = context.Request.Form["pid"]; string result = "0"; try { string[] idarry = ids.Split(','); foreach (string id in idarry) { if (id != "") { #region 文件移动 JsonModel model = Bll.GetEntityById(int.Parse(id)); MyResource resource = (MyResource)(model.retData); string FileUrl = resource.FileUrl; if (resource.postfix == "") { resource.FileUrl = url + resource.FileUrl.Substring(resource.FileUrl.LastIndexOf("/")); if (pid == id) { jsonModel = new JsonModel { errNum = 500, errMsg = "目标目录和当前目录一致", retData = "" }; break; } Directory.Move(context.Server.MapPath(FileUrl), context.Server.MapPath(resource.FileUrl)); if (code != "0") { resource.code = code + "|" + pid; } else { resource.code = pid; } resource.PID = int.Parse(pid); } else { resource.FileUrl = url + resource.FileUrl.Substring(resource.FileUrl.LastIndexOf("/")); if (pid == id) { jsonModel = new JsonModel { errNum = 500, errMsg = "目标目录和当前目路一致", retData = "" }; break; } FileHelper.Move(context.Server.MapPath(FileUrl), context.Server.MapPath(resource.FileUrl)); if (code != "0") { resource.code = code + "|" + pid; } else { resource.code = pid; } resource.PID = int.Parse(pid); } jsonModel = Bll.Update(resource); #endregion } } } catch (Exception ex) { jsonModel = new JsonModel() { errNum = 400, errMsg = ex.Message, retData = "" }; LogService.WriteErrorLog(ex.Message); } result = "{\"result\":" + jss.Serialize(jsonModel) + "}"; context.Response.Write(result); context.Response.End(); }
public void AddingNullResourceShouldThrowException() { MyResource nullResource = null; Assert.Throws <NullReferenceException>(() => inventory.AddItem(nullResource)); }
public bool PosTest3() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest3: Verify dispose interface is implemented in customer class..."); try { int i = TestLibrary.Generator.GetInt32(-55); IntPtr ip = new IntPtr(i); MyResource myRes = new MyResource(ip); myRes.Dispose(); if (myRes.handle != IntPtr.Zero) { TestLibrary.TestFramework.LogError("004","The handle should be IntPtr.zero!"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("005","Unexpected exception occurs: " + e); retVal = false; } return retVal; }
private void UploadDrive(HttpContext context) { JsonModel jsonModel = null; JavaScriptSerializer jss = new System.Web.Script.Serialization.JavaScriptSerializer(); string CreateUID = context.Request["CreateUID"].SafeToString(); string FoldUrl = ""; if (context.Request["FoldUrl"].SafeToString().IndexOf(ConfigHelper.GetConfigString("FileManageName")) < 0) { FoldUrl = ConfigHelper.GetConfigString("FileManageName") + context.Request["FoldUrl"].SafeToString(); } else { FoldUrl = context.Request["FoldUrl"].SafeToString(); } if (FoldUrl.IndexOf(CreateUID) < 0) { FoldUrl += "/" + CreateUID; } string Pid = context.Request.Form["Pid"].SafeToString(); string result = "0"; string code = context.Request.Form["code"].SafeToString().Trim(); try { if (!FileHelper.IsExistDirectory(context.Server.MapPath(FoldUrl))) { FileHelper.CreateDirectory(context.Server.MapPath(FoldUrl)); } HttpPostedFile file = context.Request.Files[0]; string ext = Path.GetExtension(file.FileName); string fileName = Path.GetFileName(file.FileName);// DateTime.Now.Ticks + ext; string p = FoldUrl + "/" + fileName; string path = context.Server.MapPath(p); #region 处理文件同名问题 if (FileHelper.IsExistFile(path)) { int i = 0; while (true) { i++; if (!FileHelper.IsExistFile(context.Server.MapPath(FoldUrl + "/" + fileName.Split('.')[0] + "(" + i + ")" + "." + fileName.Split('.')[1]))) { fileName = fileName.Split('.')[0] + "(" + i + ")" + "." + fileName.Split('.')[1]; p = FoldUrl + "/" + fileName; path = context.Server.MapPath(p); break; } } } #endregion file.SaveAs(path); MyResource re = new MyResource(); string Name = fileName.Replace(ext, ""); re.Name = Name; re.PID = int.Parse(Pid); re.FileSize = file.ContentLength; re.FileUrl = p; re.FileIcon = "ico-" + fileName.Split('.')[1] + "b.png"; re.FileIconBig = "ico-" + fileName.Split('.')[1] + "t.png"; re.postfix = ext; re.CreateUID = CreateUID; re.EditUID = CreateUID; re.IsFolder = 0; if (Pid == "0") { re.code = "0"; } else { re.code = code == "0" ? "" : code + "|" + re.PID; } jsonModel = DriveBll.Add(re); } catch (Exception ex) { jsonModel = new JsonModel() { errNum = 400, errMsg = ex.Message, retData = "" }; LogService.WriteErrorLog(ex.Message); } result = "{\"result\":" + jss.Serialize(jsonModel) + "}"; context.Response.Write(result); context.Response.End(); }
static void Main(string[] args) { MyResource obj = new MyResource((IntPtr)0); }
async void Button_Click(object s, EventArgs e) { // call start as if it is a constructor this.Resource = await new MyResource().StartAsync(); }
/// <summary> /// 新增文件夹 /// </summary> /// <returns></returns> private void AddFolder(HttpContext context) { JsonModel jsonModel = null; JavaScriptSerializer jss = new System.Web.Script.Serialization.JavaScriptSerializer(); string CreateUID = context.Request.Form["CreateUID"].SafeToString(); string FoldUrl = ""; if (context.Request["FoldUrl"].SafeToString().IndexOf(ConfigHelper.GetConfigString("FileManageName")) < 0) { FoldUrl = ConfigHelper.GetConfigString("FileManageName") + context.Request["FoldUrl"].SafeToString(); } else { FoldUrl = context.Request["FoldUrl"].SafeToString(); } // string FoldUrl = ConfigHelper.GetConfigString("FileManageName") + context.Request.Form["FoldUrl"].SafeToString(); if (FoldUrl.IndexOf(CreateUID) < 0) { FoldUrl += "/" + CreateUID; } string result = "0"; try { string FileName = context.Request.Form["FileName"].ToString().Trim(); string pid = context.Request.Form["Pid"].ToString().Trim(); string code = context.Request.Form["code"].ToString().Trim(); string RealPath = FoldUrl + "/" + FileName;// +DateTime.Now.Ticks.ToString(); string RealFullPath = context.Server.MapPath(RealPath); #region 处理文件夹重名问题 if (FileHelper.IsExistDirectory(RealFullPath)) { int i = 0; while (true) { i++; if (!FileHelper.IsExistDirectory(RealFullPath + "(" + i + ")")) { FileName += "(" + i + ")"; RealPath += "(" + i + ")"; RealFullPath += "(" + i + ")"; break; } } } #endregion if (FileHelper.CreateDirectory(RealFullPath)) { MyResource re = new MyResource(); re.Name = FileName; re.PID = int.Parse(pid); re.FileSize = 0; re.FileUrl = RealPath; re.FileIcon = "ico-file.png"; re.postfix = ""; re.CreateUID = CreateUID; re.EditUID = CreateUID; re.IsFolder = 1; if (pid == "0") { re.code = "0"; } else { if (code == "0") { re.code = re.PID.ToString(); } else { re.code = code + "|" + re.PID; } } jsonModel = Bll.Add(re); } else { jsonModel = new JsonModel() { errNum = 500, errMsg = "文件夹添加失败", retData = "" }; } } catch (Exception ex) { jsonModel = new JsonModel() { errNum = 400, errMsg = ex.Message, retData = "" }; LogService.WriteErrorLog(ex.Message); } result = "{\"result\":" + jss.Serialize(jsonModel) + "}"; context.Response.Write(result); context.Response.End(); }