在WinForm程序中嵌入ASP.NET

本文介绍了一种将ASP.NET引擎嵌入到WinForm桌面应用程序中的轻量级方法,包括如何手动创建AppDomain来避免重复代码的问题,并展示了如何处理特定请求。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

现在的流行趋势是桌面程序Web化,Web程序桌面化,呵呵。最终目标就是你中有我,我中有你。例如MSN Explorer就是一个很好的展示,让用户在使用的时候分不清什么时候是在本地什么时候是在网络。而这类程序往往需要有一个后台服务器如IIS的支持,这对大多数桌面应用来说too heavy了。本着简单就是美的设计思想,这里给出一个轻量级的解决方法,把ASP.NET嵌入到普通WinForm桌面程序中去。
     因为安全以及其它一些方面的原因,在使用ASP.NET引擎之前,必须建立一个新的 AppDomain。简单的方法是直接使用 ApplicationHost.CreateApplicationHost函数为指定的虚拟目录和物理路径建立ASP.NET引擎宿主的实例,如

 

// should create a subdirectory ./bin and copy the assembly to it
static public WebHost Create(string name, string path)
{
     if(!name.StartsWith(new string(Path.AltDirectorySeparatorChar, 1)))
     {
       name = Path.AltDirectorySeparatorChar + name;
     }

     webhost host = (webhost)applicationhost.createapplicationhost(
       typeof(WebHost), name, path);

     host.setvirtualdirectory(name);
     host.setBaseDirectory(path);

     return host;
}

 

但这样建立的程序有个bt的要求,他会在指定目录的bin子目录中去尝试载入宿主类型(webhost)的assembly,也就是说你必须把程序在bin子目录下复制一份,非常不爽。解决方法是自己手工完成整个建立过程,如下:

 

static public WebHost Create(string virtualDir, string physicalDir)
{
     if(!virtualDir.StartsWith(new string(Path.AltDirectorySeparatorChar, 1)))
     {
       virtualDir = Path.AltDirectorySeparatorChar + virtualDir;
     }

 

     if(!physicaldir.endswith(new string(path.directoryseparatorchar, 1)))
     {
       physicalDir += Path.DirectorySeparatorChar;
     }

     appdomainsetup setup = new appdomainsetup();

     setup.applicationname = "app_" + guid.newguid().tostring();
     setup.ConfigurationFile = "web.config";

     appdomain domain = appdomain.createdomain("asphost_" + guid.newguid().tostring(), null, setup);
   
     domain.SetData(".appDomain", "*");
     domain.SetData(".appPath", physicalDir);
     domain.SetData(".appVPath", virtualDir);
     domain.SetData(".domainId", domain.FriendlyName);
     domain.SetData(".hostingVirtualPath", virtualDir);
     domain.SetData(".hostingInstallDir", HttpRuntime.AspInstallDirectory);

     webhost host = (webhost)domain.createinstanceandunwrap(
       typeof(WebHost).Module.Assembly.FullName, typeof(WebHost).FullName);

     host.setapplicationdomain(domain);
     host.setVirtualDirectory(virtualDir);
     host.setBaseDirectory(physicalDir);

     return host;

}

 

这儿的一堆domain.setdata是传递参数给asp.net引擎。然后在那个appdomain中建立新的宿主类型的实例。这样就避免多份代码的尴尬。而使用asp.net就比较简单了,在宿主类中使用HttpRuntime.ProcessRequest函数处理特定请求。简单一点的话,可以直接用SimpleWorkerRequest包装请求,生成页面到一个指定的TextWriter中,如

 

private void DoRequest(string page, string query, TextWriter writer)
{
     HttpRuntime.ProcessRequest(new SimpleWorkerRequest(page, query, writer));
}

 

public void requestpage(string page, string query, stream stream)
{      
     DoRequest(page, query, new StreamWriter(stream));
}

public void requestpage(string page, stream stream)
{
     RequestPage(page, null, stream);
}

public string requestpage(string page, string query)
{
     using(StringWriter writer = new StringWriter())      
     {
       DoRequest(page, query, writer);

       return writer.tostring();
     }
}

public string requestpage(string page)
{
     return RequestPage(page, string.Empty);
}

 

这个缺省的请求包装使用是简单,但对中文的兼容性不太好,过两天有空再自己写个强一点的吧,呵呵

最终类的使用就比较简单了,在winform程序中建立一个singleton模式的属性

 

static private WebHost.WebHost _host = null;

 

public webhost.webhost host
{
     get
     {
       if(_host == null)
       {
         _host = WebHost.WebHost.Create();
       }
       return _host;
     }
}

 

然后请求指定的asp.net页面,如

html = host.requestpage(_page);

即可完成从动态的asp.net脚本到静态html的转换。嵌入winform程序中,还可以通过host类型完成两者之间的双向通讯,实现互相控制。下次有空继续,呵呵

参考资料:
     1.Using the ASP.Net Runtime for extending desktop applications with dynamic HTML Scripts
     ::URL::http://www.west-wind.com/presentations/aspnetruntime/aspnetruntime.asp

     2.executing asmx files without a web server       ::URL::http://radio.weblogs.com/0105476/stories/2002/10/24/executingAsmxFilesWithoutAWebServer.html

     3.asp. net client-side hosting with cassini
     ::URL::http://msdn.microsoft.com/msdnmag/issues/03/01/CuttingEdge/

     4.using asp.net runtime in desktop applications
     ::URL::http://www.codeguru.com/cs_internet/UsingAspRuntime.html

### 使用Transformer模型进行图像分类的方法 #### 方法概述 为了使Transformer能够应用于图像分类任务,一种有效的方式是将图像分割成固定大小的小块(patches),这些小块被线性映射为向量,并加上位置编码以保留空间信息[^2]。 #### 数据预处理 在准备输入数据的过程中,原始图片会被切分成多个不重叠的patch。假设一张尺寸为\(H \times W\)的RGB图像是要处理的对象,则可以按照设定好的宽度和高度参数来划分该图像。例如,对于分辨率为\(224\times 224\)像素的图像,如果选择每边切成16个部分的话,那么最终会得到\((224/16)^2=196\)个小方格作为单独的特征表示单元。之后,每一个这样的补丁都会通过一个简单的全连接层转换成为维度固定的嵌入向量。 ```python import torch from torchvision import transforms def preprocess_image(image_path, patch_size=16): transform = transforms.Compose([ transforms.Resize(256), transforms.CenterCrop(224), # 假设目标分辨率是224x224 transforms.ToTensor(), ]) image = Image.open(image_path).convert('RGB') tensor = transform(image) patches = [] for i in range(tensor.shape[-2] // patch_size): # 高度方向上的循环 row_patches = [] for j in range(tensor.shape[-1] // patch_size): # 宽度方向上的循环 patch = tensor[:, :, i*patch_size:(i+1)*patch_size, j*patch_size:(j+1)*patch_size].flatten() row_patches.append(patch) patches.extend(row_patches) return torch.stack(patches) ``` #### 构建Transformer架构 构建Vision Transformer (ViT),通常包括以下几个组成部分: - **Patch Embedding Layer**: 将每个图像块转化为低维向量; - **Positional Encoding Layer**: 添加绝对或相对位置信息给上述获得的向量序列; - **Multiple Layers of Self-Attention and Feed Forward Networks**: 多层自注意机制与前馈神经网络交替堆叠而成的核心模块; 最后,在顶层附加一个全局平均池化层(Global Average Pooling)以及一个多类别Softmax回归器用于预测类标签。 ```python class VisionTransformer(nn.Module): def __init__(self, num_classes=1000, embed_dim=768, depth=12, num_heads=12, mlp_ratio=4., qkv_bias=False, drop_rate=0.): super().__init__() self.patch_embed = PatchEmbed(embed_dim=embed_dim) self.pos_embed = nn.Parameter(torch.zeros(1, self.patch_embed.num_patches + 1, embed_dim)) self.cls_token = nn.Parameter(torch.zeros(1, 1, embed_dim)) dpr = [drop_rate for _ in range(depth)] self.blocks = nn.Sequential(*[ Block( dim=embed_dim, num_heads=num_heads, mlp_ratio=mlp_ratio, qkv_bias=qkv_bias, drop=dpr[i], ) for i in range(depth)]) self.norm = nn.LayerNorm(embed_dim) self.head = nn.Linear(embed_dim, num_classes) def forward(self, x): B = x.shape[0] cls_tokens = self.cls_token.expand(B, -1, -1) x = self.patch_embed(x) x = torch.cat((cls_tokens, x), dim=1) x += self.pos_embed x = self.blocks(x) x = self.norm(x) return self.head(x[:, 0]) ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值