惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

Attack and Defense Labs
Attack and Defense Labs
T
Threatpost
C
Cybersecurity and Infrastructure Security Agency CISA
H
Hackread – Cybersecurity News, Data Breaches, AI and More
I
Intezer
C
Cyber Attacks, Cyber Crime and Cyber Security
The Register - Security
The Register - Security
量子位
Security Latest
Security Latest
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
大猫的无限游戏
大猫的无限游戏
小众软件
小众软件
Exploit-DB.com RSS Feed
Exploit-DB.com RSS Feed
C
CXSECURITY Database RSS Feed - CXSecurity.com
MyScale Blog
MyScale Blog
J
Java Code Geeks
Apple Machine Learning Research
Apple Machine Learning Research
Google DeepMind News
Google DeepMind News
WordPress大学
WordPress大学
Spread Privacy
Spread Privacy
Jina AI
Jina AI
博客园 - 【当耐特】
P
Palo Alto Networks Blog
Last Week in AI
Last Week in AI
SecWiki News
SecWiki News
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
G
GRAHAM CLULEY
宝玉的分享
宝玉的分享
Hacker News - Newest:
Hacker News - Newest: "LLM"
T
The Blog of Author Tim Ferriss
V
Vulnerabilities – Threatpost
有赞技术团队
有赞技术团队
T
Tor Project blog
H
Hacker News: Front Page
A
Arctic Wolf
NISL@THU
NISL@THU
A
About on SuperTechFans
云风的 BLOG
云风的 BLOG
Engineering at Meta
Engineering at Meta
V
V2EX
N
News and Events Feed by Topic
Webroot Blog
Webroot Blog
Know Your Adversary
Know Your Adversary
P
Privacy International News Feed
I
InfoQ
D
Docker
L
LINUX DO - 最新话题
K
KPMG report finds enterprise disconnect between AI and its ROI | CIO
U
Unit 42

博客园 - 分享 共赢

大爱,netbeans的远程开发 lvs + keepalived udp小结 web项目下,甩开RazorTemplateEngine做模板处理 将watin的ui单元测试集成到cc.net 命令行发布web项目 Microsoft © SilverlightTM Release History 针对sl的ICSharpCode.SharpZipLib,只保留zip,gzip的流压缩、解压缩功能 不同IComparer对数组排序Array.Sort,Linq orderby的性能的影响 c# 编译器优化的功劳?与泛型有关的代码的疑惑 高效获取某个数字的最后2位 centos asp.net运行环境配置 [转]我在微软做PM ... Linq to sql 简单性能差异指引 April Rosario(vs2010?) CTP now available! 手工杀毒利器 在form上设定了defaultbutton属性之后,切换提交按钮的解决办法 在form上设定了defaultbutton属性之后,切换提交按钮的解决办法 Bingo Day-展示自我,共享成功! 使用System.Net.Mail发送邮件,vs2005与vs2008存在差别?
扣出MSLinqToSQLGenerator的基类,可用于开发自定义工具(custom tool)
分享 共赢 · 2008-07-19 · via 博客园 - 分享 共赢

    代码有小小整理过

namespace CodeGenerator
{
    
using Microsoft.VisualStudio.Shell.Interop;
    
using System;
    
using System.Runtime.InteropServices;

    
internal abstract class BaseCodeGenerator : IVsSingleFileGenerator
    
{
        
private string codeFileNameSpace = string.Empty;
        
private string codeFilePath = string.Empty;
        
private IVsGeneratorProgress codeGeneratorProgress;

        
protected BaseCodeGenerator()
        
{
        }


        
public abstract int DefaultExtension(out string extension);
        
public int Generate(string wszInputFilePath, string bstrInputFileContents, string wszDefaultNamespace, IntPtr[] pbstrOutputFileContents, out uint pbstrOutputFileContentSize, IVsGeneratorProgress pGenerateProgress)
        
{
            
if (bstrInputFileContents == null)
            
{
                
throw new ArgumentNullException(bstrInputFileContents);
            }

            
this.codeFilePath = wszInputFilePath;
            
this.codeFileNameSpace = wszDefaultNamespace;
            
this.codeGeneratorProgress = pGenerateProgress;
            
byte[] source = this.GenerateCode(wszInputFilePath, bstrInputFileContents);
            
if (source == null)
            
{
                pbstrOutputFileContents 
= null;
                pbstrOutputFileContentSize 
= 0;
            }

            
else
            
{
                pbstrOutputFileContentSize 
= (uint) source.Length;
                pbstrOutputFileContents[
0= Marshal.AllocCoTaskMem(source.Length);
                Marshal.Copy(source, 
0, pbstrOutputFileContents[0], source.Length);
            }

            
return 0;
        }


        
protected abstract byte[] GenerateCode(string inputFileName, string inputFileContent);
        
protected virtual void GeneratorErrorCallback(int warning, uint level, string message, uint line, uint column)
        
{
            IVsGeneratorProgress codeGeneratorProgress 
= this.CodeGeneratorProgress;
            
if (codeGeneratorProgress != null)
            
{
                codeGeneratorProgress.GeneratorError(warning, level, message, line, column);
            }

        }


        
internal IVsGeneratorProgress CodeGeneratorProgress
        
{
            
get
            
{
                
return this.codeGeneratorProgress;
            }

        }


        
protected string FileNameSpace
        
{
            
get
            
{
                
return this.codeFileNameSpace;
            }

        }


        
protected string InputFilePath
        
{
            
get
            
{
                
return this.codeFilePath;
            }

        }

    }

}


namespace CodeGenerator
{
    
using Microsoft.VisualStudio.OLE.Interop;
    
using System;
    
using System.CodeDom.Compiler;
    
using System.Collections.Generic;
    
using System.ComponentModel;
    
using System.Runtime.InteropServices;
    
using System.Text;
    
using Microsoft.VisualStudio.Shell;
    
using Microsoft.VisualStudio.Shell.Interop;
    
using System.Diagnostics.CodeAnalysis;
    
using EnvDTE;
    
using VsWebSite;
    
using VSLangProj;
    
using Microsoft.VisualStudio.Designer.Interfaces;
    
using System.IO;

    
public abstract class BaseCodeGeneratorWithSite : BaseCodeGenerator, IObjectWithSite
    
{
        
private CodeDomProvider codeDomProvider;
        
private ServiceProvider serviceProvider;
        
private object site;

        
protected BaseCodeGeneratorWithSite()
        
{
        }


        
protected void AddReferenceDLLsToProject(ICollection<string> referenceDLLs)
        
{
            
string str = AddReferenceDLLToProject(this.SiteServiceProvider, referenceDLLs);
            
if (!EmptyOrSpace(str))
            
{
                
this.GeneratorErrorCallback(01, str, 00);
            }

        }


        
public static bool EmptyOrSpace(string str)
        
{
            
if (str != null)
            
{
                
return (0 >= str.Trim().Length);
            }

            
return true;
        }


        
private static object GetProjectObject(Project containingProject)
        
{
            
object obj2 = containingProject.Object;
            
if (IsWebProject(containingProject) && (obj2 is VSWebSite))
            
{
                
return obj2;
            }

            
if (obj2 is VSProject)
            
{
                
return obj2;
            }

            
return null;
        }


        
public static bool IsWebProject(Project p)
        
{
            
if (p == null)
            
{
                
return false;
            }

            
return (p.Kind == "{E24C65DC-7377-472b-9ABA-BC803B73C61A}");
        }


        
private static void AddReferenceToProjectObject(object projectObj, string referenceDll)
        
{
            
if (projectObj != null)
            
{
                
if (projectObj is VSWebSite)
                
{
                    VSWebSite site 
= projectObj as VSWebSite;
                    site.References.AddFromGAC(referenceDll);
                }

                
else if (projectObj is VSProject)
                
{
                    VSProject project 
= projectObj as VSProject;
                    project.References.Add(referenceDll);
                }

            }

        }


        [SuppressMessage(
"Microsoft.Design""CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Failure only of interest to devs")]
        
public static string AddReferenceDLLToProject(System.IServiceProvider serviceProvider, ICollection<string> referenceDLL)
        
{
            
try
            
{
                
if (referenceDLL.Count == 0)
                
{
                    
return string.Empty;
                }

                
object service = serviceProvider.GetService(typeof(ProjectItem));
                
if (service == null)
                
{
                    
return "Failed to add reference dll.";
                }

                Project containingProject 
= ((ProjectItem)service).ContainingProject;
                
if (containingProject == null)
                
{
                    
return "Failed to add reference dll.";
                }

                
object projectObject = GetProjectObject(containingProject);
                
if (projectObject == null)
                
{
                    
return "Failed to add reference dll.";
                }

                IVsHierarchy hierarchy 
= (IVsHierarchy)serviceProvider.GetService(typeof(IVsHierarchy));
                IVsProjectBuildSystem system 
= hierarchy as IVsProjectBuildSystem;
                
if (system != null)
                
{
                    system.StartBatchEdit();
                }

                
try
                
{
                    
foreach (string str in referenceDLL)
                    
{
                        AddReferenceToProjectObject(projectObject, str);
                    }

                    
if (system != null)
                    
{
                        system.EndBatchEdit();
                    }

                }

                
catch
                
{
                    
if (system != null)
                    
{
                        system.CancelBatchEdit();
                    }

                    
return "Failed to add reference dll.";
                }

            }

            
catch (Exception)
            
{
                
return "Failed to add reference dll.";
            }

            
return string.Empty;
        }


        
protected virtual string CreateExceptionMessage(Exception e)
        
{
            StringBuilder builder 
= new StringBuilder();
            builder.Append((e.Message 
!= null? e.Message : string.Empty);
            
for (Exception exception = e.InnerException; exception != null; exception = exception.InnerException)
            
{
                
string message = exception.Message;
                
if ((message != null&& (message.Length > 0))
                
{
                    builder.Append(
" ");
                    builder.Append(message);
                }

            }

            
return builder.ToString();
        }


        
public string GetGeneratedCodeFile(string inputFileName)
        
{
            
string extension = null;
            
this.DefaultExtension(out extension);
            
return Path.ChangeExtension(inputFileName, extension);
        }


        
public override int DefaultExtension(out string extension)
        
{
            CodeDomProvider codeProvider 
= this.CodeProvider;
            extension 
= "designer." + codeProvider.FileExtension;
            
if (((extension != null&& (extension.Length > 0)) && (extension[0!= '.'))
            
{
                extension 
= "." + extension;
            }

            
return 0;
        }


        
public byte[] StringToByteArray(string inputContents, Encoding encoding)
        
{
            
byte[] preamble = encoding.GetPreamble();
            
byte[] bytes = encoding.GetBytes(inputContents);
            MemoryStream stream 
= new MemoryStream(preamble.Length + bytes.Length); 
            stream.Write(preamble, 
0, preamble.Length);
            stream.Write(bytes, 
0, bytes.Length);
            stream.Position 
= 0L;
            
return stream.ToArray();
        }


        
protected object GetService(Guid serviceGuid)
        
{
            
return this.SiteServiceProvider.GetService(serviceGuid);
        }


        
protected object GetService(Type serviceType)
        
{
            
return this.SiteServiceProvider.GetService(serviceType);
        }


        
public virtual void GetSite(ref Guid riid, out IntPtr pSite)
        
{
            
if (this.site == null)
            
{
                
throw new Win32Exception();
            }

            IntPtr iUnknownForObject 
= Marshal.GetIUnknownForObject(this.site);
            pSite 
= IntPtr.Zero;
            
try
            
{
                Marshal.QueryInterface(iUnknownForObject, 
ref riid, out pSite);
            }

            
finally
            
{
                
if (iUnknownForObject != IntPtr.Zero)
                
{
                    Marshal.Release(iUnknownForObject);
                }

            }

            
if (pSite == IntPtr.Zero)
            
{
                
throw new Win32Exception();
            }

        }


        
public virtual void SetSite(object pUnkSite)
        
{
            
this.site = pUnkSite;
            
this.codeDomProvider = null;
            
this.serviceProvider = null;
        }


        
public static CodeDomProvider GetCodeDomProviderFromServiceProvider(System.IServiceProvider sp)
        
{
            
if (sp == null)
            
{
                
return null;
            }

            ServiceInstance instance 
= new ServiceInstance(sp);
            IVSMDCodeDomProvider iVSMDCodeDomProvider 
= instance.IVSMDCodeDomProvider;
            
if (iVSMDCodeDomProvider == null)
            
{
                
return null;
            }

            
return (iVSMDCodeDomProvider.CodeDomProvider as CodeDomProvider);
        }


        
protected virtual CodeDomProvider CodeProvider
        
{
            
get
            
{
                
if (this.codeDomProvider == null)
                
{
                    
try
                    
{
                        
this.codeDomProvider = GetCodeDomProviderFromServiceProvider(this.SiteServiceProvider);
                    }

                    
catch
                    
{
                        
this.codeDomProvider = CodeDomProvider.CreateProvider("cs");
                    }

                }

                
return this.codeDomProvider;
            }

            
set
            
{
                
if (value == null)
                
{
                    
throw new ArgumentNullException();
                }

                
this.codeDomProvider = value;
            }

        }


        
protected ServiceProvider SiteServiceProvider
        
{
            
get
            
{
                
if (this.serviceProvider == null)
                
{
                    Microsoft.VisualStudio.OLE.Interop.IServiceProvider site 
= this.site as Microsoft.VisualStudio.OLE.Interop.IServiceProvider;
                    
this.serviceProvider = new ServiceProvider(site);
                }

                
return this.serviceProvider;
            }

        }

    }

}


使用的时候重写GenerateCode方法即可