context stringlengths 2.52k 185k | gt stringclasses 1
value |
|---|---|
using System;
using System.Collections.Generic;
using Gtk;
using Moscrif.IDE.Devices;
using Moscrif.IDE.Controls;
using Moscrif.IDE.Workspace;
using Moscrif.IDE.Components;
using Moscrif.IDE.Task;
using MessageDialogs = Moscrif.IDE.Controls.MessageDialog;
using Moscrif.IDE.Iface.Entities;
using Moscrif.IDE.Option;
using Moscrif.IDE.Iface;
using System.Threading;
namespace Moscrif.IDE.Controls.Wizard
{
public partial class PublishDialogWizzard : Gtk.Dialog
{
private Notebook notebook;
private Project project;
private CheckButton chbOpenOutputDirectory;
private CheckButton chbSignApp;
private CheckButton chbIncludeAllResolution;
private CheckButton chbDebugLog;
Thread secondTaskThread;
TaskList tlpublish;
//PublishAsynchronTask pt;
ListStore storeOutput;
private DropDownRadioButton ddbTypPublish = new DropDownRadioButton();
private DropDownRadioButton ddbTypRemote = new DropDownRadioButton();
DropDownButton.ComboItemSet publishItems = new DropDownButton.ComboItemSet ();
DropDownButton.ComboItemSet remoteItems = new DropDownButton.ComboItemSet ();
Label lblRemote = new Label("Remote: ");
DropDownButton.ComboItem ciDeviceTesting ;
DropDownButton.ComboItem ciDeviceDistribution;
private bool runningPublish = false;
int status = 0;
public PublishDialogWizzard()
{
project = MainClass.Workspace.ActualProject;
this.TransientFor = MainClass.MainWindow;
this.Build();
ciDeviceTesting = new DropDownButton.ComboItem(MainClass.Languages.Translate("device_testing"),0);
ciDeviceDistribution = new DropDownButton.ComboItem(MainClass.Languages.Translate("market_distribution"),1);
btnResetMatrix.Label = MainClass.Languages.Translate("reset_matrix");
chbSignApp= new CheckButton( MainClass.Languages.Translate("sign_app"));
chbSignApp.Active = MainClass.Workspace.SignApp;
chbSignApp.Toggled += new EventHandler(OnChbSignAppToggled);
chbSignApp.Sensitive = true;//MainClass.Settings.SignAllow;
notebook1.ShowTabs = false;
notebook1.ShowBorder = false;
notebook1.Page = 0;
Table tblHeader = new Table(1,4,false);
ddbTypPublish = new DropDownRadioButton();
ddbTypPublish.Changed+= delegate(object sender, DropDownButton.ChangedEventArgs e)
{
if(e.Item !=null){
int selTyp = (int)e.Item;
if(selTyp == 0){
lblRemote.Visible = true;
ddbTypRemote.Visible = true;
chbSignApp.Sensitive= false;
} else {
if(!MainClass.LicencesSystem.CheckFunction("marketdistribution",this)){
ddbTypPublish.SelectItem(publishItems,ciDeviceTesting);
return;
}
lblRemote.Visible = false;
ddbTypRemote.Visible = false;
chbSignApp.Sensitive= true;
}
MainClass.Workspace.ActualProject.TypPublish = selTyp;
}
};
ddbTypPublish.WidthRequest = 175;
ddbTypPublish.SetItemSet(publishItems);
ddbTypRemote = new DropDownRadioButton();
ddbTypRemote.Changed+= delegate(object sender, DropDownButton.ChangedEventArgs e)
{
if(e.Item !=null){
string ipAdress = (string)e.Item;
MainClass.Settings.RemoteIpAdress = ipAdress;
}
};
ddbTypRemote.WidthRequest = 175;
ddbTypRemote.SetItemSet(remoteItems);
publishItems.Add(ciDeviceTesting);
publishItems.Add(ciDeviceDistribution);
ddbTypPublish.SelectItem(publishItems,ciDeviceTesting);
/*if(MainClass.Workspace.ActualProject.TypPublish ==1)
ddbTypPublish.SelectItem(publishItems,ciDeviceDistribution);
else
ddbTypPublish.SelectItem(publishItems,ciDeviceTesting);*/
DropDownButton.ComboItem addRemote0 = new DropDownButton.ComboItem(MainClass.Languages.Translate("remote_none"),"0");
remoteItems.Add(addRemote0);
bool findSelect = false;
List<string> listIp = Moscrif.IDE.Tool.Network.GetIpAdress();
foreach (string ip in listIp){
DropDownButton.ComboItem addIP = new DropDownButton.ComboItem(ip,ip);
remoteItems.Add(addIP);
/*if(ip== MainClass.Settings.RemoteIpAdress){
ddbTypRemote.SelectItem(remoteItems,addIP);
findSelect = true;
}*/
}
if(!findSelect){
ddbTypRemote.SelectItem(remoteItems,addRemote0);;
}
tblHeader.Attach(new Label("Publish: "),0,1,0,1,AttachOptions.Fill,AttachOptions.Fill,5,0);
tblHeader.Attach(ddbTypPublish,1,2,0,1,AttachOptions.Fill,AttachOptions.Fill,0,0);
tblHeader.Attach(lblRemote,2,3,0,1,AttachOptions.Fill,AttachOptions.Fill,5,0);
tblHeader.Attach(ddbTypRemote,3,4,0,1,AttachOptions.Fill,AttachOptions.Fill,0,0);
this.vbox2.PackStart(tblHeader,false,false,0);
storeOutput = new ListStore (typeof (string), typeof (string), typeof (Gdk.Pixbuf),typeof (bool));
nvOutput.Model = storeOutput;
Gtk.CellRendererText collumnRenderer = new Gtk.CellRendererText();
//nvOutput.AppendColumn ("", new Gtk.CellRendererPixbuf (), "pixbuf", 2);
nvOutput.AppendColumn ("", collumnRenderer, "text", 0);
nvOutput.AppendColumn ("", collumnRenderer, "text", 1);
nvOutput.Columns[0].FixedWidth = 200;
nvOutput.Columns[1].Expand = true;
//nvOutput.Columns[0].SetCellDataFunc(collumnRenderer, new Gtk.TreeCellDataFunc(RenderOutput));
//nvOutput.Columns[1].SetCellDataFunc(collumnRenderer, new Gtk.TreeCellDataFunc(RenderOutput));
this.Title = MainClass.Languages.Translate("publish_title" , project.ProjectName);
if(project.ProjectUserSetting.CombinePublish == null || project.ProjectUserSetting.CombinePublish.Count==0){
project.GeneratePublishCombination();
}
if(project.DevicesSettings == null || project.DevicesSettings.Count == 0)
project.GenerateDevices();
foreach (Rule rl in MainClass.Settings.Platform.Rules){
if( (rl.Tag == -1 ) && !MainClass.Settings.ShowUnsupportedDevices) continue;
if( (rl.Tag == -2 ) && !MainClass.Settings.ShowDebugDevices) continue;
Device dvc = project.DevicesSettings.Find(x => x.TargetPlatformId == rl.Id);
if (dvc == null) {
Console.WriteLine("generate device -{0}",rl.Id);
dvc = new Device();
dvc.TargetPlatformId = rl.Id;
dvc.PublishPropertisMask = project.GeneratePublishPropertisMask(rl.Id);
project.DevicesSettings.Add(dvc);
}
}
project.Save();
notebook = new Notebook();
GenerateNotebookPages();
this.vbox2.PackStart(notebook,true,true,0);//PackEnd
VBox vbox1 = new VBox();
chbOpenOutputDirectory = new CheckButton( MainClass.Languages.Translate("open_open_directory_after_publish"));
chbOpenOutputDirectory.Toggled += new EventHandler(OnChbOpenOutputDirectoryToggled);
chbIncludeAllResolution = new CheckButton( MainClass.Languages.Translate("include_all_resolution"));
chbIncludeAllResolution.Active = project.IncludeAllResolution;
chbIncludeAllResolution.Sensitive = false;
chbIncludeAllResolution.Toggled+= delegate {
project.IncludeAllResolution =chbIncludeAllResolution.Active;
};
vbox1.PackStart(chbIncludeAllResolution,false,false,0);
vbox3.PackEnd(chbOpenOutputDirectory,false,false,0);
chbDebugLog = new Gtk.CheckButton(MainClass.Languages.Translate("debug_log_publish"));
chbDebugLog.Active = MainClass.Settings.LogPublish;
chbDebugLog.Toggled+= delegate {
MainClass.Settings.LogPublish = chbDebugLog.Active;
};
vbox1.PackEnd(chbDebugLog,false,false,0);
this.vbox2.PackEnd(vbox1,false,false,0);
VBox hbox = new VBox();
hbox.PackStart(chbSignApp,false,false,0);
this.vbox2.PackEnd(hbox,false,false,0);
this.ShowAll();
int cpage = project.ProjectUserSetting.PublishPage;
notebook.SwitchPage += delegate(object o, SwitchPageArgs args) {
project.ProjectUserSetting.PublishPage = notebook.CurrentPage;
NotebookLabel nl = (NotebookLabel)notebook.GetTabLabel(notebook.CurrentPageWidget);
chbIncludeAllResolution.Sensitive = false;
if(nl.Tag == null) return;
Device d = project.DevicesSettings.Find(x=>(int)x.Devicetype==(int)nl.Tag);
if(d!=null){
if(d.Includes != null){
if(d.Includes.Skin!=null){
if(!String.IsNullOrEmpty(d.Includes.Skin.Name))
chbIncludeAllResolution.Sensitive = true;
}
}
}
};
chbOpenOutputDirectory.Active = MainClass.Settings.OpenOutputAfterPublish;
notebook.CurrentPage =cpage;
btnNext.GrabFocus();
}
private void GenerateNotebookPages(){
string platformName = MainClass.Settings.Platform.Name;
foreach(Rule rl in MainClass.Settings.Platform.Rules){
bool iOsNoMac = false;
if( (rl.Tag == -1 ) && !MainClass.Settings.ShowUnsupportedDevices) continue;
if( (rl.Tag == -2 ) && !MainClass.Settings.ShowDebugDevices) continue;
bool validDevice = true;
if(!Device.CheckDevice(rl.Specific) ){
Tool.Logger.Debug("Invalid Device " + rl.Specific);
validDevice = false;
}
ScrolledWindow sw= new ScrolledWindow();
sw.ShadowType = ShadowType.EtchedOut;
TreeView tvList = new TreeView();
List<CombinePublish> lcp = project.ProjectUserSetting.CombinePublish.FindAll(x=> x.combineRule.FindIndex(y=>y.ConditionName==platformName && y.RuleId == rl.Id) >-1);
List<CombinePublish> lcpDennied = new List<CombinePublish>();
string deviceName = rl.Name;
int deviceTyp = rl.Id;
ListStore ls = new ListStore(typeof(bool),typeof(string),typeof(CombinePublish),typeof(string),typeof(bool));
string ico="empty.png";
switch (deviceTyp) {
case (int)DeviceType.Android_1_6:{
ico = "android.png";
break;}
case (int)DeviceType.Android_2_2:{
ico = "android.png";
break;}
case (int)DeviceType.Bada_1_0:
case (int)DeviceType.Bada_1_1:
case (int)DeviceType.Bada_1_2:
case (int)DeviceType.Bada_2_0:{
ico = "bada.png";
break;}
case (int)DeviceType.Symbian_9_4:{
ico = "symbian.png";
break;}
case (int)DeviceType.iOS_5_0:{
ico = "apple.png";
if(!MainClass.Platform.IsMac){
iOsNoMac = true;
}
break;
}
case (int)DeviceType.PocketPC_2003SE:
case (int)DeviceType.WindowsMobile_5:
case (int)DeviceType.WindowsMobile_6:{
ico = "windows.png";
break;}
case (int)DeviceType.Windows:{
ico = "win32.png";
break;}
case (int)DeviceType.MacOs:{
ico = "macos.png";
break;}
}
List<CombinePublish> tmp = lcp.FindAll(x=>x.IsSelected == true);
NotebookLabel nl = new NotebookLabel(ico,String.Format("{0} ({1})",deviceName,tmp.Count ));
nl.Tag=deviceTyp;
if(iOsNoMac){
Label lbl=new Label(MainClass.Languages.Translate("ios_available_Mac"));
Pango.FontDescription customFont = Pango.FontDescription.FromString(MainClass.Settings.ConsoleTaskFont);
customFont.Weight = Pango.Weight.Bold;
lbl.ModifyFont(customFont);
notebook.AppendPage(lbl, nl);
continue;
}
if(!validDevice){
Label lbl=new Label(MainClass.Languages.Translate("publish_tool_missing"));
Pango.FontDescription customFont = Pango.FontDescription.FromString(MainClass.Settings.ConsoleTaskFont);
customFont.Weight = Pango.Weight.Bold;
lbl.ModifyFont(customFont);
notebook.AppendPage(lbl, nl);
continue;
}
;
CellRendererToggle crt = new CellRendererToggle();
crt.Activatable = true;
crt.Sensitive = true;
tvList.AppendColumn ("", crt, "active", 0);
Gtk.CellRendererText fileNameRenderer = new Gtk.CellRendererText();
Gtk.CellRendererText collumnResolRenderer = new Gtk.CellRendererText();
tvList.AppendColumn(MainClass.Languages.Translate("file_name"),fileNameRenderer, "text", 1);
tvList.AppendColumn(MainClass.Languages.Translate("resolution_f1"), collumnResolRenderer, "text", 1);
tvList.Columns[1].SetCellDataFunc(fileNameRenderer, new Gtk.TreeCellDataFunc(RenderCombine));
tvList.Columns[2].SetCellDataFunc(collumnResolRenderer, new Gtk.TreeCellDataFunc(RenderResolution));
// povolene resolution pre danu platformu
PlatformResolution listPR = MainClass.Settings.PlatformResolutions.Find(x=>x.IdPlatform ==deviceTyp);
Device dvc = project.DevicesSettings.Find(x=>x.TargetPlatformId ==deviceTyp);
string stringTheme = "";
List<System.IO.DirectoryInfo> themeResolution = new List<System.IO.DirectoryInfo>(); // resolution z adresara themes po novom
if((project.NewSkin) && (dvc != null)){
Skin skin =dvc.Includes.Skin;
if((skin != null) && ( !String.IsNullOrEmpty(skin.Name)) && (!String.IsNullOrEmpty(skin.Theme)) ){
string skinDir = System.IO.Path.Combine(MainClass.Workspace.RootDirectory, MainClass.Settings.SkinDir);
stringTheme = System.IO.Path.Combine(skinDir,skin.Name);
stringTheme = System.IO.Path.Combine(stringTheme, "themes");
stringTheme = System.IO.Path.Combine(stringTheme, skin.Theme);
if (System.IO.Directory.Exists(stringTheme)){
System.IO.DirectoryInfo di = new System.IO.DirectoryInfo(stringTheme);
themeResolution = new List<System.IO.DirectoryInfo>(di.GetDirectories());
}
}
}
crt.Toggled += delegate(object o, ToggledArgs args) {
if((deviceTyp == (int)DeviceType.Windows)||(deviceTyp == (int)DeviceType.MacOs)){
if(!MainClass.LicencesSystem.CheckFunction("windowsandmac",this)){
return;
}
}
TreeIter iter;
if (ls.GetIter (out iter, new TreePath(args.Path))) {
bool old = (bool) ls.GetValue(iter,0);
CombinePublish cp =(CombinePublish) ls.GetValue(iter,2);
cp.IsSelected = !old;
ls.SetValue(iter,0,!old);
List<CombinePublish> tmp2 = lcp.FindAll(x=>x.IsSelected == true);
nl.SetLabel (String.Format("{0} ({1})",deviceName,tmp2.Count ));
//if(dvc == null) return;
//if(dvc.Includes == null) return;
if(dvc.Includes.Skin == null) return;
if(String.IsNullOrEmpty(dvc.Includes.Skin.Name) || String.IsNullOrEmpty(dvc.Includes.Skin.Theme)) return;
if(cp.IsSelected){
// Najdem ake je rozlisenie v danej combinacii
CombineCondition cc = cp.combineRule.Find(x=>x.ConditionId == MainClass.Settings.Resolution.Id);
if(cc == null) return; /// nema ziadne rozlisenie v combinacii
int indxResol = themeResolution.FindIndex(x=>x.Name.ToLower() == cc.RuleName.ToLower());
if(indxResol<0){
// theme chyba prislusne rozlisenie
string error =String.Format("Invalid {0} Skin and {1} Theme, using in {2}. Missing resolutions: {3}. ",dvc.Includes.Skin.Name,dvc.Includes.Skin.Theme,deviceName,cc.RuleName.ToLower());
MainClass.MainWindow.OutputConsole.WriteError(error+"\n");
List<string> lst = new List<string>();
lst.Add(error);
MainClass.MainWindow.ErrorWritte("","",lst);
}
}
}
};
int cntOfAdded = 0;
foreach (CombinePublish cp in lcp){
bool isValid = cp.IsSelected;
if (!validDevice) isValid = false;
// Najdem ake je rozlisenie v danej combinacii
CombineCondition cc = cp.combineRule.Find(x=>x.ConditionId == MainClass.Settings.Resolution.Id);
if(cc == null) continue; /// nema ziadne rozlisenie v combinacii
int indx = MainClass.Settings.Resolution.Rules.FindIndex(x=> x.Id == cc.RuleId );
if(indx<0) continue; /// rozlisenie pouzite v danej combinacii nexistuje
if(cc!= null){
bool isValidResolution = false;
//ak nema definovane ziadne povolenia, tak povolene su vsetky
if((listPR==null) || (listPR.AllowResolution == null) ||
(listPR.AllowResolution.Count<1)){
isValidResolution = true;
} else {
isValidResolution = listPR.IsValidResolution(cc.RuleId);
}
if(isValidResolution){
// po novom vyhodom aj tie ktore niesu v adresaru themes - pokial je thema definovana
if((project.NewSkin) && (themeResolution.Count > 0)){
//cntResolution = 0;
int indxResol = themeResolution.FindIndex(x=>x.Name.ToLower() == cc.RuleName.ToLower());
if(indxResol>-1){
ls.AppendValues(isValid,cp.ProjectName,cp,cp.ProjectName,true);
cntOfAdded++;
} else {
lcpDennied.Add(cp);
}
} else {
ls.AppendValues(isValid,cp.ProjectName,cp,cp.ProjectName,true);
cntOfAdded++;
}
} else {
lcpDennied.Add(cp);
}
}
//}
}
// pridam tie zakazane, ktore su vybrate na publish
foreach (CombinePublish cp in lcpDennied){
if(cp.IsSelected){
ls.AppendValues(cp.IsSelected,cp.ProjectName,cp,cp.ProjectName,false);
cntOfAdded++;
}
}
if(cntOfAdded == 0){
MainClass.MainWindow.OutputConsole.WriteError(String.Format("Missing publish settings for {0}.\n",deviceName));
}
bool showAll = false;
tvList.ButtonReleaseEvent += delegate(object o, ButtonReleaseEventArgs args){
if (args.Event.Button == 3) {
TreeSelection ts = tvList.Selection;
Gtk.TreePath[] selRow = ts.GetSelectedRows();
if(selRow.Length<1){
TreeIter tiFirst= new TreeIter();
ls.GetIterFirst(out tiFirst);
tvList.Selection.SelectIter(tiFirst);
selRow = ts.GetSelectedRows();
}
if(selRow.Length<1) return;
Gtk.TreePath tp = selRow[0];
TreeIter ti = new TreeIter();
ls.GetIter(out ti,tp);
CombinePublish combinePublish= (CombinePublish)ls.GetValue(ti,2);
if(combinePublish!=null){
Menu popupMenu = new Menu();
if(!showAll){
MenuItem miShowDenied = new MenuItem( MainClass.Languages.Translate("show_denied" ));
miShowDenied.Activated+= delegate(object sender, EventArgs e) {
// odoberem zakazane, ktore sa zobrazuju kedze su zaceknute na publish
List<TreeIter> lst= new List<TreeIter>();
ls.Foreach((model, path, iterr) => {
bool cp =(bool) ls.GetValue(iterr,4);
bool selected =(bool) ls.GetValue(iterr,0);
if(!cp && selected){
lst.Add(iterr);
}
return false;
});
foreach(TreeIter ti2 in lst){
TreeIter ti3 =ti2;
ls.Remove(ref ti3);
}
// pridam zakazane
if( (lcpDennied==null) || (lcpDennied.Count<1))
return;
foreach (CombinePublish cp in lcpDennied){
ls.AppendValues(cp.IsSelected,cp.ProjectName,cp,cp.ProjectName,false);
}
showAll = true;
};
popupMenu.Append(miShowDenied);
} else {
MenuItem miHideDenied = new MenuItem( MainClass.Languages.Translate("hide_denied" ));
miHideDenied.Activated+= delegate(object sender, EventArgs e) {
List<TreeIter> lst= new List<TreeIter>();
ls.Foreach((model, path, iterr) => {
bool cp =(bool) ls.GetValue(iterr,4);
bool selected =(bool) ls.GetValue(iterr,0);
if(!cp && !selected){
lst.Add(iterr);
}
return false;
});
foreach(TreeIter ti2 in lst){
TreeIter ti3 =ti2;
ls.Remove(ref ti3);
}
showAll = false;
};
popupMenu.Append(miHideDenied);
}
popupMenu.Append(new SeparatorMenuItem());
MenuItem miCheckAll = new MenuItem( MainClass.Languages.Translate("check_all" ));
miCheckAll.Activated+= delegate(object sender, EventArgs e) {
if((deviceTyp == (int)DeviceType.Windows)||(deviceTyp == (int)DeviceType.MacOs)){
if(!MainClass.LicencesSystem.CheckFunction("windowsandmac",this)){
return;
}
}
int cnt = 0;
ls.Foreach((model, path, iterr) => {
CombinePublish cp =(CombinePublish) ls.GetValue(iterr,2);
cp.IsSelected = true;
ls.SetValue(iterr,0,true);
cnt ++;
return false;
});
nl.SetLabel (String.Format("{0} ({1})",deviceName,cnt ));
};
popupMenu.Append(miCheckAll);
MenuItem miUnCheckAll = new MenuItem( MainClass.Languages.Translate("uncheck_all" ));
miUnCheckAll.Activated+= delegate(object sender, EventArgs e) {
ls.Foreach((model, path, iterr) => {
CombinePublish cp =(CombinePublish) ls.GetValue(iterr,2);
cp.IsSelected = false;
ls.SetValue(iterr,0,false);
return false;
});
nl.SetLabel (String.Format("{0} ({1})",deviceName,0 ));
};
popupMenu.Append(miUnCheckAll);
popupMenu.Popup();
popupMenu.ShowAll();
}
}
};
tvList.Model = ls;
if (!validDevice) tvList.Sensitive = false;
sw.Add(tvList);
notebook.AppendPage(sw, nl);
}
}
private void RenderOutput(Gtk.TreeViewColumn column, Gtk.CellRenderer cell, Gtk.TreeModel model, Gtk.TreeIter iter)
{
bool isError = (bool) model.GetValue (iter, 3);
if (isError) {
(cell as Gtk.CellRendererText).Foreground = "Red";
} else {
(cell as Gtk.CellRendererText).Foreground = "Black";
}
}
private void RenderResolution(Gtk.TreeViewColumn column, Gtk.CellRenderer cell, Gtk.TreeModel model, Gtk.TreeIter iter)
{
CombinePublish cp = (CombinePublish) model.GetValue (iter, 2);
bool type = (bool) model.GetValue (iter, 4);
// Najdem ake je rozlisenie v danej combinacii
CombineCondition cc = cp.combineRule.Find(x=>x.ConditionId == MainClass.Settings.Resolution.Id);
if(cc == null) return;
Rule rl = MainClass.Settings.Resolution.Rules.Find(x=>x.Id == cc.RuleId);
if(rl == null) {
return;
}
if(cc == null) return; /// nema ziadne rozlisenie v combinacii
Pango.FontDescription fd = new Pango.FontDescription();
(cell as Gtk.CellRendererText).Text =String.Format("{0}x{1}",rl.Width,rl.Height);
if (!type) {
fd.Style = Pango.Style.Italic;
} else {
fd.Style = Pango.Style.Normal;
}
(cell as Gtk.CellRendererText).FontDesc = fd;
}
private void RenderCombine(Gtk.TreeViewColumn column, Gtk.CellRenderer cell, Gtk.TreeModel model, Gtk.TreeIter iter)
{
bool type = (bool) model.GetValue (iter, 4);
Pango.FontDescription fd = new Pango.FontDescription();
if (!type) {
fd.Style = Pango.Style.Italic;
} else {
fd.Style = Pango.Style.Normal;
}
(cell as Gtk.CellRendererText).FontDesc = fd;
//(cell as Gtk.CellRendererText).Text = type;
}
protected virtual void OnChbSignAppToggled (object sender, System.EventArgs e)
{
if(chbSignApp.Active){
if(MainClass.LicencesSystem.CheckFunction("signapp",this)){
MainClass.Workspace.SignApp = chbSignApp.Active;
} else {
chbSignApp.Active = false;
}
}
}
protected virtual void OnChbOpenOutputDirectoryToggled (object sender, System.EventArgs e)
{
MainClass.Settings.OpenOutputAfterPublish = chbOpenOutputDirectory.Active;
}
private bool LogginAndVerification(){
LoggUser vc = new LoggUser();
if((MainClass.User == null)||(string.IsNullOrEmpty(MainClass.User.Token))){
LoginRegisterDialog ld = new LoginRegisterDialog(this);
int res = ld.Run();
if (res == (int)Gtk.ResponseType.Cancel){
ld.Destroy();
return false;
}
ld.Destroy();
}
if(!vc.Ping(MainClass.User.Token)){
MessageDialogs md = new MessageDialogs(MessageDialogs.DialogButtonType.Ok, MainClass.Languages.Translate("invalid_login_f1"), "", Gtk.MessageType.Error,this);
md.ShowDialog();
LoginRegisterDialog ld = new LoginRegisterDialog(this);
int res = ld.Run();
if (res == (int)Gtk.ResponseType.Cancel){
ld.Destroy();
return false;
}else if(res == (int)Gtk.ResponseType.Ok){
ld.Destroy();
return true;
}
}
return true;
}
protected void OnBtnNextClicked (object sender, EventArgs e)
{
if(notebook1.Page == 0){
//btnResetMatrix.Visib
List<CombinePublish> list =project.ProjectUserSetting.CombinePublish.FindAll(x=>x.IsSelected==true);
if(list==null || list.Count<1){
MessageDialogs md = new MessageDialogs(MessageDialogs.DialogButtonType.Ok, MainClass.Languages.Translate("pleas_select_application"), "", Gtk.MessageType.Error,this);
md.ShowDialog();
return;
}
int selectTyp = (int)ddbTypPublish.CurrentItem;
if((selectTyp != 0) && (MainClass.Workspace.SignApp)){
if(!LogginAndVerification()){
return;
}
}
notebook1.Page = 1;
btnResetMatrix.Sensitive = false;
btnNext.Sensitive = false;
btnCancel.Label = "_Close";
RunPublishTask(list);
}
}
private void RunPublishTask(List<CombinePublish> list){
LoggingInfo log = new LoggingInfo();
log.LoggWebThread(LoggingInfo.ActionId.IDEPublish,project.ProjectName);
int selectTyp = (int)ddbTypPublish.CurrentItem;
if((selectTyp == 0) || (!MainClass.Workspace.SignApp)){
tlpublish = new TaskList();
tlpublish.TasksList = new System.Collections.Generic.List<Moscrif.IDE.Task.ITask>();
string selectRemote = (string)ddbTypRemote.CurrentItem;
Console.WriteLine("selectRemote-"+selectRemote);
if(selectRemote != "0"){
AppFile appF = MainClass.Workspace.ActualProject.AppFile;
appF.Remote_Console =selectRemote+":"+MainClass.Settings.SocetServerPort;
appF.Save();
Console.WriteLine("MainClass.Workspace.ActualProject.AppFile.Remote_Console-"+MainClass.Workspace.ActualProject.AppFile.Remote_Console);
} else {
AppFile appF = MainClass.Workspace.ActualProject.AppFile;
appF.Remote_Console ="";
appF.Save();
}
PublishAsynchronTask pt = new PublishAsynchronTask();
pt.ParentWindow = this;
pt.EndTaskWrite+= MainClass.MainWindow.EndTaskWritte;
pt.EndTaskWrite+= delegate(object sender, string name, string status, List<TaskMessage> errors) {
runningPublish = false;
btnCancel.Label = "_Close";
if(selectRemote != "0"){
AppFile appF = MainClass.Workspace.ActualProject.AppFile;
appF.Remote_Console ="";
appF.Save();
}
};
pt.ErrorWrite+= MainClass.MainWindow.ErrorTaskWritte;
pt.LogWrite+= MainClass.MainWindow.LogTaskWritte;
pt.WriteStep+= delegate(object sender, StepEventArgs e) {
storeOutput.AppendValues(e.Message1,e.Message2,null,e.IsError);
if(status!=1)
status = e.Status;
while (Gtk.Application.EventsPending ())
Gtk.Application.RunIteration ();
};
pt.Initialize(list);
tlpublish.TasksList.Add(pt);
secondTaskThread = new Thread(new ThreadStart(tlpublish.ExecuteTaskOnlineWrite ));
secondTaskThread.Name = "Publish Second Task";
secondTaskThread.IsBackground = true;
runningPublish = true;
btnCancel.Label = "_Cancel";
secondTaskThread.Start();
} else {
tlpublish = new TaskList();
tlpublish.TasksList = new System.Collections.Generic.List<Moscrif.IDE.Task.ITask>();
SignPublishAsynchronTask pt = new SignPublishAsynchronTask();
pt.ParentWindow = this;
pt.EndTaskWrite+= MainClass.MainWindow.EndTaskWritte;
pt.EndTaskWrite+= delegate(object sender, string name, string status, List<TaskMessage> errors) {
runningPublish = false;
btnCancel.Label = "_Close";
};
pt.ErrorWrite+= MainClass.MainWindow.ErrorTaskWritte;
pt.LogWrite+= MainClass.MainWindow.LogTaskWritte;
pt.WriteStep+= delegate(object sender, StepEventArgs e) {
storeOutput.AppendValues(e.Message1,e.Message2,null,e.IsError);
if(status!=1)
status = e.Status;
while (Gtk.Application.EventsPending ())
Gtk.Application.RunIteration ();
};
pt.Initialize(list);
tlpublish.TasksList.Add(pt);
secondTaskThread = new Thread(new ThreadStart(tlpublish.ExecuteTaskOnlineWrite ));
secondTaskThread.Name = "Publish Second Task";
secondTaskThread.IsBackground = true;
runningPublish = true;
btnCancel.Label = "_Cancel";
secondTaskThread.Start();
}
}
protected void OnBtnResetMatrixClicked (object sender, EventArgs e)
{
project.GeneratePublishCombination();
int page = notebook.NPages;
for (int i = page ; i>=0 ;i--){
notebook.RemovePage(i);
}
GenerateNotebookPages();
notebook.ShowAll();
}
protected void OnBtnCancelClicked (object sender, EventArgs e)
{
if(runningPublish){
if(tlpublish!= null){
storeOutput.AppendValues(MainClass.Languages.Translate("waiting_cancel"),"",null,false);
tlpublish.StopAsynchronTask();
}
return;
}
if(notebook1.Page == 1){
if((MainClass.Settings.OpenOutputAfterPublish) && (status==1) ){
if (!String.IsNullOrEmpty(project.ProjectOutput)){
MainClass.Tools.OpenFolder(project.OutputMaskToFullPath);
}
}
}
this.Respond(ResponseType.Close);
}
}
}
| |
using System;
using System.Diagnostics;
using System.Net;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using DeOps.Services.Location;
using DeOps.Implementation.Dht;
using DeOps.Implementation.Protocol;
using DeOps.Implementation.Protocol.Comm;
using DeOps.Implementation.Protocol.Net;
namespace DeOps.Implementation.Transport
{
public enum RudpState {Connecting, Connected, Finishing, Closed};
public enum CloseReason
{
NORMAL_CLOSE = 0x0,
YOU_CLOSED = 0x1,
TIMEOUT = 0x2,
LARGE_PACKET = 0x3,
TOO_MANY_RESENDS = 0x4
};
public class RudpSocket
{
OpCore Core;
DhtNetwork Network;
RudpSession Session;
// properties
public RudpAddress PrimaryAddress;
public Dictionary<int, RudpAddress> AddressMap = new Dictionary<int, RudpAddress>();
public ushort PeerID;
public ushort RemotePeerID;
public RudpState State = RudpState.Connecting;
public bool Listening;
byte CurrentSeq;
MovingAvg AvgLatency = new MovingAvg(10);
MovingAvg AvgBytesSent = new MovingAvg(10);
const int MAX_WINDOW_SIZE = 50;
public const int SEND_BUFFER_SIZE = 64 * 1024;
const int CHUNK_SIZE = 1024;
const int MAX_CHUNK_SIZE = 1024;
const int RECEIVE_BUFFER_SIZE = MAX_CHUNK_SIZE * MAX_WINDOW_SIZE;
// connecting
bool SynAckSent;
bool SynAckReceieved;
// sending
Queue<TrackPacket> SendPacketMap = new Queue<TrackPacket>();
int SendWindowSize = 5;
public int SendBuffLength;
public bool RudpSendBlock;
object SendSection = new object();
public byte[] SendBuff = new byte[SEND_BUFFER_SIZE];
DateTime LastSend;
// receiving
SortedDictionary<byte, RudpPacket> RecvPacketMap = new SortedDictionary<byte, RudpPacket>(); // needs to be locked because used by timer and network threads
byte HighestSeqRecvd;
byte NextSeq;
int RecvBuffLength;
byte[] RecvBuff = new byte[RECEIVE_BUFFER_SIZE];
// acks
Hashtable AckMap = Hashtable.Synchronized(new Hashtable());
Queue AckOrder = Queue.Synchronized(new Queue());
int InOrderAcks;
int ReTransmits;
// finishing
bool FinSent, FinReceived;
int FinTimeout;
RudpPacket FinPacket;
// bandwidth
public BandwidthLog Bandwidth;
public RudpSocket(RudpSession session, bool listening)
{
Session = session;
Core = session.Core;
Network = Session.Network;
Bandwidth = new BandwidthLog(Core.RecordBandwidthSeconds);
Listening = listening;
PeerID = (ushort)Core.RndGen.Next(1, ushort.MaxValue);
lock (Session.RudpControl.SocketMap)
Session.RudpControl.SocketMap[PeerID] = this;
}
public void Connect()
{
AvgLatency.Input(500); // set retry for syn to half sec
AvgLatency.Next();
SendSyn();
}
public void AddAddress(RudpAddress address)
{
if (!AddressMap.ContainsKey(address.GetHashCode()))
{
address.Ident = (uint) Core.RndGen.Next();
AddressMap[address.GetHashCode()] = address;
}
if (PrimaryAddress == null)
PrimaryAddress = address;
}
public void Send(byte[] data, ref int length)
{
if (State != RudpState.Connected)
return;// -1;
//Session.Log("Send " + buffLength + " bytes");
// multiplied by 2 so room to expand and basically 2 second buffer
int bufferSize = GetSendBuffSize();
int copySize = 0;
//int MaxBufferSize = SEND_BUFFER_SIZE;//m_SendWindowSize * CHUNK_SIZE;
lock (SendSection)
{
if (SendBuffLength >= bufferSize)
{
RudpSendBlock = true;
return;// -1;
}
int space = bufferSize - SendBuffLength;
copySize = (space >= length) ? length : space;
Buffer.BlockCopy(data, 0, SendBuff, SendBuffLength, copySize);
SendBuffLength += copySize;
if (copySize != length)
RudpSendBlock = true;
}
if (copySize > 0)
{
// length and session buffers modified here (not in calling function) because
// manageSendWindow -> OnSend -> FlushSend -> Send .. is recursive
length -= copySize;
Buffer.BlockCopy(data, copySize, data, 0, length);
}
ManageSendWindow(); // try to send immedaitely
}
int GetSendBuffSize()
{
int maxBuffSize = AvgBytesSent.GetAverage() * 2;
maxBuffSize = maxBuffSize < 4096 ? 4096 : maxBuffSize;
maxBuffSize = maxBuffSize > SEND_BUFFER_SIZE ? SEND_BUFFER_SIZE : maxBuffSize;
return maxBuffSize;
}
public bool SendBuffLow()
{
// if outstanding bytes are more than 3/4 of the max buffer size, we are low
if (SendBuffLength > GetSendBuffSize() * 3 / 4)
{
RudpSendBlock = true;
return true;
}
return false;
}
public int Receive(byte[] buff, int buffOffset, int buffLen)
{
if(RecvBuffLength > buffLen)
return FinishReceive(buff, buffOffset, buffLen);
lock (RecvPacketMap)
{
ArrayList removeList = new ArrayList();
// copy data from packets
// while next element of map equals next in sequence
foreach (byte seq in RecvPacketMap.Keys) // read keys because they are sorted
{
RudpPacket packet = RecvPacketMap[seq];
// deal with reading in order at 0xFF to zero boundry
if (NextSeq > 0xFF - 25 && packet.Sequence < 25)
continue;
if (packet.Sequence != NextSeq)
break;
if (packet.PacketType == RudpPacketType.Data)
{
int dataSize = packet.Payload.Length;
if (dataSize > MAX_CHUNK_SIZE)
{
Session.Log("Too Large Packet Received Size " + packet.Payload.Length + ", Type Data");
RudpClose(CloseReason.LARGE_PACKET);
return -1;
}
// copy data
packet.Payload.CopyTo(RecvBuff, RecvBuffLength);
RecvBuffLength += packet.Payload.Length;
//Session.Log("Data Recv, Seq " + packet.Sequence.ToString() + ", ID " + packet.PeerID.ToString());
}
else
break;
HighestSeqRecvd = packet.Sequence;
removeList.Add(packet.Sequence);
NextSeq++;
if (RecvBuffLength > buffLen)
break;
}
foreach (byte seq in removeList)
RecvPacketMap.Remove(seq);
}
//Log("Reliable Receive " + NumtoStr(copysize) + ", " + NumtoStr(m_RecvBuffLength) + " left");
return FinishReceive(buff, buffOffset, buffLen);
}
int FinishReceive(byte[] buff, int buffOffset, int buffLen)
{
// copy extra data from recv buffer
int copysize = (RecvBuffLength > buffLen) ? buffLen : RecvBuffLength;
Buffer.BlockCopy(RecvBuff, 0, buff, buffOffset, copysize);
if(copysize != RecvBuffLength)
Buffer.BlockCopy(RecvBuff, copysize, RecvBuff, 0, RecvBuffLength - copysize);
RecvBuffLength -= copysize;
return copysize;
}
public void Close()
{
if (State == RudpState.Connecting)
{
ChangeState(RudpState.Closed);
return;
}
else if(State == RudpState.Connected)
StartFin(CloseReason.NORMAL_CLOSE);
}
void SetConnected()
{
if(Listening)
Session.OnAccept();
else
Session.OnConnect();
}
public void RudpReceive(G2ReceivedPacket raw, RudpPacket packet, bool global)
{
// check if packet meant for another socket
if(packet.PeerID != 0 && packet.PeerID != PeerID)
return;
// check for errors
string error = null;
if(packet.Sequence > HighestSeqRecvd && State == RudpState.Closed) // accept only packets that came before the fin
error = "Packet Received while in Close State ID " + packet.PeerID.ToString() + ", Type " + packet.PacketType.ToString();
else if (packet.Payload.Length > 4096)
{
error = "Too Large Packet Received Size " + packet.Payload.Length.ToString() + ", Type " + packet.PacketType.ToString();
RudpClose(CloseReason.LARGE_PACKET);
}
if( error != null )
{
Session.Log(error);
return;
}
Bandwidth.InPerSec += raw.Root.Data.Length;
// add proxied and direct addresses
// proxied first because that packet has highest chance of being received, no need for retry
// also allows quick udp hole punching
if (raw.ReceivedTcp)
AddAddress(new RudpAddress(raw.Source, raw.Tcp));
AddAddress( new RudpAddress(raw.Source) ); // either direct node, or node's proxy
// received syn, ident 5, from 1001 over tcp
/*string log = "Received " + packet.PacketType.ToString();
if (packet.Ident != 0) log += " ID:" + packet.Ident.ToString();
log += " from " + raw.Source.ToString();
if (raw.Tcp != null)
log += " tcp";
else
log += " udp";
Session.Log(log);*/
if (packet.PacketType == RudpPacketType.Unreliable)
{
Session.UnreliableReceive(packet.Payload);
return;
}
// try to clear up bufffer, helps if full, better than calling this on each return statement
ManageRecvWindow();
// if ACK, PING, or PONG
if (packet.PacketType == RudpPacketType.Ack || packet.PacketType == RudpPacketType.Ping || packet.PacketType == RudpPacketType.Pong)
{
if (packet.PacketType == RudpPacketType.Ack)
ReceiveAck(packet);
if (packet.PacketType == RudpPacketType.Ping)
ReceivePing(packet);
if (packet.PacketType == RudpPacketType.Pong)
ReceivePong(packet);
return;
}
// if SYN, DATA or FIN packet
// stop acking so remote host catches up
if (packet.Sequence > HighestSeqRecvd + MAX_WINDOW_SIZE || RecvPacketMap.Count > MAX_WINDOW_SIZE)
{
//Session.Log("Error Packet Overflow");
return;
}
// Send Ack - cant combine if statements doesnt work
if( AckMap.Contains(packet.Sequence) )
{
//Session.Log("Error Packet Seq " + packet.Sequence.ToString() + " Already Received");
SendAck(packet);
return;
}
// insert into recv map
lock (RecvPacketMap)
{
RecvPacketMap[packet.Sequence] = packet;
}
ManageRecvWindow();
// ack down here so highest received is iterated, syns send own acks
if (packet.PacketType != RudpPacketType.Syn)
SendAck(packet);
}
void SendSyn()
{
RudpPacket syn = new RudpPacket();
lock (SendSection) // ensure queued in right order with right current seq
{
syn.TargetID = Session.UserID;
syn.TargetClient = Session.ClientID;
syn.PeerID = 0;
syn.PacketType = RudpPacketType.Syn;
syn.Sequence = CurrentSeq++;
syn.Payload = RudpSyn.Encode(1, Network.Local.UserID, Network.Local.ClientID, PeerID);
SendPacketMap.Enqueue(new TrackPacket(syn));
}
ManageSendWindow();
}
void ReceiveSyn(RudpPacket packet)
{
RudpSyn syn = new RudpSyn(packet.Payload);
if(RemotePeerID == 0)
RemotePeerID = syn.ConnID;
//Session.Log("Syn Recv, Seq " + packet.Sequence.ToString() + ", ID " + syn.ConnID.ToString());
SendAck(packet); // send ack here also because peerID now set
SynAckSent = true;
if(SynAckSent && SynAckReceieved)
{
Session.Log("Connected (recv syn)");
ChangeState(RudpState.Connected);
SetConnected();
}
}
void SendAck(RudpPacket packet)
{
RudpPacket ack = new RudpPacket();
ack.TargetID = Session.UserID;
ack.TargetClient = Session.ClientID;
ack.PeerID = RemotePeerID;
ack.PacketType = RudpPacketType.Ack;
ack.Sequence = packet.Sequence;
ack.Payload = RudpAck.Encode(HighestSeqRecvd, (byte) (MAX_WINDOW_SIZE - RecvPacketMap.Count));
ack.Ident = packet.Ident;
//Session.Log("Ack Sent, Seq " + ack.Sequence.ToString() + ", ID " + ack.PeerID.ToString() + ", highest " + HighestSeqRecvd.ToString());
if( !AckMap.Contains(ack.Sequence) )
{
AckMap[ack.Sequence] = true;
AckOrder.Enqueue(ack.Sequence);
}
while(AckMap.Count > MAX_WINDOW_SIZE * 2)
AckMap.Remove( AckOrder.Dequeue() );
SendTracked( new TrackPacket(ack) );
}
void ReceiveAck(RudpPacket packet)
{
int latency = 0;
int retries = -1;
// find original packet that was sent
TrackPacket sent = null;
lock (SendSection)
{
foreach (TrackPacket tracked in SendPacketMap)
if (tracked.Packet.Sequence == packet.Sequence)
{
sent = tracked;
break;
}
}
// mark packet as acked
if (sent != null)
{
sent.Target.LastAck = Core.TimeNow;
// connect handshake
if (State == RudpState.Connecting && sent.Packet.PacketType == RudpPacketType.Syn)
{
SynAckReceieved = true;
SetPrimaryAddress(packet.Ident);
if(SynAckSent && SynAckReceieved)
{
Session.Log("Connected (recv ack)");
ChangeState(RudpState.Connected);
SetConnected();
// if data packets received before final connection ack, process them now
ManageRecvWindow();
}
}
if (!sent.Acked)
{
InOrderAcks++;
if (sent.Retries == 0)
{
latency = (int) sent.TimeEllapsed(Core);
latency = latency < 5 ? 5 : latency;
AvgLatency.Input(latency);
AvgLatency.Next();
}
}
retries = sent.Retries;
sent.Acked = true;
}
RudpAck ack = new RudpAck(packet.Payload);
//Session.Log("Ack Recv, Seq " + packet.Sequence.ToString() + ", ID " + packet.PeerID.ToString() + ", highest " + ack.Start.ToString() + ", retries " + retries.ToString() + ", latency " + latency.ToString());
lock (SendSection)
{
// ack possibly un-acked packets
foreach (TrackPacket tracked in SendPacketMap)
{
// ack if start past the zero boundry with sequences behind
if (tracked.Packet.Sequence > 0xFF - 25 && ack.Start < 25)
tracked.Acked = true;
// break start before boundry and sequences ahead are not recvd/acked yet
if (ack.Start > 0xFF - 25 && tracked.Packet.Sequence < 25)
break;
// normal acking procedure
else if (ack.Start >= tracked.Packet.Sequence)
tracked.Acked = true;
else
break;
}
// remove acked, only remove packets from front
while (SendPacketMap.Count > 0 && SendPacketMap.Peek().Acked)
{
// calculate receive speed of remote host by rate they ack
AvgBytesSent.Input(SendPacketMap.Peek().Packet.Payload.Length);
SendPacketMap.Dequeue();
PacketsCompleted++;
}
}
// increase window if packets removed from beginning of buffer
//if(packetsRemoved && SendWindowSize < 25)
// SendWindowSize++;
ManageSendWindow();
}
void SendPing(RudpAddress address)
{
RudpPacket ping = new RudpPacket();
ping.TargetID = Session.UserID;
ping.TargetClient = Session.ClientID;
ping.PeerID = RemotePeerID;
ping.PacketType = RudpPacketType.Ping;
ping.Sequence = 0;
ping.Payload = BitConverter.GetBytes(address.Ident);
//Session.Log("Keep Alive Sent, Seq " + alive.Sequence.ToString() + ", ID " + alive.PeerID.ToString());
TrackPacket tracked = new TrackPacket(ping);
tracked.Target = address;
tracked.SpecialTarget = true;
SendTracked(tracked);
}
void ReceivePing(RudpPacket ping)
{
RudpPacket pong = new RudpPacket();
pong.TargetID = Session.UserID;
pong.TargetClient = Session.ClientID;
pong.PeerID = RemotePeerID;
pong.PacketType = RudpPacketType.Pong;
pong.Sequence = 0;
pong.Payload = ping.Payload;
SendTracked(new TrackPacket(pong));
}
void ReceivePong(RudpPacket pong)
{
if (pong.Payload != null)
{
uint ident = BitConverter.ToUInt32(pong.Payload, 0);
SetPrimaryAddress(ident);
}
}
private void SetPrimaryAddress(uint ident)
{
foreach (RudpAddress address in AddressMap.Values)
if (address.Ident == ident)
{
address.LastAck = Core.TimeNow;
// if primary address needs to be reset, replace with this one
// (which would be first/fastest received)
if (PrimaryAddress.Reset)
{
PrimaryAddress.Reset = false;
PrimaryAddress = address;
}
break;
}
}
void StartFin(CloseReason reason)
{
FinPacket = new RudpPacket();
lock (SendSection) // ensure queued in right order with right current seq
{
FinPacket.TargetID = Session.UserID;
FinPacket.TargetClient = Session.ClientID;
FinPacket.PeerID = RemotePeerID;
FinPacket.PacketType = RudpPacketType.Fin;
FinPacket.Payload = new byte[1] { (byte)reason };
}
ChangeState(RudpState.Finishing);
FinTimeout = 15;
TrySendFin();
//Session.Log("Fin Sent, Seq " + fin.Sequence.ToString() + ", ID " + fin.PeerID.ToString() + ", Reason " + reason.ToString());
ManageSendWindow(); // immediately try to send the fin
}
void TrySendFin()
{
ManageSendWindow(); // try to clear any pending data from buffer
if (SendBuffLength > 0)
return;
FinSent = true;
FinTimeout = 15; // reset timeout - wait for ack
FinPacket.Sequence = CurrentSeq++;
SendPacketMap.Enqueue(new TrackPacket(FinPacket));
}
void ReceiveFin(RudpPacket packet)
{
//Session.Log("Fin Recv, Seq " + packet.Sequence.ToString() + ", ID " + packet.PeerID.ToString() + ", Reason " + packet.Payload[0].ToString());
FinReceived = true;
SendAck(packet);
if(!FinSent)
RudpClose(CloseReason.YOU_CLOSED);
}
void ManageSendWindow()
{
ArrayList retransmit = new ArrayList();
int rtt = AvgLatency.GetAverage();
int outstanding = 0;
lock (SendSection)
{
// iter through send window
foreach (TrackPacket packet in SendPacketMap)
{
if (packet.Acked)
continue;
else if (packet.TimeSent == 0)
retransmit.Add(packet);
// connecting so must be a syn packet
else if (State == RudpState.Connecting)
{
if (packet.TimeEllapsed(Core) > 1000 * 2) // dont combine with above cause then next else if would always run
retransmit.Add(packet);
}
// send packets that havent been sent yet, and ones that need to be retransmitted
else if (packet.TimeEllapsed(Core) > rtt * 2)
retransmit.Add(packet);
// mark as outstanding
else
outstanding++;
}
}
// re-transmit packets
foreach (TrackPacket track in retransmit)
if (outstanding < SendWindowSize)
{
//Session.Log("Re-Send ID " + track.Packet.PeerID.ToString() +
// ", Type " + track.Packet.Type.ToString() +
// ", Seq " + track.Packet.Sequence.ToString() + ", Retries " + track.Retries.ToString() +
// ", Passed " + track.TimeEllapsed().ToString() + " ms");
track.Retries++;
ReTransmits++;
SendTracked(track);
outstanding++;
}
else
break;
lock (SendSection)
{
// send number of packets so that outstanding equals window size
while (outstanding < SendWindowSize && SendBuffLength > 0 && SendPacketMap.Count < MAX_WINDOW_SIZE)
{
int buffLen = (SendBuffLength > CHUNK_SIZE) ? CHUNK_SIZE : SendBuffLength;
RudpPacket data = new RudpPacket();
data.TargetID = Session.UserID;
data.TargetClient = Session.ClientID;
data.PeerID = RemotePeerID;
data.PacketType = RudpPacketType.Data;
data.Sequence = CurrentSeq++;
data.Payload = Utilities.ExtractBytes(SendBuff, 0, buffLen);
// move next data on deck for next send
if (SendBuffLength > buffLen)
Buffer.BlockCopy(SendBuff, buffLen, SendBuff, 0, SendBuffLength - buffLen);
SendBuffLength -= buffLen;
TrackPacket track = new TrackPacket(data);
SendPacketMap.Enqueue(track);
//Session.Log("Data Sent, Seq " + data.Sequence.ToString() + ", ID " + data.PeerID.ToString() + ", Size " + buffLen.ToString());
SendTracked(track);
outstanding++;
}
}
// if we can take more data call onsend
if(SendBuffLength == 0 && RudpSendBlock)
{
//Session.Log("OnSend Called");
RudpSendBlock = false;
Session.OnSend();
}
}
void ManageRecvWindow()
{
bool dataReceived = false;
lock (RecvPacketMap)
{
ArrayList removeList = new ArrayList();
foreach (byte seq in RecvPacketMap.Keys)
{
RudpPacket packet = RecvPacketMap[seq];
// deal with reading in order at 0xFF to zero boundry
if (NextSeq > 0xFF - 25 && packet.Sequence < 25)
continue;
if (packet.Sequence != NextSeq)
break;
if (packet.PacketType == RudpPacketType.Syn)
ReceiveSyn(packet);
else if (packet.PacketType == RudpPacketType.Data)
{
// if local is closing connection, dump pending data so we can get to the fin packet and process it
if (State != RudpState.Finishing)
{
dataReceived = true;
break;
}
}
else if (packet.PacketType == RudpPacketType.Fin)
ReceiveFin(packet);
HighestSeqRecvd = packet.Sequence;
removeList.Add(packet.Sequence);
NextSeq++;
}
foreach (byte seq in removeList)
RecvPacketMap.Remove(seq);
}
// if data waiting to be read
// dont let data receive if still connecting (getting ahead of ourselves) need successful ack return path before we recv data
if(State == RudpState.Connected && (RecvBuffLength > 0 || dataReceived))
Session.OnReceive();
}
public void SendTracked(TrackPacket tracked)
{
if (AddressMap.Count == 0)
return;
RudpAddress target = tracked.SpecialTarget ? tracked.Target : PrimaryAddress;
LastSend = Core.TimeNow;
tracked.TimeSent = Core.TimeNow.Ticks;
tracked.Target = target;
tracked.Packet.SenderID = Network.Local.UserID;
tracked.Packet.SenderClient = Network.Local.ClientID;
if (tracked.Packet.PacketType != RudpPacketType.Syn)
SendPacket(tracked.Packet, target);
else
{
PrimaryAddress.Reset = true;
foreach (RudpAddress address in AddressMap.Values)
{
tracked.Packet.Ident = address.Ident;
tracked.Target = address;
SendPacket(tracked.Packet, address);
}
}
}
public void SendPacket(RudpPacket packet, RudpAddress target)
{
Debug.Assert(packet.Payload != null);
// sending syn to (tracked target) through (address target) udp / tcp
/*string log = "Sending " + tracked.Packet.PacketType.ToString();
if (tracked.Packet.Ident != 0) log += ", ID " + tracked.Packet.Ident.ToString();
log += " to " + Utilities.IDtoBin(tracked.Packet.TargetID).Substring(0, 10);
log += " target address " + target.Address.ToString();*/
int sentBytes = 0;
// same code used in lightComm
if (Core.Firewall != FirewallType.Blocked && target.LocalProxy == null)
{
sentBytes = Network.SendPacket(target.Address, packet);
}
else if (target.Address.TunnelClient != null)
sentBytes = Network.SendTunnelPacket(target.Address, packet);
else
{
packet.ToAddress = target.Address;
TcpConnect proxy = Network.TcpControl.GetProxy(target.LocalProxy);
if (proxy != null)
sentBytes = proxy.SendPacket(packet);
else
sentBytes = Network.TcpControl.SendRandomProxy(packet);
//log += " proxied by local tcp";
}
Bandwidth.OutPerSec += sentBytes;
//Session.Log(log);
}
void RudpClose(CloseReason code)
{
StartFin(code);
Session.OnClose();
}
DateTime NextCheckRoutes;
int PacketsCompleted;
public void SecondTimer()
{
int packetLoss = 0;
if(State == RudpState.Connected)
{
//Debug.WriteLine(Core.User.Settings.UserName + ":" + Core.TimeNow.Second + " - Send Window: " + SendWindowSize + ", Packets Sent: " + PacketsCompleted + ", Retransmits: " + ReTransmits); //crit delete
PacketsCompleted = 0;
// manage send window
packetLoss = 0;
if(InOrderAcks > 0)
packetLoss = ReTransmits * 100 / InOrderAcks;
ReTransmits = 0;
InOrderAcks = 0;
//Session.Log("PL: " + packetLoss.ToString() +
// ", SW: " + SendWindowSize.ToString() +
// ", SQ: " + SendPacketMap.Count.ToString() +
// ", SB: " + SendBuffLength.ToString());
if (packetLoss < 10 && SendWindowSize < MAX_WINDOW_SIZE)
SendWindowSize++;
if(packetLoss > 20 && SendWindowSize > 1)
SendWindowSize /= 2;
// if data waiting to be read
if (State == RudpState.Connected && RecvBuffLength > 0)
Session.OnReceive();
// dead - 5 secs send ping, 10 secs reset primary addr, 15 secs close
DateTime lastRecv = PrimaryAddress.LastAck;
// if nothing received for 15 seconds disconnect
if (Core.TimeNow > lastRecv.AddSeconds(15))
RudpClose(CloseReason.TIMEOUT);
// re-analyze alternate routes after 10 secs dead, or half min interval
else if (Core.TimeNow > lastRecv.AddSeconds(10) || Core.TimeNow > NextCheckRoutes)
{
// after connection this should immediately be called to find best route
CheckRoutes();
NextCheckRoutes = Core.TimeNow.AddSeconds(30);
}
// send keep alive if nothing received after 5 secs
else if (Core.TimeNow > lastRecv.AddSeconds(5))
{
SendPing(PrimaryAddress);
}
}
// prune addressMap to last 6 addresses seen
while (AddressMap.Count > 6)
{
RudpAddress lastSeen = null;
foreach (RudpAddress address in AddressMap.Values)
if (lastSeen == null || address.LastAck < lastSeen.LastAck)
lastSeen = address;
AddressMap.Remove(lastSeen.GetHashCode());
}
// finishing
if (State == RudpState.Finishing)
{
if (!FinSent)
TrySendFin();
if (FinTimeout > 0)
FinTimeout--;
if (FinTimeout == 0)
ChangeState(RudpState.Closed);
// buffer clear, all packets acked in sequence including fins
if (FinSent && FinReceived && SendPacketMap.Count == 0)
ChangeState(RudpState.Closed);
}
// re-send packets in out buffer
if(State != RudpState.Closed)
{
ManageSendWindow();
}
// update bandwidth rate used for determining public send buffer
AvgBytesSent.Next();
// bandwidth stats
Bandwidth.NextSecond();
}
public void CheckRoutes()
{
PrimaryAddress.Reset = true;
foreach (RudpAddress address in AddressMap.Values)
SendPing(address);
}
private void ChangeState(RudpState state)
{
Session.Log("Socket - " + state);
State = state;
}
}
public class TrackPacket
{
public RudpPacket Packet;
public bool Acked;
public int Retries;
public RudpAddress Target;
public bool SpecialTarget;
public long TimeSent;
public TrackPacket(RudpPacket packet)
{
Packet = packet;
}
public long TimeEllapsed(OpCore core)
{
if (TimeSent == 0)
return 0;
return (core.TimeNow.Ticks - TimeSent) / TimeSpan.TicksPerMillisecond;
}
}
public class RudpAddress
{
public DhtAddress Address;
public DhtClient LocalProxy; // NAT -> proxy -> host, NAT will only recv packets from specific proxy
public uint Ident;
public DateTime LastAck; // so not removed from address list when added
public bool Reset;
public RudpAddress(DhtAddress address)
{
Address = address;
}
public RudpAddress(DhtAddress address, TcpConnect proxy)
{
Address = address;
LocalProxy = new DhtClient(proxy);
}
public override int GetHashCode()
{
int hash = Address.GetHashCode();
if(LocalProxy != null)
hash = hash ^ LocalProxy.GetHashCode();
return hash;
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Fixtures.Azure.AcceptanceTestsAzureSpecials
{
using System.Linq;
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Models;
/// <summary>
/// SubscriptionInMethodOperations operations.
/// </summary>
internal partial class SubscriptionInMethodOperations : Microsoft.Rest.IServiceOperations<AutoRestAzureSpecialParametersTestClient>, ISubscriptionInMethodOperations
{
/// <summary>
/// Initializes a new instance of the SubscriptionInMethodOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
internal SubscriptionInMethodOperations(AutoRestAzureSpecialParametersTestClient client)
{
if (client == null)
{
throw new System.ArgumentNullException("client");
}
this.Client = client;
}
/// <summary>
/// Gets a reference to the AutoRestAzureSpecialParametersTestClient
/// </summary>
public AutoRestAzureSpecialParametersTestClient Client { get; private set; }
/// <summary>
/// POST method with subscriptionId modeled in the method. pass in
/// subscription id = '1234-5678-9012-3456' to succeed
/// </summary>
/// <param name='subscriptionId'>
/// This should appear as a method parameter, use value '1234-5678-9012-3456'
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse> PostMethodLocalValidWithHttpMessagesAsync(string subscriptionId, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
if (subscriptionId == null)
{
throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "subscriptionId");
}
// Tracing
bool _shouldTrace = Microsoft.Rest.ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = Microsoft.Rest.ServiceClientTracing.NextInvocationId.ToString();
System.Collections.Generic.Dictionary<string, object> tracingParameters = new System.Collections.Generic.Dictionary<string, object>();
tracingParameters.Add("subscriptionId", subscriptionId);
tracingParameters.Add("cancellationToken", cancellationToken);
Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "PostMethodLocalValid", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "azurespecials/subscriptionId/method/string/none/path/local/1234-5678-9012-3456/{subscriptionId}").ToString();
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(subscriptionId));
System.Collections.Generic.List<string> _queryParameters = new System.Collections.Generic.List<string>();
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
System.Net.Http.HttpRequestMessage _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.HttpMethod("POST");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (this.Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (Newtonsoft.Json.JsonException)
{
// Ignore the exception
}
ex.Request = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new Microsoft.Rest.Azure.AzureOperationResponse();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// POST method with subscriptionId modeled in the method. pass in
/// subscription id = null, client-side validation should prevent you from
/// making this call
/// </summary>
/// <param name='subscriptionId'>
/// This should appear as a method parameter, use value null, client-side
/// validation should prvenet the call
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse> PostMethodLocalNullWithHttpMessagesAsync(string subscriptionId, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
if (subscriptionId == null)
{
throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "subscriptionId");
}
// Tracing
bool _shouldTrace = Microsoft.Rest.ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = Microsoft.Rest.ServiceClientTracing.NextInvocationId.ToString();
System.Collections.Generic.Dictionary<string, object> tracingParameters = new System.Collections.Generic.Dictionary<string, object>();
tracingParameters.Add("subscriptionId", subscriptionId);
tracingParameters.Add("cancellationToken", cancellationToken);
Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "PostMethodLocalNull", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "azurespecials/subscriptionId/method/string/none/path/local/null/{subscriptionId}").ToString();
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(subscriptionId));
System.Collections.Generic.List<string> _queryParameters = new System.Collections.Generic.List<string>();
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
System.Net.Http.HttpRequestMessage _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.HttpMethod("POST");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (this.Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (Newtonsoft.Json.JsonException)
{
// Ignore the exception
}
ex.Request = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new Microsoft.Rest.Azure.AzureOperationResponse();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// POST method with subscriptionId modeled in the method. pass in
/// subscription id = '1234-5678-9012-3456' to succeed
/// </summary>
/// <param name='subscriptionId'>
/// Should appear as a method parameter -use value '1234-5678-9012-3456'
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse> PostPathLocalValidWithHttpMessagesAsync(string subscriptionId, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
if (subscriptionId == null)
{
throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "subscriptionId");
}
// Tracing
bool _shouldTrace = Microsoft.Rest.ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = Microsoft.Rest.ServiceClientTracing.NextInvocationId.ToString();
System.Collections.Generic.Dictionary<string, object> tracingParameters = new System.Collections.Generic.Dictionary<string, object>();
tracingParameters.Add("subscriptionId", subscriptionId);
tracingParameters.Add("cancellationToken", cancellationToken);
Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "PostPathLocalValid", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "azurespecials/subscriptionId/path/string/none/path/local/1234-5678-9012-3456/{subscriptionId}").ToString();
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(subscriptionId));
System.Collections.Generic.List<string> _queryParameters = new System.Collections.Generic.List<string>();
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
System.Net.Http.HttpRequestMessage _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.HttpMethod("POST");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (this.Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (Newtonsoft.Json.JsonException)
{
// Ignore the exception
}
ex.Request = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new Microsoft.Rest.Azure.AzureOperationResponse();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// POST method with subscriptionId modeled in the method. pass in
/// subscription id = '1234-5678-9012-3456' to succeed
/// </summary>
/// <param name='subscriptionId'>
/// The subscriptionId, which appears in the path, the value is always
/// '1234-5678-9012-3456'
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse> PostSwaggerLocalValidWithHttpMessagesAsync(string subscriptionId, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
if (subscriptionId == null)
{
throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "subscriptionId");
}
// Tracing
bool _shouldTrace = Microsoft.Rest.ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = Microsoft.Rest.ServiceClientTracing.NextInvocationId.ToString();
System.Collections.Generic.Dictionary<string, object> tracingParameters = new System.Collections.Generic.Dictionary<string, object>();
tracingParameters.Add("subscriptionId", subscriptionId);
tracingParameters.Add("cancellationToken", cancellationToken);
Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "PostSwaggerLocalValid", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "azurespecials/subscriptionId/swagger/string/none/path/local/1234-5678-9012-3456/{subscriptionId}").ToString();
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(subscriptionId));
System.Collections.Generic.List<string> _queryParameters = new System.Collections.Generic.List<string>();
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
System.Net.Http.HttpRequestMessage _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.HttpMethod("POST");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (this.Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (Newtonsoft.Json.JsonException)
{
// Ignore the exception
}
ex.Request = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new Microsoft.Rest.Azure.AzureOperationResponse();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
}
}
| |
// ********************************************************************************************************
// Product Name: DotSpatial.Tools.ToolDialog
// Description: The tool dialog to be used by tools. It get populated by DialogElements once it is created
//
// ********************************************************************************************************
//
// The Original Code is Toolbox.dll for the DotSpatial 4.6/6 ToolManager project
//
// The Initializeializeial Developer of this Original Code is Brian Marchionni. Created in Oct, 2008.
//
// Contributor(s): (Open source contributors should list themselves and their modifications here).
//
// ********************************************************************************************************
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Drawing;
using System.Linq;
using System.Windows.Forms;
using DotSpatial.Data;
using DotSpatial.Modeling.Forms.Elements;
using DotSpatial.Modeling.Forms.Parameters;
namespace DotSpatial.Modeling.Forms
{
/// <summary>
/// A generic form that works with the various dialog elements in order to create a fully working process.
/// </summary>
public partial class ToolDialog : Form
{
#region Constants and Fields
private List<DataSetArray> _dataSets = new List<DataSetArray>();
private int _elementHeight = 3;
private readonly Extent _extent;
private readonly List<DialogElement> _listOfDialogElements = new List<DialogElement>();
private ITool _tool;
private readonly IContainer components = null;
#endregion
#region Constructors and Destructors
/// <summary>
/// The constructor for the ToolDialog
/// </summary>
/// <param name="tool">The ITool to create the dialog box for</param>
/// <param name="dataSets">The list of available DataSets available</param>
/// <param name="mapExtent">Creates a new instance of the tool dialog with map extent.</param>
public ToolDialog(ITool tool, List<DataSetArray> dataSets, Extent mapExtent)
{
// Required by the designer
InitializeComponent();
DataSets = dataSets;
_extent = mapExtent;
Initialize(tool);
}
/// <summary>
/// The constructor for the ToolDialog
/// </summary>
/// <param name="tool">The ITool to create the dialog box for</param>
/// <param name="modelElements">A list of all model elements</param>
public ToolDialog(ITool tool, IEnumerable<ModelElement> modelElements)
{
// Required by the designer
InitializeComponent();
// We store all the element names here and extract the datasets
foreach (ModelElement me in modelElements)
{
DataElement de = me as DataElement;
if (de != null)
{
bool addData = true;
foreach (Parameter par in tool.OutputParameters)
{
if (par.ModelName == de.Parameter.ModelName)
{
addData = false;
}
break;
}
if (addData)
{
_dataSets.Add(new DataSetArray(me.Name, de.Parameter.Value as IDataSet));
}
}
}
Initialize(tool);
}
#endregion
#region Public Properties
/// <summary>
/// Returns a list of IDataSet that are available in the ToolDialog excluding any of its own outputs.
/// </summary>
public List<DataSetArray> DataSets
{
get
{
return _dataSets;
}
set
{
_dataSets = value;
}
}
/// <summary>
/// Gets the status of the tool
/// </summary>
public ToolStatus ToolStatus
{
get
{
return _listOfDialogElements.Any(de => de.Status != ToolStatus.Ok) ? ToolStatus.Error : ToolStatus.Ok;
}
}
#endregion
#region Methods
/// <summary>
/// This adds the Elements to the form incrementally lower down
/// </summary>
/// <param name="element">The element to add</param>
private void AddElement(DialogElement element)
{
_listOfDialogElements.Add(element);
panelElementContainer.Controls.Add(element);
element.Clicked += ElementClicked;
element.Location = new Point(5, _elementHeight);
_elementHeight = element.Height + _elementHeight;
}
/// <summary>
/// When one of the DialogElements is clicked this event fires to populate the help
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ElementClicked(object sender, EventArgs e)
{
DialogElement element = sender as DialogElement;
if (element == null)
{
PopulateHelp(_tool.Name, _tool.Description, _tool.HelpImage);
}
else if (element.Param == null)
{
PopulateHelp(_tool.Name, _tool.Description, _tool.HelpImage);
}
else if (element.Param.HelpText == string.Empty)
{
PopulateHelp(_tool.Name, _tool.Description, _tool.HelpImage);
}
else
{
PopulateHelp(element.Param.Name, element.Param.HelpText, element.Param.HelpImage);
}
}
/// <summary>
/// The constructor for the ToolDialog
/// </summary>
/// <param name="tool">The ITool to create the dialog box for</param>
private void Initialize(ITool tool)
{
SuspendLayout();
// Generates the form based on what inputs the ITool has
_tool = tool;
Text = tool.Name;
// Sets up the help link
if (string.IsNullOrEmpty(tool.HelpUrl))
{
helpHyperlink.Visible = false;
}
else
{
helpHyperlink.Links[0].LinkData = tool.HelpUrl;
helpHyperlink.Links.Add(0, helpHyperlink.Text.Length, tool.HelpUrl);
}
// Sets-up the icon for the Dialog
Icon = Images.HammerSmall;
panelToolIcon.BackgroundImage = tool.Icon ?? Images.Hammer;
DialogSpacerElement inputSpacer = new DialogSpacerElement();
inputSpacer.Text = ModelingMessageStrings.Input;
AddElement(inputSpacer);
// Populates the dialog with input elements
PopulateInputElements();
DialogSpacerElement outputSpacer = new DialogSpacerElement();
outputSpacer.Text = ModelingMessageStrings.Output;
AddElement(outputSpacer);
// Populates the dialog with output elements
PopulateOutputElements();
// Populate the help text
PopulateHelp(_tool.Name, _tool.Description, _tool.HelpImage);
ResumeLayout();
}
/// <summary>
/// Fires when a parameter is changed
/// </summary>
/// <param name="sender"></param>
private void ParamValueChanged(Parameter sender)
{
_tool.ParameterChanged(sender);
}
/// <summary>
/// This adds a Bitmap to the help section.
/// </summary>
/// <param name="title">The text to appear in the help box.</param>
/// <param name="body">The title to appear in the help box.</param>
/// <param name="image">The bitmap to appear at the bottom of the help box.</param>
private void PopulateHelp(string title, string body, Image image)
{
rtbHelp.Text = string.Empty;
rtbHelp.Size = new Size(0, 0);
// Add the Title
Font fBold = new Font("Tahoma", 14, FontStyle.Bold);
rtbHelp.SelectionFont = fBold;
rtbHelp.SelectionColor = Color.Black;
rtbHelp.SelectedText = title + "\r\n\r\n";
// Add the text body
fBold = new Font("Tahoma", 8, FontStyle.Bold);
rtbHelp.SelectionFont = fBold;
rtbHelp.SelectionColor = Color.Black;
rtbHelp.SelectedText = body;
rtbHelp.Size = new Size(rtbHelp.Width, rtbHelp.GetPositionFromCharIndex(rtbHelp.Text.Length).Y + 30);
// Add the image to the bottom
if (image != null)
{
pnlHelpImage.Visible = true;
if (image.Size.Width > 250)
{
double height = image.Size.Height;
double width = image.Size.Width;
int newHeight = Convert.ToInt32(250 * (height / width));
pnlHelpImage.BackgroundImage = new Bitmap(image, new Size(250, newHeight));
pnlHelpImage.Size = new Size(250, newHeight);
}
else
{
pnlHelpImage.BackgroundImage = image;
pnlHelpImage.Size = image.Size;
}
}
else
{
pnlHelpImage.Visible = false;
pnlHelpImage.BackgroundImage = null;
pnlHelpImage.Size = new Size(0, 0);
}
}
/// <summary>
/// Adds Elements to the dialog based on what input Parameter the ITool contains
/// </summary>
private void PopulateInputElements()
{
// Loops through all the Parameter in the tool and generated their element
foreach (Parameter param in _tool.InputParameters)
{
// We make sure that the input parameter is defined
if (param == null)
{
continue;
}
// We add an event handler that fires if the parameter is changed
param.ValueChanged += ParamValueChanged;
ExtentParam p = param as ExtentParam;
if (p != null && p.DefaultToMapExtent)
{
p.Value = _extent;
}
// Retrieve the dialog element from the parameter and add it to the dialog
AddElement(param.InputDialogElement(DataSets));
}
}
/// <summary>
/// Adds Elements to the dialog based on what output Parameter the ITool contains
/// </summary>
private void PopulateOutputElements()
{
if (_tool.OutputParameters == null)
{
return;
}
// Loops through all the Parameter in the tool and generated their element
foreach (Parameter param in _tool.OutputParameters)
{
// We add an event handler that fires if the parameter is changed
param.ValueChanged += ParamValueChanged;
// Retrieve the dialog element from the parameter and add it to the dialog
AddElement(param.OutputDialogElement(DataSets));
}
}
/// <summary>
/// When the user clicks Cancel
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnCancel_Click(object sender, EventArgs e)
{
DialogResult = DialogResult.Cancel;
}
/// <summary>
/// When the user clicks OK
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnOK_Click(object sender, EventArgs e)
{
DialogResult = DialogResult.OK;
Close();
}
/// <summary>
/// When the hyperlink is clicked this event fires.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void helpHyperlink_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
// Determine which link was clicked within the LinkLabel.
helpHyperlink.Links[helpHyperlink.Links.IndexOf(e.Link)].Visited = true;
// Display the appropriate link based on the value of the
// LinkData property of the Link object.
string target = e.Link.LinkData as string;
if (target != null)
Process.Start(target);
}
/// <summary>
/// If the user clicks out side of one of the tool elements
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void otherElement_Click(object sender, EventArgs e)
{
PopulateHelp(_tool.Name, _tool.Description, _tool.HelpImage);
}
/// <summary>
/// When the size of the help panel changes this event fires to move stuff around.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void panelHelp_SizeChanged(object sender, EventArgs e)
{
rtbHelp.Size = new Size(rtbHelp.Width, rtbHelp.GetPositionFromCharIndex(rtbHelp.Text.Length).Y + 30);
}
#endregion
}
}
| |
//===========================================================================
//
// File : DataGroupsDialog.cs
//
//---------------------------------------------------------------------------
//
// The contents of this file are subject to the "END USER LICENSE AGREEMENT FOR F5
// Software Development Kit for iControl"; you may not use this file except in
// compliance with the License. The License is included in the iControl
// Software Development Kit.
//
// Software distributed under the License is distributed on an "AS IS"
// basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See
// the License for the specific language governing rights and limitations
// under the License.
//
// The Original Code is iControl Code and related documentation
// distributed by F5.
//
// The Initial Developer of the Original Code is F5 Networks, Inc.
// Seattle, WA, USA.
// Portions created by F5 are Copyright (C) 2006 F5 Networks, Inc.
// All Rights Reserved.
// iControl (TM) is a registered trademark of F5 Networks, Inc.
//
// Alternatively, the contents of this file may be used under the terms
// of the GNU General Public License (the "GPL"), in which case the
// provisions of GPL are applicable instead of those above. If you wish
// to allow use of your version of this file only under the terms of the
// GPL and not to allow others to use your version of this file under the
// License, indicate your decision by deleting the provisions above and
// replace them with the notice and other provisions required by the GPL.
// If you do not delete the provisions above, a recipient may use your
// version of this file under either the License or the GPL.
//
//===========================================================================
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using iRuler.Utility;
namespace iRuler.Dialogs
{
public partial class DataGroupsDialog : Form
{
public DataGroupsDialog()
{
InitializeComponent();
}
private void refreshClasses()
{
if (null != Clients.Class)
{
getAddressClasses();
getIntegerClasses();
getStringClasses();
}
}
private void getAddressClasses()
{
listBox_Address.Items.Clear();
String [] class_list = Clients.Class.get_address_class_list();
for (int i = 0; i < class_list.Length; i++)
{
listBox_Address.Items.Add(class_list[i]);
}
}
private void getIntegerClasses()
{
listBox_Integer.Items.Clear();
String[] class_list = Clients.Class.get_value_class_list();
for (int i = 0; i < class_list.Length; i++)
{
listBox_Integer.Items.Add(class_list[i]);
}
}
private void getStringClasses()
{
listBox_String.Items.Clear();
String[] class_list = Clients.Class.get_string_class_list();
for (int i = 0; i < class_list.Length; i++)
{
listBox_String.Items.Add(class_list[i]);
}
}
private void addClass(System.Windows.Forms.ListBox lb, iControl.LocalLBClassClassType type)
{
DataGroupDialog dlg = new DataGroupDialog();
dlg.m_type = type;
dlg.m_mode = DataGroupDialog.DialogMode.DIALOGMODE_NEW;
DialogResult dr = dlg.ShowDialog();
if (DialogResult.OK == dr)
{
lb.Items.Add(dlg.m_name);
}
}
private void editClass(System.Windows.Forms.ListBox lb, iControl.LocalLBClassClassType type)
{
int index = lb.SelectedIndex;
if (-1 != index)
{
DataGroupDialog dlg = new DataGroupDialog();
dlg.m_type = type;
dlg.m_name = lb.Items[index].ToString();
dlg.m_mode = DataGroupDialog.DialogMode.DIALOGMODE_EDIT;
DialogResult dr = dlg.ShowDialog();
}
}
private void deleteClass(System.Windows.Forms.ListBox lb)
{
int index = lb.SelectedIndex;
if ( -1 != index )
{
String sItem = lb.Items[index].ToString();
DialogResult dr = MessageBox.Show("Are you sure you want to delete the '" + sItem + "' data group?",
"Are you sure?", MessageBoxButtons.YesNo);
if (DialogResult.Yes == dr)
{
try
{
Clients.Class.delete_class(new String[] { sItem });
Clients.ConfigSync.save_configuration("", iControl.SystemConfigSyncSaveMode.SAVE_HIGH_LEVEL_CONFIG);
lb.Items.RemoveAt(index);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message.ToString(), "Error");
}
}
}
}
private void updateButtons()
{
bool bItemSelected = (-1 != listBox_Address.SelectedIndex);
button_DeleteAddress.Enabled = bItemSelected;
button_EditAddress.Enabled = bItemSelected;
bItemSelected = (-1 != listBox_Integer.SelectedIndex);
button_DeleteInteger.Enabled = bItemSelected;
button_EditInteger.Enabled = bItemSelected;
bItemSelected = (-1 != listBox_String.SelectedIndex);
button_DeleteString.Enabled = bItemSelected;
button_EditString.Enabled = bItemSelected;
}
private void DataGroupsDialog_Load(object sender, EventArgs e)
{
refreshClasses();
}
private void button_AddAddress_Click(object sender, EventArgs e)
{
addClass(listBox_Address, iControl.LocalLBClassClassType.CLASS_TYPE_ADDRESS);
}
private void button_EditAddress_Click(object sender, EventArgs e)
{
editClass(listBox_Address, iControl.LocalLBClassClassType.CLASS_TYPE_ADDRESS);
}
private void button_DeleteAddress_Click(object sender, EventArgs e)
{
deleteClass(listBox_Address);
}
private void button_AddInteger_Click(object sender, EventArgs e)
{
addClass(listBox_Integer, iControl.LocalLBClassClassType.CLASS_TYPE_VALUE);
}
private void button_EditInteger_Click(object sender, EventArgs e)
{
editClass(listBox_Integer, iControl.LocalLBClassClassType.CLASS_TYPE_VALUE);
}
private void button_DeleteInteger_Click(object sender, EventArgs e)
{
deleteClass(listBox_Integer);
}
private void button_AddString_Click(object sender, EventArgs e)
{
addClass(listBox_String, iControl.LocalLBClassClassType.CLASS_TYPE_STRING);
}
private void button_EditString_Click(object sender, EventArgs e)
{
editClass(listBox_String, iControl.LocalLBClassClassType.CLASS_TYPE_STRING);
}
private void button_DeleteString_Click(object sender, EventArgs e)
{
deleteClass(listBox_String);
}
private void listBox_Address_SelectedIndexChanged(object sender, EventArgs e)
{
updateButtons();
}
private void listBox_Integer_SelectedIndexChanged(object sender, EventArgs e)
{
updateButtons();
}
private void listBox_String_SelectedIndexChanged(object sender, EventArgs e)
{
updateButtons();
}
private void button_OK_Click(object sender, EventArgs e)
{
this.DialogResult = DialogResult.OK;
this.Close();
}
private void button_Refresh_Click(object sender, EventArgs e)
{
refreshClasses();
}
private void DataGroupsDialog_HelpButtonClicked(object sender, CancelEventArgs e)
{
Configuration.LaunchProcess(Configuration.getWebHelpURL() + "#DataGroupsDialog");
}
private void DataGroupsDialog_Paint(object sender, PaintEventArgs e)
{
updateButtons();
}
}
}
| |
/*
| Version 10.1.84
| Copyright 2013 Esri
|
| Licensed under the Apache License, Version 2.0 (the "License");
| you may not use this file except in compliance with the License.
| You may obtain a copy of the License at
|
| http://www.apache.org/licenses/LICENSE-2.0
|
| Unless required by applicable law or agreed to in writing, software
| distributed under the License is distributed on an "AS IS" BASIS,
| WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
| See the License for the specific language governing permissions and
| limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Text.RegularExpressions;
using System.Windows;
using System.Windows.Documents;
using System.Windows.Forms;
namespace ESRI.ArcLogistics.App.Dialogs
{
/// <summary>
/// An extended message box with lot of customizing capabilities.
/// </summary>
internal class MessageBoxEx
{
#region Public static methods
///////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////
/// <summary>
/// Displays a customized message box in front of the specified window.
/// </summary>
/// <param name="owner">Owner window of the message box.</param>
/// <param name="messageBoxText">Text to display.</param>
/// <param name="caption">Title bar caption to display.</param>
/// <param name="button">A value that specifies which button or buttons to display.</param>
/// <param name="icon">Icon to display.</param>
/// <returns>Button value which message box is clicked by the user.</returns>
public static MessageBoxExButtonType Show(Window owner, string messageBoxText, string caption,
MessageBoxButtons button, MessageBoxImage icon)
{
bool checkBoxState = false; // NOTE: ignored
MessageBoxEx msbBox = new MessageBoxEx();
return msbBox._Show(owner, messageBoxText, caption, button, icon, null, ref checkBoxState);
}
/// <summary>
/// Displays a customized message box in front of the specified window.
/// </summary>
/// <param name="owner">Owner window of the message box.</param>
/// <param name="messageBoxText">Text to display.</param>
/// <param name="caption">Title bar caption to display.</param>
/// <param name="button">A value that specifies which button or buttons to display.</param>
/// <param name="icon">Icon to display.</param>
/// <param name="checkBoxText">Response check box caption.</param>
/// <param name="checkBoxState">Response check box default\return state.</param>
/// <returns>Button value which message box is clicked by the user.</returns>
public static MessageBoxExButtonType Show(Window owner, string messageBoxText, string caption,
MessageBoxButtons button, MessageBoxImage icon,
string checkBoxText, ref bool checkBoxState)
{
MessageBoxEx msbBox = new MessageBoxEx();
return msbBox._Show(owner, messageBoxText, caption, button, icon, checkBoxText, ref checkBoxState);
}
/// <summary>
/// Displays a customized message box in front of the specified window.
/// </summary>
/// <param name="owner">Owner window of the message box.</param>
/// <param name="messageBoxTextFormat">Text format to display.</param>
/// <param name="links">List of links on text.</param>
/// <param name="caption">Title bar caption to display.</param>
/// <param name="button">A value that specifies which button or buttons to display.</param>
/// <param name="icon">Icon to display.</param>
/// <returns>Button value which message box is clicked by the user.</returns>
public static MessageBoxExButtonType Show(Window owner, string messageBoxTextFormat,
IList<Hyperlink> links, string caption,
MessageBoxButtons button, MessageBoxImage icon)
{
bool checkBoxState = false; // NOTE: ignored
MessageBoxEx msbBox = new MessageBoxEx();
return msbBox._Show(owner, messageBoxTextFormat, links, caption, button, icon,
null, ref checkBoxState);
}
/// <summary>
/// Displays a customized message box in front of the specified window.
/// </summary>
/// <param name="owner">Owner window of the message box.</param>
/// <param name="messageBoxTextFormat">Format for text to display.</param>
/// <param name="links">Link list to inject in to message.</param>
/// <param name="caption">Title bar caption to display.</param>
/// <param name="button">A value that specifies which button or buttons to display.</param>
/// <param name="icon">Icon to display.</param>
/// <param name="checkBoxText">Response check box caption.</param>
/// <param name="checkBoxState">Response check box default\return state.</param>
/// <returns>Button value which message box is clicked by the user.</returns>
public static MessageBoxExButtonType Show(Window owner, string messageBoxTextFormat,
IList<Hyperlink> links, string caption,
MessageBoxButtons button, MessageBoxImage icon,
string checkBoxText, ref bool checkBoxState)
{
MessageBoxEx msbBox = new MessageBoxEx();
return msbBox._Show(owner, messageBoxTextFormat, links, caption, button, icon,
checkBoxText, ref checkBoxState);
}
#endregion // Public static methods
#region Constructors
///////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////
private MessageBoxEx()
{
}
#endregion // Constructors
#region Private methods
///////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////
/// <summary>
/// Creates message content composition.
/// </summary>
/// <param name="messageTextFormat">Message format.</param>
/// <param name="links">Inserted list of links.</param>
/// <returns>Content composition.</returns>
private IList<Inline> _CreateMessageText(string messageTextFormat, IList<Hyperlink> links)
{
List<Inline> inlines = new List<Inline>();
MatchCollection mc = Regex.Matches(messageTextFormat, @"({\d+})");
if ((0 == mc.Count) || (null == links))
inlines.Add(new Run(messageTextFormat));
else
{
int index = 0;
for (int i = 0; i < mc.Count; ++i)
{
// add text before link
string stringObj = mc[i].Value;
int startIndex = messageTextFormat.IndexOf(stringObj, index);
if (0 < startIndex)
inlines.Add(new Run(messageTextFormat.Substring(index, startIndex - index)));
index = startIndex + stringObj.Length;
// add link
MatchCollection mcNum = Regex.Matches(stringObj, @"(\d+)");
if (1 == mcNum.Count)
{
int objNum = Int32.Parse(mcNum[0].Value);
if (objNum < links.Count)
inlines.Add(links[objNum]);
}
}
// add text after all links
if (index < messageTextFormat.Length)
inlines.Add(new Run(messageTextFormat.Substring(index, messageTextFormat.Length - index)));
}
return inlines;
}
/// <summary>
/// Add standard buttons to the message box.
/// </summary>
/// <param name="buttons">The standard buttons to add.</param>
private void _AddButtons(MessageBoxButtons buttons)
{
switch(buttons)
{
case MessageBoxButtons.OK:
_AddButton(MessageBoxExButtonType.Ok, true);
break;
case MessageBoxButtons.AbortRetryIgnore:
_AddButton(MessageBoxExButtonType.Abort, false);
_AddButton(MessageBoxExButtonType.Retry, false);
_AddButton(MessageBoxExButtonType.Ignore, true);
break;
case MessageBoxButtons.OKCancel:
_AddButton(MessageBoxExButtonType.Ok, false);
_AddButton(MessageBoxExButtonType.Cancel, true);
break;
case MessageBoxButtons.RetryCancel:
_AddButton(MessageBoxExButtonType.Retry, false);
_AddButton(MessageBoxExButtonType.Cancel, true);
break;
case MessageBoxButtons.YesNo:
_AddButton(MessageBoxExButtonType.Yes, false);
_AddButton(MessageBoxExButtonType.No, true);
break;
case MessageBoxButtons.YesNoCancel:
_AddButton(MessageBoxExButtonType.Yes, false);
_AddButton(MessageBoxExButtonType.No, false);
_AddButton(MessageBoxExButtonType.Cancel, true);
break;
default:
Debug.Assert(false); // NOTE: not supported
break;
}
}
/// <summary>
/// Add a standard button to the message box.
/// </summary>
/// <param name="button">The standard button to add.</param>
/// <param name="isCancelResult">The return value for this button in case if dialog
/// closes without pressing any button.</param>
private void _AddButton(MessageBoxExButtonType buttonType, bool isCancelResult)
{
// The text of the button.
string caption = _GetButtonCaption(buttonType);
// Text must be not null.
Debug.Assert(!string.IsNullOrEmpty(caption));
// Create button.
MessageBoxExButton button = new MessageBoxExButton();
button.Caption = caption;
// The return value in case this button is clicked.
button.Value = buttonType;
if (isCancelResult)
button.IsCancelButton = true;
// Add a custom button to the message box.
_msgBox.Buttons.Add(button);
}
/// <summary>
/// Gets button localized caption by button type.
/// </summary>
/// <param name="button">Button type.</param>
/// <returns>Caption text from resources.</returns>
private string _GetButtonCaption(MessageBoxExButtonType button)
{
string resourceName = null;
switch(button)
{
case MessageBoxExButtonType.Ok:
resourceName = "ButtonHeaderOk";
break;
case MessageBoxExButtonType.Cancel:
resourceName = "ButtonHeaderCancel";
break;
case MessageBoxExButtonType.Yes:
resourceName = "ButtonHeaderYes";
break;
case MessageBoxExButtonType.No:
resourceName = "ButtonHeaderNo";
break;
case MessageBoxExButtonType.Abort:
resourceName = "ButtonHeaderAbort";
break;
case MessageBoxExButtonType.Retry:
resourceName = "ButtonHeaderRetry";
break;
case MessageBoxExButtonType.Ignore:
resourceName = "ButtonHeaderIgnore";
break;
default:
Debug.Assert(false); // NOTE: not supported
break;
}
Debug.Assert(null != resourceName);
return (string)App.Current.FindResource(resourceName);
}
/// <summary>
/// Displays a customized message box in front of the specified window.
/// </summary>
/// <param name="owner">Owner window of the message box.</param>
/// <param name="messageBoxTextComposition">Text composition to display.</param>
/// <param name="caption">Title bar caption to display.</param>
/// <param name="button">A value that specifies which button or buttons to display.</param>
/// <param name="icon">Icon to display.</param>
/// <param name="checkBoxText">Response check box caption.</param>
/// <param name="checkBoxState">Response check box default\return state.</param>
/// <returns>Button value which message box is clicked by the user.</returns>
private MessageBoxExButtonType _Show(Window owner, IList<Inline> messageBoxTextComposition, string caption,
MessageBoxButtons button, MessageBoxImage icon,
string checkBoxText, ref bool checkBoxState)
{
// initialize components of message box
_msgBox = new MessageBoxExDlg();
_msgBox.Caption = caption;
_msgBox.StandardIcon = icon;
_msgBox._textBlockQuestion.Inlines.Clear();
foreach (Inline inline in messageBoxTextComposition)
_msgBox._textBlockQuestion.Inlines.Add(inline);
if (string.IsNullOrEmpty(checkBoxText))
_msgBox.ResponseText = null;
else
{
_msgBox.ResponseText = checkBoxText;
_msgBox.Response = checkBoxState;
}
_AddButtons(button);
if (null != owner)
_msgBox.Owner = owner;
using (MouseHelper.OverrideCursor(null))
{
// populate dialog
_msgBox.ShowDialog(); // NOTE: ignore result
}
// get results
if (!string.IsNullOrEmpty(checkBoxText))
checkBoxState = _msgBox.Response;
return _msgBox.Result;
}
/// <summary>
/// Displays a customized message box in front of the specified window.
/// </summary>
/// <param name="owner">Owner window of the message box.</param>
/// <param name="messageBoxTextFormat">Text format to display.</param>
/// <param name="links">List of links on text.</param>
/// <param name="caption">Title bar caption to display.</param>
/// <param name="button">A value that specifies which button or buttons to display.</param>
/// <param name="icon">Icon to display.</param>
/// <param name="checkBoxText">Response check box caption.</param>
/// <param name="checkBoxState">Response check box default\return state.</param>
/// <returns>Button value which message box is clicked by the user.</returns>
public MessageBoxExButtonType _Show(Window owner, string messageBoxTextFormat,
IList<Hyperlink> links, string caption,
MessageBoxButtons button, MessageBoxImage icon,
string checkBoxText, ref bool checkBoxState)
{
IList<Inline> messageBoxTextComposition = _CreateMessageText(messageBoxTextFormat, links);
return _Show(owner, messageBoxTextComposition, caption, button, icon, checkBoxText,
ref checkBoxState);
}
/// <summary>
/// Displays a customized message box in front of the specified window.
/// </summary>
/// <param name="owner">Owner window of the message box.</param>
/// <param name="messageBoxText">Text to display.</param>
/// <param name="caption">Title bar caption to display.</param>
/// <param name="button">A value that specifies which button or buttons to display.</param>
/// <param name="icon">Icon to display.</param>
/// <param name="checkBoxText">Response check box caption.</param>
/// <param name="checkBoxState">Response check box default\return state.</param>
/// <returns>Button value which message box is clicked by the user.</returns>
private MessageBoxExButtonType _Show(Window owner, string messageBoxText, string caption,
MessageBoxButtons button, MessageBoxImage icon,
string checkBoxText, ref bool checkBoxState)
{
IList<Inline> messageBoxTextComposition = _CreateMessageText(messageBoxText, null);
return _Show(owner, messageBoxTextComposition, caption, button, icon, checkBoxText,
ref checkBoxState);
}
#endregion // Private methods
#region Private fields
///////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////
/// <summary>
/// Customized message box instance.
/// </summary>
private MessageBoxExDlg _msgBox = null;
#endregion // Private fields
}
}
| |
using MatterHackers.Agg.RasterizerScanline;
using MatterHackers.VectorMath;
//----------------------------------------------------------------------------
// Anti-Grain Geometry - Version 2.4
// Copyright (C) 2002-2005 Maxim Shemanarev (http://www.antigrain.com)
//
// C# port by: Lars Brubaker
// larsbrubaker@gmail.com
// Copyright (C) 2007
//
// Permission to copy, use, modify, sell and distribute this software
// is granted provided this copyright notice appears in all copies.
// This software is provided "as is" without express or implied
// warranty, and with no claim as to its suitability for any purpose.
//
//----------------------------------------------------------------------------
// Contact: mcseem@antigrain.com
// mcseemagg@yahoo.com
// http://www.antigrain.com
//----------------------------------------------------------------------------
using System;
namespace MatterHackers.Agg.Image
{
public class ImageBufferFloat : IImageFloat
{
public const int OrderB = 0;
public const int OrderG = 1;
public const int OrderR = 2;
public const int OrderA = 3;
internal class InternalImageGraphics2D : ImageGraphics2D
{
private ImageBufferFloat m_Owner;
internal InternalImageGraphics2D(ImageBufferFloat owner)
: base()
{
m_Owner = owner;
ScanlineRasterizer rasterizer = new ScanlineRasterizer();
ImageClippingProxyFloat imageClippingProxy = new ImageClippingProxyFloat(owner);
Initialize(imageClippingProxy, rasterizer);
ScanlineCache = new ScanlineCachePacked8();
}
};
protected int[] m_yTable;
protected int[] m_xTable;
private float[] m_FloatBuffer;
private int m_BufferOffset; // the beginning of the image in this buffer
private int m_BufferFirstPixel; // Pointer to first pixel depending on strideInFloats and image position
private int m_Width; // Width in pixels
private int m_Height; // Height in pixels
private int m_StrideInFloats; // Number of bytes per row. Can be < 0
private int m_DistanceInFloatsBetweenPixelsInclusive;
private int m_BitDepth;
private Vector2 m_OriginOffset = new Vector2(0, 0);
private IRecieveBlenderFloat m_Blender;
private int changedCount = 0;
public int ChangedCount { get { return changedCount; } }
public void MarkImageChanged()
{
// mark this unchecked as we don't want to throw an exception if this rolls over.
unchecked
{
changedCount++;
}
}
public ImageBufferFloat()
{
}
public ImageBufferFloat(IRecieveBlenderFloat blender)
{
SetRecieveBlender(blender);
}
public ImageBufferFloat(IImageFloat sourceImage, IRecieveBlenderFloat blender)
{
SetDimmensionAndFormat(sourceImage.Width, sourceImage.Height, sourceImage.StrideInFloats(), sourceImage.BitDepth, sourceImage.GetFloatsBetweenPixelsInclusive());
int offset = sourceImage.GetBufferOffsetXY(0, 0);
float[] buffer = sourceImage.GetBuffer();
float[] newBuffer = new float[buffer.Length];
agg_basics.memcpy(newBuffer, offset, buffer, offset, buffer.Length - offset);
SetBuffer(newBuffer, offset);
SetRecieveBlender(blender);
}
public ImageBufferFloat(int width, int height, int bitsPerPixel, IRecieveBlenderFloat blender)
{
Allocate(width, height, width * (bitsPerPixel / 32), bitsPerPixel);
SetRecieveBlender(blender);
}
#if false
public ImageBuffer(IImageFloat image, IBlenderFloat blender, GammaLookUpTable gammaTable)
{
unsafe
{
AttachBuffer(image.GetBuffer(), image.Width, image.Height, image.StrideInBytes(), image.BitDepth, image.GetDistanceBetweenPixelsInclusive());
}
SetRecieveBlender(blender);
}
#endif
public ImageBufferFloat(IImageFloat sourceImageToCopy, IRecieveBlenderFloat blender, int distanceBetweenPixelsInclusive, int bufferOffset, int bitsPerPixel)
{
SetDimmensionAndFormat(sourceImageToCopy.Width, sourceImageToCopy.Height, sourceImageToCopy.StrideInFloats(), bitsPerPixel, distanceBetweenPixelsInclusive);
int offset = sourceImageToCopy.GetBufferOffsetXY(0, 0);
float[] buffer = sourceImageToCopy.GetBuffer();
float[] newBuffer = new float[buffer.Length];
throw new NotImplementedException();
//agg_basics.memcpy(newBuffer, offset, buffer, offset, buffer.Length - offset);
//SetBuffer(newBuffer, offset + bufferOffset);
//SetRecieveBlender(blender);
}
public void AttachBuffer(float[] buffer, int bufferOffset, int width, int height, int strideInBytes, int bitDepth, int distanceInBytesBetweenPixelsInclusive)
{
m_FloatBuffer = null;
SetDimmensionAndFormat(width, height, strideInBytes, bitDepth, distanceInBytesBetweenPixelsInclusive);
SetBuffer(buffer, bufferOffset);
}
public void Attach(IImageFloat sourceImage, IRecieveBlenderFloat blender, int distanceBetweenPixelsInclusive, int bufferOffset, int bitsPerPixel)
{
SetDimmensionAndFormat(sourceImage.Width, sourceImage.Height, sourceImage.StrideInFloats(), bitsPerPixel, distanceBetweenPixelsInclusive);
int offset = sourceImage.GetBufferOffsetXY(0, 0);
float[] buffer = sourceImage.GetBuffer();
SetBuffer(buffer, offset + bufferOffset);
SetRecieveBlender(blender);
}
public void Attach(IImageFloat sourceImage, IRecieveBlenderFloat blender)
{
Attach(sourceImage, blender, sourceImage.GetFloatsBetweenPixelsInclusive(), 0, sourceImage.BitDepth);
}
public bool Attach(IImageFloat sourceImage, int x1, int y1, int x2, int y2)
{
m_FloatBuffer = null;
DettachBuffer();
if (x1 > x2 || y1 > y2)
{
throw new Exception("You need to have your x1 and y1 be the lower left corner of your sub image.");
}
RectangleInt boundsRect = new RectangleInt(x1, y1, x2, y2);
if (boundsRect.clip(new RectangleInt(0, 0, (int)sourceImage.Width - 1, (int)sourceImage.Height - 1)))
{
SetDimmensionAndFormat(boundsRect.Width, boundsRect.Height, sourceImage.StrideInFloats(), sourceImage.BitDepth, sourceImage.GetFloatsBetweenPixelsInclusive());
int bufferOffset = sourceImage.GetBufferOffsetXY(boundsRect.Left, boundsRect.Bottom);
float[] buffer = sourceImage.GetBuffer();
SetBuffer(buffer, bufferOffset);
return true;
}
return false;
}
public void SetAlpha(byte value)
{
if (BitDepth != 32)
{
throw new Exception("You don't have alpha channel to set. Your image has a bit depth of " + BitDepth.ToString() + ".");
}
int numPixels = Width * Height;
int offset;
float[] buffer = GetBuffer(out offset);
for (int i = 0; i < numPixels; i++)
{
buffer[offset + i * 4 + 3] = value;
}
}
private void Deallocate()
{
m_FloatBuffer = null;
SetDimmensionAndFormat(0, 0, 0, 32, 4);
}
public void Allocate(int inWidth, int inHeight, int inScanWidthInFloats, int bitsPerPixel)
{
if (bitsPerPixel != 128 && bitsPerPixel != 96 && bitsPerPixel != 32)
{
throw new Exception("Unsupported bits per pixel.");
}
if (inScanWidthInFloats < inWidth * (bitsPerPixel / 32))
{
throw new Exception("Your scan width is not big enough to hold your width and height.");
}
SetDimmensionAndFormat(inWidth, inHeight, inScanWidthInFloats, bitsPerPixel, bitsPerPixel / 32);
m_FloatBuffer = new float[m_StrideInFloats * m_Height];
SetUpLookupTables();
}
public Graphics2D NewGraphics2D()
{
InternalImageGraphics2D imageRenderer = new InternalImageGraphics2D(this);
imageRenderer.Rasterizer.SetVectorClipBox(0, 0, Width, Height);
return imageRenderer;
}
public void CopyFrom(IImageFloat sourceImage)
{
CopyFrom(sourceImage, sourceImage.GetBounds(), 0, 0);
}
protected void CopyFromNoClipping(IImageFloat sourceImage, RectangleInt clippedSourceImageRect, int destXOffset, int destYOffset)
{
if (GetFloatsBetweenPixelsInclusive() != BitDepth / 32
|| sourceImage.GetFloatsBetweenPixelsInclusive() != sourceImage.BitDepth / 32)
{
throw new Exception("WIP we only support packed pixel formats at this time.");
}
if (BitDepth == sourceImage.BitDepth)
{
int lengthInFloats = clippedSourceImageRect.Width * GetFloatsBetweenPixelsInclusive();
int sourceOffset = sourceImage.GetBufferOffsetXY(clippedSourceImageRect.Left, clippedSourceImageRect.Bottom);
float[] sourceBuffer = sourceImage.GetBuffer();
int destOffset;
float[] destBuffer = GetPixelPointerXY(clippedSourceImageRect.Left + destXOffset, clippedSourceImageRect.Bottom + destYOffset, out destOffset);
for (int i = 0; i < clippedSourceImageRect.Height; i++)
{
agg_basics.memmove(destBuffer, destOffset, sourceBuffer, sourceOffset, lengthInFloats);
sourceOffset += sourceImage.StrideInFloats();
destOffset += StrideInFloats();
}
}
else
{
bool haveConversion = true;
switch (sourceImage.BitDepth)
{
case 24:
switch (BitDepth)
{
case 32:
{
int numPixelsToCopy = clippedSourceImageRect.Width;
for (int i = clippedSourceImageRect.Bottom; i < clippedSourceImageRect.Top; i++)
{
int sourceOffset = sourceImage.GetBufferOffsetXY(clippedSourceImageRect.Left, clippedSourceImageRect.Bottom + i);
float[] sourceBuffer = sourceImage.GetBuffer();
int destOffset;
float[] destBuffer = GetPixelPointerXY(
clippedSourceImageRect.Left + destXOffset,
clippedSourceImageRect.Bottom + i + destYOffset,
out destOffset);
for (int x = 0; x < numPixelsToCopy; x++)
{
destBuffer[destOffset++] = sourceBuffer[sourceOffset++];
destBuffer[destOffset++] = sourceBuffer[sourceOffset++];
destBuffer[destOffset++] = sourceBuffer[sourceOffset++];
destBuffer[destOffset++] = 255;
}
}
}
break;
default:
haveConversion = false;
break;
}
break;
default:
haveConversion = false;
break;
}
if (!haveConversion)
{
throw new NotImplementedException("You need to write the " + sourceImage.BitDepth.ToString() + " to " + BitDepth.ToString() + " conversion");
}
}
}
public void CopyFrom(IImageFloat sourceImage, RectangleInt sourceImageRect, int destXOffset, int destYOffset)
{
RectangleInt sourceImageBounds = sourceImage.GetBounds();
RectangleInt clippedSourceImageRect = new RectangleInt();
if (clippedSourceImageRect.IntersectRectangles(sourceImageRect, sourceImageBounds))
{
RectangleInt destImageRect = clippedSourceImageRect;
destImageRect.Offset(destXOffset, destYOffset);
RectangleInt destImageBounds = GetBounds();
RectangleInt clippedDestImageRect = new RectangleInt();
if (clippedDestImageRect.IntersectRectangles(destImageRect, destImageBounds))
{
// we need to make sure the source is also clipped to the dest. So, we'll copy this back to source and offset it.
clippedSourceImageRect = clippedDestImageRect;
clippedSourceImageRect.Offset(-destXOffset, -destYOffset);
CopyFromNoClipping(sourceImage, clippedSourceImageRect, destXOffset, destYOffset);
}
}
}
public Vector2 OriginOffset
{
get { return m_OriginOffset; }
set { m_OriginOffset = value; }
}
public int Width { get { return m_Width; } }
public int Height { get { return m_Height; } }
public int StrideInFloats()
{
return m_StrideInFloats;
}
public int StrideInFloatsAbs()
{
return System.Math.Abs(m_StrideInFloats);
}
public int GetFloatsBetweenPixelsInclusive()
{
return m_DistanceInFloatsBetweenPixelsInclusive;
}
public int BitDepth
{
get { return m_BitDepth; }
}
public virtual RectangleInt GetBounds()
{
return new RectangleInt(-(int)m_OriginOffset.X, -(int)m_OriginOffset.Y, Width - (int)m_OriginOffset.X, Height - (int)m_OriginOffset.Y);
}
public IRecieveBlenderFloat GetBlender()
{
return m_Blender;
}
public void SetRecieveBlender(IRecieveBlenderFloat value)
{
if (value != null && value.NumPixelBits != BitDepth)
{
throw new NotSupportedException("The blender has to support the bit depth of this image.");
}
m_Blender = value;
}
private void SetUpLookupTables()
{
m_yTable = new int[m_Height];
for (int i = 0; i < m_Height; i++)
{
m_yTable[i] = i * m_StrideInFloats;
}
m_xTable = new int[m_Width];
for (int i = 0; i < m_Width; i++)
{
m_xTable[i] = i * m_DistanceInFloatsBetweenPixelsInclusive;
}
}
public void FlipY()
{
m_StrideInFloats *= -1;
m_BufferFirstPixel = m_BufferOffset;
if (m_StrideInFloats < 0)
{
int addAmount = -((int)((int)m_Height - 1) * m_StrideInFloats);
m_BufferFirstPixel = addAmount + m_BufferOffset;
}
SetUpLookupTables();
}
public void SetBuffer(float[] floatBuffer, int bufferOffset)
{
if (floatBuffer.Length < m_Height * m_StrideInFloats)
{
throw new Exception("Your buffer does not have enough room for your height and strideInBytes.");
}
m_FloatBuffer = floatBuffer;
m_BufferOffset = m_BufferFirstPixel = bufferOffset;
if (m_StrideInFloats < 0)
{
int addAmount = -((int)((int)m_Height - 1) * m_StrideInFloats);
m_BufferFirstPixel = addAmount + m_BufferOffset;
}
SetUpLookupTables();
}
private void SetDimmensionAndFormat(int width, int height, int strideInFloats, int bitDepth, int distanceInFloatsBetweenPixelsInclusive)
{
if (m_FloatBuffer != null)
{
throw new Exception("You already have a buffer set. You need to set dimensions before the buffer. You may need to clear the buffer first.");
}
m_Width = width;
m_Height = height;
m_StrideInFloats = strideInFloats;
m_BitDepth = bitDepth;
if (distanceInFloatsBetweenPixelsInclusive > 4)
{
throw new System.Exception("It looks like you are passing bits per pixel rather than distance in Floats.");
}
if (distanceInFloatsBetweenPixelsInclusive < (bitDepth / 32))
{
throw new Exception("You do not have enough room between pixels to support your bit depth.");
}
m_DistanceInFloatsBetweenPixelsInclusive = distanceInFloatsBetweenPixelsInclusive;
if (strideInFloats < distanceInFloatsBetweenPixelsInclusive * width)
{
throw new Exception("You do not have enough strideInFloats to hold the width and pixel distance you have described.");
}
}
public void DettachBuffer()
{
m_FloatBuffer = null;
m_Width = m_Height = m_StrideInFloats = m_DistanceInFloatsBetweenPixelsInclusive = 0;
}
public float[] GetBuffer()
{
return m_FloatBuffer;
}
public float[] GetBuffer(out int bufferOffset)
{
bufferOffset = m_BufferOffset;
return m_FloatBuffer;
}
public float[] GetPixelPointerY(int y, out int bufferOffset)
{
bufferOffset = m_BufferFirstPixel + m_yTable[y];
//bufferOffset = GetBufferOffsetXY(0, y);
return m_FloatBuffer;
}
public float[] GetPixelPointerXY(int x, int y, out int bufferOffset)
{
bufferOffset = GetBufferOffsetXY(x, y);
return m_FloatBuffer;
}
public ColorF GetPixel(int x, int y)
{
return m_Blender.PixelToColorRGBA_Floats(m_FloatBuffer, GetBufferOffsetXY(x, y));
}
public virtual void SetPixel(int x, int y, ColorF color)
{
x -= (int)m_OriginOffset.X;
y -= (int)m_OriginOffset.Y;
m_Blender.CopyPixels(GetBuffer(), GetBufferOffsetXY(x, y), color, 1);
}
public int GetBufferOffsetY(int y)
{
return m_BufferFirstPixel + m_yTable[y];
}
public int GetBufferOffsetXY(int x, int y)
{
return m_BufferFirstPixel + m_yTable[y] + m_xTable[x];
}
public void copy_pixel(int x, int y, float[] c, int ByteOffset)
{
throw new System.NotImplementedException();
//byte* p = GetPixelPointerXY(x, y);
//((int*)p)[0] = ((int*)c)[0];
//p[OrderR] = c.r;
//p[OrderG] = c.g;
//p[OrderB] = c.b;
//p[OrderA] = c.a;
}
public void BlendPixel(int x, int y, ColorF c, byte cover)
{
throw new System.NotImplementedException();
/*
cob_type::copy_or_blend_pix(
(value_type*)m_rbuf->row_ptr(x, y, 1) + x + x + x,
c.r, c.g, c.b, c.a,
cover);*/
}
public void SetPixelFromColor(float[] destPixel, IColorType c)
{
throw new System.NotImplementedException();
//pDestPixel[OrderR] = (byte)c.R_Byte;
//pDestPixel[OrderG] = (byte)c.G_Byte;
//pDestPixel[OrderB] = (byte)c.B_Byte;
}
public void copy_hline(int x, int y, int len, ColorF sourceColor)
{
int bufferOffset;
float[] buffer = GetPixelPointerXY(x, y, out bufferOffset);
m_Blender.CopyPixels(buffer, bufferOffset, sourceColor, len);
}
public void copy_vline(int x, int y, int len, ColorF sourceColor)
{
throw new NotImplementedException();
#if false
int scanWidth = StrideInBytes();
byte* pDestBuffer = GetPixelPointerXY(x, y);
do
{
m_Blender.CopyPixel(pDestBuffer, sourceColor);
pDestBuffer = &pDestBuffer[scanWidth];
}
while (--len != 0);
#endif
}
public void blend_hline(int x1, int y, int x2, ColorF sourceColor, byte cover)
{
if (sourceColor.alpha != 0)
{
int len = x2 - x1 + 1;
int bufferOffset;
float[] buffer = GetPixelPointerXY(x1, y, out bufferOffset);
float alpha = sourceColor.alpha * (cover * (1.0f / 255.0f));
if (alpha == 1)
{
m_Blender.CopyPixels(buffer, bufferOffset, sourceColor, len);
}
else
{
do
{
m_Blender.BlendPixel(buffer, bufferOffset, new ColorF(sourceColor.red, sourceColor.green, sourceColor.blue, alpha));
bufferOffset += m_DistanceInFloatsBetweenPixelsInclusive;
}
while (--len != 0);
}
}
}
public void blend_vline(int x, int y1, int y2, ColorF sourceColor, byte cover)
{
throw new NotImplementedException();
#if false
int ScanWidth = StrideInBytes();
if (sourceColor.m_A != 0)
{
unsafe
{
int len = y2 - y1 + 1;
byte* p = GetPixelPointerXY(x, y1);
sourceColor.m_A = (byte)(((int)(sourceColor.m_A) * (cover + 1)) >> 8);
if (sourceColor.m_A == base_mask)
{
byte cr = sourceColor.m_R;
byte cg = sourceColor.m_G;
byte cb = sourceColor.m_B;
do
{
m_Blender.CopyPixel(p, sourceColor);
p = &p[ScanWidth];
}
while (--len != 0);
}
else
{
if (cover == 255)
{
do
{
m_Blender.BlendPixel(p, sourceColor);
p = &p[ScanWidth];
}
while (--len != 0);
}
else
{
do
{
m_Blender.BlendPixel(p, sourceColor);
p = &p[ScanWidth];
}
while (--len != 0);
}
}
}
}
#endif
}
public void blend_solid_hspan(int x, int y, int len, ColorF sourceColor, byte[] covers, int coversIndex)
{
float colorAlpha = sourceColor.alpha;
if (colorAlpha != 0)
{
unchecked
{
int bufferOffset;
float[] buffer = GetPixelPointerXY(x, y, out bufferOffset);
do
{
float alpha = colorAlpha * (covers[coversIndex] * (1.0f / 255.0f));
if (alpha == 1)
{
m_Blender.CopyPixels(buffer, bufferOffset, sourceColor, 1);
}
else
{
m_Blender.BlendPixel(buffer, bufferOffset, new ColorF(sourceColor.red, sourceColor.green, sourceColor.blue, alpha));
}
bufferOffset += m_DistanceInFloatsBetweenPixelsInclusive;
coversIndex++;
}
while (--len != 0);
}
}
}
public void blend_solid_vspan(int x, int y, int len, ColorF c, byte[] covers, int coversIndex)
{
throw new NotImplementedException();
#if false
if (sourceColor.m_A != 0)
{
int ScanWidth = StrideInBytes();
unchecked
{
byte* p = GetPixelPointerXY(x, y);
do
{
byte oldAlpha = sourceColor.m_A;
sourceColor.m_A = (byte)(((int)(sourceColor.m_A) * ((int)(*covers++) + 1)) >> 8);
if (sourceColor.m_A == base_mask)
{
m_Blender.CopyPixel(p, sourceColor);
}
else
{
m_Blender.BlendPixel(p, sourceColor);
}
p = &p[ScanWidth];
sourceColor.m_A = oldAlpha;
}
while (--len != 0);
}
}
#endif
}
public void copy_color_hspan(int x, int y, int len, ColorF[] colors, int colorsIndex)
{
int bufferOffset = GetBufferOffsetXY(x, y);
do
{
m_Blender.CopyPixels(m_FloatBuffer, bufferOffset, colors[colorsIndex], 1);
++colorsIndex;
bufferOffset += m_DistanceInFloatsBetweenPixelsInclusive;
}
while (--len != 0);
}
public void copy_color_vspan(int x, int y, int len, ColorF[] colors, int colorsIndex)
{
int bufferOffset = GetBufferOffsetXY(x, y);
do
{
m_Blender.CopyPixels(m_FloatBuffer, bufferOffset, colors[colorsIndex], 1);
++colorsIndex;
bufferOffset += m_StrideInFloats;
}
while (--len != 0);
}
public void blend_color_hspan(int x, int y, int len, ColorF[] colors, int colorsIndex, byte[] covers, int coversIndex, bool firstCoverForAll)
{
int bufferOffset = GetBufferOffsetXY(x, y);
m_Blender.BlendPixels(m_FloatBuffer, bufferOffset, colors, colorsIndex, covers, coversIndex, firstCoverForAll, len);
}
public void blend_color_vspan(int x, int y, int len, ColorF[] colors, int colorsIndex, byte[] covers, int coversIndex, bool firstCoverForAll)
{
int bufferOffset = GetBufferOffsetXY(x, y);
int ScanWidth = StrideInFloatsAbs();
if (!firstCoverForAll)
{
do
{
DoCopyOrBlendFloat.BasedOnAlphaAndCover(m_Blender, m_FloatBuffer, bufferOffset, colors[colorsIndex], covers[coversIndex++]);
bufferOffset += ScanWidth;
++colorsIndex;
}
while (--len != 0);
}
else
{
if (covers[coversIndex] == 1)
{
do
{
DoCopyOrBlendFloat.BasedOnAlpha(m_Blender, m_FloatBuffer, bufferOffset, colors[colorsIndex]);
bufferOffset += ScanWidth;
++colorsIndex;
}
while (--len != 0);
}
else
{
do
{
DoCopyOrBlendFloat.BasedOnAlphaAndCover(m_Blender, m_FloatBuffer, bufferOffset, colors[colorsIndex], covers[coversIndex]);
bufferOffset += ScanWidth;
++colorsIndex;
}
while (--len != 0);
}
}
}
public void apply_gamma_inv(GammaLookUpTable g)
{
throw new System.NotImplementedException();
//for_each_pixel(apply_gamma_inv_rgba<color_type, order_type, GammaLut>(g));
}
private bool IsPixelVisible(int x, int y)
{
ColorF pixelValue = GetBlender().PixelToColorRGBA_Floats(m_FloatBuffer, GetBufferOffsetXY(x, y));
return (pixelValue.Alpha0To255 != 0 || pixelValue.Red0To255 != 0 || pixelValue.Green0To255 != 0 || pixelValue.Blue0To255 != 0);
}
public void GetVisibleBounds(out RectangleInt visibleBounds)
{
visibleBounds = new RectangleInt(0, 0, Width, Height);
// trim the bottom
bool aPixelsIsVisible = false;
for (int y = 0; y < m_Height; y++)
{
for (int x = 0; x < m_Width; x++)
{
if (IsPixelVisible(x, y))
{
visibleBounds.Bottom = y;
y = m_Height;
x = m_Width;
aPixelsIsVisible = true;
}
}
}
// if we don't run into any pixels set for the top trim than there are no pixels set at all
if (!aPixelsIsVisible)
{
visibleBounds.SetRect(0, 0, 0, 0);
return;
}
// trim the bottom
for (int y = m_Height - 1; y >= 0; y--)
{
for (int x = 0; x < m_Width; x++)
{
if (IsPixelVisible(x, y))
{
visibleBounds.Top = y + 1;
y = -1;
x = m_Width;
}
}
}
// trim the left
for (int x = 0; x < m_Width; x++)
{
for (int y = 0; y < m_Height; y++)
{
if (IsPixelVisible(x, y))
{
visibleBounds.Left = x;
y = m_Height;
x = m_Width;
}
}
}
// trim the right
for (int x = m_Width - 1; x >= 0; x--)
{
for (int y = 0; y < m_Height; y++)
{
if (IsPixelVisible(x, y))
{
visibleBounds.Right = x + 1;
y = m_Height;
x = -1;
}
}
}
}
public void CropToVisible()
{
Vector2 OldOriginOffset = OriginOffset;
//Move the HotSpot to 0, 0 so PPoint will work the way we want
OriginOffset = new Vector2(0, 0);
RectangleInt visibleBounds;
GetVisibleBounds(out visibleBounds);
if (visibleBounds.Width == Width
&& visibleBounds.Height == Height)
{
OriginOffset = OldOriginOffset;
return;
}
// check if the Not0Rect has any size
if (visibleBounds.Width > 0)
{
ImageBufferFloat TempImage = new ImageBufferFloat();
// set TempImage equal to the Not0Rect
TempImage.Initialize(this, visibleBounds);
// set the frame equal to the TempImage
Initialize(TempImage);
OriginOffset = new Vector2(-visibleBounds.Left + OldOriginOffset.X, -visibleBounds.Bottom + OldOriginOffset.Y);
}
else
{
Deallocate();
}
}
public RectangleInt GetBoundingRect()
{
RectangleInt boundingRect = new RectangleInt(0, 0, Width, Height);
boundingRect.Offset((int)OriginOffset.X, (int)OriginOffset.Y);
return boundingRect;
}
private void Initialize(ImageBufferFloat sourceImage)
{
RectangleInt sourceBoundingRect = sourceImage.GetBoundingRect();
Initialize(sourceImage, sourceBoundingRect);
OriginOffset = sourceImage.OriginOffset;
}
private void Initialize(ImageBufferFloat sourceImage, RectangleInt boundsToCopyFrom)
{
if (sourceImage == this)
{
throw new Exception("We do not create a temp buffer for this to work. You must have a source distinct from the dest.");
}
Deallocate();
Allocate(boundsToCopyFrom.Width, boundsToCopyFrom.Height, boundsToCopyFrom.Width * sourceImage.BitDepth / 8, sourceImage.BitDepth);
SetRecieveBlender(sourceImage.GetBlender());
if (m_Width != 0 && m_Height != 0)
{
RectangleInt DestRect = new RectangleInt(0, 0, boundsToCopyFrom.Width, boundsToCopyFrom.Height);
RectangleInt AbsoluteSourceRect = boundsToCopyFrom;
// The first thing we need to do is make sure the frame is cleared. LBB [3/15/2004]
Graphics2D graphics2D = NewGraphics2D();
graphics2D.Clear(new ColorF(0, 0, 0, 0));
int x = -boundsToCopyFrom.Left - (int)sourceImage.OriginOffset.X;
int y = -boundsToCopyFrom.Bottom - (int)sourceImage.OriginOffset.Y;
graphics2D.Render(sourceImage, x, y, 0, 1, 1);
}
}
}
public static class DoCopyOrBlendFloat
{
private const byte base_mask = 255;
public static void BasedOnAlpha(IRecieveBlenderFloat Blender, float[] destBuffer, int bufferOffset, ColorF sourceColor)
{
//if (sourceColor.m_A != 0)
{
#if false // we blend regardless of the alpha so that we can get Light Opacity working (used this way we have additive and faster blending in one blender) LBB
if (sourceColor.m_A == base_mask)
{
Blender.CopyPixel(pDestBuffer, sourceColor);
}
else
#endif
{
Blender.BlendPixel(destBuffer, bufferOffset, sourceColor);
}
}
}
public static void BasedOnAlphaAndCover(IRecieveBlenderFloat Blender, float[] destBuffer, int bufferOffset, ColorF sourceColor, int cover)
{
if (cover == 255)
{
BasedOnAlpha(Blender, destBuffer, bufferOffset, sourceColor);
}
else
{
//if (sourceColor.m_A != 0)
{
sourceColor.alpha = sourceColor.alpha * ((float)cover * (1 / 255));
#if false // we blend regardless of the alpha so that we can get Light Opacity working (used this way we have additive and faster blending in one blender) LBB
if (sourceColor.m_A == base_mask)
{
Blender.CopyPixel(pDestBuffer, sourceColor);
}
else
#endif
{
Blender.BlendPixel(destBuffer, bufferOffset, sourceColor);
}
}
}
}
};
}
| |
/*
* MindTouch Core - open source enterprise collaborative networking
* Copyright (c) 2006-2010 MindTouch Inc.
* www.mindtouch.com oss@mindtouch.com
*
* For community documentation and downloads visit www.opengarden.org;
* please review the licensing section.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
* http://www.gnu.org/copyleft/gpl.html
*/
using System.Collections.Generic;
using NUnit.Framework;
using MindTouch.Dream;
using MindTouch.Xml;
namespace MindTouch.Deki.Tests.ServiceTests {
[TestFixture]
public class XmlAuthTests {
private const string SID = "sid://mindtouch.com/2008/08/xml-authentication";
private const string Description = "XmlAuthentication";
private XDoc CreateDefaultXml() {
return new XDoc("dekiauth")
.Start("users")
.Start("user").Attr("name", "foo")
.Start("password").Attr("type", "md5").Value("9a618248b64db62d15b300a07b00580b").End()
.Elem("email", "foo@somewhere.com")
.Elem("fullname", "Foo Smith")
.Elem("status", "enabled")
.End()
.Start("user").Attr("name", "joe")
.Start("password").Attr("type", "plain").Value("supersecret").End()
.Elem("email", "joe@somewhere.com")
.Elem("fullname", "Joe Smith")
.Elem("status", "enabled")
.End()
.End()
.Start("groups")
.Start("group").Attr("name", "sales")
.Start("user").Attr("name", "foo").End()
.Start("user").Attr("name", "joe").End()
.End()
.Start("group").Attr("name", "admin")
.Start("user").Attr("name", "joe").End()
.End()
.End();
}
private string GetServiceIDBySID(Plug p, string sid) {
DreamMessage msg = p.At("site", "services").With("limit","all").Get();
foreach(XDoc service in msg.ToDocument()["service"]) {
if(service["sid"].AsText == sid)
return service["@id"].AsText;
}
return null;
}
private void AddNewUserToXml(Plug p, string serviceid, string username, string password) {
DreamMessage msg = p.At("site", "services", serviceid).Get();
Assert.AreEqual(DreamStatus.Ok, msg.Status);
string filename = msg.ToDocument()["config/value[@key='xmlauth-path']"].AsText;
XDoc xdoc = XDocFactory.LoadFrom(filename, MimeType.XML);
xdoc["users"]
.Start("user").Attr("name", username)
.Start("password").Attr("type", "plain").Value(password).End()
.Elem("email", username + "@somewhere.com")
.Elem("fullname", username)
.Elem("status", "enabled")
.End();
xdoc.Save(filename);
}
private void AddNewGroupToXml(Plug p, string serviceid, string groupname) {
DreamMessage msg = p.At("site", "services", serviceid).Get();
Assert.AreEqual(DreamStatus.Ok, msg.Status);
string filename = msg.ToDocument()["config/value[@key='xmlauth-path']"].AsText;
XDoc xdoc = XDocFactory.LoadFrom(filename, MimeType.XML);
xdoc["groups"].Start("group").Attr("name", groupname).End();
xdoc.Save(filename);
}
[TestFixtureSetUp]
public void Start() {
XDoc authxdoc = CreateDefaultXml();
string filename = System.IO.Path.GetTempFileName() + ".xml";
authxdoc.Save(filename);
Plug p = Utils.BuildPlugForAdmin();
string serviceid = GetServiceIDBySID(p, SID);
DreamMessage msg = null;
XDoc xdoc = null;
if(serviceid == null) {
xdoc = new XDoc("service")
.Elem("sid", SID)
.Elem("uri", string.Empty)
.Elem("type", "auth")
.Elem("description", Description)
.Elem("status", "enabled")
.Elem("local", "true")
.Elem("init", "native")
.Start("config")
.Start("value").Attr("key", "xmlauth-path").Value(filename).End()
.End();
msg = p.At("site", "services").Post(DreamMessage.Ok(xdoc));
Assert.AreEqual(DreamStatus.Ok, msg.Status);
serviceid = msg.ToDocument()["@id"].AsText;
msg = p.At("site", "services", serviceid, "start").Post();
Assert.AreEqual(DreamStatus.Ok, msg.Status);
} else {
msg = p.At("site", "services", serviceid, "stop").Post();
Assert.AreEqual(DreamStatus.Ok, msg.Status);
msg = p.At("site", "services", serviceid).Get();
Assert.AreEqual(DreamStatus.Ok, msg.Status);
xdoc = msg.ToDocument();
xdoc["config/value[@key='xmlauth-path']"].ReplaceValue(filename);
msg = p.At("site", "services", serviceid).Put(xdoc);
Assert.AreEqual(DreamStatus.Ok, msg.Status);
msg = p.At("site", "services", serviceid, "start").PostAsync().Wait();
Assert.AreEqual(DreamStatus.Ok, msg.Status);
}
}
public void StopAndDelete() {
Plug p = Utils.BuildPlugForAdmin();
string serviceid = GetServiceIDBySID(p, SID);
if(!string.IsNullOrEmpty(serviceid)) {
p.At("site", "services", serviceid).DeleteAsync().Wait();
}
}
[TestFixtureTearDown]
public void GlobalTearDown() {
StopAndDelete();
}
[Test]
public void TryToLoginThroughExternalService() {
//Assumptions:
// users joe:supersecret and foo:supersecret exist
//Actions:
// try to login with both users credentials
//Expected result:
// ok
Plug p = Utils.BuildPlugForAdmin();
string serviceid = GetServiceIDBySID(p, SID);
DreamMessage msg = null;
p = Utils.BuildPlugForAnonymous().WithCredentials("joe", "supersecret");
msg = p.At("users", "authenticate").WithQuery("authprovider=" + serviceid).PostAsync().Wait();
Assert.AreEqual(DreamStatus.Ok, msg.Status);
p = Utils.BuildPlugForAnonymous().WithCredentials("foo", "supersecret");
msg = p.At("users", "authenticate").WithQuery("authprovider=" + serviceid).PostAsync().Wait();
Assert.AreEqual(DreamStatus.Ok, msg.Status);
}
[Test]
public void CreateUser() {
//Assumptions:
// user joe:supersecret exists
//Actions:
// try to create user from xml
// try to create user which doesn't exist in xml
//Expected result:
// ok
// notfound
Plug p = Utils.BuildPlugForAdmin();
string serviceid = GetServiceIDBySID(p, SID);
string username = Utils.GenerateUniqueName();
string password = "test";
AddNewUserToXml(p, serviceid, username, password);
XDoc userDoc = new XDoc("user")
.Elem("username", username)
.Start("service.authentication").Attr("id", serviceid).End()
.Start("permissions.user")
.Elem("role", "Contributor")
.End();
DreamMessage msg = p.At("users").
With("authusername", "joe").With("authpassword", "supersecret").Post(userDoc);
Assert.AreEqual(DreamStatus.Ok, msg.Status);
string userid = msg.ToDocument()["@id"].AsText;
Assert.IsFalse(string.IsNullOrEmpty(userid));
try {
userDoc = new XDoc("user")
.Elem("username", Utils.GenerateUniqueName())
.Start("service.authentication").Attr("id", serviceid).End()
.Start("permissions.user")
.Elem("role", "Contributor")
.End();
msg = p.At("users").With("authusername", "joe").
With("authpassword", "supersecret").Post(userDoc);
Assert.Fail();
} catch(DreamResponseException ex) {
Assert.IsTrue(ex.Response.Status == DreamStatus.NotFound);
}
}
[Test]
public void AddNewUserAndLoginThroughPost() {
//Assumptions:
// user joe:supersecret exists
//Actions:
// create new user in xml file
// try to with new user credentials
//Expected result:
// ok
Plug p = Utils.BuildPlugForAdmin();
string serviceid = GetServiceIDBySID(p, SID);
string username = Utils.GenerateUniqueName();
string password = "test";
AddNewUserToXml(p, serviceid, username, password);
p = Utils.BuildPlugForAnonymous().At("users", "authenticate");
DreamMessage msg = p.WithCredentials(username, password).With("authprovider", serviceid).PostAsync().Wait();
Assert.AreEqual(DreamStatus.Ok, msg.Status);
}
[Test]
public void AddNewUserAndLoginThroughGet() {
//Assumptions:
// user joe:supersecret exists
//Actions:
// create new user in xml file
// try to with new user credentials
//Expected result:
// ok
Plug p = Utils.BuildPlugForAdmin();
string serviceid = GetServiceIDBySID(p, SID);
string username = Utils.GenerateUniqueName();
string password = "test";
AddNewUserToXml(p, serviceid, username, password);
p = Utils.BuildPlugForAnonymous().At("users", "authenticate");
// Because GET:users/authenticate doesn't create users
DreamMessage msg = p.WithCredentials(username, password).With("authprovider", serviceid).PostAsync().Wait();
Assert.AreEqual(DreamStatus.Ok, msg.Status);
p = Utils.BuildPlugForAnonymous().At("users", "authenticate");
msg = p.WithCredentials(username, password).With("authprovider", serviceid).GetAsync().Wait();
Assert.AreEqual(DreamStatus.Ok, msg.Status);
}
[Test]
public void AddNewGroup() {
//Assumptions:
// user joe:supersecret exists
//Actions:
// create new group in xml file
// try to create group from xml
// try to receive new group from server
//Expected result:
// new group created in deki
Plug p = Utils.BuildPlugForAdmin();
string serviceid = GetServiceIDBySID(p, SID);
DreamMessage msg = p.At("site", "services", serviceid).Get();
Assert.AreEqual(DreamStatus.Ok, msg.Status);
string filename = msg.ToDocument()["config/value[@key='xmlauth-path']"].AsText;
string groupname = Utils.GenerateUniqueName();
XDoc xdoc = XDocFactory.LoadFrom(filename, MimeType.XML);
xdoc["groups"]
.Start("group").Attr("name", groupname).End();
xdoc.Save(filename);
XDoc groupDoc = new XDoc("group")
.Elem("name", groupname)
.Start("service.authentication").Attr("id", serviceid).End()
.Start("permissions.group")
.Elem("role", "Contributor")
.End()
.Start("users")
.End();
msg = p.At("groups").WithQuery("authusername=joe").WithQuery("authpassword=supersecret").Post(groupDoc);
Assert.AreEqual(DreamStatus.Ok, msg.Status);
string groupid = msg.ToDocument()["@id"].AsText;
Assert.IsFalse(string.IsNullOrEmpty(groupid));
msg = p.At("groups").WithQuery("authprovider=" + serviceid).Get();
Assert.AreEqual(DreamStatus.Ok, msg.Status);
Assert.IsFalse(msg.ToDocument()[string.Format("group[groupname=\"{0}\"]", groupname)].IsEmpty);
msg = p.At("groups", groupid).Delete();
Assert.AreEqual(DreamStatus.Ok, msg.Status);
}
[Test]
public void SortUsersByService() {
//Assumptions:
// user joe:supersecret exists
//Actions:
// Create user for local service
// Create user for xmlauth
// Sort users by service
//Expected result:
// ok
Plug p = Utils.BuildPlugForAdmin();
string id = null;
string usernameFilter = Utils.GenerateUniqueName();
DreamMessage msg = null;
msg = UserUtils.CreateUser(p, "Contributor", "password", out id,
usernameFilter + Utils.GenerateUniqueName());
string serviceid = GetServiceIDBySID(p, SID);
string username = usernameFilter + Utils.GenerateUniqueName();
AddNewUserToXml(p, serviceid, username, "test");
XDoc userDoc = new XDoc("user")
.Elem("username", username)
.Start("service.authentication").Attr("id", serviceid).End()
.Start("permissions.user")
.Elem("role", "Contributor")
.End();
msg = p.At("users").With("authusername", "joe").With("authpassword", "supersecret").Post(userDoc);
Assert.AreEqual(DreamStatus.Ok, msg.Status);
Dictionary<string, string> serviceDescriptions = Utils.GetDictionaryFromDoc(p.At("site", "services").With("limit", "all").Get().ToDocument(), "service", "@id", "description");
Utils.TestSortingOfDocByField(
p.At("users").With("sortby", "service").With("usernamefilter", usernameFilter).Get().ToDocument(),
"user", "service.authentication/@id", true, serviceDescriptions);
Utils.TestSortingOfDocByField(
p.At("users").With("sortby", "-service").With("usernamefilter", usernameFilter).Get().ToDocument(),
"user", "service.authentication/@id", false, serviceDescriptions);
}
[Test]
public void SortGroupsByService() {
//Assumptions:
// user joe:supersecret exists
//Actions:
// Create group for local service
// Create group for xmlauth
// Sort groups by service
//Expected result:
// ok
Plug p = Utils.BuildPlugForAdmin();
string id = null;
string groupnameFilter = Utils.GenerateUniqueName();
DreamMessage msg = null;
msg = UserUtils.CreateGroup(p, "Contributor", null, out id, groupnameFilter + Utils.GenerateUniqueName());
string serviceid = GetServiceIDBySID(p, SID);
string groupname = groupnameFilter + Utils.GenerateUniqueName();
AddNewGroupToXml(p, serviceid, groupname);
XDoc groupDoc = new XDoc("group")
.Elem("name", groupname)
.Start("service.authentication").Attr("id", serviceid).End()
.Start("permissions.group")
.Elem("role", "Contributor")
.End();
msg = p.At("groups").With("authusername", "joe").With("authpassword", "supersecret").Post(groupDoc);
Assert.AreEqual(DreamStatus.Ok, msg.Status);
Dictionary<string, string> serviceDescriptions = Utils.GetDictionaryFromDoc(p.At("site", "services").With("limit", "all").Get().ToDocument(), "service", "@id", "description");
Utils.TestSortingOfDocByField(
p.At("groups").With("sortby", "service").With("groupnamefilter", groupnameFilter).Get().ToDocument(),
"group", "service.authentication/@id", true, serviceDescriptions);
Utils.TestSortingOfDocByField(
p.At("groups").With("sortby", "-service").With("groupnamefilter", groupnameFilter).Get().ToDocument(),
"group", "service.authentication/@id", false, serviceDescriptions);
}
[Test]
public void DeleteService() {
//Assumptions:
// user joe:supersecret exists
//Actions:
// create new group1 in xml file
// create new user1 in xml file
// create group1 from xml
// create user1 from xml
// delete auth service
//Expected result:
// service.authentication/@id for group1 changed
// service.authentication/@id for user1 changed
Plug p = Utils.BuildPlugForAdmin();
string serviceid = GetServiceIDBySID(p, SID);
DreamMessage msg = p.At("site", "services", serviceid).Get();
Assert.AreEqual(DreamStatus.Ok, msg.Status);
string filename = msg.ToDocument()["config/value[@key='xmlauth-path']"].AsText;
string groupname = "group" + Utils.GenerateUniqueName();
XDoc xdoc = XDocFactory.LoadFrom(filename, MimeType.XML);
xdoc["groups"]
.Start("group").Attr("name", groupname).End();
xdoc.Save(filename);
XDoc groupDoc = new XDoc("group")
.Elem("name", groupname)
.Start("service.authentication").Attr("id", serviceid).End()
.Start("permissions.group")
.Elem("role", "Contributor")
.End()
.Start("users")
.End();
msg = p.At("groups").
WithQuery("authusername=joe").WithQuery("authpassword=supersecret").PostAsync(groupDoc).Wait();
Assert.AreEqual(DreamStatus.Ok, msg.Status);
string groupid = msg.ToDocument()["@id"].AsText;
Assert.IsFalse(string.IsNullOrEmpty(groupid));
string username = Utils.GenerateUniqueName();
string password = "test";
AddNewUserToXml(p, serviceid, username, password);
XDoc userDoc = new XDoc("user")
.Elem("username", username)
.Start("service.authentication").Attr("id", serviceid).End()
.Start("permissions.user")
.Elem("role", "Contributor")
.End();
msg = p.At("users").With("authusername", "joe").With("authpassword", "supersecret").Post(userDoc);
Assert.AreEqual(DreamStatus.Ok, msg.Status);
string userid = msg.ToDocument()["@id"].AsText;
Assert.IsFalse(string.IsNullOrEmpty(userid));
msg = p.At("groups", groupid).Get();
Assert.AreEqual(DreamStatus.Ok, msg.Status);
Assert.AreEqual(msg.ToDocument()["service.authentication/@id"].AsText, serviceid);
msg = p.At("users", userid).Get();
Assert.AreEqual(DreamStatus.Ok, msg.Status);
Assert.AreEqual(msg.ToDocument()["service.authentication/@id"].AsText, serviceid);
msg = p.At("site", "services", serviceid).DeleteAsync().Wait();
Assert.AreEqual(DreamStatus.Ok, msg.Status);
msg = p.At("groups", groupid).Get();
Assert.AreEqual(DreamStatus.Ok, msg.Status);
Assert.AreNotEqual(msg.ToDocument()["service.authentication/@id"].AsText, serviceid);
msg = p.At("groups").WithQuery("authprovider=" + serviceid).Get();
Assert.AreEqual(DreamStatus.Ok, msg.Status);
Assert.AreEqual(msg.ToDocument()["@count"].AsInt, 0);
msg = p.At("users", userid).Get();
Assert.AreEqual(DreamStatus.Ok, msg.Status);
Assert.AreNotEqual(msg.ToDocument()["service.authentication/@id"].AsText, serviceid);
msg = p.At("users").WithQuery("authprovider=" + serviceid).Get();
Assert.AreEqual(DreamStatus.Ok, msg.Status);
Assert.AreEqual(msg.ToDocument()["@count"].AsInt, 0);
msg = p.At("groups", groupid).Delete();
Assert.AreEqual(DreamStatus.Ok, msg.Status);
Start(); // For return service
}
}
}
| |
// <copyright file="JaegerExporter.cs" company="OpenTelemetry Authors">
// Copyright The OpenTelemetry Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// </copyright>
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Runtime.CompilerServices;
using OpenTelemetry.Exporter.Jaeger.Implementation;
using OpenTelemetry.Internal;
using OpenTelemetry.Resources;
using Thrift.Protocol;
using Process = OpenTelemetry.Exporter.Jaeger.Implementation.Process;
namespace OpenTelemetry.Exporter
{
public class JaegerExporter : BaseExporter<Activity>
{
internal uint NumberOfSpansInCurrentBatch;
private readonly byte[] uInt32Storage = new byte[8];
private readonly int maxPayloadSizeInBytes;
private readonly IJaegerClient client;
private readonly TProtocol batchWriter;
private readonly TProtocol spanWriter;
private readonly bool sendUsingEmitBatchArgs;
private int minimumBatchSizeInBytes;
private int currentBatchSizeInBytes;
private int spanStartPosition;
private uint sequenceId;
private bool disposed;
public JaegerExporter(JaegerExporterOptions options)
: this(options, null)
{
}
internal JaegerExporter(JaegerExporterOptions options, TProtocolFactory protocolFactory = null, IJaegerClient client = null)
{
Guard.ThrowIfNull(options);
this.maxPayloadSizeInBytes = (!options.MaxPayloadSizeInBytes.HasValue || options.MaxPayloadSizeInBytes <= 0)
? JaegerExporterOptions.DefaultMaxPayloadSizeInBytes
: options.MaxPayloadSizeInBytes.Value;
if (options.Protocol == JaegerExportProtocol.UdpCompactThrift)
{
protocolFactory ??= new TCompactProtocol.Factory();
client ??= new JaegerUdpClient(options.AgentHost, options.AgentPort);
this.sendUsingEmitBatchArgs = true;
}
else if (options.Protocol == JaegerExportProtocol.HttpBinaryThrift)
{
protocolFactory ??= new TBinaryProtocol.Factory();
client ??= new JaegerHttpClient(
options.Endpoint,
options.HttpClientFactory?.Invoke() ?? throw new InvalidOperationException("JaegerExporterOptions was missing HttpClientFactory or it returned null."));
}
else
{
throw new NotSupportedException();
}
this.client = client;
this.batchWriter = protocolFactory.GetProtocol(this.maxPayloadSizeInBytes * 2);
this.spanWriter = protocolFactory.GetProtocol(this.maxPayloadSizeInBytes);
string serviceName = (string)this.ParentProvider.GetDefaultResource().Attributes.FirstOrDefault(
pair => pair.Key == ResourceSemanticConventions.AttributeServiceName).Value;
this.Process = new Process(serviceName);
client.Connect();
}
internal Process Process { get; set; }
internal EmitBatchArgs EmitBatchArgs { get; private set; }
internal Batch Batch { get; private set; }
/// <inheritdoc/>
public override ExportResult Export(in Batch<Activity> activityBatch)
{
try
{
if (this.Batch == null)
{
this.SetResourceAndInitializeBatch(this.ParentProvider.GetResource());
}
foreach (var activity in activityBatch)
{
var jaegerSpan = activity.ToJaegerSpan();
this.AppendSpan(jaegerSpan);
jaegerSpan.Return();
}
this.SendCurrentBatch();
return ExportResult.Success;
}
catch (Exception ex)
{
JaegerExporterEventSource.Log.FailedExport(ex);
return ExportResult.Failure;
}
}
internal void SetResourceAndInitializeBatch(Resource resource)
{
Guard.ThrowIfNull(resource);
var process = this.Process;
string serviceName = null;
string serviceNamespace = null;
foreach (var label in resource.Attributes)
{
string key = label.Key;
if (label.Value is string strVal)
{
switch (key)
{
case ResourceSemanticConventions.AttributeServiceName:
serviceName = strVal;
continue;
case ResourceSemanticConventions.AttributeServiceNamespace:
serviceNamespace = strVal;
continue;
}
}
if (process.Tags == null)
{
process.Tags = new Dictionary<string, JaegerTag>();
}
process.Tags[key] = label.ToJaegerTag();
}
if (serviceName != null)
{
serviceName = string.IsNullOrEmpty(serviceNamespace)
? serviceName
: serviceNamespace + "." + serviceName;
}
if (!string.IsNullOrEmpty(serviceName))
{
process.ServiceName = serviceName;
}
this.Batch = new Batch(this.Process, this.batchWriter);
if (this.sendUsingEmitBatchArgs)
{
this.EmitBatchArgs = new EmitBatchArgs(this.batchWriter);
this.Batch.SpanCountPosition += this.EmitBatchArgs.EmitBatchArgsBeginMessage.Length;
this.batchWriter.WriteRaw(this.EmitBatchArgs.EmitBatchArgsBeginMessage);
}
this.batchWriter.WriteRaw(this.Batch.BatchBeginMessage);
this.spanStartPosition = this.batchWriter.Position;
this.minimumBatchSizeInBytes = this.EmitBatchArgs?.MinimumMessageSize ?? 0
+ this.Batch.MinimumMessageSize;
this.ResetBatch();
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal void AppendSpan(JaegerSpan jaegerSpan)
{
jaegerSpan.Write(this.spanWriter);
try
{
var spanTotalBytesNeeded = this.spanWriter.Length;
if (this.NumberOfSpansInCurrentBatch > 0
&& this.currentBatchSizeInBytes + spanTotalBytesNeeded >= this.maxPayloadSizeInBytes)
{
this.SendCurrentBatch();
}
var spanData = this.spanWriter.WrittenData;
this.batchWriter.WriteRaw(spanData);
this.NumberOfSpansInCurrentBatch++;
this.currentBatchSizeInBytes += spanTotalBytesNeeded;
}
finally
{
this.spanWriter.Clear();
}
}
internal void SendCurrentBatch()
{
try
{
this.batchWriter.WriteRaw(this.Batch.BatchEndMessage);
if (this.sendUsingEmitBatchArgs)
{
this.batchWriter.WriteRaw(this.EmitBatchArgs.EmitBatchArgsEndMessage);
this.WriteUInt32AtPosition(this.EmitBatchArgs.SeqIdPosition, ++this.sequenceId);
}
this.WriteUInt32AtPosition(this.Batch.SpanCountPosition, this.NumberOfSpansInCurrentBatch);
var writtenData = this.batchWriter.WrittenData;
this.client.Send(writtenData.Array, writtenData.Offset, writtenData.Count);
}
finally
{
this.ResetBatch();
}
}
/// <inheritdoc/>
protected override void Dispose(bool disposing)
{
if (!this.disposed)
{
if (disposing)
{
try
{
this.client.Close();
}
catch
{
}
this.client.Dispose();
this.batchWriter.Dispose();
this.spanWriter.Dispose();
}
this.disposed = true;
}
base.Dispose(disposing);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private void WriteUInt32AtPosition(int position, uint value)
{
this.batchWriter.Position = position;
int numberOfBytes = this.batchWriter.WriteUI32(value, this.uInt32Storage);
this.batchWriter.WriteRaw(this.uInt32Storage, 0, numberOfBytes);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private void ResetBatch()
{
this.currentBatchSizeInBytes = this.minimumBatchSizeInBytes;
this.NumberOfSpansInCurrentBatch = 0;
this.batchWriter.Clear(this.spanStartPosition);
}
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using Microsoft.CodeAnalysis.CodeGen;
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Microsoft.CodeAnalysis.ExpressionEvaluator;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using System;
using System.Collections.Immutable;
using Xunit;
using Roslyn.Test.PdbUtilities;
using Microsoft.VisualStudio.Debugger.Evaluation;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests
{
public class NoPIATests : ExpressionCompilerTestBase
{
[WorkItem(1033598)]
[Fact]
public void ExplicitEmbeddedType()
{
var source =
@"using System.Runtime.InteropServices;
[TypeIdentifier]
[Guid(""863D5BC0-46A1-49AD-97AA-A5F0D441A9D8"")]
public interface I
{
object F();
}
class C
{
void M()
{
var o = (I)null;
}
static void Main()
{
(new C()).M();
}
}";
var compilation0 = CSharpTestBase.CreateCompilationWithMscorlib(
source,
options: TestOptions.DebugExe,
assemblyName: ExpressionCompilerUtilities.GenerateUniqueName());
var runtime = CreateRuntimeInstance(compilation0);
var context = CreateMethodContext(runtime, "C.M");
ResultProperties resultProperties;
string error;
var testData = new CompilationTestData();
var result = context.CompileExpression("this", out resultProperties, out error, testData);
Assert.Null(error);
testData.GetMethodData("<>x.<>m0").VerifyIL(
@"{
// Code size 2 (0x2)
.maxstack 1
.locals init (I V_0) //o
IL_0000: ldarg.0
IL_0001: ret
}");
}
[WorkItem(1035310)]
[Fact]
public void EmbeddedType()
{
var sourcePIA =
@"using System.Runtime.InteropServices;
[assembly: PrimaryInteropAssembly(0, 0)]
[assembly: Guid(""863D5BC0-46A1-49AC-97AA-A5F0D441A9DA"")]
[ComImport]
[Guid(""863D5BC0-46A1-49AD-97AA-A5F0D441A9DA"")]
public interface I
{
object F();
}";
var source =
@"class C
{
static void M()
{
var o = (I)null;
}
}";
var compilationPIA = CreateCompilationWithMscorlib(sourcePIA, options: TestOptions.DebugDll);
var referencePIA = compilationPIA.EmitToImageReference(embedInteropTypes: true);
var compilation0 = CreateCompilationWithMscorlib(
source,
options: TestOptions.DebugDll,
assemblyName: Guid.NewGuid().ToString("D"),
references: new MetadataReference[] { referencePIA });
byte[] exeBytes;
byte[] pdbBytes;
ImmutableArray<MetadataReference> references;
compilation0.EmitAndGetReferences(out exeBytes, out pdbBytes, out references);
// References should not include PIA.
Assert.Equal(references.Length, 1);
Assert.True(references[0].Display.StartsWith("mscorlib", StringComparison.Ordinal));
var runtime = CreateRuntimeInstance(
Guid.NewGuid().ToString("D"),
references,
exeBytes,
new SymReader(pdbBytes));
var context = CreateMethodContext(runtime, "C.M");
ResultProperties resultProperties;
string error;
var testData = new CompilationTestData();
var result = context.CompileExpression("o", out resultProperties, out error, testData);
Assert.Null(error);
testData.GetMethodData("<>x.<>m0").VerifyIL(
@"{
// Code size 2 (0x2)
.maxstack 1
.locals init (I V_0) //o
IL_0000: ldloc.0
IL_0001: ret
}");
}
/// <summary>
/// Duplicate type definitions: in PIA
/// and as embedded type.
/// </summary>
[Fact]
public void PIATypeAndEmbeddedType()
{
var sourcePIA =
@"using System.Runtime.InteropServices;
[assembly: PrimaryInteropAssembly(0, 0)]
[assembly: Guid(""863D5BC0-46A1-49AC-97AA-A5F0D441A9DC"")]
[ComImport]
[Guid(""863D5BC0-46A1-49AD-97AA-A5F0D441A9DC"")]
public interface I
{
object F();
}";
var sourceA =
@"public class A
{
public static void M(I x)
{
}
}";
var sourceB =
@"class B
{
static void Main()
{
I y = null;
A.M(y);
}
}";
var compilationPIA = CreateCompilationWithMscorlib(sourcePIA, options: TestOptions.DebugDll);
byte[] exePIA;
byte[] pdbPIA;
ImmutableArray<MetadataReference> referencesPIA;
compilationPIA.EmitAndGetReferences(out exePIA, out pdbPIA, out referencesPIA);
var metadataPIA = AssemblyMetadata.CreateFromImage(exePIA);
var referencePIA = metadataPIA.GetReference();
// csc /t:library /l:PIA.dll A.cs
var compilationA = CreateCompilationWithMscorlib(
sourceA,
options: TestOptions.DebugDll,
assemblyName: ExpressionCompilerUtilities.GenerateUniqueName(),
references: new MetadataReference[] { metadataPIA.GetReference(embedInteropTypes: true) });
byte[] exeA;
byte[] pdbA;
ImmutableArray<MetadataReference> referencesA;
compilationA.EmitAndGetReferences(out exeA, out pdbA, out referencesA);
var metadataA = AssemblyMetadata.CreateFromImage(exeA);
var referenceA = metadataA.GetReference();
// csc /r:A.dll /r:PIA.dll B.cs
var compilationB = CreateCompilationWithMscorlib(
sourceB,
options: TestOptions.DebugExe,
assemblyName: Guid.NewGuid().ToString("D"),
references: new MetadataReference[] { metadataA.GetReference(), metadataPIA.GetReference() });
byte[] exeB;
byte[] pdbB;
ImmutableArray<MetadataReference> referencesB;
compilationB.EmitAndGetReferences(out exeB, out pdbB, out referencesB);
var metadataB = AssemblyMetadata.CreateFromImage(exeB);
var referenceB = metadataB.GetReference();
// Create runtime from modules { mscorlib, PIA, A, B }.
var modulesBuilder = ArrayBuilder<ModuleInstance>.GetInstance();
modulesBuilder.Add(MscorlibRef.ToModuleInstance(fullImage: null, symReader: null));
modulesBuilder.Add(referenceA.ToModuleInstance(fullImage: exeA, symReader: new SymReader(pdbA)));
modulesBuilder.Add(referencePIA.ToModuleInstance(fullImage: null, symReader: null));
modulesBuilder.Add(referenceB.ToModuleInstance(fullImage: exeB, symReader: new SymReader(pdbB)));
using (var runtime = new RuntimeInstance(modulesBuilder.ToImmutableAndFree()))
{
var context = CreateMethodContext(runtime, "A.M");
ResultProperties resultProperties;
string error;
// Bind to local of embedded PIA type.
var testData = new CompilationTestData();
context.CompileExpression("x", out resultProperties, out error, testData);
Assert.Null(error);
testData.GetMethodData("<>x.<>m0").VerifyIL(
@"{
// Code size 2 (0x2)
.maxstack 1
IL_0000: ldarg.0
IL_0001: ret
}");
// Binding to method on original PIA should fail
// since it was not included in embedded type.
ImmutableArray<AssemblyIdentity> missingAssemblyIdentities;
context.CompileExpression(
DefaultInspectionContext.Instance,
"x.F()",
DkmEvaluationFlags.TreatAsExpression,
DiagnosticFormatter.Instance,
out resultProperties,
out error,
out missingAssemblyIdentities,
EnsureEnglishUICulture.PreferredOrNull,
testData: null);
AssertEx.SetEqual(missingAssemblyIdentities, EvaluationContextBase.SystemCoreIdentity);
Assert.Equal(error, "error CS1061: 'I' does not contain a definition for 'F' and no extension method 'F' accepting a first argument of type 'I' could be found (are you missing a using directive or an assembly reference?)");
// Binding to method on original PIA should succeed
// in assembly referencing PIA.dll.
context = CreateMethodContext(runtime, "B.Main");
testData = new CompilationTestData();
context.CompileExpression("y.F()", out resultProperties, out error, testData);
Assert.Null(error);
testData.GetMethodData("<>x.<>m0").VerifyIL(
@"{
// Code size 7 (0x7)
.maxstack 1
.locals init (I V_0) //y
IL_0000: ldloc.0
IL_0001: callvirt ""object I.F()""
IL_0006: ret
}");
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Text;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Windows.Forms;
using Office = Microsoft.Office.Core;
using Outlook = Microsoft.Office.Interop.Outlook;
using Deja.Crypto.BcPgp;
using System.Text.RegularExpressions;
using NLog;
namespace OutlookPrivacyPlugin
{
public class ButtonStateData
{
public bool SignButton = false;
public bool EncryptButton = false;
public ButtonStateData(bool sign, bool encrypt)
{
SignButton = sign;
EncryptButton = encrypt;
}
}
[ComVisible(true)]
public class OppRibbon : Office.IRibbonExtensibility
{
static NLog.Logger logger = LogManager.GetCurrentClassLogger();
private Office.IRibbonUI ribbon;
public ToggleButton SignButton;
public ToggleButton EncryptButton;
public ToggleButton VerifyButton;
public ToggleButton DecryptButton;
public ToggleButton AttachPublicKeyButton;
public Dictionary<string, ButtonStateData> ButtonState = new Dictionary<string, ButtonStateData>();
private Dictionary<string, ToggleButton> Buttons = new Dictionary<string, ToggleButton>();
public OppRibbon()
{
SignButton = new ToggleButton("signButton");
EncryptButton = new ToggleButton("encryptButton");
VerifyButton = new ToggleButton("verifyButton");
DecryptButton = new ToggleButton("decryptButton");
AttachPublicKeyButton = new ToggleButton("attachPublicKeyButton");
Buttons.Add(SignButton.Id, SignButton);
Buttons.Add(EncryptButton.Id, EncryptButton);
Buttons.Add(VerifyButton.Id, VerifyButton);
Buttons.Add(DecryptButton.Id, DecryptButton);
Buttons.Add(AttachPublicKeyButton.Id, AttachPublicKeyButton);
}
#region IRibbonExtensibility Members
public string GetCustomUI(string ribbonID)
{
String ui = null;
if (ribbonID == "Microsoft.Outlook.Explorer")
{
ui = GetResourceText("OutlookPrivacyPlugin.RibbonMain.xml");
}
// Examine the ribbonID to see if the current item
// is a Mail inspector.
else if (ribbonID == "Microsoft.Outlook.Mail.Read")
{
// Retrieve the customized Ribbon XML.
ui = GetResourceText("OutlookPrivacyPlugin.RibbonRead.xml");
}
else if (ribbonID == "Microsoft.Outlook.Mail.Compose")
{
// Retrieve the customized Ribbon XML.
ui = GetResourceText("OutlookPrivacyPlugin.RibbonCompose.xml");
}
return ui;
}
#endregion
internal void UpdateButtons(Properties.Settings settings)
{
// Compose Mail
EncryptButton.Checked = settings.AutoEncrypt;
SignButton.Checked = settings.AutoSign;
AttachPublicKeyButton.Checked = false;
// Read Mail
DecryptButton.Checked = settings.AutoDecrypt;
VerifyButton.Checked = settings.AutoVerify;
}
internal void InvalidateButtons()
{
if (ribbon == null)
return;
ribbon.InvalidateControl(SignButton.Id);
ribbon.InvalidateControl(EncryptButton.Id);
ribbon.InvalidateControl(VerifyButton.Id);
ribbon.InvalidateControl(DecryptButton.Id);
ribbon.InvalidateControl(AttachPublicKeyButton.Id);
}
#region Ribbon Callbacks
public void OnLoad(Office.IRibbonUI ribbonUI)
{
this.ribbon = ribbonUI;
}
public void OnEncryptButton(Office.IRibbonControl control, bool isPressed)
{
logger.Trace("OnEncryptButton("+control.Id+", "+isPressed+")");
var mailItem = ((Outlook.Inspector)control.Context).CurrentItem as Outlook.MailItem;
if (mailItem == null)
logger.Trace("OnEncryptButton: mailItem == null");
if (isPressed == true)
{
if (mailItem != null)
{
var settings = new Properties.Settings();
if (settings.Default2PlainFormat)
{
string body = mailItem.Body;
mailItem.BodyFormat = Outlook.OlBodyFormat.olFormatPlain;
mailItem.Body = body;
}
}
}
OutlookPrivacyPlugin.SetProperty(mailItem, "GnuPGSetting.Encrypt", isPressed);
EncryptButton.Checked = isPressed;
ribbon.InvalidateControl(EncryptButton.Id);
}
public void OnDecryptButton(Office.IRibbonControl control)
{
var mailItem = ((Outlook.Inspector)control.Context).CurrentItem as Outlook.MailItem;
if (mailItem != null)
Globals.OutlookPrivacyPlugin.DecryptEmail(mailItem);
}
public void OnSignButton(Office.IRibbonControl control, bool isPressed)
{
var mailItem = ((Outlook.Inspector)control.Context).CurrentItem as Outlook.MailItem;
if (isPressed == true)
{
if (mailItem != null)
{
var settings = new Properties.Settings();
if (settings.Default2PlainFormat)
{
string body = mailItem.Body;
mailItem.BodyFormat = Outlook.OlBodyFormat.olFormatPlain;
mailItem.Body = body;
}
}
}
OutlookPrivacyPlugin.SetProperty(mailItem, "GnuPGSetting.Sign", isPressed);
SignButton.Checked = isPressed;
ribbon.InvalidateControl(SignButton.Id);
}
public void OnVerifyButton(Office.IRibbonControl control)
{
var mailItem = ((Outlook.Inspector)control.Context).CurrentItem as Outlook.MailItem;
if (mailItem != null)
Globals.OutlookPrivacyPlugin.VerifyEmail(mailItem);
}
public void OnAttachPublicKeyButton(Office.IRibbonControl control)
{
var mailItem = ((Outlook.Inspector)control.Context).CurrentItem as Outlook.MailItem;
if (mailItem == null)
{
// TODO - Generate a log message
MessageBox.Show("Error, mailItem was null.");
return;
}
var smtp = Globals.OutlookPrivacyPlugin.GetSMTPAddress(mailItem);
var crypto = new PgpCrypto(new CryptoContext());
var headers = new Dictionary<string, string>();
headers["Version"] = "Outlook Privacy Plugin";
var publicKey = crypto.PublicKey(smtp, headers);
if(publicKey == null)
{
// TODO - Generate log message
MessageBox.Show("Error, unable to find public KeyItem to attach.");
return;
}
var attachName = smtp.Replace("@", "_at_") + ".asc";
attachName = Regex.Replace(attachName, @"[:\\/=+!@#$%^&*(){}[\]|<>,'"";~`]", "_");
var tempFile = Path.Combine(Path.GetTempPath(), attachName);
File.WriteAllText(tempFile, publicKey);
try
{
mailItem.Attachments.Add(
tempFile,
Outlook.OlAttachmentType.olByValue,
1,
attachName);
mailItem.Save();
}
finally
{
File.Delete(tempFile);
}
}
public void OnSettingsButtonRead(Office.IRibbonControl control)
{
Globals.OutlookPrivacyPlugin.Settings();
}
public void OnSettingsButtonNew(Office.IRibbonControl control)
{
Globals.OutlookPrivacyPlugin.Settings();
// Force an update of button state:
ribbon.InvalidateControl(SignButton.Id);
ribbon.InvalidateControl(EncryptButton.Id);
}
public void OnAboutButton(Office.IRibbonControl control)
{
Globals.OutlookPrivacyPlugin.About();
}
public stdole.IPictureDisp
GetCustomImage(Office.IRibbonControl control)
{
stdole.IPictureDisp pictureDisp = null;
switch (control.Id)
{
case "settingsButtonNew":
case "settingsButtonRead":
pictureDisp = ImageConverter.Convert(Properties.Resources.database_gear);
break;
case "aboutButtonNew":
case "aboutButtonRead":
pictureDisp = ImageConverter.Convert(Properties.Resources.Logo);
break;
case "attachPublicKeyButton":
pictureDisp = ImageConverter.Convert(Properties.Resources.attach);
break;
default:
if ((control.Id == EncryptButton.Id) || (control.Id == DecryptButton.Id))
pictureDisp = ImageConverter.Convert(Properties.Resources.lock_edit);
if ((control.Id == SignButton.Id) || (control.Id == VerifyButton.Id))
pictureDisp = ImageConverter.Convert(Properties.Resources.link_edit);
break;
}
return pictureDisp;
}
public bool GetPressed(Office.IRibbonControl control)
{
logger.Trace("GetPressed("+control.Id+")");
if (control.Id == SignButton.Id)
{
var mailItem = ((Outlook.Inspector)control.Context).CurrentItem as Outlook.MailItem;
return (bool)OutlookPrivacyPlugin.GetProperty(mailItem, "GnuPGSetting.Sign", false);
}
if (control.Id == EncryptButton.Id)
{
var mailItem = ((Outlook.Inspector)control.Context).CurrentItem as Outlook.MailItem;
return (bool)OutlookPrivacyPlugin.GetProperty(mailItem, "GnuPGSetting.Encrypt", false);
}
logger.Trace("GetPressed: Button did not match encrypt or sign!");
if (Buttons.ContainsKey(control.Id))
return Buttons[control.Id].Checked;
return false;
}
public bool GetEnabled(Office.IRibbonControl control)
{
if (Buttons.ContainsKey(control.Id))
return Buttons[control.Id].Enabled;
return false;
}
#endregion
#region Helpers
private static string GetResourceText(string resourceName)
{
var asm = Assembly.GetExecutingAssembly();
var resourceNames = asm.GetManifestResourceNames();
foreach (var resource in resourceNames)
{
if (string.Compare(resourceName, resource, StringComparison.OrdinalIgnoreCase) != 0) continue;
using (var resourceReader = new StreamReader(asm.GetManifestResourceStream(resource)))
{
return resourceReader.ReadToEnd();
}
}
return null;
}
#endregion
}
internal class ImageConverter : AxHost
{
private ImageConverter()
: base(null)
{
}
public static stdole.IPictureDisp Convert(System.Drawing.Image image)
{
return (stdole.IPictureDisp)AxHost.GetIPictureDispFromPicture(image);
}
}
public class ToggleButton
{
public ToggleButton(string controlId)
{
Checked = false;
Id = controlId;
}
public bool Checked { get; set; }
public bool Enabled { get; set; }
public string Id { get; set; }
}
}
| |
// dnlib: See LICENSE.txt for more info
using System;
using System.Collections.Generic;
using System.IO;
using dnlib.IO;
using dnlib.PE;
namespace dnlib.DotNet.Writer {
/// <summary>
/// <see cref="PEHeaders"/> options
/// </summary>
public sealed class PEHeadersOptions {
/// <summary>
/// Default DLL characteristics
/// </summary>
public const DllCharacteristics DefaultDllCharacteristics = dnlib.PE.DllCharacteristics.TerminalServerAware | dnlib.PE.DllCharacteristics.NoSeh | dnlib.PE.DllCharacteristics.NxCompat | dnlib.PE.DllCharacteristics.DynamicBase;
/// <summary>
/// Default subsystem value
/// </summary>
public const Subsystem DEFAULT_SUBSYSTEM = dnlib.PE.Subsystem.WindowsGui;
/// <summary>
/// Default major linker version
/// </summary>
public const byte DEFAULT_MAJOR_LINKER_VERSION = 11;
/// <summary>
/// Default minor linker version
/// </summary>
public const byte DEFAULT_MINOR_LINKER_VERSION = 0;
/// <summary>
/// IMAGE_FILE_HEADER.Machine value
/// </summary>
public Machine? Machine;
/// <summary>
/// IMAGE_FILE_HEADER.TimeDateStamp value
/// </summary>
public uint? TimeDateStamp;
/// <summary>
/// IMAGE_FILE_HEADER.PointerToSymbolTable value
/// </summary>
public uint? PointerToSymbolTable;
/// <summary>
/// IMAGE_FILE_HEADER.NumberOfSymbols value
/// </summary>
public uint? NumberOfSymbols;
/// <summary>
/// IMAGE_FILE_HEADER.Characteristics value. <see cref="dnlib.PE.Characteristics.Dll"/> bit
/// is ignored and set/cleared depending on whether it's a EXE or a DLL file.
/// </summary>
public Characteristics? Characteristics;
/// <summary>
/// IMAGE_OPTIONAL_HEADER.MajorLinkerVersion value
/// </summary>
public byte? MajorLinkerVersion;
/// <summary>
/// IMAGE_OPTIONAL_HEADER.MinorLinkerVersion value
/// </summary>
public byte? MinorLinkerVersion;
/// <summary>
/// IMAGE_OPTIONAL_HEADER.ImageBase value
/// </summary>
public ulong? ImageBase;
/// <summary>
/// IMAGE_OPTIONAL_HEADER.SectionAlignment value
/// </summary>
public uint? SectionAlignment;
/// <summary>
/// IMAGE_OPTIONAL_HEADER.FileAlignment value
/// </summary>
public uint? FileAlignment;
/// <summary>
/// IMAGE_OPTIONAL_HEADER.MajorOperatingSystemVersion value
/// </summary>
public ushort? MajorOperatingSystemVersion;
/// <summary>
/// IMAGE_OPTIONAL_HEADER.MinorOperatingSystemVersion value
/// </summary>
public ushort? MinorOperatingSystemVersion;
/// <summary>
/// IMAGE_OPTIONAL_HEADER.MajorImageVersion value
/// </summary>
public ushort? MajorImageVersion;
/// <summary>
/// IMAGE_OPTIONAL_HEADER.MinorImageVersion value
/// </summary>
public ushort? MinorImageVersion;
/// <summary>
/// IMAGE_OPTIONAL_HEADER.MajorSubsystemVersion value
/// </summary>
public ushort? MajorSubsystemVersion;
/// <summary>
/// IMAGE_OPTIONAL_HEADER.MinorSubsystemVersion value
/// </summary>
public ushort? MinorSubsystemVersion;
/// <summary>
/// IMAGE_OPTIONAL_HEADER.Win32VersionValue value
/// </summary>
public uint? Win32VersionValue;
/// <summary>
/// IMAGE_OPTIONAL_HEADER.Subsystem value
/// </summary>
public Subsystem? Subsystem;
/// <summary>
/// IMAGE_OPTIONAL_HEADER.DllCharacteristics value
/// </summary>
public DllCharacteristics? DllCharacteristics;
/// <summary>
/// IMAGE_OPTIONAL_HEADER.SizeOfStackReserve value
/// </summary>
public ulong? SizeOfStackReserve;
/// <summary>
/// IMAGE_OPTIONAL_HEADER.SizeOfStackCommit value
/// </summary>
public ulong? SizeOfStackCommit;
/// <summary>
/// IMAGE_OPTIONAL_HEADER.SizeOfHeapReserve value
/// </summary>
public ulong? SizeOfHeapReserve;
/// <summary>
/// IMAGE_OPTIONAL_HEADER.SizeOfHeapCommit value
/// </summary>
public ulong? SizeOfHeapCommit;
/// <summary>
/// IMAGE_OPTIONAL_HEADER.LoaderFlags value
/// </summary>
public uint? LoaderFlags;
/// <summary>
/// IMAGE_OPTIONAL_HEADER.NumberOfRvaAndSizes value
/// </summary>
public uint? NumberOfRvaAndSizes;
/// <summary>
/// Creates a new time date stamp using current time
/// </summary>
/// <returns>A new time date stamp</returns>
public static uint CreateNewTimeDateStamp() {
return (uint)(DateTime.UtcNow - Epoch).TotalSeconds;
}
static readonly DateTime Epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
}
/// <summary>
/// DOS and PE headers
/// </summary>
public sealed class PEHeaders : IChunk {
IList<PESection> sections;
readonly PEHeadersOptions options;
FileOffset offset;
RVA rva;
uint length;
readonly uint sectionAlignment;
readonly uint fileAlignment;
ulong imageBase;
long startOffset;
long checkSumOffset;
bool isExeFile;
// Copied from Partition II.25.2.1
static readonly byte[] dosHeader = new byte[0x80] {
0x4D, 0x5A, 0x90, 0x00, 0x03, 0x00, 0x00, 0x00,
0x04, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0x00, 0x00,
0xB8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x80, 0x00, 0x00, 0x00,
0x0E, 0x1F, 0xBA, 0x0E, 0x00, 0xB4, 0x09, 0xCD,
0x21, 0xB8, 0x01, 0x4C, 0xCD, 0x21, 0x54, 0x68,
0x69, 0x73, 0x20, 0x70, 0x72, 0x6F, 0x67, 0x72,
0x61, 0x6D, 0x20, 0x63, 0x61, 0x6E, 0x6E, 0x6F,
0x74, 0x20, 0x62, 0x65, 0x20, 0x72, 0x75, 0x6E,
0x20, 0x69, 0x6E, 0x20, 0x44, 0x4F, 0x53, 0x20,
0x6D, 0x6F, 0x64, 0x65, 0x2E, 0x0D, 0x0D, 0x0A,
0x24, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
};
/// <summary>
/// Gets/sets the native entry point
/// </summary>
public StartupStub StartupStub { get; set; }
/// <summary>
/// Gets/sets the COR20 header
/// </summary>
public ImageCor20Header ImageCor20Header { get; set; }
/// <summary>
/// Gets/sets the IAT
/// </summary>
public ImportAddressTable ImportAddressTable { get; set; }
/// <summary>
/// Gets/sets the <see cref="ImportDirectory"/>
/// </summary>
public ImportDirectory ImportDirectory { get; set; }
/// <summary>
/// Gets/sets the Win32 resources
/// </summary>
public Win32ResourcesChunk Win32Resources { get; set; }
/// <summary>
/// Gets/sets the relocation directory
/// </summary>
public RelocDirectory RelocDirectory { get; set; }
/// <summary>
/// Gets/sets the debug directory
/// </summary>
public DebugDirectory DebugDirectory { get; set; }
/// <summary>
/// Gets the image base
/// </summary>
public ulong ImageBase {
get { return imageBase; }
}
/// <summary>
/// Gets/sets a value indicating whether this is a EXE or a DLL file
/// </summary>
public bool IsExeFile {
get { return isExeFile; }
set { isExeFile = value; }
}
/// <inheritdoc/>
public FileOffset FileOffset {
get { return offset; }
}
/// <inheritdoc/>
public RVA RVA {
get { return rva; }
}
/// <summary>
/// Gets the section alignment
/// </summary>
public uint SectionAlignment {
get { return sectionAlignment; }
}
/// <summary>
/// Gets the file alignment
/// </summary>
public uint FileAlignment {
get { return fileAlignment; }
}
/// <summary>
/// Gets/sets the <see cref="PESection"/>s
/// </summary>
public IList<PESection> PESections {
get { return sections; }
set { sections = value; }
}
/// <summary>
/// Default constructor
/// </summary>
public PEHeaders()
: this(new PEHeadersOptions()) {
}
/// <summary>
/// Constructor
/// </summary>
/// <param name="options">Options</param>
public PEHeaders(PEHeadersOptions options) {
this.options = options ?? new PEHeadersOptions();
this.sectionAlignment = this.options.SectionAlignment ?? 0x2000;
this.fileAlignment = this.options.FileAlignment ?? 0x200;
}
/// <inheritdoc/>
public void SetOffset(FileOffset offset, RVA rva) {
this.offset = offset;
this.rva = rva;
length = (uint)dosHeader.Length;
length += 4 + 0x14;
length += Use32BitOptionalHeader() ? 0xE0U : 0xF0;
length += (uint)sections.Count * 0x28;
if (Use32BitOptionalHeader())
imageBase = options.ImageBase ?? 0x00400000;
else
imageBase = options.ImageBase ?? 0x0000000140000000;
}
/// <inheritdoc/>
public uint GetFileLength() {
return length;
}
/// <inheritdoc/>
public uint GetVirtualSize() {
return GetFileLength();
}
IEnumerable<SectionSizeInfo> GetSectionSizeInfos() {
foreach (var section in PESections)
yield return new SectionSizeInfo(section.GetVirtualSize(), section.Characteristics);
}
/// <inheritdoc/>
public void WriteTo(BinaryWriter writer) {
startOffset = writer.BaseStream.Position;
// DOS header
writer.Write(dosHeader);
// PE magic
writer.Write(0x00004550);
// Image file header
writer.Write((ushort)GetMachine());
writer.Write((ushort)sections.Count);
writer.Write(options.TimeDateStamp ?? PEHeadersOptions.CreateNewTimeDateStamp());
writer.Write(options.PointerToSymbolTable ?? 0);
writer.Write(options.NumberOfSymbols ?? 0);
writer.Write((ushort)(Use32BitOptionalHeader() ? 0xE0U : 0xF0));
writer.Write((ushort)GetCharacteristics());
var sectionSizes = new SectionSizes(fileAlignment, sectionAlignment, length, () => GetSectionSizeInfos());
// Image optional header
uint ep = StartupStub == null ? 0 : (uint)StartupStub.EntryPointRVA;
if (Use32BitOptionalHeader()) {
writer.Write((ushort)0x010B);
writer.Write(options.MajorLinkerVersion ?? PEHeadersOptions.DEFAULT_MAJOR_LINKER_VERSION);
writer.Write(options.MinorLinkerVersion ?? PEHeadersOptions.DEFAULT_MINOR_LINKER_VERSION);
writer.Write(sectionSizes.SizeOfCode);
writer.Write(sectionSizes.SizeOfInitdData);
writer.Write(sectionSizes.SizeOfUninitdData);
writer.Write(ep);
writer.Write(sectionSizes.BaseOfCode);
writer.Write(sectionSizes.BaseOfData);
writer.Write((uint)imageBase);
writer.Write(sectionAlignment);
writer.Write(fileAlignment);
writer.Write(options.MajorOperatingSystemVersion ?? 4);
writer.Write(options.MinorOperatingSystemVersion ?? 0);
writer.Write(options.MajorImageVersion ?? 0);
writer.Write(options.MinorImageVersion ?? 0);
writer.Write(options.MajorSubsystemVersion ?? 4);
writer.Write(options.MinorSubsystemVersion ?? 0);
writer.Write(options.Win32VersionValue ?? 0);
writer.Write(sectionSizes.SizeOfImage);
writer.Write(sectionSizes.SizeOfHeaders);
checkSumOffset = writer.BaseStream.Position;
writer.Write(0); // CheckSum
writer.Write((ushort)(options.Subsystem ?? PEHeadersOptions.DEFAULT_SUBSYSTEM));
writer.Write((ushort)(options.DllCharacteristics ?? PEHeadersOptions.DefaultDllCharacteristics));
writer.Write((uint)(options.SizeOfStackReserve ?? 0x00100000));
writer.Write((uint)(options.SizeOfStackCommit ?? 0x00001000));
writer.Write((uint)(options.SizeOfHeapReserve ?? 0x00100000));
writer.Write((uint)(options.SizeOfHeapCommit ?? 0x00001000));
writer.Write(options.LoaderFlags ?? 0x00000000);
writer.Write(options.NumberOfRvaAndSizes ?? 0x00000010);
}
else {
writer.Write((ushort)0x020B);
writer.Write(options.MajorLinkerVersion ?? PEHeadersOptions.DEFAULT_MAJOR_LINKER_VERSION);
writer.Write(options.MinorLinkerVersion ?? PEHeadersOptions.DEFAULT_MINOR_LINKER_VERSION);
writer.Write(sectionSizes.SizeOfCode);
writer.Write(sectionSizes.SizeOfInitdData);
writer.Write(sectionSizes.SizeOfUninitdData);
writer.Write(ep);
writer.Write(sectionSizes.BaseOfCode);
writer.Write(imageBase);
writer.Write(sectionAlignment);
writer.Write(fileAlignment);
writer.Write(options.MajorOperatingSystemVersion ?? 4);
writer.Write(options.MinorOperatingSystemVersion ?? 0);
writer.Write(options.MajorImageVersion ?? 0);
writer.Write(options.MinorImageVersion ?? 0);
writer.Write(options.MajorSubsystemVersion ?? 4);
writer.Write(options.MinorSubsystemVersion ?? 0);
writer.Write(options.Win32VersionValue ?? 0);
writer.Write(sectionSizes.SizeOfImage);
writer.Write(sectionSizes.SizeOfHeaders);
checkSumOffset = writer.BaseStream.Position;
writer.Write(0); // CheckSum
writer.Write((ushort)(options.Subsystem ?? PEHeadersOptions.DEFAULT_SUBSYSTEM));
writer.Write((ushort)(options.DllCharacteristics ?? PEHeadersOptions.DefaultDllCharacteristics));
writer.Write(options.SizeOfStackReserve ?? 0x0000000000400000);
writer.Write(options.SizeOfStackCommit ?? 0x0000000000004000);
writer.Write(options.SizeOfHeapReserve ?? 0x0000000000100000);
writer.Write(options.SizeOfHeapCommit ?? 0x0000000000002000);
writer.Write(options.LoaderFlags ?? 0x00000000);
writer.Write(options.NumberOfRvaAndSizes ?? 0x00000010);
}
writer.WriteDataDirectory(null); // Export table
writer.WriteDataDirectory(ImportDirectory);
writer.WriteDataDirectory(Win32Resources);
writer.WriteDataDirectory(null); // Exception table
writer.WriteDataDirectory(null); // Certificate table
writer.WriteDataDirectory(RelocDirectory);
writer.WriteDataDirectory(DebugDirectory, DebugDirectory.HEADER_SIZE);
writer.WriteDataDirectory(null); // Architecture-specific data
writer.WriteDataDirectory(null); // Global pointer register RVA
writer.WriteDataDirectory(null); // Thread local storage
writer.WriteDataDirectory(null); // Load configuration table
writer.WriteDataDirectory(null); // Bound import table
writer.WriteDataDirectory(ImportAddressTable);
writer.WriteDataDirectory(null); // Delay import descriptor
writer.WriteDataDirectory(ImageCor20Header);
writer.WriteDataDirectory(null); // Reserved
// Sections
uint rva = Utils.AlignUp(sectionSizes.SizeOfHeaders, sectionAlignment);
foreach (var section in sections)
rva += section.WriteHeaderTo(writer, fileAlignment, sectionAlignment, rva);
}
/// <summary>
/// Calculates the PE checksum and writes it to the checksum field
/// </summary>
/// <param name="writer">Writer</param>
/// <param name="length">Length of PE file</param>
public void WriteCheckSum(BinaryWriter writer, long length) {
writer.BaseStream.Position = startOffset;
uint checkSum = new BinaryReader(writer.BaseStream).CalculatePECheckSum(length, checkSumOffset);
writer.BaseStream.Position = checkSumOffset;
writer.Write(checkSum);
}
Machine GetMachine() {
return options.Machine ?? Machine.I386;
}
bool Use32BitOptionalHeader() {
var mach = GetMachine();
return mach != Machine.IA64 && mach != Machine.AMD64 && mach != Machine.ARM64;
}
Characteristics GetCharacteristics() {
var chr = options.Characteristics ?? GetDefaultCharacteristics();
if (IsExeFile)
chr &= ~Characteristics.Dll;
else
chr |= Characteristics.Dll;
return chr;
}
Characteristics GetDefaultCharacteristics() {
if (Use32BitOptionalHeader())
return Characteristics._32BitMachine | Characteristics.ExecutableImage;
return Characteristics.ExecutableImage | Characteristics.LargeAddressAware;
}
}
}
| |
// Copyright (c) Charlie Poole, Rob Prouse and Contributors. MIT License - see LICENSE.txt
using System;
using NUnit.Framework;
using System.Threading.Tasks;
namespace NUnit.TestData.AssertMultipleData
{
// NOTE: Some of these methods were getting optimized out of
// existence in the AppVeyor build. For that reason, we turned
// optimization off for the testdata assembly.
public class AssertMultipleFixture
{
private static readonly ComplexNumber complex = new ComplexNumber(5.2, 3.9);
[Test]
public void EmptyBlock()
{
Assert.Multiple(() => { });
}
[Test]
public void SingleAssertSucceeds()
{
Assert.Multiple(() =>
{
Assert.That(2 + 2, Is.EqualTo(4));
});
}
[Test]
public void TwoAssertsSucceed()
{
Assert.Multiple(() =>
{
Assert.That(complex.RealPart, Is.EqualTo(5.2));
Assert.That(complex.ImaginaryPart, Is.EqualTo(3.9));
});
}
[Test]
public void ThreeAssertsSucceed()
{
Assert.Multiple(() =>
{
Assert.That(2 + 2, Is.EqualTo(4));
Assert.That(complex.RealPart, Is.EqualTo(5.2));
Assert.That(complex.ImaginaryPart, Is.EqualTo(3.9));
});
}
[Test]
public void NestedBlock_ThreeAssertsSucceed()
{
Assert.Multiple(() =>
{
Assert.That(2 + 2, Is.EqualTo(4));
Assert.Multiple(() =>
{
Assert.That(complex.RealPart, Is.EqualTo(5.2));
Assert.That(complex.ImaginaryPart, Is.EqualTo(3.9));
});
});
}
[Test]
public void TwoNestedBlocks_ThreeAssertsSucceed()
{
Assert.Multiple(() =>
{
Assert.Multiple(() =>
{
Assert.That(2 + 2, Is.EqualTo(4));
});
Assert.Multiple(() =>
{
Assert.That(complex.RealPart, Is.EqualTo(5.2));
Assert.That(complex.ImaginaryPart, Is.EqualTo(3.9));
});
});
}
[Test]
public void NestedBlocksInMethodCalls()
{
SingleAssertSucceeds();
TwoAssertsSucceed();
}
[Test]
public void ThreeAssertWarns()
{
Assert.Multiple(() =>
{
Assert.Warn("WARNING1");
Assert.Warn("WARNING2");
Assert.Warn("WARNING3");
});
}
[Test]
public void ThreeWarnIf_AllPass()
{
Assert.Multiple(() =>
{
Warn.If(false, "WARNING1");
Warn.If(false, "WARNING2");
Warn.If(false, "WARNING3");
});
}
[Test]
public void ThreeWarnIf_TwoFail()
{
Assert.Multiple(() =>
{
Warn.If(true, "WARNING1");
Warn.If(false, "WARNING2");
Warn.If(true, "WARNING3");
});
}
[Test]
public void ThreeWarnUnless_AllPass()
{
Assert.Multiple(() =>
{
Warn.Unless(true, "WARNING1");
Warn.Unless(true, "WARNING2");
Warn.Unless(true, "WARNING3");
});
}
[Test]
public void ThreeWarnUnless_TwoFail()
{
Assert.Multiple(() =>
{
Warn.Unless(false, "WARNING1");
Warn.Unless(true, "WARNING2");
Warn.Unless(false, "WARNING3");
});
}
[Test]
public void MethodCallsFail()
{
Assert.Multiple(() =>
{
Assert.Fail("Message from Assert.Fail");
});
}
[Test]
public void MethodCallsFailAfterTwoAssertsFail()
{
Assert.Multiple(() =>
{
Assert.That(complex.RealPart, Is.EqualTo(5.0), "RealPart");
Assert.That(complex.ImaginaryPart, Is.EqualTo(4.2), "ImaginaryPart");
Assert.Fail("Message from Assert.Fail");
});
}
[Test]
public void WarningAfterTwoAssertsFail()
{
Assert.Multiple(() =>
{
Assert.That(complex.RealPart, Is.EqualTo(5.0), "RealPart");
Assert.That(complex.ImaginaryPart, Is.EqualTo(4.2), "ImaginaryPart");
Assert.Warn("WARNING");
});
}
[Test]
public void TwoAssertsFailAfterWarning()
{
Assert.Multiple(() =>
{
Assert.Warn("WARNING");
Assert.That(complex.RealPart, Is.EqualTo(5.0), "RealPart");
Assert.That(complex.ImaginaryPart, Is.EqualTo(4.2), "ImaginaryPart");
});
}
[Test]
public void TwoAsserts_FirstAssertFails()
{
Assert.Multiple(() =>
{
Assert.That(complex.RealPart, Is.EqualTo(5.0), "RealPart");
Assert.That(complex.ImaginaryPart, Is.EqualTo(3.9), "ImaginaryPart");
});
}
[Test]
public void TwoAsserts_SecondAssertFails()
{
Assert.Multiple(() =>
{
Assert.That(complex.RealPart, Is.EqualTo(5.2), "RealPart");
Assert.That(complex.ImaginaryPart, Is.EqualTo(4.2), "ImaginaryPart");
});
}
[Test]
public void TwoAsserts_BothAssertsFail()
{
Assert.Multiple(() =>
{
Assert.That(complex.RealPart, Is.EqualTo(5.0), "RealPart");
Assert.That(complex.ImaginaryPart, Is.EqualTo(4.2), "ImaginaryPart");
});
}
[Test]
public void NestedBlock_FirstAssertFails()
{
Assert.Multiple(() =>
{
Assert.That(2 + 2, Is.EqualTo(5));
Assert.Multiple(() =>
{
Assert.That(complex.RealPart, Is.EqualTo(5.2), "RealPart");
Assert.That(complex.ImaginaryPart, Is.EqualTo(3.9), "ImaginaryPart");
});
});
}
[Test]
public void NestedBlock_TwoAssertsFail()
{
Assert.Multiple(() =>
{
Assert.That(2 + 2, Is.EqualTo(5));
Assert.Multiple(() =>
{
Assert.That(complex.RealPart, Is.EqualTo(5.2), "RealPart");
Assert.That(complex.ImaginaryPart, Is.EqualTo(4.2), "ImaginaryPart");
});
});
}
[Test]
public void TwoNestedBlocks_FirstAssertFails()
{
Assert.Multiple(() =>
{
Assert.Multiple(() =>
{
Assert.That(2 + 2, Is.EqualTo(5));
});
Assert.Multiple(() =>
{
Assert.That(complex.RealPart, Is.EqualTo(5.2), "RealPart");
Assert.That(complex.ImaginaryPart, Is.EqualTo(3.9), "ImaginaryPart");
});
});
}
[Test]
public void TwoNestedBlocks_TwoAssertsFail()
{
Assert.Multiple(() =>
{
Assert.Multiple(() =>
{
Assert.That(2 + 2, Is.EqualTo(5));
});
Assert.Multiple(() =>
{
Assert.That(complex.RealPart, Is.EqualTo(5.2), "RealPart");
Assert.That(complex.ImaginaryPart, Is.EqualTo(4.2), "ImaginaryPart");
});
});
}
[Test]
public void ExceptionThrown()
{
Assert.Multiple(() =>
{
throw new Exception("Simulated Error");
});
}
[Test]
public void ExceptionThrownAfterTwoFailures()
{
Assert.Multiple(() =>
{
Assert.AreEqual(5, 2 + 2, "Failure 1");
Assert.True(1 == 0, "Failure 2");
throw new Exception("Simulated Error");
});
}
[Test]
public void ExceptionThrownAfterWarning()
{
Assert.Multiple(() =>
{
Assert.Warn("WARNING");
throw new Exception("Simulated Error");
});
}
[Test]
public void AssertPassInBlock()
{
Assert.Multiple(() =>
{
Assert.Pass("Message from Assert.Pass");
});
}
[Test]
public void AssertIgnoreInBlock()
{
Assert.Multiple(() =>
{
Assert.Ignore("Message from Assert.Ignore");
});
}
[Test]
public void AssertInconclusiveInBlock()
{
Assert.Multiple(() =>
{
Assert.Inconclusive("Message from Assert.Inconclusive");
});
}
[Test]
public void AssumptionInBlock()
{
Assert.Multiple(() =>
{
Assume.That(2 + 2 == 4);
});
}
[Test]
public void ThreeAssertsSucceed_Async()
{
Assert.Multiple(async () =>
{
await Task.Delay(100);
Assert.That(2 + 2, Is.EqualTo(4));
Assert.That(complex.RealPart, Is.EqualTo(5.2));
Assert.That(complex.ImaginaryPart, Is.EqualTo(3.9));
});
}
[Test]
public void NestedBlock_ThreeAssertsSucceed_Async()
{
Assert.Multiple(async () =>
{
await Task.Delay(100);
Assert.That(2 + 2, Is.EqualTo(4));
Assert.Multiple(async () =>
{
await Task.Delay(100);
Assert.That(complex.RealPart, Is.EqualTo(5.2));
Assert.That(complex.ImaginaryPart, Is.EqualTo(3.9));
});
});
}
[Test]
public void TwoNestedBlocks_ThreeAssertsSucceed_Async()
{
Assert.Multiple(() =>
{
Assert.Multiple(async () =>
{
await Task.Delay(100);
Assert.That(2 + 2, Is.EqualTo(4));
});
Assert.Multiple(async () =>
{
Assert.That(complex.RealPart, Is.EqualTo(5.2));
await Task.Delay(100);
Assert.That(complex.ImaginaryPart, Is.EqualTo(3.9));
});
});
}
[Test]
public void TwoAsserts_BothAssertsFail_Async()
{
Assert.Multiple(async () =>
{
await Task.Delay(100);
Assert.That(complex.RealPart, Is.EqualTo(5.0), "RealPart");
Assert.That(complex.ImaginaryPart, Is.EqualTo(4.2), "ImaginaryPart");
});
}
[Test]
public void TwoNestedBlocks_TwoAssertsFail_Async()
{
Assert.Multiple(() =>
{
Assert.Multiple(async () =>
{
await Task.Delay(100);
Assert.That(2 + 2, Is.EqualTo(5));
});
Assert.Multiple(async () =>
{
await Task.Delay(100);
Assert.That(complex.RealPart, Is.EqualTo(5.2), "RealPart");
Assert.That(complex.ImaginaryPart, Is.EqualTo(4.2), "ImaginaryPart");
});
});
}
}
class ComplexNumber
{
public ComplexNumber(double realPart, double imaginaryPart)
{
RealPart = realPart;
ImaginaryPart = imaginaryPart;
}
public double RealPart;
public double ImaginaryPart;
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;
#if !ES_BUILD_AGAINST_DOTNET_V35
using Contract = System.Diagnostics.Contracts.Contract;
#else
using Contract = Microsoft.Diagnostics.Contracts.Internal.Contract;
#endif
#if ES_BUILD_STANDALONE
namespace Microsoft.Diagnostics.Tracing
#else
namespace System.Diagnostics.Tracing
#endif
{
/// <summary>
/// Tracks activities. This is meant to be a singledon (accessed by the ActivityTracer.Instance static property)
///
/// Logically this is simply holds the m_current variable that holds the async local that holds the current ActivityInfo
/// An ActivityInfo is represents a actvity (which knows its creator and thus knows its path).
///
/// Most of the magic is in the async local (it gets copied to new tasks)
///
/// On every start event call OnStart
///
/// Guid activityID;
/// Guid relatedActivityID;
/// if (OnStart(activityName, out activityID, out relatedActivityID, ForceStop, options))
/// // Log Start event with activityID and relatedActivityID
///
/// On every stop event call OnStop
///
/// Guid activityID;
/// if (OnStop(activityName, ref activityID ForceStop))
/// // Stop event with activityID
///
/// On any normal event log the event with activityTracker.CurrentActivityId
/// </summary>
internal class ActivityTracker
{
/// <summary>
/// Called on work item begins. The activity name = providerName + activityName without 'Start' suffix.
/// It updates CurrentActivityId to track.
///
/// It returns true if the Start should be logged, otherwise (if it is illegal recurision) it return false.
///
/// The start event should use as its activity ID the CurrentActivityId AFTER calling this routine and its
/// RelatedActivityID the CurrentActivityId BEFORE calling this routine (the creator).
///
/// If activity tracing is not on, then activityId and relatedActivityId are not set
/// </summary>
public void OnStart(string providerName, string activityName, int task, ref Guid activityId, ref Guid relatedActivityId, EventActivityOptions options)
{
if (m_current == null) // We are not enabled
return;
Contract.Assert((options & EventActivityOptions.Disable) == 0);
var currentActivity = m_current.Value;
var fullActivityName = NormalizeActivityName(providerName, activityName, task);
var etwLog = TplEtwProvider.Log;
if (etwLog.Debug)
{
etwLog.DebugFacilityMessage("OnStartEnter", fullActivityName);
etwLog.DebugFacilityMessage("OnStartEnterActivityState", ActivityInfo.LiveActivities(currentActivity));
}
if (currentActivity != null)
{
// Stop activity tracking if we reached the maximum allowed depth
if (currentActivity.m_level >= MAX_ACTIVITY_DEPTH)
{
activityId = Guid.Empty;
relatedActivityId = Guid.Empty;
if (etwLog.Debug)
etwLog.DebugFacilityMessage("OnStartRET", "Fail");
return;
}
// Check for recursion, and force-stop any activities if the activity already started.
if ((options & EventActivityOptions.Recursive) == 0)
{
ActivityInfo existingActivity = FindActiveActivity(fullActivityName, currentActivity);
if (existingActivity != null)
{
OnStop(providerName, activityName, task, ref activityId);
currentActivity = m_current.Value;
}
}
}
// Get a unique ID for this activity.
long id;
if (currentActivity == null)
id = Interlocked.Increment(ref m_nextId);
else
id = Interlocked.Increment(ref currentActivity.m_lastChildID);
// Remember the previous ID so we can log it
relatedActivityId = currentActivity != null ? currentActivity.ActivityId : Guid.Empty;
// Add to the list of started but not stopped activities.
ActivityInfo newActivity = new ActivityInfo(fullActivityName, id, currentActivity, options);
m_current.Value = newActivity;
// Remember the current ID so we can log it
activityId = newActivity.ActivityId;
if (etwLog.Debug)
{
etwLog.DebugFacilityMessage("OnStartRetActivityState", ActivityInfo.LiveActivities(newActivity));
etwLog.DebugFacilityMessage1("OnStartRet", activityId.ToString(), relatedActivityId.ToString());
}
}
/// <summary>
/// Called when a work item stops. The activity name = providerName + activityName without 'Stop' suffix.
/// It updates CurrentActivityId to track this fact. The Stop event associated with stop should log the ActivityID associated with the event.
///
/// If activity tracing is not on, then activityId and relatedActivityId are not set
/// </summary>
public void OnStop(string providerName, string activityName, int task, ref Guid activityId)
{
if (m_current == null) // We are not enabled
return;
var fullActivityName = NormalizeActivityName(providerName, activityName, task);
var etwLog = TplEtwProvider.Log;
if (etwLog.Debug)
{
etwLog.DebugFacilityMessage("OnStopEnter", fullActivityName);
etwLog.DebugFacilityMessage("OnStopEnterActivityState", ActivityInfo.LiveActivities(m_current.Value));
}
for (; ;) // This is a retry loop.
{
ActivityInfo currentActivity = m_current.Value;
ActivityInfo newCurrentActivity = null; // if we have seen any live activities (orphans), at he first one we have seen.
// Search to find the activity to stop in one pass. This insures that we don't let one mistake
// (stopping something that was not started) cause all active starts to be stopped
// By first finding the target start to stop we are more robust.
ActivityInfo activityToStop = FindActiveActivity(fullActivityName, currentActivity);
// ignore stops where we can't find a start because we may have popped them previously.
if (activityToStop == null)
{
activityId = Guid.Empty;
// Basically could not find matching start.
if (etwLog.Debug)
etwLog.DebugFacilityMessage("OnStopRET", "Fail");
return;
}
activityId = activityToStop.ActivityId;
// See if there are any orphans that need to be stopped.
ActivityInfo orphan = currentActivity;
while (orphan != activityToStop && orphan != null)
{
if (orphan.m_stopped != 0) // Skip dead activities.
{
orphan = orphan.m_creator;
continue;
}
if (orphan.CanBeOrphan())
{
// We can't pop anything after we see a valid orphan, remember this for later when we update m_current.
if (newCurrentActivity == null)
newCurrentActivity = orphan;
}
else
{
orphan.m_stopped = 1;
Contract.Assert(orphan.m_stopped != 0);
}
orphan = orphan.m_creator;
}
// try to Stop the activity atomically. Other threads may be trying to do this as well.
if (Interlocked.CompareExchange(ref activityToStop.m_stopped, 1, 0) == 0)
{
// I succeeded stopping this activity. Now we update our m_current pointer
// If I haven't yet determined the new current activity, it is my creator.
if (newCurrentActivity == null)
newCurrentActivity = activityToStop.m_creator;
m_current.Value = newCurrentActivity;
if (etwLog.Debug)
{
etwLog.DebugFacilityMessage("OnStopRetActivityState", ActivityInfo.LiveActivities(newCurrentActivity));
etwLog.DebugFacilityMessage("OnStopRet", activityId.ToString());
}
return;
}
// We failed to stop it. We must have hit a race condition to stop it. Just start over and try again.
}
}
/// <summary>
/// Turns on activity tracking. It is sticky, once on it stays on (race issues otherwise)
/// </summary>
[System.Security.SecuritySafeCritical]
public void Enable()
{
if (m_current == null)
{
EventSource.OutputDebugString("Enabling Activity Tracking");
m_current = new AsyncLocal<ActivityInfo>(ActivityChanging);
}
}
/// <summary>
/// An activity tracker is a singleton, this is how you get the one and only instance.
/// </summary>
public static ActivityTracker Instance { get { return s_activityTrackerInstance; } }
#region private
/// <summary>
/// The current activity ID. Use this to log normal events.
/// </summary>
private Guid CurrentActivityId { get { return m_current.Value.ActivityId; } }
/// <summary>
/// Searched for a active (nonstopped) activity with the given name. Returns null if not found.
/// </summary>
private ActivityInfo FindActiveActivity(string name, ActivityInfo startLocation)
{
var activity = startLocation;
while (activity != null)
{
if (name == activity.m_name && activity.m_stopped == 0)
return activity;
activity = activity.m_creator;
}
return null;
}
/// <summary>
/// Strip out "Start" or "End" suffix from activity name and add providerName prefix.
/// If 'task' it does not end in Start or Stop and Task is non-zero use that as the name of the activity
/// </summary>
private string NormalizeActivityName(string providerName, string activityName, int task)
{
if (activityName.EndsWith(EventSource.s_ActivityStartSuffix))
activityName = activityName.Substring(0, activityName.Length - EventSource.s_ActivityStartSuffix.Length);
else if (activityName.EndsWith(EventSource.s_ActivityStopSuffix))
activityName = activityName.Substring(0, activityName.Length - EventSource.s_ActivityStopSuffix.Length);
else if (task != 0)
activityName = "task" + task.ToString();
// We use provider name to distinguish between activities from different providers.
return providerName + activityName;
}
// *******************************************************************************
/// <summary>
/// An ActivityInfo repesents a particular activity. It is almost read-only the only
/// fields that change after creation are
/// m_lastChildID - used to generate unique IDs for the children activities and for the most part can be ignored.
/// m_stopped - indicates that this activity is dead
/// This read-only ness is important because an activity's m_creator chain forms the
/// 'Path of creation' for the activity (which is also its unique ID) but is also used as
/// the 'list of live parents' which indicate of those ancestors, which are alive (if they
/// are not marked dead they are alive).
/// </summary>
private class ActivityInfo
{
public ActivityInfo(string name, long uniqueId, ActivityInfo creator, EventActivityOptions options)
{
m_name = name;
m_eventOptions = options;
m_creator = creator;
m_uniqueId = uniqueId;
m_level = creator != null ? creator.m_level + 1 : 0;
// Create a nice GUID that encodes the chain of activities that started this one.
CreateActivityPathGuid(out m_guid, out m_activityPathGuidOffset);
}
public Guid ActivityId
{
get
{
return m_guid;
}
}
public static string Path(ActivityInfo activityInfo)
{
if (activityInfo == null)
return("");
return Path(activityInfo.m_creator) + "/" + activityInfo.m_uniqueId;
}
public override string ToString()
{
string dead = "";
if (m_stopped != 0)
dead = ",DEAD";
return m_name + "(" + Path(this) + dead + ")";
}
public static string LiveActivities(ActivityInfo list)
{
if (list == null)
return "";
return list.ToString() + ";" + LiveActivities(list.m_creator);
}
public bool CanBeOrphan()
{
if ((m_eventOptions & EventActivityOptions.Detachable) != 0)
return true;
return false;
}
#region private
#region CreateActivityPathGuid
/// <summary>
/// Logically every activity Path (see Path()) that describes the activities that caused this
/// (rooted in an activity that predates activity tracking.
///
/// We wish to encode this path in the Guid to the extent that we can. Many of the paths have
/// many small numbers in them and we take advatage of this in the encoding to output as long
/// a path in the GUID as possible.
///
/// Because of the possiblility of GUID collistion, we only use 96 of the 128 bits of the GUID
/// for encoding the path. The last 32 bits are a simple checksum (and random number) that
/// identifies this as using the convention defined here.
///
/// It returns both the GUID which has the path as well as the offset that points just beyond
/// the end of the activity (so it can be appended to). Note that if the end is in a nibble
/// (it uses nibbles instead of bytes as the unit of encoding, then it will point at the unfinished
/// byte (since the top nibble can't be zero you can determine if this is true by seeing if
/// this byte is nonZero. This offset is needed to efficiently create the ID for child activities.
/// </summary>
[System.Security.SecuritySafeCritical]
private unsafe void CreateActivityPathGuid(out Guid idRet, out int activityPathGuidOffset)
{
fixed (Guid* outPtr = &idRet)
{
int activityPathGuidOffsetStart = 0;
if (m_creator != null)
{
activityPathGuidOffsetStart = m_creator.m_activityPathGuidOffset;
idRet = m_creator.m_guid;
}
else
{
// We start with the appdomain number to make this unique among appdomains.
activityPathGuidOffsetStart = AddIdToGuid(outPtr, activityPathGuidOffsetStart, (uint) System.Threading.Thread.GetDomainID());
}
activityPathGuidOffset = AddIdToGuid(outPtr, activityPathGuidOffsetStart, (uint) m_uniqueId);
// If the path does not fit, Make a GUID by incrementing rather than as a path, keeping as much of the path as possible
if (12 < activityPathGuidOffset)
CreateOverflowGuid(outPtr);
}
}
/// <summary>
/// If we can't fit the activity Path into the GUID we come here. What we do is simply
/// generate a 4 byte number (s_nextOverflowId). Then look for an anscesor that has
/// sufficient space for this ID. By doing this, we preserve the fact that this activity
/// is a child (of unknown depth) from that ancestor.
/// </summary>
[System.Security.SecurityCritical]
private unsafe void CreateOverflowGuid(Guid* outPtr)
{
// Seach backwards for an ancestor that has sufficient space to put the ID.
for(ActivityInfo ancestor = m_creator; ancestor != null; ancestor = ancestor.m_creator)
{
if (ancestor.m_activityPathGuidOffset <= 10) // we need at least 2 bytes.
{
uint id = (uint) Interlocked.Increment(ref ancestor.m_lastChildID); // Get a unique ID
// Try to put the ID into the GUID
*outPtr = ancestor.m_guid;
int endId = AddIdToGuid(outPtr, ancestor.m_activityPathGuidOffset, id, true);
// Does it fit?
if (endId <= 12)
break;
}
}
}
/// <summary>
/// The encoding for a list of numbers used to make Activity Guids. Basically
/// we operate on nibbles (which are nice becase they show up as hex digits). The
/// list is ended with a end nibble (0) and depending on the nibble value (Below)
/// the value is either encoded into nibble itself or it can spill over into the
/// bytes that follow.
/// </summary>
enum NumberListCodes : byte
{
End = 0x0, // ends the list. No valid value has this prefix.
LastImmediateValue = 0xA,
PrefixCode = 0xB, // all the 'long' encodings go here. If the next nibble is MultiByte1-4
// than this is a 'overflow' id. Unlike the hierarchitcal IDs these are
// allocated densly but don't tell you anything about nesting. we use
// these when we run out of space in the GUID to store the path.
MultiByte1 = 0xC, // 1 byte follows. If this Nibble is in the high bits, it the high bits of the number are stored in the low nibble.
// commented out because the code does not explicitly reference the names (but they are logically defined).
// MultiByte2 = 0xD, // 2 bytes follow (we don't bother with the nibble optimzation)
// MultiByte3 = 0xE, // 3 bytes follow (we don't bother with the nibble optimzation)
// MultiByte4 = 0xF, // 4 bytes follow (we don't bother with the nibble optimzation)
}
/// Add the acivity id 'id' to the output Guid 'outPtr' starting at the offset 'whereToAddId'
/// Thus if this number is 6 that is where 'id' will be added. This will return 13 (12
/// is the maximum number of bytes that fit in a GUID) if the path did not fit.
/// If 'overflow' is true, then the number is encoded as an 'overflow number (which has a
/// special (longer prefix) that indicates that this ID is allocated differently
[System.Security.SecurityCritical]
private static unsafe int AddIdToGuid(Guid* outPtr, int whereToAddId, uint id, bool overflow = false)
{
byte* ptr = (byte*)outPtr;
byte* endPtr = ptr + 12;
ptr += whereToAddId;
if (endPtr <= ptr)
return 13; // 12 means we might exactly fit, 13 means we definately did not fit
if (0 < id && id <= (uint)NumberListCodes.LastImmediateValue && !overflow)
WriteNibble(ref ptr, endPtr, id);
else
{
uint len = 4;
if (id <= 0xFF)
len = 1;
else if (id <= 0xFFFF)
len = 2;
else if (id <= 0xFFFFFF)
len = 3;
if (overflow)
{
if (endPtr <= ptr + 2) // I need at least 2 bytes
return 13;
// Write out the prefix code nibble and the length nibble
WriteNibble(ref ptr, endPtr, (uint) NumberListCodes.PrefixCode);
}
// The rest is the same for overflow and non-overflow case
WriteNibble(ref ptr, endPtr, (uint)NumberListCodes.MultiByte1 + (len - 1));
// Do we have an odd nibble? If so flush it or use it for the 12 byte case.
if (ptr < endPtr && *ptr != 0)
{
// If the value < 4096 we can use the nibble we are otherwise just outputing as padding.
if (id < 4096)
{
// Indicate this is a 1 byte multicode with 4 high order bits in the lower nibble.
*ptr = (byte)(((uint)NumberListCodes.MultiByte1 << 4) + (id >> 8));
id &= 0xFF; // Now we only want the low order bits.
}
ptr++;
}
// Write out the bytes.
while(0 < len)
{
if (endPtr <= ptr)
{
ptr++; // Indicate that we have overflowed
break;
}
*ptr++ = (byte)id;
id = (id >> 8);
--len;
}
}
// Compute the checksum
uint* sumPtr = (uint*)outPtr;
// We set the last DWORD the sum of the first 3 DWORDS in the GUID. This
sumPtr[3] = sumPtr[0] + sumPtr[1] + sumPtr[2] + 0x599D99AD; // This last number is a random number (it identifies us as us)
return (int)(ptr - ((byte*)outPtr));
}
/// <summary>
/// Write a single Nible 'value' (must be 0-15) to the byte buffer represented by *ptr.
/// Will not go past 'endPtr'. Also it assumes that we never write 0 so we can detect
/// whether a nibble has already been written to ptr because it will be nonzero.
/// Thus if it is non-zero it adds to the current byte, otherwise it advances and writes
/// the new byte (in the high bits) of the next byte.
/// </summary>
[System.Security.SecurityCritical]
private static unsafe void WriteNibble(ref byte* ptr, byte* endPtr, uint value)
{
Contract.Assert(0 <= value && value < 16);
Contract.Assert(ptr < endPtr);
if (*ptr != 0)
*ptr++ |= (byte)value;
else
*ptr = (byte)(value << 4);
}
#endregion // CreateGuidForActivityPath
readonly internal string m_name; // The name used in the 'start' and 'stop' APIs to help match up
readonly long m_uniqueId; // a small number that makes this activity unique among its siblings
internal readonly Guid m_guid; // Activity Guid, it is bascially an encoding of the Path() (see CreateActivityPathGuid)
internal readonly int m_activityPathGuidOffset; // Keeps track of where in m_guid the causality path stops (used to generated child GUIDs)
internal readonly int m_level; // current depth of the Path() of the activity (used to keep recursion under control)
readonly internal EventActivityOptions m_eventOptions; // Options passed to start.
internal long m_lastChildID; // used to create a unique ID for my children activities
internal int m_stopped; // This work item has stopped
readonly internal ActivityInfo m_creator; // My parent (creator). Forms the Path() for the activity.
#endregion
}
// This callback is used to initialize the m_current AsyncLocal Variable.
// Its job is to keep the ETW Activity ID (part of thread local storage) in sync
// with m_current.ActivityID
void ActivityChanging(AsyncLocalValueChangedArgs<ActivityInfo> args)
{
if (args.PreviousValue == args.CurrentValue)
return;
if (args.CurrentValue != null)
{
// Allow subsequent activities inside this thread to automatically get the current activity ID.
EventSource.SetCurrentThreadActivityId(args.CurrentValue.ActivityId);
}
else
EventSource.SetCurrentThreadActivityId(Guid.Empty);
}
/// <summary>
/// Async local variables have the propery that the are automatically copied whenever a task is created and used
/// while that task is running. Thus m_current 'flows' to any task that is caused by the current thread that
/// last set it.
///
/// This variable points a a linked list that represents all Activities that have started but have not stopped.
/// </summary>
AsyncLocal<ActivityInfo> m_current;
// Singleton
private static ActivityTracker s_activityTrackerInstance = new ActivityTracker();
// Used to create unique IDs at the top level. Not used for nested Ids (each activity has its own id generator)
static long m_nextId = 0;
private const ushort MAX_ACTIVITY_DEPTH = 100; // Limit maximum depth of activities to be tracked at 100.
// This will avoid leaking memory in case of activities that are never stopped.
#endregion
}
}
| |
//
// ListViewBackend.cs
//
// Author:
// Lluis Sanchez <lluis@xamarin.com>
//
// Copyright (c) 2011 Xamarin Inc
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using System;
using Xwt.Backends;
using System.Linq;
namespace Xwt.GtkBackend
{
public class ListViewBackend: TableViewBackend, IListViewBackend
{
bool showBorder;
protected override void ButtonPressedInternal(ButtonEventArgs a)
{
if (a.Button == PointerButton.Right && SelectedRows.Length > 1)
{
a.Handled = true;
}
}
protected new IListViewEventSink EventSink {
get { return (IListViewEventSink)base.EventSink; }
}
public override void EnableEvent (object eventId)
{
base.EnableEvent (eventId);
if (eventId is ListViewEvent) {
if (((ListViewEvent)eventId) == ListViewEvent.RowActivated)
Widget.RowActivated += HandleRowActivated;
}
}
public override void DisableEvent (object eventId)
{
base.DisableEvent (eventId);
if (eventId is ListViewEvent) {
if (((ListViewEvent)eventId) == ListViewEvent.RowActivated)
Widget.RowActivated -= HandleRowActivated;
}
}
void HandleRowActivated (object o, Gtk.RowActivatedArgs args)
{
ApplicationContext.InvokeUserCode (delegate {
EventSink.OnRowActivated (args.Path.Indices[0]);
});
}
public void SetSource (IListDataSource source, IBackend sourceBackend)
{
ListStoreBackend b = sourceBackend as ListStoreBackend;
if (b == null) {
CustomListModel model = new CustomListModel (source, Widget);
Widget.Model = model.Store;
} else
Widget.Model = b.Store;
}
public void SelectRow (int row)
{
Gtk.TreeIter it;
if (!Widget.Model.IterNthChild (out it, row))
return;
Widget.Selection.SelectIter (it);
/* INTRODUCED BY houen */
// scrolls the listview to the selected cell
var path = Widget.Model.GetPath(it);
var column = Widget.Columns[0];
Widget.ScrollToCell(path, column, false, 0, 0);
/* INTRODUCED BY houen */
}
public void UnselectRow (int row)
{
Gtk.TreeIter it;
if (!Widget.Model.IterNthChild (out it, row))
return;
Widget.Selection.UnselectIter (it);
}
public void ScrollToRow (int row)
{
Gtk.TreeIter it;
if (!Widget.Model.IterNthChild (out it, row))
return;
ScrollToRow (it);
}
public int[] SelectedRows {
get {
var sel = Widget.Selection.GetSelectedRows ();
int[] res = new int [sel.Length];
for (int n=0; n<sel.Length; n++)
res [n] = sel [n].Indices[0];
return res;
}
}
public int FocusedRow {
get {
Gtk.TreePath path;
Gtk.TreeViewColumn column;
Widget.GetCursor (out path, out column);
if (path == null)
return -1;
return path.Indices [0];
}
set {
Gtk.TreePath path = new Gtk.TreePath (new [] { value >= 0 ? value : int.MaxValue });
Widget.SetCursor (path, null, false);
}
}
public int CurrentEventRow {
get;
internal set;
}
public bool BorderVisible {
get {
return ScrolledWindow.ShadowType == Gtk.ShadowType.In;
}
set {
showBorder = value;
UpdateBorder ();
}
}
void UpdateBorder ()
{
var shadowType = showBorder ? Gtk.ShadowType.In : Gtk.ShadowType.None;
if (ScrolledWindow.Child is Gtk.Viewport)
((Gtk.Viewport) ScrolledWindow.Child).ShadowType = shadowType;
else
ScrolledWindow.ShadowType = shadowType;
}
public bool HeadersVisible {
get {
return Widget.HeadersVisible;
}
set {
Widget.HeadersVisible = value;
}
}
public int GetRowAtPosition (Point p)
{
Gtk.TreePath path = GetPathAtPosition (p);
if (path != null)
return path.Indices [0];
return -1;
}
public Rectangle GetCellBounds (int row, CellView cell, bool includeMargin)
{
var col = GetCellColumn (cell);
var cr = GetCellRenderer (cell);
Gtk.TreePath path = new Gtk.TreePath (new [] { row });
Gtk.TreeIter iter;
if (!Widget.Model.GetIterFromString (out iter, path.ToString ()))
return Rectangle.Zero;
if (includeMargin)
return ((ICellRendererTarget)this).GetCellBackgroundBounds (col, cr, iter);
else
return ((ICellRendererTarget)this).GetCellBounds (col, cr, iter);
}
public Rectangle GetRowBounds (int row, bool includeMargin)
{
Gtk.TreePath path = new Gtk.TreePath (new [] { row });
Gtk.TreeIter iter;
if (!Widget.Model.GetIterFromString (out iter, path.ToString ()))
return Rectangle.Zero;
if (includeMargin)
return GetRowBackgroundBounds (iter);
else
return GetRowBounds (iter);
}
public override void SetCurrentEventRow (string path)
{
if (path.Contains (":")) {
path = path.Split (':') [0];
}
CurrentEventRow = int.Parse (path);
}
}
}
| |
using System;
using System.IO;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using RestSharp;
using IO.Swagger.Client;
using IO.Swagger.Model;
namespace IO.Swagger.Api
{
/// <summary>
/// Represents a collection of functions to interact with the API endpoints
/// </summary>
public interface IReputationApi
{
#region Synchronous Operations
/// <summary>
/// Report: report spam calls received to better tune our algorithms based upon spam calls you receive
/// </summary>
/// <remarks>
/// This returns information required to perform basic call blocking behaviors<br />\r\n Try with api_key 'demo' and phone numbers 18008472911, 13157244022, 17275567300, 18008276655, and 12061231234 (last one not spam)
/// </remarks>
/// <exception cref="IO.Swagger.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="callReport">[FromBody] Call Report\r\n PhoneNumber, \r\n Caller name(optional), \r\n Call category(optional), \r\n Comment or tags(free text) (optional), \r\n Unwanted call - yes/no(optional),</param>
/// <returns></returns>
void ReputationReport (CallReport callReport);
/// <summary>
/// Report: report spam calls received to better tune our algorithms based upon spam calls you receive
/// </summary>
/// <remarks>
/// This returns information required to perform basic call blocking behaviors<br />\r\n Try with api_key 'demo' and phone numbers 18008472911, 13157244022, 17275567300, 18008276655, and 12061231234 (last one not spam)
/// </remarks>
/// <exception cref="IO.Swagger.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="callReport">[FromBody] Call Report\r\n PhoneNumber, \r\n Caller name(optional), \r\n Call category(optional), \r\n Comment or tags(free text) (optional), \r\n Unwanted call - yes/no(optional),</param>
/// <returns>ApiResponse of Object(void)</returns>
ApiResponse<Object> ReputationReportWithHttpInfo (CallReport callReport);
/// <summary>
/// Reputation:\r\n Premium service which returns a reputation informaiton of a phone number via API.
/// </summary>
/// <remarks>
/// This returns information required to perform basic call blocking behaviors<br />\r\n Try with api_key 'demo' and phone numbers 18008472911, 13157244022, 17275567300, 18008276655, and 12061231234 (last one not spam)
/// </remarks>
/// <exception cref="IO.Swagger.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="phoneNumber">phone number to search</param>
/// <returns>Reputation</returns>
Reputation ReputationReputation (string phoneNumber);
/// <summary>
/// Reputation:\r\n Premium service which returns a reputation informaiton of a phone number via API.
/// </summary>
/// <remarks>
/// This returns information required to perform basic call blocking behaviors<br />\r\n Try with api_key 'demo' and phone numbers 18008472911, 13157244022, 17275567300, 18008276655, and 12061231234 (last one not spam)
/// </remarks>
/// <exception cref="IO.Swagger.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="phoneNumber">phone number to search</param>
/// <returns>ApiResponse of Reputation</returns>
ApiResponse<Reputation> ReputationReputationWithHttpInfo (string phoneNumber);
#endregion Synchronous Operations
#region Asynchronous Operations
/// <summary>
/// Report: report spam calls received to better tune our algorithms based upon spam calls you receive
/// </summary>
/// <remarks>
/// This returns information required to perform basic call blocking behaviors<br />\r\n Try with api_key 'demo' and phone numbers 18008472911, 13157244022, 17275567300, 18008276655, and 12061231234 (last one not spam)
/// </remarks>
/// <exception cref="IO.Swagger.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="callReport">[FromBody] Call Report\r\n PhoneNumber, \r\n Caller name(optional), \r\n Call category(optional), \r\n Comment or tags(free text) (optional), \r\n Unwanted call - yes/no(optional),</param>
/// <returns>Task of void</returns>
System.Threading.Tasks.Task ReputationReportAsync (CallReport callReport);
/// <summary>
/// Report: report spam calls received to better tune our algorithms based upon spam calls you receive
/// </summary>
/// <remarks>
/// This returns information required to perform basic call blocking behaviors<br />\r\n Try with api_key 'demo' and phone numbers 18008472911, 13157244022, 17275567300, 18008276655, and 12061231234 (last one not spam)
/// </remarks>
/// <exception cref="IO.Swagger.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="callReport">[FromBody] Call Report\r\n PhoneNumber, \r\n Caller name(optional), \r\n Call category(optional), \r\n Comment or tags(free text) (optional), \r\n Unwanted call - yes/no(optional),</param>
/// <returns>Task of ApiResponse</returns>
System.Threading.Tasks.Task<ApiResponse<Object>> ReputationReportAsyncWithHttpInfo (CallReport callReport);
/// <summary>
/// Reputation:\r\n Premium service which returns a reputation informaiton of a phone number via API.
/// </summary>
/// <remarks>
/// This returns information required to perform basic call blocking behaviors<br />\r\n Try with api_key 'demo' and phone numbers 18008472911, 13157244022, 17275567300, 18008276655, and 12061231234 (last one not spam)
/// </remarks>
/// <exception cref="IO.Swagger.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="phoneNumber">phone number to search</param>
/// <returns>Task of Reputation</returns>
System.Threading.Tasks.Task<Reputation> ReputationReputationAsync (string phoneNumber);
/// <summary>
/// Reputation:\r\n Premium service which returns a reputation informaiton of a phone number via API.
/// </summary>
/// <remarks>
/// This returns information required to perform basic call blocking behaviors<br />\r\n Try with api_key 'demo' and phone numbers 18008472911, 13157244022, 17275567300, 18008276655, and 12061231234 (last one not spam)
/// </remarks>
/// <exception cref="IO.Swagger.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="phoneNumber">phone number to search</param>
/// <returns>Task of ApiResponse (Reputation)</returns>
System.Threading.Tasks.Task<ApiResponse<Reputation>> ReputationReputationAsyncWithHttpInfo (string phoneNumber);
#endregion Asynchronous Operations
}
/// <summary>
/// Represents a collection of functions to interact with the API endpoints
/// </summary>
public class ReputationApi : IReputationApi
{
/// <summary>
/// Initializes a new instance of the <see cref="ReputationApi"/> class.
/// </summary>
/// <returns></returns>
public ReputationApi(String basePath)
{
this.Configuration = new Configuration(new ApiClient(basePath));
// ensure API client has configuration ready
if (Configuration.ApiClient.Configuration == null)
{
this.Configuration.ApiClient.Configuration = this.Configuration;
}
}
/// <summary>
/// Initializes a new instance of the <see cref="ReputationApi"/> class
/// using Configuration object
/// </summary>
/// <param name="configuration">An instance of Configuration</param>
/// <returns></returns>
public ReputationApi(Configuration configuration = null)
{
if (configuration == null) // use the default one in Configuration
this.Configuration = Configuration.Default;
else
this.Configuration = configuration;
// ensure API client has configuration ready
if (Configuration.ApiClient.Configuration == null)
{
this.Configuration.ApiClient.Configuration = this.Configuration;
}
}
/// <summary>
/// Gets the base path of the API client.
/// </summary>
/// <value>The base path</value>
public String GetBasePath()
{
return this.Configuration.ApiClient.RestClient.BaseUrl.ToString();
}
/// <summary>
/// Sets the base path of the API client.
/// </summary>
/// <value>The base path</value>
[Obsolete("SetBasePath is deprecated, please do 'Configuraiton.ApiClient = new ApiClient(\"http://new-path\")' instead.")]
public void SetBasePath(String basePath)
{
// do nothing
}
/// <summary>
/// Gets or sets the configuration object
/// </summary>
/// <value>An instance of the Configuration</value>
public Configuration Configuration {get; set;}
/// <summary>
/// Gets the default header.
/// </summary>
/// <returns>Dictionary of HTTP header</returns>
[Obsolete("DefaultHeader is deprecated, please use Configuration.DefaultHeader instead.")]
public Dictionary<String, String> DefaultHeader()
{
return this.Configuration.DefaultHeader;
}
/// <summary>
/// Add default header.
/// </summary>
/// <param name="key">Header field name.</param>
/// <param name="value">Header field value.</param>
/// <returns></returns>
[Obsolete("AddDefaultHeader is deprecated, please use Configuration.AddDefaultHeader instead.")]
public void AddDefaultHeader(string key, string value)
{
this.Configuration.AddDefaultHeader(key, value);
}
/// <summary>
/// Report: report spam calls received to better tune our algorithms based upon spam calls you receive This returns information required to perform basic call blocking behaviors<br />\r\n Try with api_key 'demo' and phone numbers 18008472911, 13157244022, 17275567300, 18008276655, and 12061231234 (last one not spam)
/// </summary>
/// <exception cref="IO.Swagger.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="callReport">[FromBody] Call Report\r\n PhoneNumber, \r\n Caller name(optional), \r\n Call category(optional), \r\n Comment or tags(free text) (optional), \r\n Unwanted call - yes/no(optional),</param>
/// <returns></returns>
public void ReputationReport (CallReport callReport)
{
ReputationReportWithHttpInfo(callReport);
}
/// <summary>
/// Report: report spam calls received to better tune our algorithms based upon spam calls you receive This returns information required to perform basic call blocking behaviors<br />\r\n Try with api_key 'demo' and phone numbers 18008472911, 13157244022, 17275567300, 18008276655, and 12061231234 (last one not spam)
/// </summary>
/// <exception cref="IO.Swagger.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="callReport">[FromBody] Call Report\r\n PhoneNumber, \r\n Caller name(optional), \r\n Call category(optional), \r\n Comment or tags(free text) (optional), \r\n Unwanted call - yes/no(optional),</param>
/// <returns>ApiResponse of Object(void)</returns>
public ApiResponse<Object> ReputationReportWithHttpInfo (CallReport callReport)
{
// verify the required parameter 'callReport' is set
if (callReport == null)
throw new ApiException(400, "Missing required parameter 'callReport' when calling ReputationApi->ReputationReport");
var localVarPath = "/api/2015-11-01/Report";
var localVarPathParams = new Dictionary<String, String>();
var localVarQueryParams = new Dictionary<String, String>();
var localVarHeaderParams = new Dictionary<String, String>(Configuration.DefaultHeader);
var localVarFormParams = new Dictionary<String, String>();
var localVarFileParams = new Dictionary<String, FileParameter>();
Object localVarPostBody = null;
// to determine the Content-Type header
String[] localVarHttpContentTypes = new String[] {
"application/json", "text/json", "application/xml", "text/xml", "application/x-www-form-urlencoded"
};
String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes);
// to determine the Accept header
String[] localVarHttpHeaderAccepts = new String[] {
"application/json", "text/json", "application/xml", "text/xml"
};
String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts);
if (localVarHttpHeaderAccept != null)
localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept);
// set "format" to json by default
// e.g. /pet/{petId}.{format} becomes /pet/{petId}.json
localVarPathParams.Add("format", "json");
if (callReport.GetType() != typeof(byte[]))
{
localVarPostBody = Configuration.ApiClient.Serialize(callReport); // http body (model) parameter
}
else
{
localVarPostBody = callReport; // byte array
}
// make the HTTP request
IRestResponse localVarResponse = (IRestResponse) Configuration.ApiClient.CallApi(localVarPath,
Method.POST, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams,
localVarPathParams, localVarHttpContentType);
int localVarStatusCode = (int) localVarResponse.StatusCode;
if (localVarStatusCode >= 400)
throw new ApiException (localVarStatusCode, "Error calling ReputationReport: " + localVarResponse.Content, localVarResponse.Content);
else if (localVarStatusCode == 0)
throw new ApiException (localVarStatusCode, "Error calling ReputationReport: " + localVarResponse.ErrorMessage, localVarResponse.ErrorMessage);
return new ApiResponse<Object>(localVarStatusCode,
localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()),
null);
}
/// <summary>
/// Report: report spam calls received to better tune our algorithms based upon spam calls you receive This returns information required to perform basic call blocking behaviors<br />\r\n Try with api_key 'demo' and phone numbers 18008472911, 13157244022, 17275567300, 18008276655, and 12061231234 (last one not spam)
/// </summary>
/// <exception cref="IO.Swagger.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="callReport">[FromBody] Call Report\r\n PhoneNumber, \r\n Caller name(optional), \r\n Call category(optional), \r\n Comment or tags(free text) (optional), \r\n Unwanted call - yes/no(optional),</param>
/// <returns>Task of void</returns>
public async System.Threading.Tasks.Task ReputationReportAsync (CallReport callReport)
{
await ReputationReportAsyncWithHttpInfo(callReport);
}
/// <summary>
/// Report: report spam calls received to better tune our algorithms based upon spam calls you receive This returns information required to perform basic call blocking behaviors<br />\r\n Try with api_key 'demo' and phone numbers 18008472911, 13157244022, 17275567300, 18008276655, and 12061231234 (last one not spam)
/// </summary>
/// <exception cref="IO.Swagger.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="callReport">[FromBody] Call Report\r\n PhoneNumber, \r\n Caller name(optional), \r\n Call category(optional), \r\n Comment or tags(free text) (optional), \r\n Unwanted call - yes/no(optional),</param>
/// <returns>Task of ApiResponse</returns>
public async System.Threading.Tasks.Task<ApiResponse<Object>> ReputationReportAsyncWithHttpInfo (CallReport callReport)
{
// verify the required parameter 'callReport' is set
if (callReport == null) throw new ApiException(400, "Missing required parameter 'callReport' when calling ReputationReport");
var localVarPath = "/api/2015-11-01/Report";
var localVarPathParams = new Dictionary<String, String>();
var localVarQueryParams = new Dictionary<String, String>();
var localVarHeaderParams = new Dictionary<String, String>(Configuration.DefaultHeader);
var localVarFormParams = new Dictionary<String, String>();
var localVarFileParams = new Dictionary<String, FileParameter>();
Object localVarPostBody = null;
// to determine the Content-Type header
String[] localVarHttpContentTypes = new String[] {
"application/json", "text/json", "application/xml", "text/xml", "application/x-www-form-urlencoded"
};
String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes);
// to determine the Accept header
String[] localVarHttpHeaderAccepts = new String[] {
"application/json", "text/json", "application/xml", "text/xml"
};
String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts);
if (localVarHttpHeaderAccept != null)
localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept);
// set "format" to json by default
// e.g. /pet/{petId}.{format} becomes /pet/{petId}.json
localVarPathParams.Add("format", "json");
if (callReport.GetType() != typeof(byte[]))
{
localVarPostBody = Configuration.ApiClient.Serialize(callReport); // http body (model) parameter
}
else
{
localVarPostBody = callReport; // byte array
}
// make the HTTP request
IRestResponse localVarResponse = (IRestResponse) await Configuration.ApiClient.CallApiAsync(localVarPath,
Method.POST, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams,
localVarPathParams, localVarHttpContentType);
int localVarStatusCode = (int) localVarResponse.StatusCode;
if (localVarStatusCode >= 400)
throw new ApiException (localVarStatusCode, "Error calling ReputationReport: " + localVarResponse.Content, localVarResponse.Content);
else if (localVarStatusCode == 0)
throw new ApiException (localVarStatusCode, "Error calling ReputationReport: " + localVarResponse.ErrorMessage, localVarResponse.ErrorMessage);
return new ApiResponse<Object>(localVarStatusCode,
localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()),
null);
}
/// <summary>
/// Reputation:\r\n Premium service which returns a reputation informaiton of a phone number via API. This returns information required to perform basic call blocking behaviors<br />\r\n Try with api_key 'demo' and phone numbers 18008472911, 13157244022, 17275567300, 18008276655, and 12061231234 (last one not spam)
/// </summary>
/// <exception cref="IO.Swagger.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="phoneNumber">phone number to search</param>
/// <returns>Reputation</returns>
public Reputation ReputationReputation (string phoneNumber)
{
ApiResponse<Reputation> localVarResponse = ReputationReputationWithHttpInfo(phoneNumber);
return localVarResponse.Data;
}
/// <summary>
/// Reputation:\r\n Premium service which returns a reputation informaiton of a phone number via API. This returns information required to perform basic call blocking behaviors<br />\r\n Try with api_key 'demo' and phone numbers 18008472911, 13157244022, 17275567300, 18008276655, and 12061231234 (last one not spam)
/// </summary>
/// <exception cref="IO.Swagger.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="phoneNumber">phone number to search</param>
/// <returns>ApiResponse of Reputation</returns>
public ApiResponse< Reputation > ReputationReputationWithHttpInfo (string phoneNumber)
{
// verify the required parameter 'phoneNumber' is set
if (phoneNumber == null)
throw new ApiException(400, "Missing required parameter 'phoneNumber' when calling ReputationApi->ReputationReputation");
var localVarPath = "/api/2015-11-01/Reputation/{phoneNumber}";
var localVarPathParams = new Dictionary<String, String>();
var localVarQueryParams = new Dictionary<String, String>();
var localVarHeaderParams = new Dictionary<String, String>(Configuration.DefaultHeader);
var localVarFormParams = new Dictionary<String, String>();
var localVarFileParams = new Dictionary<String, FileParameter>();
Object localVarPostBody = null;
// to determine the Content-Type header
String[] localVarHttpContentTypes = new String[] {
};
String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes);
// to determine the Accept header
String[] localVarHttpHeaderAccepts = new String[] {
"application/json", "text/json", "application/xml", "text/xml"
};
String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts);
if (localVarHttpHeaderAccept != null)
localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept);
// set "format" to json by default
// e.g. /pet/{petId}.{format} becomes /pet/{petId}.json
localVarPathParams.Add("format", "json");
if (phoneNumber != null) localVarPathParams.Add("phoneNumber", Configuration.ApiClient.ParameterToString(phoneNumber)); // path parameter
// make the HTTP request
IRestResponse localVarResponse = (IRestResponse) Configuration.ApiClient.CallApi(localVarPath,
Method.GET, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams,
localVarPathParams, localVarHttpContentType);
int localVarStatusCode = (int) localVarResponse.StatusCode;
if (localVarStatusCode >= 400)
throw new ApiException (localVarStatusCode, "Error calling ReputationReputation: " + localVarResponse.Content, localVarResponse.Content);
else if (localVarStatusCode == 0)
throw new ApiException (localVarStatusCode, "Error calling ReputationReputation: " + localVarResponse.ErrorMessage, localVarResponse.ErrorMessage);
return new ApiResponse<Reputation>(localVarStatusCode,
localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()),
(Reputation) Configuration.ApiClient.Deserialize(localVarResponse, typeof(Reputation)));
}
/// <summary>
/// Reputation:\r\n Premium service which returns a reputation informaiton of a phone number via API. This returns information required to perform basic call blocking behaviors<br />\r\n Try with api_key 'demo' and phone numbers 18008472911, 13157244022, 17275567300, 18008276655, and 12061231234 (last one not spam)
/// </summary>
/// <exception cref="IO.Swagger.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="phoneNumber">phone number to search</param>
/// <returns>Task of Reputation</returns>
public async System.Threading.Tasks.Task<Reputation> ReputationReputationAsync (string phoneNumber)
{
ApiResponse<Reputation> localVarResponse = await ReputationReputationAsyncWithHttpInfo(phoneNumber);
return localVarResponse.Data;
}
/// <summary>
/// Reputation:\r\n Premium service which returns a reputation informaiton of a phone number via API. This returns information required to perform basic call blocking behaviors<br />\r\n Try with api_key 'demo' and phone numbers 18008472911, 13157244022, 17275567300, 18008276655, and 12061231234 (last one not spam)
/// </summary>
/// <exception cref="IO.Swagger.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="phoneNumber">phone number to search</param>
/// <returns>Task of ApiResponse (Reputation)</returns>
public async System.Threading.Tasks.Task<ApiResponse<Reputation>> ReputationReputationAsyncWithHttpInfo (string phoneNumber)
{
// verify the required parameter 'phoneNumber' is set
if (phoneNumber == null) throw new ApiException(400, "Missing required parameter 'phoneNumber' when calling ReputationReputation");
var localVarPath = "/api/2015-11-01/Reputation/{phoneNumber}";
var localVarPathParams = new Dictionary<String, String>();
var localVarQueryParams = new Dictionary<String, String>();
var localVarHeaderParams = new Dictionary<String, String>(Configuration.DefaultHeader);
var localVarFormParams = new Dictionary<String, String>();
var localVarFileParams = new Dictionary<String, FileParameter>();
Object localVarPostBody = null;
// to determine the Content-Type header
String[] localVarHttpContentTypes = new String[] {
};
String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes);
// to determine the Accept header
String[] localVarHttpHeaderAccepts = new String[] {
"application/json", "text/json", "application/xml", "text/xml"
};
String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts);
if (localVarHttpHeaderAccept != null)
localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept);
// set "format" to json by default
// e.g. /pet/{petId}.{format} becomes /pet/{petId}.json
localVarPathParams.Add("format", "json");
if (phoneNumber != null) localVarPathParams.Add("phoneNumber", Configuration.ApiClient.ParameterToString(phoneNumber)); // path parameter
// make the HTTP request
IRestResponse localVarResponse = (IRestResponse) await Configuration.ApiClient.CallApiAsync(localVarPath,
Method.GET, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams,
localVarPathParams, localVarHttpContentType);
int localVarStatusCode = (int) localVarResponse.StatusCode;
if (localVarStatusCode >= 400)
throw new ApiException (localVarStatusCode, "Error calling ReputationReputation: " + localVarResponse.Content, localVarResponse.Content);
else if (localVarStatusCode == 0)
throw new ApiException (localVarStatusCode, "Error calling ReputationReputation: " + localVarResponse.ErrorMessage, localVarResponse.ErrorMessage);
return new ApiResponse<Reputation>(localVarStatusCode,
localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()),
(Reputation) Configuration.ApiClient.Deserialize(localVarResponse, typeof(Reputation)));
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using MS.Internal.Xml.Cache;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
namespace System.Xml.XPath
{
/// <summary>
/// XDocument follows the XPath/XQuery data model. All nodes in the tree reference the document,
/// and the document references the root node of the tree. All namespaces are stored out-of-line,
/// in an Element --> In-Scope-Namespaces map.
/// </summary>
public class XPathDocument : IXPathNavigable
{
private XPathNode[] pageText, pageRoot, pageXmlNmsp;
private int idxText, idxRoot, idxXmlNmsp;
private XmlNameTable nameTable;
private bool hasLineInfo;
private Dictionary<XPathNodeRef, XPathNodeRef> mapNmsp;
private Dictionary<string, XPathNodeRef> idValueMap = null;
/// <summary>
/// Flags that control Load behavior.
/// </summary>
internal enum LoadFlags
{
None = 0,
AtomizeNames = 1, // Do not assume that names passed to XPathDocumentBuilder have been pre-atomized, and atomize them
Fragment = 2, // Create a document with no document node
}
//-----------------------------------------------
// Creation Methods
//-----------------------------------------------
/// <summary>
/// Create a new empty document.
/// </summary>
internal XPathDocument()
{
this.nameTable = new NameTable();
}
/// <summary>
/// Create a new document and load the content from the reader.
/// </summary>
public XPathDocument(XmlReader reader) : this(reader, XmlSpace.Default)
{
}
/// <summary>
/// Create a new document from "reader", with whitespace handling controlled according to "space".
/// </summary>
public XPathDocument(XmlReader reader, XmlSpace space)
{
if (reader == null)
throw new ArgumentNullException("reader");
LoadFromReader(reader, space);
}
/// <summary>
/// Create a new document and load the content from the text reader.
/// </summary>
public XPathDocument(TextReader textReader)
{
using (XmlReader reader = XmlReader.Create(textReader))
{
LoadFromReader(reader, XmlSpace.Default);
}
}
/// <summary>
/// Create a new document and load the content from the stream.
/// </summary>
public XPathDocument(Stream stream)
{
using (XmlReader reader = XmlReader.Create(stream))
{
LoadFromReader(reader, XmlSpace.Default);
}
}
/// <summary>
/// Create a new document and load the content from the Uri.
/// </summary>
public XPathDocument(string uri) : this(uri, XmlSpace.Default)
{
}
/// <summary>
/// Create a new document and load the content from the Uri, with whitespace handling controlled according to "space".
/// </summary>
public XPathDocument(string uri, XmlSpace space)
{
using (XmlReader reader = XmlReader.Create(uri))
{
LoadFromReader(reader, space);
}
}
/// <summary>
/// Create a writer that can be used to create nodes in this document. The root node will be assigned "baseUri", and flags
/// can be passed to indicate that names should be atomized by the builder and/or a fragment should be created.
/// </summary>
internal void LoadFromReader(XmlReader reader, XmlSpace space)
{
XPathDocumentBuilder builder;
IXmlLineInfo lineInfo;
string xmlnsUri;
bool topLevelReader;
int initialDepth;
if (reader == null)
throw new ArgumentNullException("reader");
// Determine line number provider
lineInfo = reader as IXmlLineInfo;
if (lineInfo == null || !lineInfo.HasLineInfo())
lineInfo = null;
this.hasLineInfo = (lineInfo != null);
this.nameTable = reader.NameTable;
builder = new XPathDocumentBuilder(this, lineInfo, reader.BaseURI, LoadFlags.None);
try
{
// Determine whether reader is in initial state
topLevelReader = (reader.ReadState == ReadState.Initial);
initialDepth = reader.Depth;
// Get atomized xmlns uri
Debug.Assert((object)this.nameTable.Get(string.Empty) == (object)string.Empty, "NameTable must contain atomized string.Empty");
xmlnsUri = this.nameTable.Get(XmlConst.ReservedNsXmlNs);
// Read past Initial state; if there are no more events then load is complete
if (topLevelReader && !reader.Read())
return;
// Read all events
do
{
// If reader began in intermediate state, return when all siblings have been read
if (!topLevelReader && reader.Depth < initialDepth)
return;
switch (reader.NodeType)
{
case XmlNodeType.Element:
{
bool isEmptyElement = reader.IsEmptyElement;
builder.WriteStartElement(reader.Prefix, reader.LocalName, reader.NamespaceURI, reader.BaseURI);
// Add attribute and namespace nodes to element
while (reader.MoveToNextAttribute())
{
string namespaceUri = reader.NamespaceURI;
if ((object)namespaceUri == (object)xmlnsUri)
{
if (reader.Prefix.Length == 0)
{
// Default namespace declaration "xmlns"
Debug.Assert(reader.LocalName == "xmlns");
builder.WriteNamespaceDeclaration(string.Empty, reader.Value);
}
else
{
Debug.Assert(reader.Prefix == "xmlns");
builder.WriteNamespaceDeclaration(reader.LocalName, reader.Value);
}
}
else
{
builder.WriteStartAttribute(reader.Prefix, reader.LocalName, namespaceUri);
builder.WriteString(reader.Value, TextBlockType.Text);
builder.WriteEndAttribute();
}
}
if (isEmptyElement)
builder.WriteEndElement(true);
break;
}
case XmlNodeType.EndElement:
builder.WriteEndElement(false);
break;
case XmlNodeType.Text:
case XmlNodeType.CDATA:
builder.WriteString(reader.Value, TextBlockType.Text);
break;
case XmlNodeType.SignificantWhitespace:
if (reader.XmlSpace == XmlSpace.Preserve)
builder.WriteString(reader.Value, TextBlockType.SignificantWhitespace);
else
// Significant whitespace without xml:space="preserve" is not significant in XPath/XQuery data model
goto case XmlNodeType.Whitespace;
break;
case XmlNodeType.Whitespace:
// We intentionally ignore the reader.XmlSpace property here and blindly trust
// the reported node type. If the reported information is not in sync
// (in this case if the reader.XmlSpace == Preserve) then we make the choice
// to trust the reported node type. Since we have no control over the input reader
// we can't even assert here.
// Always filter top-level whitespace
if (space == XmlSpace.Preserve && (!topLevelReader || reader.Depth != 0))
builder.WriteString(reader.Value, TextBlockType.Whitespace);
break;
case XmlNodeType.Comment:
builder.WriteComment(reader.Value);
break;
case XmlNodeType.ProcessingInstruction:
builder.WriteProcessingInstruction(reader.LocalName, reader.Value, reader.BaseURI);
break;
case XmlNodeType.EntityReference:
reader.ResolveEntity();
break;
case XmlNodeType.DocumentType:
case XmlNodeType.EndEntity:
case XmlNodeType.None:
case XmlNodeType.XmlDeclaration:
break;
}
}
while (reader.Read());
}
finally
{
builder.CloseWithoutDisposing();
}
}
/// <summary>
/// Create a navigator positioned on the root node of the document.
/// </summary>
public XPathNavigator CreateNavigator()
{
return new XPathDocumentNavigator(this.pageRoot, this.idxRoot, null, 0);
}
//-----------------------------------------------
// Document Properties
//-----------------------------------------------
/// <summary>
/// Return the name table used to atomize all name parts (local name, namespace uri, prefix).
/// </summary>
internal XmlNameTable NameTable
{
get { return this.nameTable; }
}
/// <summary>
/// Return true if line number information is recorded in the cache.
/// </summary>
internal bool HasLineInfo
{
get { return this.hasLineInfo; }
}
/// <summary>
/// Return the singleton collapsed text node associated with the document. One physical text node
/// represents each logical text node in the document that is the only content-typed child of its
/// element parent.
/// </summary>
internal int GetCollapsedTextNode(out XPathNode[] pageText)
{
pageText = this.pageText;
return this.idxText;
}
/// <summary>
/// Set the page and index where the singleton collapsed text node is stored.
/// </summary>
internal void SetCollapsedTextNode(XPathNode[] pageText, int idxText)
{
this.pageText = pageText;
this.idxText = idxText;
}
/// <summary>
/// Return the root node of the document. This may not be a node of type XPathNodeType.Root if this
/// is a document fragment.
/// </summary>
internal int GetRootNode(out XPathNode[] pageRoot)
{
pageRoot = this.pageRoot;
return this.idxRoot;
}
/// <summary>
/// Set the page and index where the root node is stored.
/// </summary>
internal void SetRootNode(XPathNode[] pageRoot, int idxRoot)
{
this.pageRoot = pageRoot;
this.idxRoot = idxRoot;
}
/// <summary>
/// Every document has an implicit xmlns:xml namespace node.
/// </summary>
internal int GetXmlNamespaceNode(out XPathNode[] pageXmlNmsp)
{
pageXmlNmsp = this.pageXmlNmsp;
return this.idxXmlNmsp;
}
/// <summary>
/// Set the page and index where the implicit xmlns:xml node is stored.
/// </summary>
internal void SetXmlNamespaceNode(XPathNode[] pageXmlNmsp, int idxXmlNmsp)
{
this.pageXmlNmsp = pageXmlNmsp;
this.idxXmlNmsp = idxXmlNmsp;
}
/// <summary>
/// Associate a namespace node with an element.
/// </summary>
internal void AddNamespace(XPathNode[] pageElem, int idxElem, XPathNode[] pageNmsp, int idxNmsp)
{
Debug.Assert(pageElem[idxElem].NodeType == XPathNodeType.Element && pageNmsp[idxNmsp].NodeType == XPathNodeType.Namespace);
if (this.mapNmsp == null)
this.mapNmsp = new Dictionary<XPathNodeRef, XPathNodeRef>();
this.mapNmsp.Add(new XPathNodeRef(pageElem, idxElem), new XPathNodeRef(pageNmsp, idxNmsp));
}
/// <summary>
/// Lookup the namespace nodes associated with an element.
/// </summary>
internal int LookupNamespaces(XPathNode[] pageElem, int idxElem, out XPathNode[] pageNmsp)
{
XPathNodeRef nodeRef = new XPathNodeRef(pageElem, idxElem);
Debug.Assert(pageElem[idxElem].NodeType == XPathNodeType.Element);
// Check whether this element has any local namespaces
if (this.mapNmsp == null || !this.mapNmsp.ContainsKey(nodeRef))
{
pageNmsp = null;
return 0;
}
// Yes, so return the page and index of the first local namespace node
nodeRef = this.mapNmsp[nodeRef];
pageNmsp = nodeRef.Page;
return nodeRef.Index;
}
/// <summary>
/// Lookup the element node associated with the specified ID value.
/// </summary>
internal int LookupIdElement(string id, out XPathNode[] pageElem)
{
XPathNodeRef nodeRef;
if (this.idValueMap == null || !this.idValueMap.ContainsKey(id))
{
pageElem = null;
return 0;
}
// Extract page and index from XPathNodeRef
nodeRef = this.idValueMap[id];
pageElem = nodeRef.Page;
return nodeRef.Index;
}
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Text;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Editor.Shared.Utilities;
using Microsoft.VisualStudio.Shell.Interop;
using Microsoft.VisualStudio.Text.Editor;
using Roslyn.Utilities;
using Microsoft.VisualStudio.Text;
namespace Microsoft.VisualStudio.LanguageServices.Implementation
{
[DebuggerDisplay("{GetDebuggerDisplay(),nq}")]
internal class VisualStudioDocumentTrackingService : IDocumentTrackingService, IVsSelectionEvents, IDisposable
{
private IVsMonitorSelection _monitorSelection;
private uint _cookie;
private ImmutableList<FrameListener> _visibleFrames;
private IVsWindowFrame _activeFrame;
public VisualStudioDocumentTrackingService(IServiceProvider serviceProvider)
{
_visibleFrames = ImmutableList<FrameListener>.Empty;
_monitorSelection = (IVsMonitorSelection)serviceProvider.GetService(typeof(SVsShellMonitorSelection));
_monitorSelection.AdviseSelectionEvents(this, out _cookie);
}
public event EventHandler<DocumentId> ActiveDocumentChanged;
/// <summary>
/// Get the <see cref="DocumentId"/> of the active document. May be called from any thread.
/// May return null if there is no active document or the active document is not part of this
/// workspace.
/// </summary>
/// <returns>The ID of the active document (if any)</returns>
public DocumentId GetActiveDocument()
{
var snapshot = _visibleFrames;
if (_activeFrame == null || snapshot.IsEmpty)
{
return null;
}
foreach (var listener in snapshot)
{
if (listener.Frame == _activeFrame)
{
return listener.Id;
}
}
return null;
}
/// <summary>
/// Get a read only collection of the <see cref="DocumentId"/>s of all the visible documents in the workspace.
/// </summary>
public ImmutableArray<DocumentId> GetVisibleDocuments()
{
var snapshot = _visibleFrames;
if (snapshot.IsEmpty)
{
return ImmutableArray.Create<DocumentId>();
}
var ids = ArrayBuilder<DocumentId>.GetInstance(snapshot.Count);
foreach (var frame in snapshot)
{
ids.Add(frame.Id);
}
return ids.ToImmutableAndFree();
}
/// <summary>
/// Called via the DocumentProvider's RDT OnBeforeDocumentWindowShow notification when a workspace document is being shown.
/// </summary>
/// <param name="frame">The frame containing the document being shown.</param>
/// <param name="id">The <see cref="DocumentId"/> of the document being shown.</param>
/// <param name="firstShow">Indicates whether this is a first or subsequent show.</param>
public void DocumentFrameShowing(IVsWindowFrame frame, DocumentId id, bool firstShow)
{
Contract.ThrowIfNull(frame);
Contract.ThrowIfNull(id);
if (!firstShow && !_visibleFrames.IsEmpty)
{
foreach (FrameListener frameListener in _visibleFrames)
{
if (frameListener.Frame == frame)
{
// Already in the visible list
return;
}
}
}
_visibleFrames = _visibleFrames.Add(new FrameListener(this, frame, id));
}
private void RemoveFrame(FrameListener frame)
{
_visibleFrames = _visibleFrames.Remove(frame);
}
public int OnSelectionChanged(IVsHierarchy pHierOld, [ComAliasName("Microsoft.VisualStudio.Shell.Interop.VSITEMID")]uint itemidOld, IVsMultiItemSelect pMISOld, ISelectionContainer pSCOld, IVsHierarchy pHierNew, [ComAliasName("Microsoft.VisualStudio.Shell.Interop.VSITEMID")]uint itemidNew, IVsMultiItemSelect pMISNew, ISelectionContainer pSCNew)
{
return VSConstants.E_NOTIMPL;
}
public int OnElementValueChanged([ComAliasName("Microsoft.VisualStudio.Shell.Interop.VSSELELEMID")]uint elementid, object varValueOld, object varValueNew)
{
if (elementid == (uint)VSConstants.VSSELELEMID.SEID_DocumentFrame)
{
// Remember the newly activated frame so it can be read from another thread.
_activeFrame = varValueNew as IVsWindowFrame;
this.ActiveDocumentChanged?.Invoke(this, GetActiveDocument());
}
return VSConstants.S_OK;
}
public int OnCmdUIContextChanged([ComAliasName("Microsoft.VisualStudio.Shell.Interop.VSCOOKIE")]uint dwCmdUICookie, [ComAliasName("Microsoft.VisualStudio.OLE.Interop.BOOL")]int fActive)
{
return VSConstants.E_NOTIMPL;
}
public event EventHandler<EventArgs> NonRoslynBufferTextChanged;
public void OnNonRoslynBufferOpened(ITextBuffer buffer)
{
buffer.PostChanged += OnNonRoslynBufferChanged;
}
public void OnNonRoslynBufferClosed(ITextBuffer buffer)
{
buffer.PostChanged -= OnNonRoslynBufferChanged;
}
private void OnNonRoslynBufferChanged(object sender, EventArgs e)
{
this.NonRoslynBufferTextChanged?.Invoke(sender, e);
}
public void Dispose()
{
if (_cookie != VSConstants.VSCOOKIE_NIL && _monitorSelection != null)
{
_activeFrame = null;
_monitorSelection.UnadviseSelectionEvents(_cookie);
_monitorSelection = null;
_cookie = VSConstants.VSCOOKIE_NIL;
}
var snapshot = _visibleFrames;
_visibleFrames = ImmutableList<FrameListener>.Empty;
if (!snapshot.IsEmpty)
{
foreach (var frame in snapshot)
{
frame.Dispose();
}
}
}
private string GetDebuggerDisplay()
{
var snapshot = _visibleFrames;
StringBuilder sb = new StringBuilder();
sb.Append("Visible frames: ");
if (snapshot.IsEmpty)
{
sb.Append("{empty}");
}
else
{
foreach (var frame in snapshot)
{
sb.Append(frame.GetDebuggerDisplay());
sb.Append(' ');
}
}
return sb.ToString();
}
/// <summary>
/// Listens to frame notifications for a visible frame. When the frame becomes invisible or closes,
/// then it automatically disconnects.
/// </summary>
[DebuggerDisplay("{GetDebuggerDisplay(),nq}")]
private class FrameListener : IVsWindowFrameNotify, IVsWindowFrameNotify2, IDisposable
{
public readonly IVsWindowFrame Frame;
public readonly DocumentId Id;
private readonly VisualStudioDocumentTrackingService _service;
private uint _cookie;
public FrameListener(VisualStudioDocumentTrackingService service, IVsWindowFrame frame, DocumentId id)
{
this.Frame = frame;
this.Id = id;
_service = service;
((IVsWindowFrame2)frame).Advise(this, out _cookie);
}
public int OnDockableChange(int fDockable)
{
return VSConstants.S_OK;
}
public int OnMove()
{
return VSConstants.S_OK;
}
public int OnShow(int fShow)
{
switch ((__FRAMESHOW)fShow)
{
case __FRAMESHOW.FRAMESHOW_WinClosed:
case __FRAMESHOW.FRAMESHOW_WinHidden:
case __FRAMESHOW.FRAMESHOW_TabDeactivated:
return Disconnect();
}
return VSConstants.S_OK;
}
public int OnSize()
{
return VSConstants.S_OK;
}
public int OnClose(ref uint pgrfSaveOptions)
{
return Disconnect();
}
private int Disconnect()
{
_service.RemoveFrame(this);
return Unadvise();
}
private int Unadvise()
{
int hr = VSConstants.S_OK;
if (_cookie != VSConstants.VSCOOKIE_NIL)
{
hr = ((IVsWindowFrame2)Frame).Unadvise(_cookie);
_cookie = VSConstants.VSCOOKIE_NIL;
}
return hr;
}
public void Dispose()
{
Unadvise();
}
internal string GetDebuggerDisplay()
{
Frame.GetProperty((int)__VSFPROPID.VSFPROPID_Caption, out var caption);
return caption.ToString();
}
}
}
}
| |
using System;
namespace ClosedXML.Excel
{
public enum XLScope
{
Workbook,
Worksheet
}
public interface IXLRangeBase: IDisposable
{
IXLWorksheet Worksheet { get; }
/// <summary>
/// Gets an object with the boundaries of this range.
/// </summary>
IXLRangeAddress RangeAddress { get; }
/// <summary>
/// Sets a value to every cell in this range.
/// <para>If the object is an IEnumerable ClosedXML will copy the collection's data into a table starting from each cell.</para>
/// <para>If the object is a range ClosedXML will copy the range starting from each cell.</para>
/// <para>Setting the value to an object (not IEnumerable/range) will call the object's ToString() method.</para>
/// <para>ClosedXML will try to translate it to the corresponding type, if it can't then the value will be left as a string.</para>
/// </summary>
/// <value>
/// The object containing the value(s) to set.
/// </value>
Object Value { set; }
/// <summary>
/// Sets the type of the cells' data.
/// <para>Changing the data type will cause ClosedXML to covert the current value to the new data type.</para>
/// <para>An exception will be thrown if the current value cannot be converted to the new data type.</para>
/// </summary>
/// <value>
/// The type of the cell's data.
/// </value>
/// <exception cref = "ArgumentException"></exception>
XLCellValues DataType { set; }
/// <summary>
/// Sets the cells' formula with A1 references.
/// </summary>
/// <value>The formula with A1 references.</value>
String FormulaA1 { set; }
/// <summary>
/// Sets the cells' formula with R1C1 references.
/// </summary>
/// <value>The formula with R1C1 references.</value>
String FormulaR1C1 { set; }
IXLStyle Style { get; set; }
/// <summary>
/// Gets or sets a value indicating whether this cell's text should be shared or not.
/// </summary>
/// <value>
/// If false the cell's text will not be shared and stored as an inline value.
/// </value>
Boolean ShareString { set; }
IXLHyperlinks Hyperlinks { get; }
/// <summary>
/// Returns the collection of cells.
/// </summary>
IXLCells Cells();
IXLCells Cells(Boolean usedCellsOnly);
IXLCells Cells(Boolean usedCellsOnly, Boolean includeFormats);
IXLCells Cells(String cells);
IXLCells Cells(Func<IXLCell, Boolean> predicate);
/// <summary>
/// Returns the collection of cells that have a value. Formats are ignored.
/// </summary>
IXLCells CellsUsed();
/// <summary>
/// Returns the collection of cells that have a value.
/// </summary>
/// <param name = "includeFormats">if set to <c>true</c> will return all cells with a value or a style different than the default.</param>
IXLCells CellsUsed(Boolean includeFormats);
IXLCells CellsUsed(Func<IXLCell, Boolean> predicate);
IXLCells CellsUsed(Boolean includeFormats, Func<IXLCell, Boolean> predicate);
/// <summary>
/// Returns the first cell of this range.
/// </summary>
IXLCell FirstCell();
/// <summary>
/// Returns the first cell with a value of this range. Formats are ignored.
/// <para>The cell's address is going to be ([First Row with a value], [First Column with a value])</para>
/// </summary>
IXLCell FirstCellUsed();
/// <summary>
/// Returns the first cell with a value of this range.
/// </summary>
/// <para>The cell's address is going to be ([First Row with a value], [First Column with a value])</para>
/// <param name = "includeFormats">if set to <c>true</c> will return all cells with a value or a style different than the default.</param>
IXLCell FirstCellUsed(Boolean includeFormats);
IXLCell FirstCellUsed(Func<IXLCell, Boolean> predicate);
IXLCell FirstCellUsed(Boolean includeFormats, Func<IXLCell, Boolean> predicate);
/// <summary>
/// Returns the last cell of this range.
/// </summary>
IXLCell LastCell();
/// <summary>
/// Returns the last cell with a value of this range. Formats are ignored.
/// <para>The cell's address is going to be ([Last Row with a value], [Last Column with a value])</para>
/// </summary>
IXLCell LastCellUsed();
/// <summary>
/// Returns the last cell with a value of this range.
/// </summary>
/// <para>The cell's address is going to be ([Last Row with a value], [Last Column with a value])</para>
/// <param name = "includeFormats">if set to <c>true</c> will return all cells with a value or a style different than the default.</param>
IXLCell LastCellUsed(Boolean includeFormats);
IXLCell LastCellUsed(Func<IXLCell, Boolean> predicate);
IXLCell LastCellUsed(Boolean includeFormats, Func<IXLCell, Boolean> predicate);
/// <summary>
/// Determines whether this range contains the specified range (completely).
/// <para>For partial matches use the range.Intersects method.</para>
/// </summary>
/// <param name = "rangeAddress">The range address.</param>
/// <returns>
/// <c>true</c> if this range contains the specified range; otherwise, <c>false</c>.
/// </returns>
Boolean Contains(String rangeAddress);
/// <summary>
/// Determines whether this range contains the specified range (completely).
/// <para>For partial matches use the range.Intersects method.</para>
/// </summary>
/// <param name = "range">The range to match.</param>
/// <returns>
/// <c>true</c> if this range contains the specified range; otherwise, <c>false</c>.
/// </returns>
Boolean Contains(IXLRangeBase range);
Boolean Contains(IXLCell cell);
/// <summary>
/// Determines whether this range intersects the specified range.
/// <para>For whole matches use the range.Contains method.</para>
/// </summary>
/// <param name = "rangeAddress">The range address.</param>
/// <returns>
/// <c>true</c> if this range intersects the specified range; otherwise, <c>false</c>.
/// </returns>
Boolean Intersects(String rangeAddress);
/// <summary>
/// Determines whether this range contains the specified range.
/// <para>For whole matches use the range.Contains method.</para>
/// </summary>
/// <param name = "range">The range to match.</param>
/// <returns>
/// <c>true</c> if this range intersects the specified range; otherwise, <c>false</c>.
/// </returns>
Boolean Intersects(IXLRangeBase range);
/// <summary>
/// Unmerges this range.
/// </summary>
IXLRange Unmerge();
/// <summary>
/// Merges this range.
/// <para>The contents and style of the merged cells will be equal to the first cell.</para>
/// </summary>
IXLRange Merge();
IXLRange Merge(Boolean checkIntersect);
/// <summary>
/// Creates a named range out of this range.
/// <para>If the named range exists, it will add this range to that named range.</para>
/// <para>The default scope for the named range is Workbook.</para>
/// </summary>
/// <param name = "rangeName">Name of the range.</param>
IXLRange AddToNamed(String rangeName);
/// <summary>
/// Creates a named range out of this range.
/// <para>If the named range exists, it will add this range to that named range.</para>
/// <param name = "rangeName">Name of the range.</param>
/// <param name = "scope">The scope for the named range.</param>
/// </summary>
IXLRange AddToNamed(String rangeName, XLScope scope);
/// <summary>
/// Creates a named range out of this range.
/// <para>If the named range exists, it will add this range to that named range.</para>
/// <param name = "rangeName">Name of the range.</param>
/// <param name = "scope">The scope for the named range.</param>
/// <param name = "comment">The comments for the named range.</param>
/// </summary>
IXLRange AddToNamed(String rangeName, XLScope scope, String comment);
/// <summary>
/// Clears the contents of this range.
/// </summary>
/// <param name="clearOptions">Specify what you want to clear.</param>
IXLRangeBase Clear(XLClearOptions clearOptions = XLClearOptions.ContentsAndFormats);
/// <summary>
/// Deletes the cell comments from this range.
/// </summary>
void DeleteComments();
IXLRangeBase SetValue<T>(T value);
/// <summary>
/// Converts this object to a range.
/// </summary>
IXLRange AsRange();
Boolean IsMerged();
Boolean IsEmpty();
Boolean IsEmpty(Boolean includeFormats);
IXLPivotTable CreatePivotTable(IXLCell targetCell);
IXLPivotTable CreatePivotTable(IXLCell targetCell, String name);
//IXLChart CreateChart(Int32 firstRow, Int32 firstColumn, Int32 lastRow, Int32 lastColumn);
IXLAutoFilter SetAutoFilter();
IXLDataValidation SetDataValidation();
IXLConditionalFormat AddConditionalFormat();
void Select();
}
}
| |
using System;
using System.CodeDom.Compiler;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Globalization;
using System.Linq;
using System.Text;
namespace EduHub.Data.Entities
{
/// <summary>
/// HRMS Import Table Data Set
/// </summary>
[GeneratedCode("EduHub Data", "0.9")]
public sealed partial class SK_HRMSDataSet : EduHubDataSet<SK_HRMS>
{
/// <inheritdoc />
public override string Name { get { return "SK_HRMS"; } }
/// <inheritdoc />
public override bool SupportsEntityLastModified { get { return false; } }
internal SK_HRMSDataSet(EduHubContext Context)
: base(Context)
{
Index_SEQ = new Lazy<Dictionary<int, SK_HRMS>>(() => this.ToDictionary(i => i.SEQ));
}
/// <summary>
/// Matches CSV file headers to actions, used to deserialize <see cref="SK_HRMS" />
/// </summary>
/// <param name="Headers">The CSV column headers</param>
/// <returns>An array of actions which deserialize <see cref="SK_HRMS" /> fields for each CSV column header</returns>
internal override Action<SK_HRMS, string>[] BuildMapper(IReadOnlyList<string> Headers)
{
var mapper = new Action<SK_HRMS, string>[Headers.Count];
for (var i = 0; i < Headers.Count; i++) {
switch (Headers[i]) {
case "SEQ":
mapper[i] = (e, v) => e.SEQ = int.Parse(v);
break;
case "DEPTID":
mapper[i] = (e, v) => e.DEPTID = v;
break;
case "EMPLID":
mapper[i] = (e, v) => e.EMPLID = v;
break;
case "JOBCODE":
mapper[i] = (e, v) => e.JOBCODE = v;
break;
case "LAST_NAME":
mapper[i] = (e, v) => e.LAST_NAME = v;
break;
case "PREFIX":
mapper[i] = (e, v) => e.PREFIX = v;
break;
case "FIRST_NAME":
mapper[i] = (e, v) => e.FIRST_NAME = v;
break;
case "MIDDLE_NAME":
mapper[i] = (e, v) => e.MIDDLE_NAME = v;
break;
case "PREF_NAME":
mapper[i] = (e, v) => e.PREF_NAME = v;
break;
case "PREV_SURNAME":
mapper[i] = (e, v) => e.PREV_SURNAME = v;
break;
case "GENDER":
mapper[i] = (e, v) => e.GENDER = v;
break;
case "BIRTH_DATE":
mapper[i] = (e, v) => e.BIRTH_DATE = v == null ? (DateTime?)null : DateTime.ParseExact(v, "d/MM/yyyy h:mm:ss tt", CultureInfo.InvariantCulture);
break;
case "H_ADDRESS01":
mapper[i] = (e, v) => e.H_ADDRESS01 = v;
break;
case "H_ADDRESS02":
mapper[i] = (e, v) => e.H_ADDRESS02 = v;
break;
case "H_ADDRESS03":
mapper[i] = (e, v) => e.H_ADDRESS03 = v;
break;
case "H_STATE":
mapper[i] = (e, v) => e.H_STATE = v;
break;
case "H_POST_CODE":
mapper[i] = (e, v) => e.H_POST_CODE = v;
break;
case "P_ADDRESS01":
mapper[i] = (e, v) => e.P_ADDRESS01 = v;
break;
case "P_ADDRESS02":
mapper[i] = (e, v) => e.P_ADDRESS02 = v;
break;
case "P_ADDRESS03":
mapper[i] = (e, v) => e.P_ADDRESS03 = v;
break;
case "P_STATE":
mapper[i] = (e, v) => e.P_STATE = v;
break;
case "P_POST_CODE":
mapper[i] = (e, v) => e.P_POST_CODE = v;
break;
case "HOME_PHONE":
mapper[i] = (e, v) => e.HOME_PHONE = v;
break;
case "MOBILE_PHONE":
mapper[i] = (e, v) => e.MOBILE_PHONE = v;
break;
case "WORK_PHONE":
mapper[i] = (e, v) => e.WORK_PHONE = v;
break;
case "EMAIL_ADDRESS":
mapper[i] = (e, v) => e.EMAIL_ADDRESS = v;
break;
case "EMERG_CONTACT":
mapper[i] = (e, v) => e.EMERG_CONTACT = v;
break;
case "EMERG_RELATE":
mapper[i] = (e, v) => e.EMERG_RELATE = v;
break;
case "EMERG_PHONE":
mapper[i] = (e, v) => e.EMERG_PHONE = v;
break;
case "START_DATE":
mapper[i] = (e, v) => e.START_DATE = v == null ? (DateTime?)null : DateTime.ParseExact(v, "d/MM/yyyy h:mm:ss tt", CultureInfo.InvariantCulture);
break;
case "FINISH_DATE":
mapper[i] = (e, v) => e.FINISH_DATE = v == null ? (DateTime?)null : DateTime.ParseExact(v, "d/MM/yyyy h:mm:ss tt", CultureInfo.InvariantCulture);
break;
case "FTE":
mapper[i] = (e, v) => e.FTE = v == null ? (short?)null : short.Parse(v);
break;
case "REC_TYPE_FLAG":
mapper[i] = (e, v) => e.REC_TYPE_FLAG = v;
break;
case "REC_PROCESS_FLAG":
mapper[i] = (e, v) => e.REC_PROCESS_FLAG = v;
break;
default:
mapper[i] = MapperNoOp;
break;
}
}
return mapper;
}
/// <summary>
/// Merges <see cref="SK_HRMS" /> delta entities
/// </summary>
/// <param name="Entities">Iterator for base <see cref="SK_HRMS" /> entities</param>
/// <param name="DeltaEntities">List of delta <see cref="SK_HRMS" /> entities</param>
/// <returns>A merged <see cref="IEnumerable{SK_HRMS}"/> of entities</returns>
internal override IEnumerable<SK_HRMS> ApplyDeltaEntities(IEnumerable<SK_HRMS> Entities, List<SK_HRMS> DeltaEntities)
{
HashSet<int> Index_SEQ = new HashSet<int>(DeltaEntities.Select(i => i.SEQ));
using (var deltaIterator = DeltaEntities.GetEnumerator())
{
using (var entityIterator = Entities.GetEnumerator())
{
while (deltaIterator.MoveNext())
{
var deltaClusteredKey = deltaIterator.Current.SEQ;
bool yieldEntity = false;
while (entityIterator.MoveNext())
{
var entity = entityIterator.Current;
bool overwritten = Index_SEQ.Remove(entity.SEQ);
if (entity.SEQ.CompareTo(deltaClusteredKey) <= 0)
{
if (!overwritten)
{
yield return entity;
}
}
else
{
yieldEntity = !overwritten;
break;
}
}
yield return deltaIterator.Current;
if (yieldEntity)
{
yield return entityIterator.Current;
}
}
while (entityIterator.MoveNext())
{
yield return entityIterator.Current;
}
}
}
}
#region Index Fields
private Lazy<Dictionary<int, SK_HRMS>> Index_SEQ;
#endregion
#region Index Methods
/// <summary>
/// Find SK_HRMS by SEQ field
/// </summary>
/// <param name="SEQ">SEQ value used to find SK_HRMS</param>
/// <returns>Related SK_HRMS entity</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public SK_HRMS FindBySEQ(int SEQ)
{
return Index_SEQ.Value[SEQ];
}
/// <summary>
/// Attempt to find SK_HRMS by SEQ field
/// </summary>
/// <param name="SEQ">SEQ value used to find SK_HRMS</param>
/// <param name="Value">Related SK_HRMS entity</param>
/// <returns>True if the related SK_HRMS entity is found</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public bool TryFindBySEQ(int SEQ, out SK_HRMS Value)
{
return Index_SEQ.Value.TryGetValue(SEQ, out Value);
}
/// <summary>
/// Attempt to find SK_HRMS by SEQ field
/// </summary>
/// <param name="SEQ">SEQ value used to find SK_HRMS</param>
/// <returns>Related SK_HRMS entity, or null if not found</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public SK_HRMS TryFindBySEQ(int SEQ)
{
SK_HRMS value;
if (Index_SEQ.Value.TryGetValue(SEQ, out value))
{
return value;
}
else
{
return null;
}
}
#endregion
#region SQL Integration
/// <summary>
/// Returns a <see cref="SqlCommand"/> which checks for the existence of a SK_HRMS table, and if not found, creates the table and associated indexes.
/// </summary>
/// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param>
public override SqlCommand GetSqlCreateTableCommand(SqlConnection SqlConnection)
{
return new SqlCommand(
connection: SqlConnection,
cmdText:
@"IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[SK_HRMS]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
CREATE TABLE [dbo].[SK_HRMS](
[SEQ] int IDENTITY NOT NULL,
[DEPTID] varchar(10) NULL,
[EMPLID] varchar(11) NULL,
[JOBCODE] varchar(6) NULL,
[LAST_NAME] varchar(30) NULL,
[PREFIX] varchar(4) NULL,
[FIRST_NAME] varchar(30) NULL,
[MIDDLE_NAME] varchar(30) NULL,
[PREF_NAME] varchar(30) NULL,
[PREV_SURNAME] varchar(30) NULL,
[GENDER] varchar(1) NULL,
[BIRTH_DATE] datetime NULL,
[H_ADDRESS01] varchar(55) NULL,
[H_ADDRESS02] varchar(55) NULL,
[H_ADDRESS03] varchar(55) NULL,
[H_STATE] varchar(6) NULL,
[H_POST_CODE] varchar(12) NULL,
[P_ADDRESS01] varchar(55) NULL,
[P_ADDRESS02] varchar(55) NULL,
[P_ADDRESS03] varchar(55) NULL,
[P_STATE] varchar(6) NULL,
[P_POST_CODE] varchar(12) NULL,
[HOME_PHONE] varchar(24) NULL,
[MOBILE_PHONE] varchar(31) NULL,
[WORK_PHONE] varchar(24) NULL,
[EMAIL_ADDRESS] varchar(70) NULL,
[EMERG_CONTACT] varchar(50) NULL,
[EMERG_RELATE] varchar(30) NULL,
[EMERG_PHONE] varchar(24) NULL,
[START_DATE] datetime NULL,
[FINISH_DATE] datetime NULL,
[FTE] smallint NULL,
[REC_TYPE_FLAG] varchar(1) NULL,
[REC_PROCESS_FLAG] varchar(1) NULL,
CONSTRAINT [SK_HRMS_Index_SEQ] PRIMARY KEY CLUSTERED (
[SEQ] ASC
)
);
END");
}
/// <summary>
/// Returns null as <see cref="SK_HRMSDataSet"/> has no non-clustered indexes.
/// </summary>
/// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param>
/// <returns>null</returns>
public override SqlCommand GetSqlDisableIndexesCommand(SqlConnection SqlConnection)
{
return null;
}
/// <summary>
/// Returns null as <see cref="SK_HRMSDataSet"/> has no non-clustered indexes.
/// </summary>
/// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param>
/// <returns>null</returns>
public override SqlCommand GetSqlRebuildIndexesCommand(SqlConnection SqlConnection)
{
return null;
}
/// <summary>
/// Returns a <see cref="SqlCommand"/> which deletes the <see cref="SK_HRMS"/> entities passed
/// </summary>
/// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param>
/// <param name="Entities">The <see cref="SK_HRMS"/> entities to be deleted</param>
public override SqlCommand GetSqlDeleteCommand(SqlConnection SqlConnection, IEnumerable<SK_HRMS> Entities)
{
SqlCommand command = new SqlCommand();
int parameterIndex = 0;
StringBuilder builder = new StringBuilder();
List<int> Index_SEQ = new List<int>();
foreach (var entity in Entities)
{
Index_SEQ.Add(entity.SEQ);
}
builder.AppendLine("DELETE [dbo].[SK_HRMS] WHERE");
// Index_SEQ
builder.Append("[SEQ] IN (");
for (int index = 0; index < Index_SEQ.Count; index++)
{
if (index != 0)
builder.Append(", ");
// SEQ
var parameterSEQ = $"@p{parameterIndex++}";
builder.Append(parameterSEQ);
command.Parameters.Add(parameterSEQ, SqlDbType.Int).Value = Index_SEQ[index];
}
builder.Append(");");
command.Connection = SqlConnection;
command.CommandText = builder.ToString();
return command;
}
/// <summary>
/// Provides a <see cref="IDataReader"/> for the SK_HRMS data set
/// </summary>
/// <returns>A <see cref="IDataReader"/> for the SK_HRMS data set</returns>
public override EduHubDataSetDataReader<SK_HRMS> GetDataSetDataReader()
{
return new SK_HRMSDataReader(Load());
}
/// <summary>
/// Provides a <see cref="IDataReader"/> for the SK_HRMS data set
/// </summary>
/// <returns>A <see cref="IDataReader"/> for the SK_HRMS data set</returns>
public override EduHubDataSetDataReader<SK_HRMS> GetDataSetDataReader(List<SK_HRMS> Entities)
{
return new SK_HRMSDataReader(new EduHubDataSetLoadedReader<SK_HRMS>(this, Entities));
}
// Modest implementation to primarily support SqlBulkCopy
private class SK_HRMSDataReader : EduHubDataSetDataReader<SK_HRMS>
{
public SK_HRMSDataReader(IEduHubDataSetReader<SK_HRMS> Reader)
: base (Reader)
{
}
public override int FieldCount { get { return 34; } }
public override object GetValue(int i)
{
switch (i)
{
case 0: // SEQ
return Current.SEQ;
case 1: // DEPTID
return Current.DEPTID;
case 2: // EMPLID
return Current.EMPLID;
case 3: // JOBCODE
return Current.JOBCODE;
case 4: // LAST_NAME
return Current.LAST_NAME;
case 5: // PREFIX
return Current.PREFIX;
case 6: // FIRST_NAME
return Current.FIRST_NAME;
case 7: // MIDDLE_NAME
return Current.MIDDLE_NAME;
case 8: // PREF_NAME
return Current.PREF_NAME;
case 9: // PREV_SURNAME
return Current.PREV_SURNAME;
case 10: // GENDER
return Current.GENDER;
case 11: // BIRTH_DATE
return Current.BIRTH_DATE;
case 12: // H_ADDRESS01
return Current.H_ADDRESS01;
case 13: // H_ADDRESS02
return Current.H_ADDRESS02;
case 14: // H_ADDRESS03
return Current.H_ADDRESS03;
case 15: // H_STATE
return Current.H_STATE;
case 16: // H_POST_CODE
return Current.H_POST_CODE;
case 17: // P_ADDRESS01
return Current.P_ADDRESS01;
case 18: // P_ADDRESS02
return Current.P_ADDRESS02;
case 19: // P_ADDRESS03
return Current.P_ADDRESS03;
case 20: // P_STATE
return Current.P_STATE;
case 21: // P_POST_CODE
return Current.P_POST_CODE;
case 22: // HOME_PHONE
return Current.HOME_PHONE;
case 23: // MOBILE_PHONE
return Current.MOBILE_PHONE;
case 24: // WORK_PHONE
return Current.WORK_PHONE;
case 25: // EMAIL_ADDRESS
return Current.EMAIL_ADDRESS;
case 26: // EMERG_CONTACT
return Current.EMERG_CONTACT;
case 27: // EMERG_RELATE
return Current.EMERG_RELATE;
case 28: // EMERG_PHONE
return Current.EMERG_PHONE;
case 29: // START_DATE
return Current.START_DATE;
case 30: // FINISH_DATE
return Current.FINISH_DATE;
case 31: // FTE
return Current.FTE;
case 32: // REC_TYPE_FLAG
return Current.REC_TYPE_FLAG;
case 33: // REC_PROCESS_FLAG
return Current.REC_PROCESS_FLAG;
default:
throw new ArgumentOutOfRangeException(nameof(i));
}
}
public override bool IsDBNull(int i)
{
switch (i)
{
case 1: // DEPTID
return Current.DEPTID == null;
case 2: // EMPLID
return Current.EMPLID == null;
case 3: // JOBCODE
return Current.JOBCODE == null;
case 4: // LAST_NAME
return Current.LAST_NAME == null;
case 5: // PREFIX
return Current.PREFIX == null;
case 6: // FIRST_NAME
return Current.FIRST_NAME == null;
case 7: // MIDDLE_NAME
return Current.MIDDLE_NAME == null;
case 8: // PREF_NAME
return Current.PREF_NAME == null;
case 9: // PREV_SURNAME
return Current.PREV_SURNAME == null;
case 10: // GENDER
return Current.GENDER == null;
case 11: // BIRTH_DATE
return Current.BIRTH_DATE == null;
case 12: // H_ADDRESS01
return Current.H_ADDRESS01 == null;
case 13: // H_ADDRESS02
return Current.H_ADDRESS02 == null;
case 14: // H_ADDRESS03
return Current.H_ADDRESS03 == null;
case 15: // H_STATE
return Current.H_STATE == null;
case 16: // H_POST_CODE
return Current.H_POST_CODE == null;
case 17: // P_ADDRESS01
return Current.P_ADDRESS01 == null;
case 18: // P_ADDRESS02
return Current.P_ADDRESS02 == null;
case 19: // P_ADDRESS03
return Current.P_ADDRESS03 == null;
case 20: // P_STATE
return Current.P_STATE == null;
case 21: // P_POST_CODE
return Current.P_POST_CODE == null;
case 22: // HOME_PHONE
return Current.HOME_PHONE == null;
case 23: // MOBILE_PHONE
return Current.MOBILE_PHONE == null;
case 24: // WORK_PHONE
return Current.WORK_PHONE == null;
case 25: // EMAIL_ADDRESS
return Current.EMAIL_ADDRESS == null;
case 26: // EMERG_CONTACT
return Current.EMERG_CONTACT == null;
case 27: // EMERG_RELATE
return Current.EMERG_RELATE == null;
case 28: // EMERG_PHONE
return Current.EMERG_PHONE == null;
case 29: // START_DATE
return Current.START_DATE == null;
case 30: // FINISH_DATE
return Current.FINISH_DATE == null;
case 31: // FTE
return Current.FTE == null;
case 32: // REC_TYPE_FLAG
return Current.REC_TYPE_FLAG == null;
case 33: // REC_PROCESS_FLAG
return Current.REC_PROCESS_FLAG == null;
default:
return false;
}
}
public override string GetName(int ordinal)
{
switch (ordinal)
{
case 0: // SEQ
return "SEQ";
case 1: // DEPTID
return "DEPTID";
case 2: // EMPLID
return "EMPLID";
case 3: // JOBCODE
return "JOBCODE";
case 4: // LAST_NAME
return "LAST_NAME";
case 5: // PREFIX
return "PREFIX";
case 6: // FIRST_NAME
return "FIRST_NAME";
case 7: // MIDDLE_NAME
return "MIDDLE_NAME";
case 8: // PREF_NAME
return "PREF_NAME";
case 9: // PREV_SURNAME
return "PREV_SURNAME";
case 10: // GENDER
return "GENDER";
case 11: // BIRTH_DATE
return "BIRTH_DATE";
case 12: // H_ADDRESS01
return "H_ADDRESS01";
case 13: // H_ADDRESS02
return "H_ADDRESS02";
case 14: // H_ADDRESS03
return "H_ADDRESS03";
case 15: // H_STATE
return "H_STATE";
case 16: // H_POST_CODE
return "H_POST_CODE";
case 17: // P_ADDRESS01
return "P_ADDRESS01";
case 18: // P_ADDRESS02
return "P_ADDRESS02";
case 19: // P_ADDRESS03
return "P_ADDRESS03";
case 20: // P_STATE
return "P_STATE";
case 21: // P_POST_CODE
return "P_POST_CODE";
case 22: // HOME_PHONE
return "HOME_PHONE";
case 23: // MOBILE_PHONE
return "MOBILE_PHONE";
case 24: // WORK_PHONE
return "WORK_PHONE";
case 25: // EMAIL_ADDRESS
return "EMAIL_ADDRESS";
case 26: // EMERG_CONTACT
return "EMERG_CONTACT";
case 27: // EMERG_RELATE
return "EMERG_RELATE";
case 28: // EMERG_PHONE
return "EMERG_PHONE";
case 29: // START_DATE
return "START_DATE";
case 30: // FINISH_DATE
return "FINISH_DATE";
case 31: // FTE
return "FTE";
case 32: // REC_TYPE_FLAG
return "REC_TYPE_FLAG";
case 33: // REC_PROCESS_FLAG
return "REC_PROCESS_FLAG";
default:
throw new ArgumentOutOfRangeException(nameof(ordinal));
}
}
public override int GetOrdinal(string name)
{
switch (name)
{
case "SEQ":
return 0;
case "DEPTID":
return 1;
case "EMPLID":
return 2;
case "JOBCODE":
return 3;
case "LAST_NAME":
return 4;
case "PREFIX":
return 5;
case "FIRST_NAME":
return 6;
case "MIDDLE_NAME":
return 7;
case "PREF_NAME":
return 8;
case "PREV_SURNAME":
return 9;
case "GENDER":
return 10;
case "BIRTH_DATE":
return 11;
case "H_ADDRESS01":
return 12;
case "H_ADDRESS02":
return 13;
case "H_ADDRESS03":
return 14;
case "H_STATE":
return 15;
case "H_POST_CODE":
return 16;
case "P_ADDRESS01":
return 17;
case "P_ADDRESS02":
return 18;
case "P_ADDRESS03":
return 19;
case "P_STATE":
return 20;
case "P_POST_CODE":
return 21;
case "HOME_PHONE":
return 22;
case "MOBILE_PHONE":
return 23;
case "WORK_PHONE":
return 24;
case "EMAIL_ADDRESS":
return 25;
case "EMERG_CONTACT":
return 26;
case "EMERG_RELATE":
return 27;
case "EMERG_PHONE":
return 28;
case "START_DATE":
return 29;
case "FINISH_DATE":
return 30;
case "FTE":
return 31;
case "REC_TYPE_FLAG":
return 32;
case "REC_PROCESS_FLAG":
return 33;
default:
throw new ArgumentOutOfRangeException(nameof(name));
}
}
}
#endregion
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Management.DataFactory.Models
{
using Microsoft.Azure;
using Microsoft.Azure.Management;
using Microsoft.Azure.Management.DataFactory;
using Newtonsoft.Json;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
/// <summary>
/// Properties of Self-hosted integration runtime node.
/// </summary>
public partial class SelfHostedIntegrationRuntimeNode
{
/// <summary>
/// Initializes a new instance of the SelfHostedIntegrationRuntimeNode
/// class.
/// </summary>
public SelfHostedIntegrationRuntimeNode()
{
CustomInit();
}
/// <summary>
/// Initializes a new instance of the SelfHostedIntegrationRuntimeNode
/// class.
/// </summary>
/// <param name="nodeName">Name of the integration runtime
/// node.</param>
/// <param name="machineName">Machine name of the integration runtime
/// node.</param>
/// <param name="hostServiceUri">URI for the host machine of the
/// integration runtime.</param>
/// <param name="status">Status of the integration runtime node.
/// Possible values include: 'NeedRegistration', 'Online', 'Limited',
/// 'Offline', 'Upgrading', 'Initializing', 'InitializeFailed'</param>
/// <param name="capabilities">The integration runtime capabilities
/// dictionary</param>
/// <param name="versionStatus">Status of the integration runtime node
/// version.</param>
/// <param name="version">Version of the integration runtime
/// node.</param>
/// <param name="registerTime">The time at which the integration
/// runtime node was registered in ISO8601 format.</param>
/// <param name="lastConnectTime">The most recent time at which the
/// integration runtime was connected in ISO8601 format.</param>
/// <param name="expiryTime">The time at which the integration runtime
/// will expire in ISO8601 format.</param>
/// <param name="lastStartTime">The time the node last started
/// up.</param>
/// <param name="lastStopTime">The integration runtime node last stop
/// time.</param>
/// <param name="lastUpdateResult">The result of the last integration
/// runtime node update. Possible values include: 'Succeed',
/// 'Fail'</param>
/// <param name="lastStartUpdateTime">The last time for the integration
/// runtime node update start.</param>
/// <param name="lastEndUpdateTime">The last time for the integration
/// runtime node update end.</param>
/// <param name="isActiveDispatcher">Indicates whether this node is the
/// active dispatcher for integration runtime requests.</param>
/// <param name="concurrentJobsLimit">Maximum concurrent jobs on the
/// integration runtime node.</param>
/// <param name="maxConcurrentJobs">The maximum concurrent jobs in this
/// integration runtime.</param>
public SelfHostedIntegrationRuntimeNode(string nodeName = default(string), string machineName = default(string), string hostServiceUri = default(string), string status = default(string), IDictionary<string, string> capabilities = default(IDictionary<string, string>), string versionStatus = default(string), string version = default(string), System.DateTime? registerTime = default(System.DateTime?), System.DateTime? lastConnectTime = default(System.DateTime?), System.DateTime? expiryTime = default(System.DateTime?), System.DateTime? lastStartTime = default(System.DateTime?), System.DateTime? lastStopTime = default(System.DateTime?), string lastUpdateResult = default(string), System.DateTime? lastStartUpdateTime = default(System.DateTime?), System.DateTime? lastEndUpdateTime = default(System.DateTime?), bool? isActiveDispatcher = default(bool?), int? concurrentJobsLimit = default(int?), int? maxConcurrentJobs = default(int?))
{
NodeName = nodeName;
MachineName = machineName;
HostServiceUri = hostServiceUri;
Status = status;
Capabilities = capabilities;
VersionStatus = versionStatus;
Version = version;
RegisterTime = registerTime;
LastConnectTime = lastConnectTime;
ExpiryTime = expiryTime;
LastStartTime = lastStartTime;
LastStopTime = lastStopTime;
LastUpdateResult = lastUpdateResult;
LastStartUpdateTime = lastStartUpdateTime;
LastEndUpdateTime = lastEndUpdateTime;
IsActiveDispatcher = isActiveDispatcher;
ConcurrentJobsLimit = concurrentJobsLimit;
MaxConcurrentJobs = maxConcurrentJobs;
CustomInit();
}
/// <summary>
/// An initialization method that performs custom operations like setting defaults
/// </summary>
partial void CustomInit();
/// <summary>
/// Gets name of the integration runtime node.
/// </summary>
[JsonProperty(PropertyName = "nodeName")]
public string NodeName { get; private set; }
/// <summary>
/// Gets machine name of the integration runtime node.
/// </summary>
[JsonProperty(PropertyName = "machineName")]
public string MachineName { get; private set; }
/// <summary>
/// Gets URI for the host machine of the integration runtime.
/// </summary>
[JsonProperty(PropertyName = "hostServiceUri")]
public string HostServiceUri { get; private set; }
/// <summary>
/// Gets status of the integration runtime node. Possible values
/// include: 'NeedRegistration', 'Online', 'Limited', 'Offline',
/// 'Upgrading', 'Initializing', 'InitializeFailed'
/// </summary>
[JsonProperty(PropertyName = "status")]
public string Status { get; private set; }
/// <summary>
/// Gets the integration runtime capabilities dictionary
/// </summary>
[JsonProperty(PropertyName = "capabilities")]
public IDictionary<string, string> Capabilities { get; private set; }
/// <summary>
/// Gets status of the integration runtime node version.
/// </summary>
[JsonProperty(PropertyName = "versionStatus")]
public string VersionStatus { get; private set; }
/// <summary>
/// Gets version of the integration runtime node.
/// </summary>
[JsonProperty(PropertyName = "version")]
public string Version { get; private set; }
/// <summary>
/// Gets the time at which the integration runtime node was registered
/// in ISO8601 format.
/// </summary>
[JsonProperty(PropertyName = "registerTime")]
public System.DateTime? RegisterTime { get; private set; }
/// <summary>
/// Gets the most recent time at which the integration runtime was
/// connected in ISO8601 format.
/// </summary>
[JsonProperty(PropertyName = "lastConnectTime")]
public System.DateTime? LastConnectTime { get; private set; }
/// <summary>
/// Gets the time at which the integration runtime will expire in
/// ISO8601 format.
/// </summary>
[JsonProperty(PropertyName = "expiryTime")]
public System.DateTime? ExpiryTime { get; private set; }
/// <summary>
/// Gets the time the node last started up.
/// </summary>
[JsonProperty(PropertyName = "lastStartTime")]
public System.DateTime? LastStartTime { get; private set; }
/// <summary>
/// Gets the integration runtime node last stop time.
/// </summary>
[JsonProperty(PropertyName = "lastStopTime")]
public System.DateTime? LastStopTime { get; private set; }
/// <summary>
/// Gets the result of the last integration runtime node update.
/// Possible values include: 'Succeed', 'Fail'
/// </summary>
[JsonProperty(PropertyName = "lastUpdateResult")]
public string LastUpdateResult { get; private set; }
/// <summary>
/// Gets the last time for the integration runtime node update start.
/// </summary>
[JsonProperty(PropertyName = "lastStartUpdateTime")]
public System.DateTime? LastStartUpdateTime { get; private set; }
/// <summary>
/// Gets the last time for the integration runtime node update end.
/// </summary>
[JsonProperty(PropertyName = "lastEndUpdateTime")]
public System.DateTime? LastEndUpdateTime { get; private set; }
/// <summary>
/// Gets indicates whether this node is the active dispatcher for
/// integration runtime requests.
/// </summary>
[JsonProperty(PropertyName = "isActiveDispatcher")]
public bool? IsActiveDispatcher { get; private set; }
/// <summary>
/// Gets maximum concurrent jobs on the integration runtime node.
/// </summary>
[JsonProperty(PropertyName = "concurrentJobsLimit")]
public int? ConcurrentJobsLimit { get; private set; }
/// <summary>
/// Gets the maximum concurrent jobs in this integration runtime.
/// </summary>
[JsonProperty(PropertyName = "maxConcurrentJobs")]
public int? MaxConcurrentJobs { get; private set; }
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Web.Http;
using System.Web.Http.Controllers;
using System.Web.Http.Description;
using AspNetIdentity.StandardApp.Areas.HelpPage.ModelDescriptions;
using AspNetIdentity.StandardApp.Areas.HelpPage.Models;
namespace AspNetIdentity.StandardApp.Areas.HelpPage
{
public static class HelpPageConfigurationExtensions
{
private const string ApiModelPrefix = "MS_HelpPageApiModel_";
/// <summary>
/// Sets the documentation provider for help page.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="documentationProvider">The documentation provider.</param>
public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider)
{
config.Services.Replace(typeof(IDocumentationProvider), documentationProvider);
}
/// <summary>
/// Sets the objects that will be used by the formatters to produce sample requests/responses.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sampleObjects">The sample objects.</param>
public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects)
{
config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects;
}
/// <summary>
/// Sets the sample request directly for the specified media type and action.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample request.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample);
}
/// <summary>
/// Sets the sample request directly for the specified media type and action with parameters.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample request.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample);
}
/// <summary>
/// Sets the sample request directly for the specified media type of the action.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample response.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample);
}
/// <summary>
/// Sets the sample response directly for the specified media type of the action with specific parameters.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample response.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample);
}
/// <summary>
/// Sets the sample directly for all actions with the specified media type.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample.</param>
/// <param name="mediaType">The media type.</param>
public static void SetSampleForMediaType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType), sample);
}
/// <summary>
/// Sets the sample directly for all actions with the specified type and media type.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="type">The parameter type or return type of an action.</param>
public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate request samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate request samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate response samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { "*" }), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate response samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type);
}
/// <summary>
/// Gets the help page sample generator.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <returns>The help page sample generator.</returns>
public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config)
{
return (HelpPageSampleGenerator)config.Properties.GetOrAdd(
typeof(HelpPageSampleGenerator),
k => new HelpPageSampleGenerator());
}
/// <summary>
/// Sets the help page sample generator.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sampleGenerator">The help page sample generator.</param>
public static void SetHelpPageSampleGenerator(this HttpConfiguration config, HelpPageSampleGenerator sampleGenerator)
{
config.Properties.AddOrUpdate(
typeof(HelpPageSampleGenerator),
k => sampleGenerator,
(k, o) => sampleGenerator);
}
/// <summary>
/// Gets the model description generator.
/// </summary>
/// <param name="config">The configuration.</param>
/// <returns>The <see cref="ModelDescriptionGenerator"/></returns>
public static ModelDescriptionGenerator GetModelDescriptionGenerator(this HttpConfiguration config)
{
return (ModelDescriptionGenerator)config.Properties.GetOrAdd(
typeof(ModelDescriptionGenerator),
k => InitializeModelDescriptionGenerator(config));
}
/// <summary>
/// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="apiDescriptionId">The <see cref="ApiDescription"/> ID.</param>
/// <returns>
/// An <see cref="HelpPageApiModel"/>
/// </returns>
public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId)
{
object model;
string modelId = ApiModelPrefix + apiDescriptionId;
if (!config.Properties.TryGetValue(modelId, out model))
{
Collection<ApiDescription> apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions;
ApiDescription apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase));
if (apiDescription != null)
{
model = GenerateApiModel(apiDescription, config);
config.Properties.TryAdd(modelId, model);
}
}
return (HelpPageApiModel)model;
}
private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HttpConfiguration config)
{
HelpPageApiModel apiModel = new HelpPageApiModel()
{
ApiDescription = apiDescription,
};
ModelDescriptionGenerator modelGenerator = config.GetModelDescriptionGenerator();
HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator();
GenerateUriParameters(apiModel, modelGenerator);
GenerateRequestModelDescription(apiModel, modelGenerator, sampleGenerator);
GenerateResourceDescription(apiModel, modelGenerator);
GenerateSamples(apiModel, sampleGenerator);
return apiModel;
}
private static void GenerateUriParameters(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator)
{
ApiDescription apiDescription = apiModel.ApiDescription;
foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions)
{
if (apiParameter.Source == ApiParameterSource.FromUri)
{
HttpParameterDescriptor parameterDescriptor = apiParameter.ParameterDescriptor;
Type parameterType = null;
ModelDescription typeDescription = null;
ComplexTypeModelDescription complexTypeDescription = null;
if (parameterDescriptor != null)
{
parameterType = parameterDescriptor.ParameterType;
typeDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
complexTypeDescription = typeDescription as ComplexTypeModelDescription;
}
// Example:
// [TypeConverter(typeof(PointConverter))]
// public class Point
// {
// public Point(int x, int y)
// {
// X = x;
// Y = y;
// }
// public int X { get; set; }
// public int Y { get; set; }
// }
// Class Point is bindable with a TypeConverter, so Point will be added to UriParameters collection.
//
// public class Point
// {
// public int X { get; set; }
// public int Y { get; set; }
// }
// Regular complex class Point will have properties X and Y added to UriParameters collection.
if (complexTypeDescription != null
&& !IsBindableWithTypeConverter(parameterType))
{
foreach (ParameterDescription uriParameter in complexTypeDescription.Properties)
{
apiModel.UriParameters.Add(uriParameter);
}
}
else if (parameterDescriptor != null)
{
ParameterDescription uriParameter =
AddParameterDescription(apiModel, apiParameter, typeDescription);
if (!parameterDescriptor.IsOptional)
{
uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Required" });
}
object defaultValue = parameterDescriptor.DefaultValue;
if (defaultValue != null)
{
uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Default value is " + Convert.ToString(defaultValue, CultureInfo.InvariantCulture) });
}
}
else
{
Debug.Assert(parameterDescriptor == null);
// If parameterDescriptor is null, this is an undeclared route parameter which only occurs
// when source is FromUri. Ignored in request model and among resource parameters but listed
// as a simple string here.
ModelDescription modelDescription = modelGenerator.GetOrCreateModelDescription(typeof(string));
AddParameterDescription(apiModel, apiParameter, modelDescription);
}
}
}
}
private static bool IsBindableWithTypeConverter(Type parameterType)
{
if (parameterType == null)
{
return false;
}
return TypeDescriptor.GetConverter(parameterType).CanConvertFrom(typeof(string));
}
private static ParameterDescription AddParameterDescription(HelpPageApiModel apiModel,
ApiParameterDescription apiParameter, ModelDescription typeDescription)
{
ParameterDescription parameterDescription = new ParameterDescription
{
Name = apiParameter.Name,
Documentation = apiParameter.Documentation,
TypeDescription = typeDescription,
};
apiModel.UriParameters.Add(parameterDescription);
return parameterDescription;
}
private static void GenerateRequestModelDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator, HelpPageSampleGenerator sampleGenerator)
{
ApiDescription apiDescription = apiModel.ApiDescription;
foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions)
{
if (apiParameter.Source == ApiParameterSource.FromBody)
{
Type parameterType = apiParameter.ParameterDescriptor.ParameterType;
apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
apiModel.RequestDocumentation = apiParameter.Documentation;
}
else if (apiParameter.ParameterDescriptor != null &&
apiParameter.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage))
{
Type parameterType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription);
if (parameterType != null)
{
apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
}
}
}
}
private static void GenerateResourceDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator)
{
ResponseDescription response = apiModel.ApiDescription.ResponseDescription;
Type responseType = response.ResponseType ?? response.DeclaredType;
if (responseType != null && responseType != typeof(void))
{
apiModel.ResourceDescription = modelGenerator.GetOrCreateModelDescription(responseType);
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")]
private static void GenerateSamples(HelpPageApiModel apiModel, HelpPageSampleGenerator sampleGenerator)
{
try
{
foreach (var item in sampleGenerator.GetSampleRequests(apiModel.ApiDescription))
{
apiModel.SampleRequests.Add(item.Key, item.Value);
LogInvalidSampleAsError(apiModel, item.Value);
}
foreach (var item in sampleGenerator.GetSampleResponses(apiModel.ApiDescription))
{
apiModel.SampleResponses.Add(item.Key, item.Value);
LogInvalidSampleAsError(apiModel, item.Value);
}
}
catch (Exception e)
{
apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture,
"An exception has occurred while generating the sample. Exception message: {0}",
HelpPageSampleGenerator.UnwrapException(e).Message));
}
}
private static bool TryGetResourceParameter(ApiDescription apiDescription, HttpConfiguration config, out ApiParameterDescription parameterDescription, out Type resourceType)
{
parameterDescription = apiDescription.ParameterDescriptions.FirstOrDefault(
p => p.Source == ApiParameterSource.FromBody ||
(p.ParameterDescriptor != null && p.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage)));
if (parameterDescription == null)
{
resourceType = null;
return false;
}
resourceType = parameterDescription.ParameterDescriptor.ParameterType;
if (resourceType == typeof(HttpRequestMessage))
{
HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator();
resourceType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription);
}
if (resourceType == null)
{
parameterDescription = null;
return false;
}
return true;
}
private static ModelDescriptionGenerator InitializeModelDescriptionGenerator(HttpConfiguration config)
{
ModelDescriptionGenerator modelGenerator = new ModelDescriptionGenerator(config);
Collection<ApiDescription> apis = config.Services.GetApiExplorer().ApiDescriptions;
foreach (ApiDescription api in apis)
{
ApiParameterDescription parameterDescription;
Type parameterType;
if (TryGetResourceParameter(api, config, out parameterDescription, out parameterType))
{
modelGenerator.GetOrCreateModelDescription(parameterType);
}
}
return modelGenerator;
}
private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample)
{
InvalidSample invalidSample = sample as InvalidSample;
if (invalidSample != null)
{
apiModel.ErrorMessages.Add(invalidSample.ErrorMessage);
}
}
}
}
| |
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Threading.Tasks;
using Orleans.Concurrency;
using Orleans.Runtime;
using Orleans.Streams;
using Microsoft.Extensions.Logging;
using System.Threading;
namespace Orleans.Providers.Streams.SimpleMessageStream
{
/// <summary>
/// Multiplexes messages to multiple different producers in the same grain over one grain-extension interface.
///
/// On the silo, we have one extension per activation and this extension multiplexes all streams on this activation
/// (different stream ids and different stream providers).
/// On the client, we have one extension per stream (we bind an extension for every StreamProducer, therefore every stream has its own extension).
/// </summary>
[Serializable]
internal class SimpleMessageStreamProducerExtension : IStreamProducerExtension
{
private readonly Dictionary<InternalStreamId, StreamConsumerExtensionCollection> remoteConsumers;
private readonly IStreamProviderRuntime providerRuntime;
private readonly IStreamPubSub streamPubSub;
private readonly bool fireAndForgetDelivery;
private readonly bool optimizeForImmutableData;
private readonly ILogger logger;
internal SimpleMessageStreamProducerExtension(IStreamProviderRuntime providerRt, IStreamPubSub pubsub, ILogger logger, bool fireAndForget, bool optimizeForImmutable)
{
providerRuntime = providerRt;
streamPubSub = pubsub;
fireAndForgetDelivery = fireAndForget;
optimizeForImmutableData = optimizeForImmutable;
remoteConsumers = new Dictionary<InternalStreamId, StreamConsumerExtensionCollection>();
this.logger = logger;
}
internal void AddStream(InternalStreamId streamId)
{
StreamConsumerExtensionCollection obs;
// no need to lock on _remoteConsumers, since on the client we have one extension per stream (per StreamProducer)
// so this call is only made once, when StreamProducer is created.
if (remoteConsumers.TryGetValue(streamId, out obs)) return;
obs = new StreamConsumerExtensionCollection(streamPubSub, this.logger);
remoteConsumers.Add(streamId, obs);
}
internal void RemoveStream(InternalStreamId streamId)
{
remoteConsumers.Remove(streamId);
}
internal void AddSubscribers(InternalStreamId streamId, ICollection<PubSubSubscriptionState> newSubscribers)
{
if (logger.IsEnabled(LogLevel.Debug))
logger.Debug("{0} AddSubscribers {1} for stream {2}", providerRuntime.ExecutingEntityIdentity(), Utils.EnumerableToString(newSubscribers), streamId);
StreamConsumerExtensionCollection consumers;
if (remoteConsumers.TryGetValue(streamId, out consumers))
{
foreach (var newSubscriber in newSubscribers)
{
consumers.AddRemoteSubscriber(newSubscriber.SubscriptionId, newSubscriber.Consumer);
}
}
else
{
// We got an item when we don't think we're the subscriber. This is a normal race condition.
// We can drop the item on the floor, or pass it to the rendezvous, or log a warning.
}
}
internal Task DeliverItem(InternalStreamId streamId, object item)
{
StreamConsumerExtensionCollection consumers;
if (remoteConsumers.TryGetValue(streamId, out consumers))
{
// Note: This is the main hot code path,
// and the caller immediately does await on the Task
// returned from this method, so we can just direct return here
// without incurring overhead of additional await.
return consumers.DeliverItem(streamId, item, fireAndForgetDelivery, optimizeForImmutableData);
}
else
{
// We got an item when we don't think we're the subscriber. This is a normal race condition.
// We can drop the item on the floor, or pass it to the rendezvous, or log a warning.
}
return Task.CompletedTask;
}
internal Task CompleteStream(InternalStreamId streamId)
{
StreamConsumerExtensionCollection consumers;
if (remoteConsumers.TryGetValue(streamId, out consumers))
{
return consumers.CompleteStream(streamId, fireAndForgetDelivery);
}
else
{
// We got an item when we don't think we're the subscriber. This is a normal race condition.
// We can drop the item on the floor, or pass it to the rendezvous, or log a warning.
}
return Task.CompletedTask;
}
internal Task ErrorInStream(InternalStreamId streamId, Exception exc)
{
StreamConsumerExtensionCollection consumers;
if (remoteConsumers.TryGetValue(streamId, out consumers))
{
return consumers.ErrorInStream(streamId, exc, fireAndForgetDelivery);
}
else
{
// We got an item when we don't think we're the subscriber. This is a normal race condition.
// We can drop the item on the floor, or pass it to the rendezvous, or log a warning.
}
return Task.CompletedTask;
}
// Called by rendezvous when new remote subsriber subscribes to this stream.
public Task AddSubscriber(GuidId subscriptionId, InternalStreamId streamId, IStreamConsumerExtension streamConsumer)
{
if (logger.IsEnabled(LogLevel.Debug))
{
logger.Debug("{0} AddSubscriber {1} for stream {2}", providerRuntime.ExecutingEntityIdentity(), streamConsumer, streamId);
}
StreamConsumerExtensionCollection consumers;
if (remoteConsumers.TryGetValue(streamId, out consumers))
{
consumers.AddRemoteSubscriber(subscriptionId, streamConsumer);
}
else
{
// We got an item when we don't think we're the subscriber. This is a normal race condition.
// We can drop the item on the floor, or pass it to the rendezvous, or log a warning.
}
return Task.CompletedTask;
}
public Task RemoveSubscriber(GuidId subscriptionId, InternalStreamId streamId)
{
if (logger.IsEnabled(LogLevel.Debug))
{
logger.Debug("{0} RemoveSubscription {1}", providerRuntime.ExecutingEntityIdentity(),
subscriptionId);
}
foreach (StreamConsumerExtensionCollection consumers in remoteConsumers.Values)
{
consumers.RemoveRemoteSubscriber(subscriptionId);
}
return Task.CompletedTask;
}
[Serializable]
internal class StreamConsumerExtensionCollection
{
private readonly ConcurrentDictionary<GuidId, IStreamConsumerExtension> consumers;
private readonly IStreamPubSub streamPubSub;
private readonly ILogger logger;
internal StreamConsumerExtensionCollection(IStreamPubSub pubSub, ILogger logger)
{
this.streamPubSub = pubSub;
this.logger = logger;
this.consumers = new ConcurrentDictionary<GuidId, IStreamConsumerExtension>();
}
internal void AddRemoteSubscriber(GuidId subscriptionId, IStreamConsumerExtension streamConsumer)
{
consumers.TryAdd(subscriptionId, streamConsumer);
}
internal void RemoveRemoteSubscriber(GuidId subscriptionId)
{
consumers.TryRemove(subscriptionId, out _);
if (consumers.Count == 0)
{
// Unsubscribe from PubSub?
}
}
internal Task DeliverItem(InternalStreamId streamId, object item, bool fireAndForgetDelivery, bool optimizeForImmutableData)
{
var tasks = fireAndForgetDelivery ? null : new List<Task>();
foreach (var subscriptionKvp in consumers)
{
IStreamConsumerExtension remoteConsumer = subscriptionKvp.Value;
Task task = DeliverToRemote(remoteConsumer, streamId, subscriptionKvp.Key, item, optimizeForImmutableData, fireAndForgetDelivery);
if (fireAndForgetDelivery) task.Ignore();
else tasks.Add(task);
}
// If there's no subscriber, presumably we just drop the item on the floor
return fireAndForgetDelivery ? Task.CompletedTask : Task.WhenAll(tasks);
}
private async Task DeliverToRemote(IStreamConsumerExtension remoteConsumer, InternalStreamId streamId, GuidId subscriptionId, object item, bool optimizeForImmutableData, bool fireAndForgetDelivery)
{
try
{
if (optimizeForImmutableData)
await remoteConsumer.DeliverImmutable(subscriptionId, streamId, new Immutable<object>(item), null, null);
else
await remoteConsumer.DeliverMutable(subscriptionId, streamId, item, null, null);
}
catch (ClientNotAvailableException)
{
if (consumers.TryRemove(subscriptionId, out _))
{
streamPubSub.UnregisterConsumer(subscriptionId, streamId).Ignore();
logger.Warn(ErrorCode.Stream_ConsumerIsDead,
"Consumer {0} on stream {1} is no longer active - permanently removing Consumer.", remoteConsumer, streamId);
}
}
catch(Exception ex)
{
if (!fireAndForgetDelivery)
{
throw;
}
this.logger.LogWarning(ex, "Failed to deliver message to consumer on {SubscriptionId} for stream {StreamId}.", subscriptionId, streamId);
}
}
internal Task CompleteStream(InternalStreamId streamId, bool fireAndForgetDelivery)
{
var tasks = fireAndForgetDelivery ? null : new List<Task>();
foreach (var kvp in consumers)
{
IStreamConsumerExtension remoteConsumer = kvp.Value;
GuidId subscriptionId = kvp.Key;
Task task = NotifyComplete(remoteConsumer, subscriptionId, streamId, fireAndForgetDelivery);
if (fireAndForgetDelivery) task.Ignore();
else tasks.Add(task);
}
// If there's no subscriber, presumably we just drop the item on the floor
return fireAndForgetDelivery ? Task.CompletedTask : Task.WhenAll(tasks);
}
private async Task NotifyComplete(IStreamConsumerExtension remoteConsumer, GuidId subscriptionId, InternalStreamId streamId, bool fireAndForgetDelivery)
{
try
{
await remoteConsumer.CompleteStream(subscriptionId);
} catch(Exception ex)
{
if (!fireAndForgetDelivery)
{
throw;
}
this.logger.LogWarning(ex, "Failed to notify consumer of stream completion on {SubscriptionId} for stream {StreamId}.", subscriptionId, streamId);
}
}
internal Task ErrorInStream(InternalStreamId streamId, Exception exc, bool fireAndForgetDelivery)
{
var tasks = fireAndForgetDelivery ? null : new List<Task>();
foreach (var kvp in consumers)
{
IStreamConsumerExtension remoteConsumer = kvp.Value;
GuidId subscriptionId = kvp.Key;
Task task = NotifyError(remoteConsumer, subscriptionId, exc, streamId, fireAndForgetDelivery);
if (fireAndForgetDelivery) task.Ignore();
else tasks.Add(task);
}
// If there's no subscriber, presumably we just drop the item on the floor
return fireAndForgetDelivery ? Task.CompletedTask : Task.WhenAll(tasks);
}
private async Task NotifyError(IStreamConsumerExtension remoteConsumer, GuidId subscriptionId, Exception exc, InternalStreamId streamId, bool fireAndForgetDelivery)
{
try
{
await remoteConsumer.ErrorInStream(subscriptionId, exc);
}
catch (Exception ex)
{
if (!fireAndForgetDelivery)
{
throw;
}
this.logger.LogWarning(ex, "Failed to notify consumer of stream error on {SubscriptionId} for stream {StreamId}. Error: {ErrorException}", subscriptionId, streamId, exc);
}
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics;
using System.Security;
namespace System.Numerics
{
// ATTENTION: always pass BitsBuffer by reference,
// it's a structure for performance reasons. Furthermore
// it's a mutable one, so use it only with care!
internal static partial class BigIntegerCalculator
{
// To spare memory allocations a buffer helps reusing memory!
// We just create the target array twice and switch between every
// operation. In order to not compute unnecessarily with all those
// leading zeros we take care of the current actual length.
internal struct BitsBuffer
{
private uint[] _bits;
private int _length;
public BitsBuffer(int size, uint value)
{
Debug.Assert(size >= 1);
_bits = new uint[size];
_length = value != 0 ? 1 : 0;
_bits[0] = value;
}
public BitsBuffer(int size, uint[] value)
{
Debug.Assert(value != null);
Debug.Assert(size >= ActualLength(value));
_bits = new uint[size];
_length = ActualLength(value);
Array.Copy(value, 0, _bits, 0, _length);
}
[SecuritySafeCritical]
public unsafe void MultiplySelf(ref BitsBuffer value,
ref BitsBuffer temp)
{
Debug.Assert(temp._length == 0);
Debug.Assert(_length + value._length <= temp._bits.Length);
// Executes a multiplication for this and value, writes the
// result to temp. Switches this and temp arrays afterwards.
fixed (uint* b = _bits, v = value._bits, t = temp._bits)
{
if (_length < value._length)
{
Multiply(v, value._length,
b, _length,
t, _length + value._length);
}
else
{
Multiply(b, _length,
v, value._length,
t, _length + value._length);
}
}
Apply(ref temp, _length + value._length);
}
[SecuritySafeCritical]
public unsafe void SquareSelf(ref BitsBuffer temp)
{
Debug.Assert(temp._length == 0);
Debug.Assert(_length + _length <= temp._bits.Length);
// Executes a square for this, writes the result to temp.
// Switches this and temp arrays afterwards.
fixed (uint* b = _bits, t = temp._bits)
{
Square(b, _length,
t, _length + _length);
}
Apply(ref temp, _length + _length);
}
public void Reduce(ref FastReducer reducer)
{
// Executes a modulo operation using an optimized reducer.
// Thus, no need of any switching here, happens in-line.
_length = reducer.Reduce(_bits, _length);
}
[SecuritySafeCritical]
public unsafe void Reduce(uint[] modulus)
{
Debug.Assert(modulus != null);
// Executes a modulo operation using the divide operation.
// Thus, no need of any switching here, happens in-line.
if (_length >= modulus.Length)
{
fixed (uint* b = _bits, m = modulus)
{
Divide(b, _length,
m, modulus.Length,
null, 0);
}
_length = ActualLength(_bits, modulus.Length);
}
}
[SecuritySafeCritical]
public unsafe void Reduce(ref BitsBuffer modulus)
{
// Executes a modulo operation using the divide operation.
// Thus, no need of any switching here, happens in-line.
if (_length >= modulus._length)
{
fixed (uint* b = _bits, m = modulus._bits)
{
Divide(b, _length,
m, modulus._length,
null, 0);
}
_length = ActualLength(_bits, modulus._length);
}
}
public void Overwrite(ulong value)
{
Debug.Assert(_bits.Length >= 2);
if (_length > 2)
{
// ensure leading zeros
Array.Clear(_bits, 2, _length - 2);
}
uint lo = (uint)value;
uint hi = (uint)(value >> 32);
_bits[0] = lo;
_bits[1] = hi;
_length = hi != 0 ? 2 : lo != 0 ? 1 : 0;
}
public void Overwrite(uint value)
{
Debug.Assert(_bits.Length >= 1);
if (_length > 1)
{
// ensure leading zeros
Array.Clear(_bits, 1, _length - 1);
}
_bits[0] = value;
_length = value != 0 ? 1 : 0;
}
public uint[] GetBits()
{
return _bits;
}
public int GetSize()
{
return _bits.Length;
}
public int GetLength()
{
return _length;
}
public void Refresh(int maxLength)
{
Debug.Assert(_bits.Length >= maxLength);
if (_length > maxLength)
{
// ensure leading zeros
Array.Clear(_bits, maxLength, _length - maxLength);
}
_length = ActualLength(_bits, maxLength);
}
private void Apply(ref BitsBuffer temp, int maxLength)
{
Debug.Assert(temp._length == 0);
Debug.Assert(maxLength <= temp._bits.Length);
// Resets this and switches this and temp afterwards.
// The caller assumed an empty temp, the next will too.
Array.Clear(_bits, 0, _length);
uint[] t = temp._bits;
temp._bits = _bits;
_bits = t;
_length = ActualLength(_bits, maxLength);
}
}
}
}
| |
#nullable enable
using System;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using Esprima;
using Esprima.Ast;
using Jint.Native;
using Jint.Native.Function;
using Jint.Native.Object;
using Jint.Runtime;
using Jint.Runtime.Environments;
using Jint.Runtime.Interpreter;
using Jint.Runtime.Interpreter.Expressions;
using Jint.Runtime.Modules;
namespace Jint
{
public static class EsprimaExtensions
{
public static JsValue GetKey<T>(this T property, Engine engine) where T : ClassProperty => GetKey(property.Key, engine, property.Computed);
public static JsValue GetKey(this Expression expression, Engine engine, bool resolveComputed = false)
{
if (expression is Literal literal)
{
if (literal.TokenType == TokenType.NullLiteral)
{
return JsValue.Null;
}
return LiteralKeyToString(literal);
}
if (!resolveComputed && expression is Identifier identifier)
{
return identifier.Name;
}
if (!resolveComputed || !TryGetComputedPropertyKey(expression, engine, out var propertyKey))
{
ExceptionHelper.ThrowArgumentException("Unable to extract correct key, node type: " + expression.Type);
return null;
}
return propertyKey;
}
private static bool TryGetComputedPropertyKey<T>(T expression, Engine engine, out JsValue propertyKey)
where T : Expression
{
if (expression.Type is Nodes.Identifier
or Nodes.CallExpression
or Nodes.BinaryExpression
or Nodes.UpdateExpression
or Nodes.AssignmentExpression
or Nodes.UnaryExpression
or Nodes.MemberExpression
or Nodes.LogicalExpression
or Nodes.ConditionalExpression
or Nodes.ArrowFunctionExpression
or Nodes.FunctionExpression)
{
var context = engine._activeEvaluationContext;
propertyKey = TypeConverter.ToPropertyKey(JintExpression.Build(engine, expression).GetValue(context).Value);
return true;
}
propertyKey = string.Empty;
return false;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal static bool IsFunctionDefinition<T>(this T node) where T : Node
{
var type = node.Type;
return type
is Nodes.FunctionExpression
or Nodes.ArrowFunctionExpression
or Nodes.ArrowParameterPlaceHolder
or Nodes.ClassExpression;
}
/// <summary>
/// https://tc39.es/ecma262/#sec-static-semantics-isconstantdeclaration
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal static bool IsConstantDeclaration(this Declaration d)
{
return d is VariableDeclaration { Kind: VariableDeclarationKind.Const };
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal static bool HasName<T>(this T node) where T : Node
{
if (!node.IsFunctionDefinition())
{
return false;
}
if ((node as IFunction)?.Id is not null)
{
return true;
}
if ((node as ClassExpression)?.Id is not null)
{
return true;
}
return false;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal static bool IsAnonymousFunctionDefinition<T>(this T node) where T : Node
{
if (!node.IsFunctionDefinition())
{
return false;
}
if (node.HasName())
{
return false;
}
return true;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal static bool IsOptional<T>(this T node) where T : Expression
{
switch (node)
{
case MemberExpression { Optional: true }:
case CallExpression { Optional: true }:
return true;
default:
return false;
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal static string LiteralKeyToString(Literal literal)
{
// prevent conversion to scientific notation
if (literal.Value is double d)
{
return TypeConverter.ToString(d);
}
return literal.Value as string ?? Convert.ToString(literal.Value, provider: null);
}
internal static void GetBoundNames(this VariableDeclaration variableDeclaration, List<string> target)
{
ref readonly var declarations = ref variableDeclaration.Declarations;
for (var i = 0; i < declarations.Count; i++)
{
var declaration = declarations[i];
GetBoundNames(declaration.Id, target);
}
}
internal static void GetBoundNames(this Node? parameter, List<string> target)
{
if (parameter is null || parameter.Type == Nodes.Literal)
{
return;
}
// try to get away without a loop
if (parameter is Identifier id)
{
target.Add(id.Name!);
return;
}
if (parameter is VariableDeclaration variableDeclaration)
{
variableDeclaration.GetBoundNames(target);
return;
}
while (true)
{
if (parameter is Identifier identifier)
{
target.Add(identifier.Name!);
return;
}
if (parameter is RestElement restElement)
{
parameter = restElement.Argument;
continue;
}
if (parameter is ArrayPattern arrayPattern)
{
ref readonly var arrayPatternElements = ref arrayPattern.Elements;
for (var i = 0; i < arrayPatternElements.Count; i++)
{
var expression = arrayPatternElements[i];
GetBoundNames(expression, target);
}
}
else if (parameter is ObjectPattern objectPattern)
{
ref readonly var objectPatternProperties = ref objectPattern.Properties;
for (var i = 0; i < objectPatternProperties.Count; i++)
{
var property = objectPatternProperties[i];
if (property is Property p)
{
GetBoundNames(p.Value, target);
}
else
{
GetBoundNames((RestElement) property, target);
}
}
}
else if (parameter is AssignmentPattern assignmentPattern)
{
parameter = assignmentPattern.Left;
continue;
}
else if (parameter is ClassDeclaration classDeclaration)
{
var name = classDeclaration.Id?.Name;
if (name != null)
{
target.Add(name);
}
}
break;
}
}
internal static void BindingInitialization(
this Expression? expression,
EvaluationContext context,
JsValue value,
EnvironmentRecord env)
{
if (expression is Identifier identifier)
{
var catchEnvRecord = (DeclarativeEnvironmentRecord) env;
catchEnvRecord.CreateMutableBindingAndInitialize(identifier.Name, canBeDeleted: false, value);
}
else if (expression is BindingPattern bindingPattern)
{
BindingPatternAssignmentExpression.ProcessPatterns(
context,
bindingPattern,
value,
env);
}
}
/// <summary>
/// https://tc39.es/ecma262/#sec-runtime-semantics-definemethod
/// </summary>
internal static Record DefineMethod(this ClassProperty m, ObjectInstance obj, ObjectInstance? functionPrototype = null)
{
var engine = obj.Engine;
var property = TypeConverter.ToPropertyKey(m.GetKey(engine));
var prototype = functionPrototype ?? engine.Realm.Intrinsics.Function.PrototypeObject;
var function = m.Value as IFunction;
if (function is null)
{
ExceptionHelper.ThrowSyntaxError(engine.Realm);
}
var functionDefinition = new JintFunctionDefinition(engine, function);
var closure = new ScriptFunctionInstance(
engine,
functionDefinition,
engine.ExecutionContext.LexicalEnvironment,
functionDefinition.ThisMode,
prototype);
closure.MakeMethod(obj);
return new Record(property, closure);
}
internal static void GetImportEntries(this ImportDeclaration import, List<ImportEntry> importEntries, HashSet<string> requestedModules)
{
var source = import.Source.StringValue!;
var specifiers = import.Specifiers;
requestedModules.Add(source!);
foreach (var specifier in specifiers)
{
switch (specifier)
{
case ImportNamespaceSpecifier namespaceSpecifier:
importEntries.Add(new ImportEntry(source, "*", namespaceSpecifier.Local.GetModuleKey()));
break;
case ImportSpecifier importSpecifier:
importEntries.Add(new ImportEntry(source, importSpecifier.Imported.GetModuleKey(), importSpecifier.Local.GetModuleKey()));
break;
case ImportDefaultSpecifier defaultSpecifier:
importEntries.Add(new ImportEntry(source, "default", defaultSpecifier.Local.GetModuleKey()));
break;
}
}
}
internal static void GetExportEntries(this ExportDeclaration export, List<ExportEntry> exportEntries, HashSet<string> requestedModules)
{
switch (export)
{
case ExportDefaultDeclaration defaultDeclaration:
GetExportEntries(true, defaultDeclaration.Declaration, exportEntries);
break;
case ExportAllDeclaration allDeclaration:
//Note: there is a pending PR for Esprima to support exporting an imported modules content as a namespace i.e. 'export * as ns from "mod"'
requestedModules.Add(allDeclaration.Source.StringValue!);
exportEntries.Add(new(allDeclaration.Exported?.GetModuleKey(), allDeclaration.Source.StringValue, "*", null));
break;
case ExportNamedDeclaration namedDeclaration:
ref readonly var specifiers = ref namedDeclaration.Specifiers;
if (specifiers.Count == 0)
{
GetExportEntries(false, namedDeclaration.Declaration!, exportEntries, namedDeclaration.Source?.StringValue);
}
else
{
for (var i = 0; i < specifiers.Count; i++)
{
var specifier = specifiers[i];
if (namedDeclaration.Source != null)
{
exportEntries.Add(new(specifier.Exported.GetModuleKey(), namedDeclaration.Source.StringValue, specifier.Local.GetModuleKey(), null));
}
else
{
exportEntries.Add(new(specifier.Exported.GetModuleKey(), null, null, specifier.Local.GetModuleKey()));
}
}
}
if (namedDeclaration.Source is not null)
{
requestedModules.Add(namedDeclaration.Source.StringValue!);
}
break;
}
}
private static void GetExportEntries(bool defaultExport, StatementListItem declaration, List<ExportEntry> exportEntries, string? moduleRequest = null)
{
var names = GetExportNames(declaration);
if (names.Count == 0)
{
if (defaultExport)
{
exportEntries.Add(new("default", null, null, "*default*"));
}
}
else
{
for (var i = 0; i < names.Count; i++)
{
var name = names[i];
var exportName = defaultExport ? "default" : name;
exportEntries.Add(new(exportName, moduleRequest, null, name));
}
}
}
private static List<string> GetExportNames(StatementListItem declaration)
{
var result = new List<string>();
switch (declaration)
{
case FunctionDeclaration functionDeclaration:
var funcName = functionDeclaration.Id?.Name;
if (funcName is not null)
{
result.Add(funcName);
}
break;
case ClassDeclaration classDeclaration:
var className = classDeclaration.Id?.Name;
if (className is not null)
{
result.Add(className);
}
break;
case VariableDeclaration variableDeclaration:
ref readonly var declarators = ref variableDeclaration.Declarations;
for (var i = 0; i < declarators.Count; i++)
{
var declarator = declarators[i];
var varName = declarator.Id.As<Identifier>()?.Name;
if (varName is not null)
{
result.Add(varName);
}
}
break;
}
return result;
}
private static string? GetModuleKey(this Expression expression)
{
return (expression as Identifier)?.Name ?? (expression as Literal)?.StringValue;
}
internal readonly record struct Record(JsValue Key, ScriptFunctionInstance Closure);
}
}
| |
// ==++==
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// ==--==
using System;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Runtime.CompilerServices;
using System.Runtime.ConstrainedExecution;
using System.Runtime.InteropServices;
using System.Diagnostics.Contracts;
using Microsoft.Win32;
using Microsoft.Win32.SafeHandles;
using System.Security.Cryptography.X509Certificates;
namespace System.Security.Cryptography {
internal enum AsymmetricPaddingMode {
/// <summary>
/// No padding
/// </summary>
None = 1, // BCRYPT_PAD_NONE
/// <summary>
/// PKCS #1 padding
/// </summary>
Pkcs1 = 2, // BCRYPT_PAD_PKCS1
/// <summary>
/// Optimal Asymmetric Encryption Padding
/// </summary>
Oaep = 4, // BCRYPT_PAD_OAEP
/// <summary>
/// Probabilistic Signature Scheme padding
/// </summary>
Pss = 8 // BCRYPT_PAD_PSS
}
/// <summary>
/// Native interop with CNG's BCrypt layer. Native definitions can be found in bcrypt.h
/// </summary>
internal static class BCryptNative {
/// <summary>
/// Well known algorithm names
/// </summary>
internal static class AlgorithmName {
public const string ECDHP256 = "ECDH_P256"; // BCRYPT_ECDH_P256_ALGORITHM
public const string ECDHP384 = "ECDH_P384"; // BCRYPT_ECDH_P384_ALGORITHM
public const string ECDHP521 = "ECDH_P521"; // BCRYPT_ECDH_P521_ALGORITHM
public const string ECDsaP256 = "ECDSA_P256"; // BCRYPT_ECDSA_P256_ALGORITHM
public const string ECDsaP384 = "ECDSA_P384"; // BCRYPT_ECDSA_P384_ALGORITHM
public const string ECDsaP521 = "ECDSA_P521"; // BCRYPT_ECDSA_P521_ALGORITHM
public const string MD5 = "MD5"; // BCRYPT_MD5_ALGORITHM
public const string Sha1 = "SHA1"; // BCRYPT_SHA1_ALGORITHM
public const string Sha256 = "SHA256"; // BCRYPT_SHA256_ALGORITHM
public const string Sha384 = "SHA384"; // BCRYPT_SHA384_ALGORITHM
public const string Sha512 = "SHA512"; // BCRYPT_SHA512_ALGORITHM
internal const string Rsa = "RSA"; // BCRYPT_RSA_ALGORITHM
}
/// <summary>
/// Well known key blob tyes
/// </summary>
internal static class KeyBlobType {
//During Win8 Windows introduced BCRYPT_PUBLIC_KEY_BLOB L"PUBLICBLOB"
//and #define BCRYPT_PRIVATE_KEY_BLOB L"PRIVATEBLOB". We should use the
//same on ProjectN and ProjectK
internal const string RsaFullPrivateBlob = "RSAFULLPRIVATEBLOB"; // BCRYPT_RSAFULLPRIVATE_BLOB
internal const string RsaPrivateBlob = "RSAPRIVATEBLOB"; // BCRYPT_RSAPRIVATE_BLOB
internal const string RsaPublicBlob = "RSAPUBLICBLOB"; // BCRYPT_PUBLIC_KEY_BLOB
}
[StructLayout(LayoutKind.Sequential)]
internal struct BCRYPT_RSAKEY_BLOB {
internal KeyBlobMagicNumber Magic;
internal int BitLength;
internal int cbPublicExp;
internal int cbModulus;
internal int cbPrime1;
internal int cbPrime2;
}
/// <summary>
/// Result codes from BCrypt APIs
/// </summary>
internal enum ErrorCode {
Success = 0x00000000, // STATUS_SUCCESS
BufferToSmall = unchecked((int)0xC0000023), // STATUS_BUFFER_TOO_SMALL
ObjectNameNotFound = unchecked((int)0xC0000034) // SATUS_OBJECT_NAME_NOT_FOUND
}
/// <summary>
/// Well known BCrypt hash property names
/// </summary>
internal static class HashPropertyName {
public const string HashLength = "HashDigestLength"; // BCRYPT_HASH_LENGTH
}
/// <summary>
/// Magic numbers identifying blob types
/// </summary>
internal enum KeyBlobMagicNumber {
ECDHPublicP256 = 0x314B4345, // BCRYPT_ECDH_PUBLIC_P256_MAGIC
ECDHPublicP384 = 0x334B4345, // BCRYPT_ECDH_PUBLIC_P384_MAGIC
ECDHPublicP521 = 0x354B4345, // BCRYPT_ECDH_PUBLIC_P521_MAGIC
ECDsaPublicP256 = 0x31534345, // BCRYPT_ECDSA_PUBLIC_P256_MAGIC
ECDsaPublicP384 = 0x33534345, // BCRYPT_ECDSA_PUBLIC_P384_MAGIC
ECDsaPublicP521 = 0x35534345, // BCRYPT_ECDSA_PUBLIC_P521_MAGIC
RsaPublic = 0x31415352, // BCRYPT_RSAPUBLIC_MAGIC
RsaPrivate = 0x32415352, // BCRYPT_RSAPRIVATE_MAGIC
RsaFullPrivateMagic = 0x33415352, //BCRYPT_RSAFULLPRIVATE_MAGIC
KeyDataBlob = 0x4d42444b // BCRYPT_KEY_DATA_BLOB_MAGIC
}
[StructLayout(LayoutKind.Sequential)]
internal struct BCRYPT_OAEP_PADDING_INFO {
[MarshalAs(UnmanagedType.LPWStr)]
internal string pszAlgId;
internal IntPtr pbLabel;
internal int cbLabel;
}
[StructLayout(LayoutKind.Sequential)]
internal struct BCRYPT_PKCS1_PADDING_INFO {
[MarshalAs(UnmanagedType.LPWStr)]
internal string pszAlgId;
}
[StructLayout(LayoutKind.Sequential)]
internal struct BCRYPT_PSS_PADDING_INFO {
[MarshalAs(UnmanagedType.LPWStr)]
internal string pszAlgId;
internal int cbSalt;
}
/// <summary>
/// Well known KDF names
/// </summary>
internal static class KeyDerivationFunction {
public const string Hash = "HASH"; // BCRYPT_KDF_HASH
public const string Hmac = "HMAC"; // BCRYPT_KDF_HMAC
public const string Tls = "TLS_PRF"; // BCRYPT_KDF_TLS_PRF
}
internal const string BCRYPT_ECCPUBLIC_BLOB = "ECCPUBLICBLOB";
internal const string BCRYPT_ECCPRIVATE_BLOB = "ECCPRIVATEBLOB";
/// <summary>
/// Well known BCrypt provider names
/// </summary>
internal static class ProviderName {
public const string MicrosoftPrimitiveProvider = "Microsoft Primitive Provider"; // MS_PRIMITIVE_PROVIDER
}
/// <summary>
/// Well known BCrypt object property names
/// </summary>
internal static class ObjectPropertyName {
public const string ObjectLength = "ObjectLength"; // BCRYPT_OBJECT_LENGTH
}
#pragma warning disable 618 // Have not migrated to v4 transparency yet
[SecurityCritical(SecurityCriticalScope.Everything)]
#pragma warning restore 618
[SuppressUnmanagedCodeSecurity]
internal static class UnsafeNativeMethods {
/// <summary>
/// Create a hash object
/// </summary>
[DllImport("bcrypt.dll", CharSet = CharSet.Unicode)]
internal static extern ErrorCode BCryptCreateHash(SafeBCryptAlgorithmHandle hAlgorithm,
[Out] out SafeBCryptHashHandle phHash,
IntPtr pbHashObject,
int cbHashObject,
IntPtr pbSecret,
int cbSecret,
int dwFlags);
/// <summary>
/// Get a property from a BCrypt algorithm object
/// </summary>
[DllImport("bcrypt.dll", CharSet = CharSet.Unicode)]
internal static extern ErrorCode BCryptGetProperty(SafeBCryptAlgorithmHandle hObject,
string pszProperty,
[MarshalAs(UnmanagedType.LPArray), In, Out] byte[] pbOutput,
int cbOutput,
[In, Out] ref int pcbResult,
int flags);
/// <summary>
/// Get a property from a BCrypt algorithm object
/// </summary>
[DllImport("bcrypt.dll", EntryPoint = "BCryptGetProperty", CharSet = CharSet.Unicode)]
internal static extern ErrorCode BCryptGetAlgorithmProperty(SafeBCryptAlgorithmHandle hObject,
string pszProperty,
[MarshalAs(UnmanagedType.LPArray), In, Out] byte[] pbOutput,
int cbOutput,
[In, Out] ref int pcbResult,
int flags);
/// <summary>
/// Get a property from a BCrypt hash object
/// </summary>
[DllImport("bcrypt.dll", EntryPoint = "BCryptGetProperty", CharSet = CharSet.Unicode)]
internal static extern ErrorCode BCryptGetHashProperty(SafeBCryptHashHandle hObject,
string pszProperty,
[MarshalAs(UnmanagedType.LPArray), In, Out] byte[] pbOutput,
int cbOutput,
[In, Out] ref int pcbResult,
int flags);
/// <summary>
/// Get the hash value of the data
/// </summary>
[DllImport("bcrypt.dll")]
internal static extern ErrorCode BCryptFinishHash(SafeBCryptHashHandle hHash,
[MarshalAs(UnmanagedType.LPArray), Out] byte[] pbInput,
int cbInput,
int dwFlags);
/// <summary>
/// Hash a block of data
/// </summary>
[DllImport("bcrypt.dll")]
internal static extern ErrorCode BCryptHashData(SafeBCryptHashHandle hHash,
[MarshalAs(UnmanagedType.LPArray), In] byte[] pbInput,
int cbInput,
int dwFlags);
/// <summary>
/// Get a handle to an algorithm provider
/// </summary>
[DllImport("bcrypt.dll", CharSet = CharSet.Unicode)]
internal static extern ErrorCode BCryptOpenAlgorithmProvider([Out] out SafeBCryptAlgorithmHandle phAlgorithm,
string pszAlgId, // BCryptAlgorithm
string pszImplementation, // ProviderNames
int dwFlags);
[DllImport("bcrypt.dll", SetLastError = true)]
internal static extern ErrorCode BCryptExportKey([In]SafeBCryptKeyHandle hKey,
[In]IntPtr hExportKey,
[In][MarshalAs(UnmanagedType.LPWStr)] string pszBlobType,
[Out, MarshalAs(UnmanagedType.LPArray)] byte[] pbOutput,
[In]int cbOutput,
[In]ref int pcbResult,
[In] int dwFlags);
[DllImport("Crypt32.dll", SetLastError = true)]
internal static extern int CryptImportPublicKeyInfoEx2([In] uint dwCertEncodingType,
[In] ref X509Native.CERT_PUBLIC_KEY_INFO pInfo,
[In] int dwFlags,
[In] IntPtr pvAuxInfo,
[Out] out SafeBCryptKeyHandle phKey);
}
//
// Wrapper and utility functions
//
/// <summary>
/// Adapter to wrap specific BCryptGetProperty P/Invokes with a generic handle type
/// </summary>
#pragma warning disable 618 // System.Core.dll still uses SecurityRuleSet.Level1
[SecurityCritical(SecurityCriticalScope.Everything)]
#pragma warning restore 618
private delegate ErrorCode BCryptPropertyGetter<T>(T hObject,
string pszProperty,
byte[] pbOutput,
int cbOutput,
ref int pcbResult,
int dwFlags) where T : SafeHandle;
private static volatile bool s_haveBcryptSupported;
private static volatile bool s_bcryptSupported;
/// <summary>
/// Determine if BCrypt is supported on the current machine
/// </summary>
internal static bool BCryptSupported {
[SecuritySafeCritical]
[SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands", Justification = "Reviewed")]
get {
if (!s_haveBcryptSupported)
{
// Attempt to load bcrypt.dll to see if the BCrypt CNG APIs are available on the machine
using (SafeLibraryHandle bcrypt = Microsoft.Win32.UnsafeNativeMethods.LoadLibraryEx("bcrypt", IntPtr.Zero, 0)) {
s_bcryptSupported = !bcrypt.IsInvalid;
s_haveBcryptSupported = true;
}
}
return s_bcryptSupported;
}
}
/// <summary>
/// Get the value of a DWORD property of a BCrypt object
/// </summary>
[System.Security.SecurityCritical]
internal static int GetInt32Property<T>(T algorithm, string property) where T : SafeHandle {
Contract.Requires(algorithm != null);
Contract.Requires(property == HashPropertyName.HashLength ||
property == ObjectPropertyName.ObjectLength);
return BitConverter.ToInt32(GetProperty(algorithm, property), 0);
}
/// <summary>
/// Get the value of a property of a BCrypt object
/// </summary>
[System.Security.SecurityCritical]
internal static byte[] GetProperty<T>(T algorithm, string property) where T : SafeHandle {
Contract.Requires(algorithm != null);
Contract.Requires(!String.IsNullOrEmpty(property));
Contract.Ensures(Contract.Result<byte[]>() != null);
BCryptPropertyGetter<T> getter = null;
if (typeof(T) == typeof(SafeBCryptAlgorithmHandle)) {
getter = new BCryptPropertyGetter<SafeBCryptAlgorithmHandle>(UnsafeNativeMethods.BCryptGetAlgorithmProperty)
as BCryptPropertyGetter<T>;
}
else if (typeof(T) == typeof(SafeBCryptHashHandle)) {
getter = new BCryptPropertyGetter<SafeBCryptHashHandle>(UnsafeNativeMethods.BCryptGetHashProperty)
as BCryptPropertyGetter<T>;
}
Debug.Assert(getter != null, "Unknown handle type");
// Figure out how big the property is
int bufferSize = 0;
ErrorCode error = getter(algorithm, property, null, 0, ref bufferSize, 0);
if (error != ErrorCode.BufferToSmall && error != ErrorCode.Success) {
throw new CryptographicException((int)error);
}
// Allocate the buffer, and return the property
Debug.Assert(bufferSize > 0, "bufferSize > 0");
byte[] buffer = new byte[bufferSize];
error = getter(algorithm, property, buffer, buffer.Length, ref bufferSize, 0);
if (error != ErrorCode.Success) {
throw new CryptographicException((int)error);
}
return buffer;
}
/// <summary>
/// Map an algorithm identifier to a key size and magic number
/// </summary>
internal static void MapAlgorithmIdToMagic(string algorithm,
out KeyBlobMagicNumber algorithmMagic,
out int keySize) {
Contract.Requires(!String.IsNullOrEmpty(algorithm));
switch (algorithm) {
case AlgorithmName.ECDHP256:
algorithmMagic = KeyBlobMagicNumber.ECDHPublicP256;
keySize = 256;
break;
case AlgorithmName.ECDHP384:
algorithmMagic = KeyBlobMagicNumber.ECDHPublicP384;
keySize = 384;
break;
case AlgorithmName.ECDHP521:
algorithmMagic = KeyBlobMagicNumber.ECDHPublicP521;
keySize = 521;
break;
case AlgorithmName.ECDsaP256:
algorithmMagic = KeyBlobMagicNumber.ECDsaPublicP256;
keySize = 256;
break;
case AlgorithmName.ECDsaP384:
algorithmMagic = KeyBlobMagicNumber.ECDsaPublicP384;
keySize = 384;
break;
case AlgorithmName.ECDsaP521:
algorithmMagic = KeyBlobMagicNumber.ECDsaPublicP521;
keySize = 521;
break;
default:
throw new ArgumentException(SR.GetString(SR.Cryptography_UnknownEllipticCurveAlgorithm));
}
}
/// <summary>
/// Open a handle to an algorithm provider
/// </summary>
[System.Security.SecurityCritical]
internal static SafeBCryptAlgorithmHandle OpenAlgorithm(string algorithm, string implementation) {
Contract.Requires(!String.IsNullOrEmpty(algorithm));
Contract.Requires(!String.IsNullOrEmpty(implementation));
Contract.Ensures(Contract.Result<SafeBCryptAlgorithmHandle>() != null &&
!Contract.Result<SafeBCryptAlgorithmHandle>().IsInvalid &&
!Contract.Result<SafeBCryptAlgorithmHandle>().IsClosed);
SafeBCryptAlgorithmHandle algorithmHandle = null;
ErrorCode error = UnsafeNativeMethods.BCryptOpenAlgorithmProvider(out algorithmHandle,
algorithm,
implementation,
0);
if (error != ErrorCode.Success) {
throw new CryptographicException((int)error);
}
return algorithmHandle;
}
[SecuritySafeCritical]
internal static SafeBCryptKeyHandle ImportAsymmetricPublicKey(X509Native.CERT_PUBLIC_KEY_INFO certPublicKeyInfo, int dwFlag) {
SafeBCryptKeyHandle keyHandle = null;
int error = UnsafeNativeMethods.CryptImportPublicKeyInfoEx2(
X509Native.X509_ASN_ENCODING,
ref certPublicKeyInfo,
dwFlag,
IntPtr.Zero,
out keyHandle);
if (error == 0) {
throw new CryptographicException(Marshal.GetLastWin32Error());
}
return keyHandle;
}
[SecuritySafeCritical]
internal static byte[] ExportBCryptKey(SafeBCryptKeyHandle hKey, string blobType) {
byte[] keyBlob = null;
int length = 0;
ErrorCode error = UnsafeNativeMethods.BCryptExportKey(hKey, IntPtr.Zero, blobType, null, 0, ref length, 0);
if (error != ErrorCode.BufferToSmall && error != ErrorCode.Success)
{
throw new CryptographicException(Marshal.GetLastWin32Error());
}
keyBlob = new byte[length];
error = UnsafeNativeMethods.BCryptExportKey(hKey, IntPtr.Zero, blobType, keyBlob, length, ref length, 0);
if (error != ErrorCode.Success) {
throw new CryptographicException(Marshal.GetLastWin32Error());
}
return keyBlob;
}
}
}
| |
/***
* FdpDataProvider
needed FirebirdClient http://sourceforge.net/project/showfiles.php?group_id=9028&package_id=62107
tested with FirebirdClient 2.1.0 Beta 3
Known troubles:
1) Some tests fails due to Fb SQL-syntax specific
2) ResultSet mapping doesn't work - not supported by client
3) UnitTests.CS.DataAccess.OutRefTest tests: Test2 && TestNullable2 doesnt work:
parameters directions should be provided correctly to functions run, that's why
output parameterd would be mapped to Entity e, so asserts should be same a in Test1.
"Features"
1) Type conversation due to http://www.firebirdsql.org/manual/migration-mssql-data-types.html
BUT! for Binary types BLOB is used! not CHAR!
2) InOut parameters faking: InOut parameters are not suppotred by Fb, but they could be
emulated: each InOut parameter should be defined in RETURNS() section, and allso has a mirror
in parameter section with name [prefix][inOutParameterName], see OutRefTest SP. Faking settings:
FdpDataProvider.InOutInputParameterPrefix = "in_";
FdpDataProvider.IsInOutParameterEmulation = true;
3) Returned values faking. Each parameter with "magic name" woul be treated as ReturnValue.
see Scalar_ReturnParameter SP. Faking settings:
FdpDataProvider.ReturnParameterName = "RETURN_VALUE";
FdpDataProvider.IsReturnValueEmulation = true;
*/
using System;
using System.Data;
using System.Data.Common;
using FirebirdSql.Data.FirebirdClient;
namespace BLToolkit.Data.DataProvider
{
using Sql.SqlProvider;
using Mapping;
public class FdpDataProvider : DataProviderBase
{
public FdpDataProvider()
{
MappingSchema = new FbMappingSchema();
}
#region InOut & ReturnValue emulation
public static string InOutInputParameterPrefix = "in_";
public static string ReturnParameterName = "RETURN_VALUE";
public static bool IsReturnValueEmulation = true;
public static bool IsInOutParameterEmulation = true;
public static bool QuoteIdentifiers = false;
#endregion
#region Overloads
public override IDbConnection CreateConnectionObject()
{
return new FbConnection();
}
public override DbDataAdapter CreateDataAdapterObject()
{
return new FbDataAdapter();
}
public override bool DeriveParameters(IDbCommand command)
{
if (command is FbCommand)
{
FbCommandBuilder.DeriveParameters((FbCommand)command);
if (IsReturnValueEmulation)
foreach (IDbDataParameter par in command.Parameters)
if (IsReturnValue(par))
par.Direction = ParameterDirection.ReturnValue;
return true;
}
return false;
}
public override object Convert(object value, ConvertType convertType)
{
switch (convertType)
{
case ConvertType.NameToQueryField:
case ConvertType.NameToQueryTable:
if (QuoteIdentifiers)
{
string name = value.ToString();
if (name.Length > 0 && name[0] == '"')
return value;
return '"' + name + '"';
}
break;
case ConvertType.NameToQueryParameter:
case ConvertType.NameToCommandParameter:
case ConvertType.NameToSprocParameter:
return "@" + value;
case ConvertType.SprocParameterToName:
if (value != null)
{
string str = value.ToString();
return str.Length > 0 && str[0] == '@' ? str.Substring(1) : str;
}
break;
case ConvertType.ExceptionToErrorNumber:
if (value is FbException)
{
FbException ex = (FbException)value;
if (ex.Errors.Count > 0)
return ex.Errors[0].Number;
}
break;
}
return value;
}
public override Type ConnectionType
{
get { return typeof(FbConnection); }
}
public override string Name
{
get { return DataProvider.ProviderName.Firebird; }
}
public override int MaxBatchSize
{
get { return 0; }
}
public override ISqlProvider CreateSqlProvider()
{
return new FirebirdSqlProvider(this);
}
public override bool IsValueParameter(IDbDataParameter parameter)
{
return parameter.Direction != ParameterDirection.ReturnValue
&& parameter.Direction != ParameterDirection.Output;
}
private string GetInputParameterName(string ioParameterName)
{
return (string)Convert(
InOutInputParameterPrefix + (string)Convert(ioParameterName, ConvertType.SprocParameterToName),
ConvertType.NameToSprocParameter);
}
private static IDbDataParameter GetParameter(string parameterName, IDbDataParameter[] commandParameters)
{
foreach (IDbDataParameter par in commandParameters)
if (string.Compare(parameterName, par.ParameterName, true) == 0)
return par;
return null;
}
private bool IsReturnValue(IDbDataParameter parameter)
{
if (string.Compare(parameter.ParameterName,
(string)Convert(ReturnParameterName, ConvertType.NameToSprocParameter), true) == 0
)
return true;
return false;
}
public override void PrepareCommand(ref CommandType commandType, ref string commandText, ref IDbDataParameter[] commandParameters)
{
if (commandParameters != null) foreach (IDbDataParameter par in commandParameters)
{
if (par.Value is bool)
{
string value = (bool)par.Value ? "1" : "0";
par.DbType = DbType.AnsiString;
par.Value = value;
par.Size = value.Length;
}
else if (par.Value is Guid)
{
string value = par.Value.ToString();
par.DbType = DbType.AnsiStringFixedLength;
par.Value = value;
par.Size = value.Length;
}
#region "smart" input-output parameter detection
if (commandType == CommandType.StoredProcedure && IsInOutParameterEmulation)
{
string iParameterName = GetInputParameterName(par.ParameterName);
IDbDataParameter fakeIOParameter = GetParameter(iParameterName, commandParameters);
if (fakeIOParameter != null)
{
fakeIOParameter.Value = par.Value;
// direction should be output, or parameter mistmath for procedure exception
// would be thrown
par.Direction = ParameterDirection.Output;
// direction should be Input
fakeIOParameter.Direction = ParameterDirection.Input;
}
}
#endregion
}
base.PrepareCommand(ref commandType, ref commandText, ref commandParameters);
}
public override bool InitParameter(IDbDataParameter parameter)
{
if (parameter.Value is bool)
{
string value = (bool)parameter.Value ? "1" : "0";
parameter.DbType = DbType.AnsiString;
parameter.Value = value;
parameter.Size = value.Length;
}
else if (parameter.Value is Guid)
{
string value = parameter.Value.ToString();
parameter.DbType = DbType.AnsiStringFixedLength;
parameter.Value = value;
parameter.Size = value.Length;
}
return base.InitParameter(parameter);
}
public override void Configure(System.Collections.Specialized.NameValueCollection attributes)
{
string inOutInputParameterPrefix = attributes["InOutInputParameterPrefix"];
if (inOutInputParameterPrefix != null)
InOutInputParameterPrefix = inOutInputParameterPrefix;
string returnParameterName = attributes["ReturnParameterName"];
if (returnParameterName != null)
ReturnParameterName = returnParameterName;
string isReturnValueEmulation = attributes["IsReturnValueEmulation"];
if (isReturnValueEmulation != null)
IsReturnValueEmulation = BLToolkit.Common.Convert.ToBoolean(isReturnValueEmulation);
string isInOutParameterEmulation = attributes["IsInOutParameterEmulation"];
if (isInOutParameterEmulation != null)
IsInOutParameterEmulation = BLToolkit.Common.Convert.ToBoolean(isInOutParameterEmulation);
string quoteIdentifiers = attributes["QuoteIdentifiers"];
if (quoteIdentifiers != null)
QuoteIdentifiers = BLToolkit.Common.Convert.ToBoolean(quoteIdentifiers);
base.Configure(attributes);
}
#endregion
#region FbDataReaderEx
public override IDataReader GetDataReader(MappingSchema schema, IDataReader dataReader)
{
return dataReader is FbDataReader?
new FbDataReaderEx((FbDataReader)dataReader):
base.GetDataReader(schema, dataReader);
}
class FbDataReaderEx : DataReaderBase<FbDataReader>, IDataReader
{
public FbDataReaderEx(FbDataReader rd): base(rd)
{
}
public new object GetValue(int i)
{
object value = DataReader.GetValue(i);
if (value is DateTime)
{
DateTime dt = (DateTime)value;
if (dt.Year == 1970 && dt.Month == 1 && dt.Day == 1)
return new DateTime(1, 1, 1, dt.Hour, dt.Minute, dt.Second, dt.Millisecond);
}
return value;
}
public new DateTime GetDateTime(int i)
{
DateTime dt = DataReader.GetDateTime(i);
if (dt.Year == 1970 && dt.Month == 1 && dt.Day == 1)
return new DateTime(1, 1, 1, dt.Hour, dt.Minute, dt.Second, dt.Millisecond);
return dt;
}
}
#endregion
#region FbMappingSchema
public class FbMappingSchema : MappingSchema
{
public byte[] ConvertToByteArray(string value)
{
return System.Text.Encoding.UTF8.GetBytes(value);
}
public override byte[] ConvertToByteArray(object value)
{
if (value is string)
return ConvertToByteArray((string)value);
return base.ConvertToByteArray(value);
}
public bool ConvertToBoolean(string value)
{
if (value.Length == 1)
switch (value[0])
{
case '1': case 'T' :case 'Y' : case 't': case 'y': return true;
case '0': case 'F' :case 'N' : case 'f': case 'n': return false;
}
return Common.Convert.ToBoolean(value);
}
public override bool ConvertToBoolean(object value)
{
if (value is string)
return ConvertToBoolean((string)value);
return base.ConvertToBoolean(value);
}
public System.IO.Stream ConvertToStream(string value)
{
return new System.IO.MemoryStream(ConvertToByteArray(value));
}
public override System.IO.Stream ConvertToStream(object value)
{
if (value is string)
return ConvertToStream((string)value);
return base.ConvertToStream(value);
}
public System.Data.SqlTypes.SqlBinary ConvertToSqlBinary(string value)
{
return BLToolkit.Common.Convert.ToSqlBinary(ConvertToByteArray(value));
}
public override System.Data.SqlTypes.SqlBinary ConvertToSqlBinary(object value)
{
if (value is string)
return ConvertToSqlBinary((string)value);
return base.ConvertToSqlBinary(value);
}
public System.Data.SqlTypes.SqlBytes ConvertToSqlBytes(string value)
{
return BLToolkit.Common.Convert.ToSqlBytes(ConvertToByteArray(value));
}
public override System.Data.SqlTypes.SqlBytes ConvertToSqlBytes(object value)
{
if (value is string)
return ConvertToSqlBytes((string)value);
return base.ConvertToSqlBytes(value);
}
public override bool? ConvertToNullableBoolean(object value)
{
if (value is string)
return ConvertToBoolean((string)value);
return base.ConvertToNullableBoolean(value);
}
public override System.Data.SqlTypes.SqlGuid ConvertToSqlGuid(object value)
{
if (value is string)
return new System.Data.SqlTypes.SqlGuid(new Guid((string)value));
return base.ConvertToSqlGuid(value);
}
protected override object MapInternal(Reflection.InitContext initContext)
{
FbDataReader dr = initContext.SourceObject as FbDataReader;
// Fb's SP returns single row with nulls if selected object doesn't exists
// so for all DBNull's (null) should be returned, instead of object instance
//
if (dr != null)
{
int i = dr.FieldCount;
while (--i >= 0)
if (!dr.IsDBNull(i))
break;
// All field are DBNull.
//
if (i < 0)
return null;
}
return base.MapInternal(initContext);
}
}
#endregion
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Text;
using Xunit;
public class TermInfo
{
[Fact]
[PlatformSpecific(PlatformID.AnyUnix)]
public void VerifyInstalledTermInfosParse()
{
string[] locations = GetFieldValueOnObject<string[]>("_terminfoLocations", null, typeof(Console).GetTypeInfo().Assembly.GetType("System.ConsolePal+TermInfo+Database"));
foreach (string location in locations)
{
if (!Directory.Exists(location))
continue;
foreach (string term in Directory.EnumerateFiles(location, "*", SearchOption.AllDirectories))
{
if (term.ToUpper().Contains("README")) continue;
object info = CreateTermColorInfo(ReadTermInfoDatabase(Path.GetFileName(term)));
if (!string.IsNullOrEmpty(GetForegroundFormat(info)))
{
Assert.NotEmpty(EvaluateParameterizedStrings(GetForegroundFormat(info), 0 /* irrelevant, just an integer to put into the formatting*/));
}
if (!string.IsNullOrEmpty(GetBackgroundFormat(info)))
{
Assert.NotEmpty(EvaluateParameterizedStrings(GetBackgroundFormat(info), 0 /* irrelevant, just an integer to put into the formatting*/));
}
}
}
}
// Note that we cannot use a Theory here due using unprintable characters and a bug in xunit where the runner errors
// out while trying to generate a report and printing the character (bug #380 on xunit)
private void TermInfoVerification(string termToTest, string expectedForeground, string expectedBackground, int colorValue)
{
object info = CreateTermColorInfo(ReadTermInfoDatabase(termToTest));
Assert.Equal(expectedForeground, EvaluateParameterizedStrings(GetForegroundFormat(info), colorValue));
Assert.Equal(expectedBackground, EvaluateParameterizedStrings(GetBackgroundFormat(info), colorValue));
}
[Fact]
[PlatformSpecific(PlatformID.AnyUnix)]
public void Xterm256ColorDefault()
{
TermInfoVerification("xterm-256color", "\u001B\u005B\u00330m", "\u001B\u005B\u00340m", 0);
}
[Fact]
[PlatformSpecific(PlatformID.AnyUnix)]
public void Xterm256ColorLight()
{
TermInfoVerification("xterm-256color", "\u001B\u005B\u00331m", "\u001B\u005B\u00341m", 1);
}
[Fact]
[PlatformSpecific(PlatformID.AnyUnix)]
public void Xterm256ColorDark()
{
TermInfoVerification("xterm-256color", "\u001B\u005B90m", "\u001B\u005B100m", 8);
}
[Fact]
[PlatformSpecific(PlatformID.AnyUnix)]
public void ScreenTermDefault()
{
TermInfoVerification("screen", "\u001B\u005B\u00330m", "\u001B\u005B\u00340m", 0);
}
[Fact]
[PlatformSpecific(PlatformID.AnyUnix)]
public void ScreenTermLight()
{
TermInfoVerification("screen", "\u001B\u005B\u00332m", "\u001B\u005B\u00342m", 2);
}
[Fact]
[PlatformSpecific(PlatformID.AnyUnix)]
public void ScreenTermDark()
{
TermInfoVerification("screen", "\u001B\u005B\u00339m", "\u001B\u005B\u00349m", 9);
}
[Fact]
[PlatformSpecific(PlatformID.AnyUnix)]
public void EtermDefault()
{
TermInfoVerification("Eterm", "\u001B\u005B\u00330m", "\u001B\u005B\u00340m", 0);
}
[Fact]
[PlatformSpecific(PlatformID.AnyUnix)]
public void EtermLight()
{
TermInfoVerification("Eterm", "\u001B\u005B\u00333m", "\u001B\u005B\u00343m", 3);
}
[Fact]
[PlatformSpecific(PlatformID.AnyUnix)]
public void EtermDark()
{
TermInfoVerification("Eterm", "\u001B\u005B\u003310m", "\u001B\u005B\u003410m", 10);
}
[Fact]
[PlatformSpecific(PlatformID.AnyUnix)]
public void Wsvt25TermDefault()
{
TermInfoVerification("wsvt25", "\u001B\u005B\u00330m", "\u001B\u005B\u00340m", 0);
}
[Fact]
[PlatformSpecific(PlatformID.AnyUnix)]
public void Wsvt25TermLight()
{
TermInfoVerification("wsvt25", "\u001B\u005B\u00334m", "\u001B\u005B\u00344m", 4);
}
[Fact]
[PlatformSpecific(PlatformID.AnyUnix)]
public void Wsvt25TermDark()
{
TermInfoVerification("wsvt25", "\u001B\u005B\u003311m", "\u001B\u005B\u003411m", 11);
}
[Fact]
[PlatformSpecific(PlatformID.AnyUnix)]
public void MachColorTermDefault()
{
TermInfoVerification("mach-color", "\u001B\u005B\u00330m", "\u001B\u005B\u00340m", 0);
}
[Fact]
[PlatformSpecific(PlatformID.AnyUnix)]
public void MachColorTermLight()
{
TermInfoVerification("mach-color", "\u001B\u005B\u00335m", "\u001B\u005B\u00345m", 5);
}
[Fact]
[PlatformSpecific(PlatformID.AnyUnix)]
public void MachColorTermDark()
{
TermInfoVerification("mach-color", "\u001B\u005B\u003312m", "\u001B\u005B\u003412m", 12);
}
[Fact]
[PlatformSpecific(PlatformID.OSX)]
public void EmuTermInfoDoesntBreakParser()
{
// This file (available by default on OS X) is called out specifically since it contains a format where it has %i
// but only one variable instead of two. Make sure we don't break in this case
TermInfoVerification("emu", "\u001Br1;", "\u001Bs1;", 0);
}
[Fact]
[PlatformSpecific(PlatformID.AnyUnix)]
public void TryingToLoadTermThatDoesNotExistDoesNotThrow()
{
object db = ReadTermInfoDatabase("foobar____");
object info = CreateTermColorInfo(db);
Assert.Null(db);
Assert.NotNull(GetBackgroundFormat(info));
Assert.NotNull(GetForegroundFormat(info));
Assert.NotNull(GetMaxColors(info));
Assert.NotNull(GetResetFormat(info));
}
private object ReadTermInfoDatabase(string term)
{
MethodInfo readDbMethod = typeof(Console).GetTypeInfo().Assembly.GetType("System.ConsolePal+TermInfo+Database").GetTypeInfo().GetDeclaredMethods("ReadDatabase").Where(m => m.GetParameters().Count() == 1).Single();
return readDbMethod.Invoke(null, new object[] { term });
}
private object CreateTermColorInfo(object db)
{
return typeof(Console).GetTypeInfo().Assembly.GetType("System.ConsolePal+TerminalColorInfo").GetTypeInfo().DeclaredConstructors
.Where(c => c.GetParameters().Count() == 1).Single().Invoke(new object[] { db });
}
private string GetForegroundFormat(object colorInfo)
{
return GetFieldValueOnObject<string>("ForegroundFormat", colorInfo, typeof(Console).GetTypeInfo().Assembly.GetType("System.ConsolePal+TerminalColorInfo"));
}
private string GetBackgroundFormat(object colorInfo)
{
return GetFieldValueOnObject<string>("BackgroundFormat", colorInfo, typeof(Console).GetTypeInfo().Assembly.GetType("System.ConsolePal+TerminalColorInfo"));
}
private int GetMaxColors(object colorInfo)
{
return GetFieldValueOnObject<int>("MaxColors", colorInfo, typeof(Console).GetTypeInfo().Assembly.GetType("System.ConsolePal+TerminalColorInfo"));
}
private string GetResetFormat(object colorInfo)
{
return GetFieldValueOnObject<string>("ResetFormat", colorInfo, typeof(Console).GetTypeInfo().Assembly.GetType("System.ConsolePal+TerminalColorInfo"));
}
private T GetFieldValueOnObject<T>(string name, object instance, Type baseType)
{
return (T)baseType.GetTypeInfo().GetDeclaredField(name).GetValue(instance);
}
private object CreateFormatParam(object o)
{
Assert.True((o.GetType() == typeof(Int32)) || (o.GetType() == typeof(string)));
TypeInfo ti = typeof(Console).GetTypeInfo().Assembly.GetType("System.ConsolePal+TermInfo+ParameterizedStrings+FormatParam").GetTypeInfo();
ConstructorInfo ci = null;
foreach (ConstructorInfo c in ti.DeclaredConstructors)
{
Type paramType = c.GetParameters().ElementAt(0).ParameterType;
if ((paramType == typeof(string)) && (o.GetType() == typeof(string)))
{
ci = c;
break;
}
else if ((paramType == typeof(Int32)) && (o.GetType() == typeof(Int32)))
{
ci = c;
break;
}
}
Assert.True(ci != null);
return ci.Invoke(new object[] { o });
}
private string EvaluateParameterizedStrings(string format, params object[] parameters)
{
Type formatArrayType = typeof(Console).GetTypeInfo().Assembly.GetType("System.ConsolePal+TermInfo+ParameterizedStrings+FormatParam").MakeArrayType();
MethodInfo mi = typeof(Console).GetTypeInfo().Assembly.GetType("System.ConsolePal+TermInfo+ParameterizedStrings").GetTypeInfo().GetDeclaredMethod("Evaluate");
// Create individual FormatParams
object[] stringParams = new object[parameters.Length];
for (int i = 0; i < parameters.Length; i++)
stringParams[i] = CreateFormatParam(parameters[i]);
// Create the array of format params and then put the individual params in their location
Array typeArray = (Array)Activator.CreateInstance(formatArrayType, new object[] { stringParams.Length });
for (int i = 0; i < parameters.Length; i++)
typeArray.SetValue(stringParams[i], i);
// Setup the params to evaluate
object[] evalParams = new object[2];
evalParams[0] = format;
evalParams[1] = typeArray;
return (string)mi.Invoke(null, evalParams);
}
}
| |
/*
* Farseer Physics Engine based on Box2D.XNA port:
* Copyright (c) 2010 Ian Qvist
*
* Box2D.XNA port of Box2D:
* Copyright (c) 2009 Brandon Furtwangler, Nathan Furtwangler
*
* Original source Box2D:
* Copyright (c) 2006-2009 Erin Catto http://www.gphysics.com
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
* 3. This notice may not be removed or altered from any source distribution.
*/
using System;
using System.Diagnostics;
using FarseerPhysics.Common;
using Microsoft.Xna.Framework;
namespace FarseerPhysics.Dynamics.Joints
{
/// <summary>
/// The pulley joint is connected to two bodies and two fixed ground points.
/// The pulley supports a ratio such that:
/// length1 + ratio * length2 <!--<-->= ant
/// Yes, the force transmitted is scaled by the ratio.
/// The pulley also enforces a maximum length limit on both sides. This is
/// useful to prevent one side of the pulley hitting the top.
/// </summary>
public class PulleyJoint : Joint
{
/// <summary>
/// Get the first ground anchor.
/// </summary>
/// <value></value>
public Vector2 GroundAnchorA;
/// <summary>
/// Get the second ground anchor.
/// </summary>
/// <value></value>
public Vector2 GroundAnchorB;
public Vector2 LocalAnchorA;
public Vector2 LocalAnchorB;
public float MinPulleyLength = 2.0f;
private float _ant;
private float _impulse;
private float _lengthA;
private float _lengthB;
private float _limitImpulse1;
private float _limitImpulse2;
private float _limitMass1;
private float _limitMass2;
private LimitState _limitState1;
private LimitState _limitState2;
private float _maxLengthA;
private float _maxLengthB;
// Effective masses
private float _pulleyMass;
private LimitState _state;
private Vector2 _u1;
private Vector2 _u2;
internal PulleyJoint()
{
JointType = JointType.Pulley;
}
/// <summary>
/// Initialize the bodies, anchors, lengths, max lengths, and ratio using the world anchors.
/// This requires two ground anchors,
/// two dynamic body anchor points, max lengths for each side,
/// and a pulley ratio.
/// </summary>
/// <param name="bodyA">The first body.</param>
/// <param name="bodyB">The second body.</param>
/// <param name="groundAnchorA">The ground anchor for the first body.</param>
/// <param name="groundAnchorB">The ground anchor for the second body.</param>
/// <param name="localAnchorA">The first body anchor.</param>
/// <param name="localAnchorB">The second body anchor.</param>
/// <param name="ratio">The ratio.</param>
public PulleyJoint(Body bodyA, Body bodyB,
Vector2 groundAnchorA, Vector2 groundAnchorB,
Vector2 localAnchorA, Vector2 localAnchorB,
float ratio)
: base(bodyA, bodyB)
{
JointType = JointType.Pulley;
GroundAnchorA = groundAnchorA;
GroundAnchorB = groundAnchorB;
LocalAnchorA = localAnchorA;
LocalAnchorB = localAnchorB;
Vector2 d1 = BodyA.GetWorldPoint(localAnchorA) - groundAnchorA;
_lengthA = d1.Length();
Vector2 d2 = BodyB.GetWorldPoint(localAnchorB) - groundAnchorB;
_lengthB = d2.Length();
Debug.Assert(ratio != 0.0f);
Debug.Assert(ratio > Settings.Epsilon);
Ratio = ratio;
float C = _lengthA + Ratio * _lengthB;
MaxLengthA = C - Ratio * MinPulleyLength;
MaxLengthB = (C - MinPulleyLength) / Ratio;
_ant = _lengthA + Ratio * _lengthB;
MaxLengthA = Math.Min(MaxLengthA, _ant - Ratio * MinPulleyLength);
MaxLengthB = Math.Min(MaxLengthB, (_ant - MinPulleyLength) / Ratio);
_impulse = 0.0f;
_limitImpulse1 = 0.0f;
_limitImpulse2 = 0.0f;
}
public override Vector2 WorldAnchorA
{
get { return BodyA.GetWorldPoint(LocalAnchorA); }
}
public override Vector2 WorldAnchorB
{
get { return BodyB.GetWorldPoint(LocalAnchorB); }
set { Debug.Assert(false, "You can't set the world anchor on this joint type."); }
}
/// <summary>
/// Get the current length of the segment attached to body1.
/// </summary>
/// <value></value>
public float LengthA
{
get
{
Vector2 d = BodyA.GetWorldPoint(LocalAnchorA) - GroundAnchorA;
return d.Length();
}
set { _lengthA = value; }
}
/// <summary>
/// Get the current length of the segment attached to body2.
/// </summary>
/// <value></value>
public float LengthB
{
get
{
Vector2 d = BodyB.GetWorldPoint(LocalAnchorB) - GroundAnchorB;
return d.Length();
}
set { _lengthB = value; }
}
/// <summary>
/// Get the pulley ratio.
/// </summary>
/// <value></value>
public float Ratio { get; set; }
public float MaxLengthA
{
get { return _maxLengthA; }
set { _maxLengthA = value; }
}
public float MaxLengthB
{
get { return _maxLengthB; }
set { _maxLengthB = value; }
}
public override Vector2 GetReactionForce(float inv_dt)
{
Vector2 P = _impulse * _u2;
return inv_dt * P;
}
public override float GetReactionTorque(float inv_dt)
{
return 0.0f;
}
internal override void InitVelocityConstraints(ref TimeStep step)
{
Body b1 = BodyA;
Body b2 = BodyB;
Transform xf1, xf2;
b1.GetTransform(out xf1);
b2.GetTransform(out xf2);
Vector2 r1 = MathUtils.Multiply(ref xf1.R, LocalAnchorA - b1.LocalCenter);
Vector2 r2 = MathUtils.Multiply(ref xf2.R, LocalAnchorB - b2.LocalCenter);
Vector2 p1 = b1.Sweep.C + r1;
Vector2 p2 = b2.Sweep.C + r2;
Vector2 s1 = GroundAnchorA;
Vector2 s2 = GroundAnchorB;
// Get the pulley axes.
_u1 = p1 - s1;
_u2 = p2 - s2;
float length1 = _u1.Length();
float length2 = _u2.Length();
if (length1 > Settings.LinearSlop)
{
_u1 *= 1.0f / length1;
}
else
{
_u1 = Vector2.Zero;
}
if (length2 > Settings.LinearSlop)
{
_u2 *= 1.0f / length2;
}
else
{
_u2 = Vector2.Zero;
}
float C = _ant - length1 - Ratio * length2;
if (C > 0.0f)
{
_state = LimitState.Inactive;
_impulse = 0.0f;
}
else
{
_state = LimitState.AtUpper;
}
if (length1 < MaxLengthA)
{
_limitState1 = LimitState.Inactive;
_limitImpulse1 = 0.0f;
}
else
{
_limitState1 = LimitState.AtUpper;
}
if (length2 < MaxLengthB)
{
_limitState2 = LimitState.Inactive;
_limitImpulse2 = 0.0f;
}
else
{
_limitState2 = LimitState.AtUpper;
}
// Compute effective mass.
float cr1u1 = MathUtils.Cross(r1, _u1);
float cr2u2 = MathUtils.Cross(r2, _u2);
_limitMass1 = b1.InvMass + b1.InvI * cr1u1 * cr1u1;
_limitMass2 = b2.InvMass + b2.InvI * cr2u2 * cr2u2;
_pulleyMass = _limitMass1 + Ratio * Ratio * _limitMass2;
Debug.Assert(_limitMass1 > Settings.Epsilon);
Debug.Assert(_limitMass2 > Settings.Epsilon);
Debug.Assert(_pulleyMass > Settings.Epsilon);
_limitMass1 = 1.0f / _limitMass1;
_limitMass2 = 1.0f / _limitMass2;
_pulleyMass = 1.0f / _pulleyMass;
if (Settings.EnableWarmstarting)
{
// Scale impulses to support variable time steps.
_impulse *= step.dtRatio;
_limitImpulse1 *= step.dtRatio;
_limitImpulse2 *= step.dtRatio;
// Warm starting.
Vector2 P1 = -(_impulse + _limitImpulse1) * _u1;
Vector2 P2 = (-Ratio * _impulse - _limitImpulse2) * _u2;
b1.LinearVelocityInternal += b1.InvMass * P1;
b1.AngularVelocityInternal += b1.InvI * MathUtils.Cross(r1, P1);
b2.LinearVelocityInternal += b2.InvMass * P2;
b2.AngularVelocityInternal += b2.InvI * MathUtils.Cross(r2, P2);
}
else
{
_impulse = 0.0f;
_limitImpulse1 = 0.0f;
_limitImpulse2 = 0.0f;
}
}
internal override void SolveVelocityConstraints(ref TimeStep step)
{
Body b1 = BodyA;
Body b2 = BodyB;
Transform xf1, xf2;
b1.GetTransform(out xf1);
b2.GetTransform(out xf2);
Vector2 r1 = MathUtils.Multiply(ref xf1.R, LocalAnchorA - b1.LocalCenter);
Vector2 r2 = MathUtils.Multiply(ref xf2.R, LocalAnchorB - b2.LocalCenter);
if (_state == LimitState.AtUpper)
{
Vector2 v1 = b1.LinearVelocityInternal + MathUtils.Cross(b1.AngularVelocityInternal, r1);
Vector2 v2 = b2.LinearVelocityInternal + MathUtils.Cross(b2.AngularVelocityInternal, r2);
float Cdot = -Vector2.Dot(_u1, v1) - Ratio * Vector2.Dot(_u2, v2);
float impulse = _pulleyMass * (-Cdot);
float oldImpulse = _impulse;
_impulse = Math.Max(0.0f, _impulse + impulse);
impulse = _impulse - oldImpulse;
Vector2 P1 = -impulse * _u1;
Vector2 P2 = -Ratio * impulse * _u2;
b1.LinearVelocityInternal += b1.InvMass * P1;
b1.AngularVelocityInternal += b1.InvI * MathUtils.Cross(r1, P1);
b2.LinearVelocityInternal += b2.InvMass * P2;
b2.AngularVelocityInternal += b2.InvI * MathUtils.Cross(r2, P2);
}
if (_limitState1 == LimitState.AtUpper)
{
Vector2 v1 = b1.LinearVelocityInternal + MathUtils.Cross(b1.AngularVelocityInternal, r1);
float Cdot = -Vector2.Dot(_u1, v1);
float impulse = -_limitMass1 * Cdot;
float oldImpulse = _limitImpulse1;
_limitImpulse1 = Math.Max(0.0f, _limitImpulse1 + impulse);
impulse = _limitImpulse1 - oldImpulse;
Vector2 P1 = -impulse * _u1;
b1.LinearVelocityInternal += b1.InvMass * P1;
b1.AngularVelocityInternal += b1.InvI * MathUtils.Cross(r1, P1);
}
if (_limitState2 == LimitState.AtUpper)
{
Vector2 v2 = b2.LinearVelocityInternal + MathUtils.Cross(b2.AngularVelocityInternal, r2);
float Cdot = -Vector2.Dot(_u2, v2);
float impulse = -_limitMass2 * Cdot;
float oldImpulse = _limitImpulse2;
_limitImpulse2 = Math.Max(0.0f, _limitImpulse2 + impulse);
impulse = _limitImpulse2 - oldImpulse;
Vector2 P2 = -impulse * _u2;
b2.LinearVelocityInternal += b2.InvMass * P2;
b2.AngularVelocityInternal += b2.InvI * MathUtils.Cross(r2, P2);
}
}
internal override bool SolvePositionConstraints()
{
Body b1 = BodyA;
Body b2 = BodyB;
Vector2 s1 = GroundAnchorA;
Vector2 s2 = GroundAnchorB;
float linearError = 0.0f;
if (_state == LimitState.AtUpper)
{
Transform xf1, xf2;
b1.GetTransform(out xf1);
b2.GetTransform(out xf2);
Vector2 r1 = MathUtils.Multiply(ref xf1.R, LocalAnchorA - b1.LocalCenter);
Vector2 r2 = MathUtils.Multiply(ref xf2.R, LocalAnchorB - b2.LocalCenter);
Vector2 p1 = b1.Sweep.C + r1;
Vector2 p2 = b2.Sweep.C + r2;
// Get the pulley axes.
_u1 = p1 - s1;
_u2 = p2 - s2;
float length1 = _u1.Length();
float length2 = _u2.Length();
if (length1 > Settings.LinearSlop)
{
_u1 *= 1.0f / length1;
}
else
{
_u1 = Vector2.Zero;
}
if (length2 > Settings.LinearSlop)
{
_u2 *= 1.0f / length2;
}
else
{
_u2 = Vector2.Zero;
}
float C = _ant - length1 - Ratio * length2;
linearError = Math.Max(linearError, -C);
C = MathHelper.Clamp(C + Settings.LinearSlop, -Settings.MaxLinearCorrection, 0.0f);
float impulse = -_pulleyMass * C;
Vector2 P1 = -impulse * _u1;
Vector2 P2 = -Ratio * impulse * _u2;
b1.Sweep.C += b1.InvMass * P1;
b1.Sweep.A += b1.InvI * MathUtils.Cross(r1, P1);
b2.Sweep.C += b2.InvMass * P2;
b2.Sweep.A += b2.InvI * MathUtils.Cross(r2, P2);
b1.SynchronizeTransform();
b2.SynchronizeTransform();
}
if (_limitState1 == LimitState.AtUpper)
{
Transform xf1;
b1.GetTransform(out xf1);
Vector2 r1 = MathUtils.Multiply(ref xf1.R, LocalAnchorA - b1.LocalCenter);
Vector2 p1 = b1.Sweep.C + r1;
_u1 = p1 - s1;
float length1 = _u1.Length();
if (length1 > Settings.LinearSlop)
{
_u1 *= 1.0f / length1;
}
else
{
_u1 = Vector2.Zero;
}
float C = MaxLengthA - length1;
linearError = Math.Max(linearError, -C);
C = MathHelper.Clamp(C + Settings.LinearSlop, -Settings.MaxLinearCorrection, 0.0f);
float impulse = -_limitMass1 * C;
Vector2 P1 = -impulse * _u1;
b1.Sweep.C += b1.InvMass * P1;
b1.Sweep.A += b1.InvI * MathUtils.Cross(r1, P1);
b1.SynchronizeTransform();
}
if (_limitState2 == LimitState.AtUpper)
{
Transform xf2;
b2.GetTransform(out xf2);
Vector2 r2 = MathUtils.Multiply(ref xf2.R, LocalAnchorB - b2.LocalCenter);
Vector2 p2 = b2.Sweep.C + r2;
_u2 = p2 - s2;
float length2 = _u2.Length();
if (length2 > Settings.LinearSlop)
{
_u2 *= 1.0f / length2;
}
else
{
_u2 = Vector2.Zero;
}
float C = MaxLengthB - length2;
linearError = Math.Max(linearError, -C);
C = MathHelper.Clamp(C + Settings.LinearSlop, -Settings.MaxLinearCorrection, 0.0f);
float impulse = -_limitMass2 * C;
Vector2 P2 = -impulse * _u2;
b2.Sweep.C += b2.InvMass * P2;
b2.Sweep.A += b2.InvI * MathUtils.Cross(r2, P2);
b2.SynchronizeTransform();
}
return linearError < Settings.LinearSlop;
}
}
}
| |
/************************************************************************************
Copyright : Copyright (c) Facebook Technologies, LLC and its affiliates. All rights reserved.
Licensed under the Oculus SDK License Version 3.4.1 (the "License");
you may not use the Oculus SDK except in compliance with the License,
which is provided at the time of installation or download, or which
otherwise accompanies this software in either electronic or hard copy form.
You may obtain a copy of the License at
https://developer.oculus.com/licenses/sdk-3.4.1
Unless required by applicable law or agreed to in writing, the Oculus SDK
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
************************************************************************************/
using UnityEngine;
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
/// <summary>
/// Miscellaneous extension methods that any script can use.
/// </summary>
public static class OVRExtensions
{
/// <summary>
/// Converts the given world-space transform to an OVRPose in tracking space.
/// </summary>
public static OVRPose ToTrackingSpacePose(this Transform transform, Camera camera)
{
OVRPose headPose;
#if UNITY_2017_2_OR_NEWER
headPose.position = UnityEngine.XR.InputTracking.GetLocalPosition(UnityEngine.XR.XRNode.Head);
headPose.orientation = UnityEngine.XR.InputTracking.GetLocalRotation(UnityEngine.XR.XRNode.Head);
#else
headPose.position = UnityEngine.VR.InputTracking.GetLocalPosition(UnityEngine.VR.VRNode.Head);
headPose.orientation = UnityEngine.VR.InputTracking.GetLocalRotation(UnityEngine.VR.VRNode.Head);
#endif
var ret = headPose * transform.ToHeadSpacePose(camera);
return ret;
}
/// <summary>
/// Converts the given pose from tracking-space to world-space.
/// </summary>
public static OVRPose ToWorldSpacePose(OVRPose trackingSpacePose)
{
OVRPose headPose;
#if UNITY_2017_2_OR_NEWER
headPose.position = UnityEngine.XR.InputTracking.GetLocalPosition(UnityEngine.XR.XRNode.Head);
headPose.orientation = UnityEngine.XR.InputTracking.GetLocalRotation(UnityEngine.XR.XRNode.Head);
#else
headPose.position = UnityEngine.VR.InputTracking.GetLocalPosition(UnityEngine.VR.VRNode.Head);
headPose.orientation = UnityEngine.VR.InputTracking.GetLocalRotation(UnityEngine.VR.VRNode.Head);
#endif
// Transform from tracking-Space to head-Space
OVRPose poseInHeadSpace = headPose.Inverse() * trackingSpacePose;
// Transform from head space to world space
OVRPose ret = Camera.main.transform.ToOVRPose() * poseInHeadSpace;
return ret;
}
/// <summary>
/// Converts the given world-space transform to an OVRPose in head space.
/// </summary>
public static OVRPose ToHeadSpacePose(this Transform transform, Camera camera)
{
return camera.transform.ToOVRPose().Inverse() * transform.ToOVRPose();
}
internal static OVRPose ToOVRPose(this Transform t, bool isLocal = false)
{
OVRPose pose;
pose.orientation = (isLocal) ? t.localRotation : t.rotation;
pose.position = (isLocal) ? t.localPosition : t.position;
return pose;
}
internal static void FromOVRPose(this Transform t, OVRPose pose, bool isLocal = false)
{
if (isLocal)
{
t.localRotation = pose.orientation;
t.localPosition = pose.position;
}
else
{
t.rotation = pose.orientation;
t.position = pose.position;
}
}
internal static OVRPose ToOVRPose(this OVRPlugin.Posef p)
{
return new OVRPose()
{
position = new Vector3(p.Position.x, p.Position.y, -p.Position.z),
orientation = new Quaternion(-p.Orientation.x, -p.Orientation.y, p.Orientation.z, p.Orientation.w)
};
}
internal static OVRTracker.Frustum ToFrustum(this OVRPlugin.Frustumf f)
{
return new OVRTracker.Frustum()
{
nearZ = f.zNear,
farZ = f.zFar,
fov = new Vector2()
{
x = Mathf.Rad2Deg * f.fovX,
y = Mathf.Rad2Deg * f.fovY
}
};
}
internal static Color FromColorf(this OVRPlugin.Colorf c)
{
return new Color() { r = c.r, g = c.g, b = c.b, a = c.a };
}
internal static OVRPlugin.Colorf ToColorf(this Color c)
{
return new OVRPlugin.Colorf() { r = c.r, g = c.g, b = c.b, a = c.a };
}
internal static Vector3 FromVector3f(this OVRPlugin.Vector3f v)
{
return new Vector3() { x = v.x, y = v.y, z = v.z };
}
internal static Vector3 FromFlippedZVector3f(this OVRPlugin.Vector3f v)
{
return new Vector3() { x = v.x, y = v.y, z = -v.z };
}
internal static OVRPlugin.Vector3f ToVector3f(this Vector3 v)
{
return new OVRPlugin.Vector3f() { x = v.x, y = v.y, z = v.z };
}
internal static OVRPlugin.Vector3f ToFlippedZVector3f(this Vector3 v)
{
return new OVRPlugin.Vector3f() { x = v.x, y = v.y, z = -v.z };
}
internal static Quaternion FromQuatf(this OVRPlugin.Quatf q)
{
return new Quaternion() { x = q.x, y = q.y, z = q.z, w = q.w };
}
internal static Quaternion FromFlippedZQuatf(this OVRPlugin.Quatf q)
{
return new Quaternion() { x = -q.x, y = -q.y, z = q.z, w = q.w };
}
internal static OVRPlugin.Quatf ToQuatf(this Quaternion q)
{
return new OVRPlugin.Quatf() { x = q.x, y = q.y, z = q.z, w = q.w };
}
internal static OVRPlugin.Quatf ToFlippedZQuatf(this Quaternion q)
{
return new OVRPlugin.Quatf() { x = -q.x, y = -q.y, z = q.z, w = q.w };
}
}
/// <summary>
/// An affine transformation built from a Unity position and orientation.
/// </summary>
[System.Serializable]
public struct OVRPose
{
/// <summary>
/// A pose with no translation or rotation.
/// </summary>
public static OVRPose identity
{
get {
return new OVRPose()
{
position = Vector3.zero,
orientation = Quaternion.identity
};
}
}
public override bool Equals(System.Object obj)
{
return obj is OVRPose && this == (OVRPose)obj;
}
public override int GetHashCode()
{
return position.GetHashCode() ^ orientation.GetHashCode();
}
public static bool operator ==(OVRPose x, OVRPose y)
{
return x.position == y.position && x.orientation == y.orientation;
}
public static bool operator !=(OVRPose x, OVRPose y)
{
return !(x == y);
}
/// <summary>
/// The position.
/// </summary>
public Vector3 position;
/// <summary>
/// The orientation.
/// </summary>
public Quaternion orientation;
/// <summary>
/// Multiplies two poses.
/// </summary>
public static OVRPose operator*(OVRPose lhs, OVRPose rhs)
{
var ret = new OVRPose();
ret.position = lhs.position + lhs.orientation * rhs.position;
ret.orientation = lhs.orientation * rhs.orientation;
return ret;
}
/// <summary>
/// Computes the inverse of the given pose.
/// </summary>
public OVRPose Inverse()
{
OVRPose ret;
ret.orientation = Quaternion.Inverse(orientation);
ret.position = ret.orientation * -position;
return ret;
}
/// <summary>
/// Converts the pose from left- to right-handed or vice-versa.
/// </summary>
internal OVRPose flipZ()
{
var ret = this;
ret.position.z = -ret.position.z;
ret.orientation.z = -ret.orientation.z;
ret.orientation.w = -ret.orientation.w;
return ret;
}
internal OVRPlugin.Posef ToPosef()
{
return new OVRPlugin.Posef()
{
Position = position.ToVector3f(),
Orientation = orientation.ToQuatf()
};
}
}
/// <summary>
/// Encapsulates an 8-byte-aligned of unmanaged memory.
/// </summary>
public class OVRNativeBuffer : IDisposable
{
private bool disposed = false;
private int m_numBytes = 0;
private IntPtr m_ptr = IntPtr.Zero;
/// <summary>
/// Creates a buffer of the specified size.
/// </summary>
public OVRNativeBuffer(int numBytes)
{
Reallocate(numBytes);
}
/// <summary>
/// Releases unmanaged resources and performs other cleanup operations before the <see cref="OVRNativeBuffer"/> is
/// reclaimed by garbage collection.
/// </summary>
~OVRNativeBuffer()
{
Dispose(false);
}
/// <summary>
/// Reallocates the buffer with the specified new size.
/// </summary>
public void Reset(int numBytes)
{
Reallocate(numBytes);
}
/// <summary>
/// The current number of bytes in the buffer.
/// </summary>
public int GetCapacity()
{
return m_numBytes;
}
/// <summary>
/// A pointer to the unmanaged memory in the buffer, starting at the given offset in bytes.
/// </summary>
public IntPtr GetPointer(int byteOffset = 0)
{
if (byteOffset < 0 || byteOffset >= m_numBytes)
return IntPtr.Zero;
return (byteOffset == 0) ? m_ptr : new IntPtr(m_ptr.ToInt64() + byteOffset);
}
/// <summary>
/// Releases all resource used by the <see cref="OVRNativeBuffer"/> object.
/// </summary>
/// <remarks>Call <see cref="Dispose"/> when you are finished using the <see cref="OVRNativeBuffer"/>. The <see cref="Dispose"/>
/// method leaves the <see cref="OVRNativeBuffer"/> in an unusable state. After calling <see cref="Dispose"/>, you must
/// release all references to the <see cref="OVRNativeBuffer"/> so the garbage collector can reclaim the memory that
/// the <see cref="OVRNativeBuffer"/> was occupying.</remarks>
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
private void Dispose(bool disposing)
{
if (disposed)
return;
if (disposing)
{
// dispose managed resources
}
// dispose unmanaged resources
Release();
disposed = true;
}
private void Reallocate(int numBytes)
{
Release();
if (numBytes > 0)
{
m_ptr = Marshal.AllocHGlobal(numBytes);
m_numBytes = numBytes;
}
else
{
m_ptr = IntPtr.Zero;
m_numBytes = 0;
}
}
private void Release()
{
if (m_ptr != IntPtr.Zero)
{
Marshal.FreeHGlobal(m_ptr);
m_ptr = IntPtr.Zero;
m_numBytes = 0;
}
}
}
| |
/*
Copyright 2014 David Bordoley
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Reactive;
using System.Reactive.Linq;
using System.Reactive.Threading.Tasks;
using System.Threading;
using System.Threading.Tasks;
namespace SQLitePCL.pretty
{
/// <summary>
/// Extensions methods for <see cref="IAsyncStatement"/>.
/// </summary>
public static class AsyncStatement
{
/// <summary>
/// Schedules the <see cref="Action"/> <paramref name="f"/> on the statement's operations queue.
/// </summary>
/// <param name="This">The async statement.</param>
/// <param name="f">The action.</param>
/// <param name="cancellationToken">Cancellation token that can be used to cancel the task.</param>
/// <returns>A task that completes when <paramref name="f"/> returns.</returns>
public static Task Use(
this IAsyncStatement This,
Action<IStatement, CancellationToken> f,
CancellationToken cancellationToken)
{
Contract.Requires(f != null);
return This.Use((stmt, ct) =>
{
f(stmt, ct);
return Enumerable.Empty<Unit>();
}, cancellationToken);
}
/// <summary>
/// Schedules the <see cref="Action"/> <paramref name="f"/> on the statement's operations queue.
/// </summary>
/// <param name="This">The async statement.</param>
/// <param name="f">The action.</param>
/// <returns>A task that completes when <paramref name="f"/> returns.</returns>
public static Task Use(this IAsyncStatement This, Action<IStatement> f) =>
This.Use((stmt, ct) => f(stmt), CancellationToken.None);
/// <summary>
/// Schedules the <see cref="Func<T,TResult>"/> <paramref name="f"/> on the statement's operations queue.
/// </summary>
/// <typeparam name="T">The result type.</typeparam>
/// <param name="This">The async statement.</param>
/// <param name="f">A function from <see cref="IAsyncStatement"/> to <typeparamref name="T"/>.</param>
/// <param name="cancellationToken">Cancellation token that can be used to cancel the task.</param>
/// <returns>A task that completes with the result of <paramref name="f"/>.</returns>
public static Task<T> Use<T>(
this IAsyncStatement This,
Func<IStatement, CancellationToken, T> f,
CancellationToken cancellationToken)
{
Contract.Requires(This != null);
Contract.Requires(f != null);
return This.Use((conn, ct) => new[] { f(conn, ct) }).ToTask(cancellationToken);
}
/// <summary>
/// Schedules the <see cref="Func<T,TResult>"/> <paramref name="f"/> on the statement's operations queue.
/// </summary>
/// <typeparam name="T">The result type.</typeparam>
/// <param name="This">The async statement.</param>
/// <param name="f">A function from <see cref="IAsyncStatement"/> to <typeparamref name="T"/>.</param>
/// <returns>A task that completes with the result of <paramref name="f"/>.</returns>
public static Task<T> Use<T>(this IAsyncStatement This, Func<IStatement, T> f) =>
This.Use((stmt, ct) => f(stmt), CancellationToken.None);
/// <summary>
/// Returns a cold IObservable which schedules the function f on the statement's database operation queue each
/// time it is is subscribed to. The published values are generated by enumerating the IEnumerable returned by f.
/// </summary>
/// <typeparam name="T">The result type.</typeparam>
/// <param name="This">The async statement.</param>
/// <param name="f">
/// A function that may synchronously use the provided IStatement and returns
/// an IEnumerable of produced values that are published to the subscribed IObserver.
/// The returned IEnumerable may block. This allows the IEnumerable to provide the results of
/// enumerating the prepared statement for instance.
/// </param>
/// <returns>A cold observable of the values produced by the function f.</returns>
public static IObservable<T> Use<T>(this IAsyncStatement This, Func<IStatement, IEnumerable<T>> f) =>
This.Use((stmt, ct) => f(stmt));
/// <summary>
/// Executes the <see cref="IStatement"/> with provided bind parameter values.
/// </summary>
/// <param name="This">The async statement.</param>
/// <param name="cancellationToken">Cancellation token that can be used to cancel the task.</param>
/// <param name="values">The position indexed values to bind.</param>
/// <returns>A <see cref="Task"/> that completes when the statement is executed.</returns>
public static Task ExecuteAsync(
this IAsyncStatement This,
CancellationToken cancellationToken,
params object[] values) =>
This.Use((stmt, ct) => { stmt.Execute(values); }, cancellationToken);
/// <summary>
/// Executes the <see cref="IStatement"/> with provided bind parameter values.
/// </summary>
/// <param name="This">The async statement.</param>
/// <param name="values">The position indexed values to bind.</param>
/// <returns>A <see cref="Task"/> that completes when the statement is executed.</returns>
public static Task ExecuteAsync(this IAsyncStatement This, params object[] values) =>
This.ExecuteAsync(CancellationToken.None, values);
/// <summary>
/// Queries the database asynchronously using the provided IStatement and provided bind variables.
/// </summary>
/// <param name="This">The async statement.</param>
/// <param name="values">The position indexed values to bind.</param>
/// <returns>A cold IObservable of the rows in the result set.</returns>
public static IObservable<IReadOnlyList<IResultSetValue>> Query(this IAsyncStatement This, params object[] values) =>
This.Use<IReadOnlyList<IResultSetValue>>(stmt => stmt.Query(values));
/// <summary>
/// Queries the database asynchronously using the provided IStatement
/// </summary>
/// <param name="This">The async statement.</param>
/// <returns>A cold IObservable of the rows in the result set.</returns>
public static IObservable<IReadOnlyList<IResultSetValue>> Query(this IAsyncStatement This) =>
This.Use<IReadOnlyList<IResultSetValue>>(stmt => stmt.Query());
}
internal class AsyncStatementImpl : IAsyncStatement
{
private readonly IStatement stmt;
private readonly IAsyncDatabaseConnection conn;
private bool disposed = false;
internal AsyncStatementImpl(IStatement stmt, IAsyncDatabaseConnection conn)
{
this.stmt = stmt;
this.conn = conn;
}
public IObservable<T> Use<T>(Func<IStatement, CancellationToken, IEnumerable<T>> f)
{
Contract.Requires(f != null);
if (disposed) { throw new ObjectDisposedException(this.GetType().FullName); }
return Observable.Create((IObserver<T> observer, CancellationToken cancellationToken) =>
{
// Prevent calls to subscribe after the statement is disposed
if (this.disposed)
{
observer.OnError(new ObjectDisposedException(this.GetType().FullName));
return Task.FromResult(Unit.Default);
}
return conn.Use((_, ct) =>
{
ct.ThrowIfCancellationRequested();
// Note: Diposing the statement wrapper doesn't dispose the underlying statement
// The intent here is to prevent access to the underlying statement outside of the
// function call.
using (var stmt = new StatementWrapper(this.stmt))
{
foreach (var e in f(stmt, ct))
{
observer.OnNext(e);
cancellationToken.ThrowIfCancellationRequested();
}
}
}, cancellationToken);
});
}
public void Dispose()
{
if (disposed)
{
return;
}
disposed = true;
conn.Use(_ =>
{
stmt.Dispose();
});
}
private sealed class StatementWrapper : IStatement
{
private readonly IStatement stmt;
private bool disposed = false;
internal StatementWrapper(IStatement stmt)
{
this.stmt = stmt;
}
public IReadOnlyOrderedDictionary<string, IBindParameter> BindParameters
{
get
{
if (disposed) { throw new ObjectDisposedException(this.GetType().FullName); }
// FIXME: If someone keeps a reference to this list it leaks the implementation out
return stmt.BindParameters;
}
}
public IReadOnlyList<ColumnInfo> Columns
{
get
{
if (disposed) { throw new ObjectDisposedException(this.GetType().FullName); }
// FIXME: If someone keeps a reference to this list it leaks the implementation out
return stmt.Columns;
}
}
public string SQL
{
get
{
if (disposed) { throw new ObjectDisposedException(this.GetType().FullName); }
return stmt.SQL;
}
}
public bool IsReadOnly
{
get
{
if (disposed) { throw new ObjectDisposedException(this.GetType().FullName); }
return stmt.IsReadOnly;
}
}
public bool IsBusy
{
get
{
if (disposed) { throw new ObjectDisposedException(this.GetType().FullName); }
return stmt.IsBusy;
}
}
public void ClearBindings()
{
if (disposed) { throw new ObjectDisposedException(this.GetType().FullName); }
stmt.ClearBindings();
}
public IReadOnlyList<IResultSetValue> Current
{
get
{
if (disposed) { throw new ObjectDisposedException(this.GetType().FullName); }
// FIXME: If someone keeps a reference to this list it leaks the implementation out
return stmt.Current;
}
}
object IEnumerator.Current => this.Current;
public bool MoveNext()
{
if (disposed) { throw new ObjectDisposedException(this.GetType().FullName); }
return stmt.MoveNext();
}
public void Reset()
{
if (disposed) { throw new ObjectDisposedException(this.GetType().FullName); }
stmt.Reset();
}
public void Dispose()
{
// Guard against someone taking a reference to this and trying to use it outside of
// the Use function delegate
disposed = true;
// We don't actually own the statement so its not disposed
}
public int Status(StatementStatusCode statusCode, bool reset)
{
if (disposed) { throw new ObjectDisposedException(this.GetType().FullName); }
return stmt.Status(statusCode, reset);
}
}
}
}
| |
// ***********************************************************************
// Copyright (c) 2014 Charlie Poole, Rob Prouse
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// ***********************************************************************
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using System.Web.UI;
using NUnit.Compatibility;
using NUnit.Framework.Interfaces;
using NUnit.Framework.Internal;
using NUnit.Tests.Assemblies;
namespace NUnit.Framework.Api
{
// Functional tests of the FrameworkController and all subordinate classes
public class FrameworkControllerTests
{
private const string MOCK_ASSEMBLY_FILE = "mock-assembly.dll";
private const string BAD_FILE = "mock-assembly.pdb";
private const string MISSING_FILE = "junk.dll";
private const string MISSING_NAME = "junk";
private const string EMPTY_FILTER = "<filter/>";
private const string FIXTURE_CAT_FILTER = "<filter><cat>FixtureCategory</cat></filter>";
private static readonly string MOCK_ASSEMBLY_NAME = typeof(MockAssembly).GetTypeInfo().Assembly.FullName;
private static readonly string EXPECTED_NAME = MOCK_ASSEMBLY_FILE;
private static readonly string MOCK_ASSEMBLY_PATH = Path.Combine(TestContext.CurrentContext.TestDirectory, MOCK_ASSEMBLY_FILE);
private IDictionary _settings = new Dictionary<string, object>();
private FrameworkController _controller;
private ICallbackEventHandler _handler;
public static IEnumerable EmptyFilters
{
get
{
yield return new TestCaseData(null);
yield return new TestCaseData("");
yield return new TestCaseData(EMPTY_FILTER);
}
}
public class FixtureCategoryTester
{
[Category("FixtureCategory")]
[Test]
public void TestInFixtureCategory()
{
}
[Test]
public void TestOutOfFixtureCategory()
{
}
}
[SetUp]
public void CreateController()
{
_controller = new FrameworkController(MOCK_ASSEMBLY_PATH, "ID", _settings);
_handler = new CallbackEventHandler();
}
#region SettingsElement Tests
[TestCaseSource(nameof(SettingsData))]
public void InsertSettingsElement_MixedSettings_CreatesCorrectSubNodes(string value)
{
var outerNode = new TNode("test");
var testSettings = new Dictionary<string, object>
{
["key1"] = "value1",
["key2"] = new Dictionary<string, object> { ["innerkey"] = value }
};
var inserted = FrameworkController.InsertSettingsElement(outerNode, testSettings);
#if PARALLEL
// in parallel, an additional node is added with number of test workers
Assert.That(inserted.ChildNodes.Count, Is.EqualTo(3));
#else
Assert.That(inserted.ChildNodes.Count, Is.EqualTo(2));
#endif
Assert.That(inserted.ChildNodes[0].Attributes["name"], Is.EqualTo("key1"));
Assert.That(inserted.ChildNodes[0].Attributes["value"], Is.EqualTo("value1"));
var innerNode = inserted.ChildNodes[1].FirstChild;
Assert.That(innerNode.Attributes["key"], Is.EqualTo("innerkey"));
Assert.That(innerNode.Attributes["value"], Is.EqualTo(value));
}
[Test]
public void InsertSettingsElement_SettingIsValue_CreatesASettingElementPerKey()
{
var outerNode = new TNode("test");
var testSettings = new Dictionary<string, object>
{
["key1"] = "value1",
["key2"] = "value2"
};
var inserted = FrameworkController.InsertSettingsElement(outerNode, testSettings);
#if PARALLEL
// in parallel, an additional node is added with number of test workers
Assert.That(inserted.ChildNodes.Count, Is.EqualTo(3));
#else
Assert.That(inserted.ChildNodes.Count, Is.EqualTo(2));
#endif
}
[TestCaseSource(nameof(SettingsData))]
public void InsertSettingsElement_SettingIsValue_SetsKeyAndValueAsAttributes(string value)
{
var outerNode = new TNode("test");
var testSettings = new Dictionary<string, object>
{
["key1"] = "value1",
["key2"] = value
};
var inserted = FrameworkController.InsertSettingsElement(outerNode, testSettings);
Assert.That(inserted.ChildNodes[0].Attributes["name"], Is.EqualTo("key1"));
Assert.That(inserted.ChildNodes[0].Attributes["value"], Is.EqualTo("value1"));
Assert.That(inserted.ChildNodes[1].Attributes["name"], Is.EqualTo("key2"));
Assert.That(inserted.ChildNodes[1].Attributes["value"], Is.EqualTo(value));
}
[TestCaseSource(nameof(SettingsData))]
public void InsertSettingsElement_SettingIsDictionary_CreatesEntriesForDictionaryElements(string value)
{
var outerNode = new TNode("test");
var testSettings = new Dictionary<string, object>
{
["outerkey"] = new Dictionary<string, object> { { "key1", "value1" }, { "key2", value } }
};
var inserted = FrameworkController.InsertSettingsElement(outerNode, testSettings);
var settingNode = inserted.FirstChild;
Assert.That(settingNode.ChildNodes.Count, Is.EqualTo(2));
}
[TestCaseSource(nameof(SettingsData))]
public void InsertSettingsElement_SettingIsDictionary_CreatesValueAttributeForDictionaryElements(string value)
{
var outerNode = new TNode("test");
var testSettings = new Dictionary<string, object>
{
["outerkey"] = new Dictionary<string, object> { { "key1", "value1" }, { "key2", value } }
};
var inserted = FrameworkController.InsertSettingsElement(outerNode, testSettings);
var settingNode = inserted.FirstChild;
Assert.That(settingNode.ChildNodes.Count, Is.EqualTo(2));
Assert.That(settingNode.Attributes["value"], Is.EqualTo($"[key1, value1], [key2, {value}]"));
}
[TestCaseSource(nameof(SettingsData))]
public void InsertSettingsElement_SettingIsDictionary_CreatesEntriesWithKeysAndValuesFromDictionary(string value)
{
var outerNode = new TNode("test");
var testSettings = new Dictionary<string, object>();
testSettings.Add("outerkey", new Dictionary<string, object> { { "key1", "value1" }, { "key2", value } });
var inserted = FrameworkController.InsertSettingsElement(outerNode, testSettings);
var settingNode = inserted.FirstChild;
var key1Node = settingNode.ChildNodes[0];
Assert.That(key1Node.Attributes["key"], Is.EqualTo("key1"));
Assert.That(key1Node.Attributes["value"], Is.EqualTo("value1"));
var key2Node = settingNode.ChildNodes[1];
Assert.That(key2Node.Attributes["key"], Is.EqualTo("key2"));
Assert.That(key2Node.Attributes["value"], Is.EqualTo(value));
}
public static IEnumerable SettingsData()
{
yield return new TestCaseData("value");
yield return new TestCaseData("");
yield return new TestCaseData("<value>");
yield return new TestCaseData("\"value\"");
yield return new TestCaseData("'value'");
yield return new TestCaseData("value1;value2");
}
#endregion
#region Construction Test
[Test]
public void ConstructController()
{
Assert.That(_controller.Builder, Is.TypeOf<DefaultTestAssemblyBuilder>());
Assert.That(_controller.Runner, Is.TypeOf<NUnitTestAssemblyRunner>());
Assert.That(_controller.AssemblyNameOrPath, Is.EqualTo(MOCK_ASSEMBLY_PATH));
Assert.That(_controller.Settings, Is.SameAs(_settings));
}
#endregion
#region LoadTestsAction
[Test]
public void LoadTestsAction_GoodFile_ReturnsRunnableSuite()
{
new FrameworkController.LoadTestsAction(_controller, _handler);
var result = TNode.FromXml(_handler.GetCallbackResult());
Assert.That(result.Name.ToString(), Is.EqualTo("test-suite"));
Assert.That(result.Attributes["type"], Is.EqualTo("Assembly"));
Assert.That(result.Attributes["id"], Is.Not.Null.And.StartWith("ID"));
Assert.That(result.Attributes["name"], Is.EqualTo(EXPECTED_NAME));
Assert.That(result.Attributes["runstate"], Is.EqualTo("Runnable"));
Assert.That(result.Attributes["testcasecount"], Is.EqualTo(MockAssembly.Tests.ToString()));
Assert.That(result.SelectNodes("test-suite").Count, Is.EqualTo(0), "Load result should not have child tests");
}
[Test]
public void LoadTestsAction_Assembly_ReturnsRunnableSuite()
{
_controller = new FrameworkController(typeof(MockAssembly).GetTypeInfo().Assembly, "ID", _settings);
new FrameworkController.LoadTestsAction(_controller, _handler);
var result = TNode.FromXml(_handler.GetCallbackResult());
Assert.That(result.Name.ToString(), Is.EqualTo("test-suite"));
Assert.That(result.Attributes["type"], Is.EqualTo("Assembly"));
Assert.That(result.Attributes["id"], Is.Not.Null.And.StartWith("ID"));
Assert.That(result.Attributes["name"], Is.EqualTo(EXPECTED_NAME).IgnoreCase);
Assert.That(result.Attributes["runstate"], Is.EqualTo("Runnable"));
Assert.That(result.Attributes["testcasecount"], Is.EqualTo(MockAssembly.Tests.ToString()));
Assert.That(result.SelectNodes("test-suite").Count, Is.EqualTo(0), "Load result should not have child tests");
}
[Test]
public void LoadTestsAction_FileNotFound_ReturnsNonRunnableSuite()
{
new FrameworkController.LoadTestsAction(new FrameworkController(MISSING_FILE, "ID", _settings), _handler);
var result = TNode.FromXml(_handler.GetCallbackResult());
Assert.That(result.Name.ToString(), Is.EqualTo("test-suite"));
Assert.That(result.Attributes["type"], Is.EqualTo("Assembly"));
Assert.That(result.Attributes["runstate"], Is.EqualTo("NotRunnable"));
Assert.That(result.Attributes["testcasecount"], Is.EqualTo("0"));
// Minimal check here to allow for platform differences
#if NETCOREAPP1_1
Assert.That(GetSkipReason(result), Contains.Substring("The system cannot find the file specified."));
#else
Assert.That(GetSkipReason(result), Contains.Substring(MISSING_NAME));
#endif
Assert.That(result.SelectNodes("test-suite").Count, Is.EqualTo(0), "Load result should not have child tests");
}
[Test]
public void LoadTestsAction_BadFile_ReturnsNonRunnableSuite()
{
new FrameworkController.LoadTestsAction(new FrameworkController(BAD_FILE, "ID", _settings), _handler);
var result = TNode.FromXml(_handler.GetCallbackResult());
Assert.That(result.Name.ToString(), Is.EqualTo("test-suite"));
Assert.That(result.Attributes["type"], Is.EqualTo("Assembly"));
Assert.That(result.Attributes["runstate"], Is.EqualTo("NotRunnable"));
// Minimal check here to allow for platform differences
Assert.That(GetSkipReason(result), Contains.Substring(BAD_FILE));
Assert.That(result.SelectNodes("test-suite").Count, Is.EqualTo(0), "Load result should not have child tests");
}
#endregion
#region ExploreTestsAction
[Test]
public void ExploreTestsAction_FilterCategory_ReturnsTests()
{
new FrameworkController.LoadTestsAction(_controller, _handler);
new FrameworkController.ExploreTestsAction(_controller, FIXTURE_CAT_FILTER, _handler);
var result = TNode.FromXml(_handler.GetCallbackResult());
Assert.That(result.Name.ToString(), Is.EqualTo("test-suite"));
Assert.That(result.Attributes["type"], Is.EqualTo("Assembly"));
Assert.That(result.Attributes["id"], Is.Not.Null.And.StartWith("ID"));
Assert.That(result.Attributes["name"], Is.EqualTo(EXPECTED_NAME));
Assert.That(result.Attributes["runstate"], Is.EqualTo("Runnable"));
Assert.That(result.Attributes["testcasecount"], Is.EqualTo(MockTestFixture.Tests.ToString()));
Assert.That(result.SelectNodes("test-suite").Count, Is.GreaterThan(0), "Explore result should have child tests");
}
[TestCaseSource(nameof(EmptyFilters))]
public void ExploreTestsAction_AfterLoad_ReturnsRunnableSuite(string filter)
{
new FrameworkController.LoadTestsAction(_controller, _handler);
new FrameworkController.ExploreTestsAction(_controller, filter, _handler);
var result = TNode.FromXml(_handler.GetCallbackResult());
Assert.That(result.Name.ToString(), Is.EqualTo("test-suite"));
Assert.That(result.Attributes["type"], Is.EqualTo("Assembly"));
Assert.That(result.Attributes["id"], Is.Not.Null.And.StartWith("ID"));
Assert.That(result.Attributes["name"], Is.EqualTo(EXPECTED_NAME));
Assert.That(result.Attributes["runstate"], Is.EqualTo("Runnable"));
Assert.That(result.Attributes["testcasecount"], Is.EqualTo(MockAssembly.Tests.ToString()));
Assert.That(result.SelectNodes("test-suite").Count, Is.GreaterThan(0), "Explore result should have child tests");
}
[TestCase(FIXTURE_CAT_FILTER)]
[TestCase(EMPTY_FILTER)]
public void ExploreTestsAction_AfterLoad_ReturnsSameCount(string filter)
{
new FrameworkController.LoadTestsAction(_controller, _handler);
new FrameworkController.ExploreTestsAction(_controller, filter, _handler);
var exploreResult = TNode.FromXml(_handler.GetCallbackResult());
var exploreTestCount = exploreResult.Attributes["testcasecount"];
new FrameworkController.CountTestsAction(_controller, filter, _handler);
var countResult = _handler.GetCallbackResult();
Assert.That(exploreTestCount, Is.EqualTo(countResult));
}
[Test]
public void ExploreTestsAction_WithoutLoad_ThrowsInvalidOperationException()
{
var ex = Assert.Throws<InvalidOperationException>(
() => new FrameworkController.ExploreTestsAction(_controller, EMPTY_FILTER, _handler));
Assert.That(ex.Message, Is.EqualTo("The Explore method was called but no test has been loaded"));
}
[Test]
public void ExploreTestsAction_FileNotFound_ReturnsNonRunnableSuite()
{
var controller = new FrameworkController(MISSING_FILE, "ID", _settings);
new FrameworkController.LoadTestsAction(controller, _handler);
new FrameworkController.ExploreTestsAction(controller, EMPTY_FILTER, _handler);
var result = TNode.FromXml(_handler.GetCallbackResult());
Assert.That(result.Name.ToString(), Is.EqualTo("test-suite"));
Assert.That(result.Attributes["type"], Is.EqualTo("Assembly"));
Assert.That(result.Attributes["runstate"], Is.EqualTo("NotRunnable"));
Assert.That(result.Attributes["testcasecount"], Is.EqualTo("0"));
// Minimal check here to allow for platform differences
#if NETCOREAPP1_1
Assert.That(GetSkipReason(result), Contains.Substring("The system cannot find the file specified."));
#else
Assert.That(GetSkipReason(result), Contains.Substring(MISSING_NAME));
#endif
Assert.That(result.SelectNodes("test-suite").Count, Is.EqualTo(0), "Result should not have child tests");
}
[Test]
public void ExploreTestsAction_BadFile_ReturnsNonRunnableSuite()
{
var controller = new FrameworkController(BAD_FILE, "ID", _settings);
new FrameworkController.LoadTestsAction(controller, _handler);
new FrameworkController.ExploreTestsAction(controller, EMPTY_FILTER, _handler);
var result = TNode.FromXml(_handler.GetCallbackResult());
Assert.That(result.Name.ToString(), Is.EqualTo("test-suite"));
Assert.That(result.Attributes["type"], Is.EqualTo("Assembly"));
Assert.That(result.Attributes["runstate"], Is.EqualTo("NotRunnable"));
Assert.That(result.Attributes["testcasecount"], Is.EqualTo("0"));
// Minimal check here to allow for platform differences
Assert.That(GetSkipReason(result), Contains.Substring(BAD_FILE));
Assert.That(result.SelectNodes("test-suite").Count, Is.EqualTo(0), "Result should not have child tests");
}
#endregion
#region CountTestsAction
[TestCaseSource(nameof(EmptyFilters))]
public void CountTestsAction_AfterLoad_ReturnsCorrectCount(string filter)
{
new FrameworkController.LoadTestsAction(_controller, _handler);
new FrameworkController.CountTestsAction(_controller, filter, _handler);
Assert.That(_handler.GetCallbackResult(), Is.EqualTo(MockAssembly.Tests.ToString()));
}
[Test]
public void CountTestsAction_WithoutLoad_ThrowsInvalidOperation()
{
var ex = Assert.Throws<InvalidOperationException>(
() => new FrameworkController.CountTestsAction(_controller, EMPTY_FILTER, _handler));
Assert.That(ex.Message, Is.EqualTo("The CountTestCases method was called but no test has been loaded"));
}
[Test]
public void CountTestsAction_FileNotFound_ReturnsZero()
{
var controller = new FrameworkController(MISSING_FILE, "ID", _settings);
new FrameworkController.LoadTestsAction(controller, _handler);
new FrameworkController.CountTestsAction(controller, EMPTY_FILTER, _handler);
Assert.That(_handler.GetCallbackResult(), Is.EqualTo("0"));
}
[Test]
public void CountTestsAction_BadFile_ReturnsZero()
{
var controller = new FrameworkController(BAD_FILE, "ID", _settings);
new FrameworkController.LoadTestsAction(controller, _handler);
new FrameworkController.CountTestsAction(controller, EMPTY_FILTER, _handler);
Assert.That(_handler.GetCallbackResult(), Is.EqualTo("0"));
}
#endregion
#region RunTestsAction
[TestCaseSource(nameof(EmptyFilters))]
public void RunTestsAction_AfterLoad_ReturnsRunnableSuite(string filter)
{
new FrameworkController.LoadTestsAction(_controller, _handler);
new FrameworkController.RunTestsAction(_controller, filter, _handler);
var result = TNode.FromXml(_handler.GetCallbackResult());
// TODO: Any failure here throws an exception because the call to RunTestsAction
// has destroyed the test context. We need to figure out how to execute the run
// in a cleaner way, perhaps on another thread or in a process.
Assert.That(result.Name.ToString(), Is.EqualTo("test-suite"));
Assert.That(result.Attributes["id"], Is.Not.Null.And.StartWith("ID"));
Assert.That(result.Attributes["name"], Is.EqualTo(EXPECTED_NAME));
Assert.That(result.Attributes["type"], Is.EqualTo("Assembly"));
Assert.That(result.Attributes["runstate"], Is.EqualTo("Runnable"));
Assert.That(result.Attributes["testcasecount"], Is.EqualTo(MockAssembly.Tests.ToString()));
Assert.That(result.Attributes["result"], Is.EqualTo("Failed"));
Assert.That(result.Attributes["passed"], Is.EqualTo(MockAssembly.Passed.ToString()));
Assert.That(result.Attributes["failed"], Is.EqualTo(MockAssembly.Failed.ToString()));
Assert.That(result.Attributes["warnings"], Is.EqualTo(MockAssembly.Warnings.ToString()));
Assert.That(result.Attributes["skipped"], Is.EqualTo(MockAssembly.Skipped.ToString()));
Assert.That(result.Attributes["inconclusive"], Is.EqualTo(MockAssembly.Inconclusive.ToString()));
Assert.That(result.SelectNodes("test-suite").Count, Is.GreaterThan(0), "Run result should have child tests");
}
[Test]
public void RunTestsAction_WithoutLoad_ReturnsError()
{
var ex = Assert.Throws<InvalidOperationException>(
() => new FrameworkController.RunTestsAction(_controller, EMPTY_FILTER, _handler));
Assert.That(ex.Message, Is.EqualTo("The Run method was called but no test has been loaded"));
}
[Test]
public void RunTestsAction_FileNotFound_ReturnsNonRunnableSuite()
{
var controller = new FrameworkController(MISSING_FILE, "ID", _settings);
new FrameworkController.LoadTestsAction(controller, _handler);
new FrameworkController.RunTestsAction(controller, EMPTY_FILTER, _handler);
var result = TNode.FromXml(_handler.GetCallbackResult());
Assert.That(result.Name.ToString(), Is.EqualTo("test-suite"));
Assert.That(result.Attributes["type"], Is.EqualTo("Assembly"));
Assert.That(result.Attributes["runstate"], Is.EqualTo("NotRunnable"));
Assert.That(result.Attributes["testcasecount"], Is.EqualTo("0"));
// Minimal check here to allow for platform differences
#if NETCOREAPP1_1
Assert.That(GetSkipReason(result), Contains.Substring("The system cannot find the file specified."));
#else
Assert.That(GetSkipReason(result), Contains.Substring(MISSING_NAME));
#endif
Assert.That(result.SelectNodes("test-suite").Count, Is.EqualTo(0), "Load result should not have child tests");
}
[Test]
public void RunTestsAction_BadFile_ReturnsNonRunnableSuite()
{
var controller = new FrameworkController(BAD_FILE, "ID", _settings);
new FrameworkController.LoadTestsAction(controller, _handler);
new FrameworkController.RunTestsAction(controller, EMPTY_FILTER, _handler);
var result = TNode.FromXml(_handler.GetCallbackResult());
Assert.That(result.Name.ToString(), Is.EqualTo("test-suite"));
Assert.That(result.Attributes["type"], Is.EqualTo("Assembly"));
Assert.That(result.Attributes["runstate"], Is.EqualTo("NotRunnable"));
Assert.That(result.Attributes["testcasecount"], Is.EqualTo("0"));
// Minimal check here to allow for platform differences
Assert.That(GetSkipReason(result), Contains.Substring(BAD_FILE));
Assert.That(result.SelectNodes("test-suite").Count, Is.EqualTo(0), "Load result should not have child tests");
}
#endregion
#region RunAsyncAction
[TestCaseSource(nameof(EmptyFilters))]
public void RunAsyncAction_AfterLoad_ReturnsRunnableSuite(string filter)
{
new FrameworkController.LoadTestsAction(_controller, _handler);
new FrameworkController.RunAsyncAction(_controller, filter, _handler);
//var result = TNode.FromXml(_handler.GetCallbackResult());
//Assert.That(result.Name.ToString(), Is.EqualTo("test-suite"));
//Assert.That(result.Attributes["type"], Is.EqualTo("Assembly"));
//Assert.That(result.Attributes["id"], Is.Not.Null.And.StartWith("ID"));
//Assert.That(result.Attributes["name"], Is.EqualTo(EXPECTED_NAME));
//Assert.That(result.Attributes["runstate"], Is.EqualTo("Runnable"));
//Assert.That(result.Attributes["testcasecount"], Is.EqualTo(MockAssembly.Tests.ToString()));
//Assert.That(result.Attributes["result"], Is.EqualTo("Failed"));
//Assert.That(result.Attributes["passed"], Is.EqualTo(MockAssembly.Success.ToString()));
//Assert.That(result.Attributes["failed"], Is.EqualTo(MockAssembly.ErrorsAndFailures.ToString()));
//Assert.That(result.Attributes["skipped"], Is.EqualTo((MockAssembly.NotRunnable + MockAssembly.Ignored).ToString()));
//Assert.That(result.Attributes["inconclusive"], Is.EqualTo(MockAssembly.Inconclusive.ToString()));
//Assert.That(result.FindDescendants("test-suite").Count, Is.GreaterThan(0), "Run result should have child tests");
}
[Test]
public void RunAsyncAction_WithoutLoad_ReturnsError()
{
var ex = Assert.Throws<InvalidOperationException>(
() => new FrameworkController.RunAsyncAction(_controller, EMPTY_FILTER, _handler));
Assert.That(ex.Message, Is.EqualTo("The Run method was called but no test has been loaded"));
}
[Test]
public void RunAsyncAction_FileNotFound_ReturnsNonRunnableSuite()
{
var controller = new FrameworkController(MISSING_FILE, "ID", _settings);
new FrameworkController.LoadTestsAction(controller, _handler);
new FrameworkController.RunAsyncAction(controller, EMPTY_FILTER, _handler);
//var result = TNode.FromXml(_handler.GetCallbackResult());
//Assert.That(result.Name.ToString(), Is.EqualTo("test-suite"));
//Assert.That(result.Attributes["type"], Is.EqualTo("Assembly"));
//Assert.That(result.Attributes["runstate"], Is.EqualTo("NotRunnable"));
//Assert.That(result.Attributes["testcasecount"], Is.EqualTo("0"));
// Minimal check here to allow for platform differences
//Assert.That(GetSkipReason(result), Contains.Substring(MISSING_FILE));
//Assert.That(result.SelectNodes("test-suite").Count, Is.EqualTo(0), "Load result should not have child tests");
}
[Test]
public void RunAsyncAction_BadFile_ReturnsNonRunnableSuite()
{
var controller = new FrameworkController(BAD_FILE, "ID", _settings);
new FrameworkController.LoadTestsAction(controller, _handler);
new FrameworkController.RunAsyncAction(controller, EMPTY_FILTER, _handler);
//var result = TNode.FromXml(_handler.GetCallbackResult());
//Assert.That(result.Name.ToString(), Is.EqualTo("test-suite"));
//Assert.That(result.Attributes["type"], Is.EqualTo("Assembly"));
//Assert.That(result.Attributes["runstate"], Is.EqualTo("NotRunnable"));
//Assert.That(result.Attributes["testcasecount"], Is.EqualTo("0"));
// Minimal check here to allow for platform differences
//Assert.That(GetSkipReason(result), Contains.Substring(BAD_FILE));
//Assert.That(result.SelectNodes("test-suite").Count, Is.EqualTo(0), "Load result should not have child tests");
}
#endregion
#region Helper Methods
private static string GetSkipReason(TNode result)
{
var propNode = result.SelectSingleNode(string.Format("properties/property[@name='{0}']", PropertyNames.SkipReason));
return propNode == null ? null : propNode.Attributes["value"];
}
#endregion
#region Nested Callback Class
private class CallbackEventHandler : System.Web.UI.ICallbackEventHandler
{
private string _result;
public string GetCallbackResult()
{
return _result;
}
public void RaiseCallbackEvent(string eventArgument)
{
_result = eventArgument;
}
}
#endregion
}
}
| |
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Copyright (c) Microsoft Corporation. All rights reserved.
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
using System;
using System.Reflection;
using Microsoft.SPOT.Platform.Test;
namespace Microsoft.SPOT.Platform.Tests
{
public class ValueDefault_ConstTests : IMFTestInterface
{
[SetUp]
public InitializeResult Initialize()
{
Log.Comment("Adding set up for the tests");
return InitializeResult.ReadyToGo;
}
[TearDown]
public void CleanUp()
{
Log.Comment("Cleaning up after the tests");
}
//ValueDefault_Const Test methods
//The following tests were ported from folder current\test\cases\client\CLR\Conformance\4_values\Value\Default_Const
//01,02,03,04,05,06,07,09,11,12,14,15,16,17
//All of these tests passed in the Baseline document
//Test Case Calls
[TestMethod]
public MFTestResults ValueDefault_Const01_Test()
{
Log.Comment("Testing byte == 0");
if (ValueDefault_ConstTestClass01.testMethod())
{
return MFTestResults.Pass;
}
return MFTestResults.Fail;
}
[TestMethod]
public MFTestResults ValueDefault_Const02_Test()
{
Log.Comment("Testing short == 0");
if (ValueDefault_ConstTestClass02.testMethod())
{
return MFTestResults.Pass;
}
return MFTestResults.Fail;
}
[TestMethod]
public MFTestResults ValueDefault_Const03_Test()
{
Log.Comment("Testing int == 0");
if (ValueDefault_ConstTestClass03.testMethod())
{
return MFTestResults.Pass;
}
return MFTestResults.Fail;
}
[TestMethod]
public MFTestResults ValueDefault_Const04_Test()
{
Log.Comment("Testing long == 0L");
if (ValueDefault_ConstTestClass04.testMethod())
{
return MFTestResults.Pass;
}
return MFTestResults.Fail;
}
[TestMethod]
public MFTestResults ValueDefault_Const05_Test()
{
Log.Comment("Testing char == \x0000");
if (ValueDefault_ConstTestClass05.testMethod())
{
return MFTestResults.Pass;
}
return MFTestResults.Fail;
}
[TestMethod]
public MFTestResults ValueDefault_Const06_Test()
{
Log.Comment("Testing float == 0.0f");
if (ValueDefault_ConstTestClass06.testMethod())
{
return MFTestResults.Pass;
}
return MFTestResults.Fail;
}
[TestMethod]
public MFTestResults ValueDefault_Const07_Test()
{
Log.Comment("Testing double == 0.0d");
if (ValueDefault_ConstTestClass07.testMethod())
{
return MFTestResults.Pass;
}
return MFTestResults.Fail;
}
[TestMethod]
public MFTestResults ValueDefault_Const09_Test()
{
Log.Comment("Testing bool == false");
if (ValueDefault_ConstTestClass09.testMethod())
{
return MFTestResults.Pass;
}
return MFTestResults.Fail;
}
[TestMethod]
public MFTestResults ValueDefault_Const11_Test()
{
Log.Comment("Testing enum");
if (ValueDefault_ConstTestClass11.testMethod())
{
return MFTestResults.Pass;
}
return MFTestResults.Fail;
}
[TestMethod]
public MFTestResults ValueDefault_Const12_Test()
{
Log.Comment("Testing struct");
if (ValueDefault_ConstTestClass12.testMethod())
{
return MFTestResults.Pass;
}
return MFTestResults.Fail;
}
[TestMethod]
public MFTestResults ValueDefault_Const14_Test()
{
Log.Comment("Testing sbyte == 0");
if (ValueDefault_ConstTestClass14.testMethod())
{
return MFTestResults.Pass;
}
return MFTestResults.Fail;
}
[TestMethod]
public MFTestResults ValueDefault_Const15_Test()
{
Log.Comment("Testing ushort == 0");
if (ValueDefault_ConstTestClass15.testMethod())
{
return MFTestResults.Pass;
}
return MFTestResults.Fail;
}
[TestMethod]
public MFTestResults ValueDefault_Const16_Test()
{
Log.Comment("Testing uint == 0");
if (ValueDefault_ConstTestClass16.testMethod())
{
return MFTestResults.Pass;
}
return MFTestResults.Fail;
}
[TestMethod]
public MFTestResults ValueDefault_Const17_Test()
{
Log.Comment("Testing ulong == 0");
if (ValueDefault_ConstTestClass17.testMethod())
{
return MFTestResults.Pass;
}
return MFTestResults.Fail;
}
//Compiled Test Cases
public class ValueDefault_ConstTestClass01
{
public static bool testMethod()
{
byte b = new byte();
if (b == (byte)0)
{
return true;
}
else
{
return false;
}
}
}
public class ValueDefault_ConstTestClass02
{
public static bool testMethod()
{
short s = new short();
if (s == (short)0)
{
return true;
}
else
{
return false;
}
}
}
public class ValueDefault_ConstTestClass03
{
public static bool testMethod()
{
int i = new int();
if (i == 0)
{
return true;
}
else
{
return false;
}
}
}
public class ValueDefault_ConstTestClass04
{
public static bool testMethod()
{
long l = new long();
if (l == 0L)
{
return true;
}
else
{
return false;
}
}
}
public class ValueDefault_ConstTestClass05
{
public static bool testMethod()
{
char c = new char();
if (c == '\x0000')
{
return true;
}
else
{
return false;
}
}
}
public class ValueDefault_ConstTestClass06
{
public static bool testMethod()
{
float f = new float();
if (f == 0.0f)
{
return true;
}
else
{
return false;
}
}
}
public class ValueDefault_ConstTestClass07
{
public static bool testMethod()
{
double d = new double();
if (d == 0.0d)
{
return true;
}
else
{
return false;
}
}
}
public class ValueDefault_ConstTestClass09
{
public static bool testMethod()
{
bool b = new bool();
if (b == false)
{
return true;
}
else
{
return false;
}
}
}
enum E { a = 1, b = 2 };
public class ValueDefault_ConstTestClass11
{
public static bool testMethod()
{
E e = new E();
if (e == ((E)0))
{
return true;
}
else
{
return false;
}
}
}
struct MyStruct
{
public int I;
public Object MyObj;
}
public class ValueDefault_ConstTestClass12
{
public static bool testMethod()
{
MyStruct TC = new MyStruct();
if ((TC.I == 0) && (TC.MyObj == null))
{
return true;
}
else
{
return false;
}
}
}
public class ValueDefault_ConstTestClass14
{
public static bool testMethod()
{
sbyte b = new sbyte();
if (b == (sbyte)0)
{
return true;
}
else
{
return false;
}
}
}
public class ValueDefault_ConstTestClass15
{
public static bool testMethod()
{
ushort b = new ushort();
if (b == (ushort)0)
{
return true;
}
else
{
return false;
}
}
}
public class ValueDefault_ConstTestClass16
{
public static bool testMethod()
{
uint b = new uint();
if (b == (uint)0)
{
return true;
}
else
{
return false;
}
}
}
public class ValueDefault_ConstTestClass17
{
public static bool testMethod()
{
ulong b = new ulong();
if (b == (ulong)0)
{
return true;
}
else
{
return false;
}
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections;
using System.ComponentModel;
using System.Diagnostics;
using System.Text;
using System.Runtime.InteropServices;
using System.Security.Principal;
namespace System.DirectoryServices.Protocols
{
public enum ExtendedDNFlag
{
HexString = 0,
StandardString = 1
}
[Flags]
public enum SecurityMasks
{
None = 0,
Owner = 1,
Group = 2,
Dacl = 4,
Sacl = 8
}
[Flags]
public enum DirectorySynchronizationOptions : long
{
None = 0,
ObjectSecurity = 0x1,
ParentsFirst = 0x0800,
PublicDataOnly = 0x2000,
IncrementalValues = 0x80000000
}
public enum SearchOption
{
DomainScope = 1,
PhantomRoot = 2
}
internal class UtilityHandle
{
private static ConnectionHandle s_handle = new ConnectionHandle();
public static ConnectionHandle GetHandle() => s_handle;
}
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
public class SortKey
{
private string _name;
private string _rule;
private bool _order = false;
public SortKey()
{
}
public SortKey(string attributeName, string matchingRule, bool reverseOrder)
{
AttributeName = attributeName;
_rule = matchingRule;
_order = reverseOrder;
}
public string AttributeName
{
get => _name;
set => _name = value ?? throw new ArgumentNullException(nameof(value));
}
public string MatchingRule
{
get => _rule;
set => _rule = value;
}
public bool ReverseOrder
{
get => _order;
set => _order = value;
}
}
public class DirectoryControl
{
internal byte[] _directoryControlValue;
public DirectoryControl(string type, byte[] value, bool isCritical, bool serverSide)
{
Type = type ?? throw new ArgumentNullException(nameof(type));
if (value != null)
{
_directoryControlValue = new byte[value.Length];
for (int i = 0; i < value.Length; i++)
{
_directoryControlValue[i] = value[i];
}
}
IsCritical = isCritical;
ServerSide = serverSide;
}
public virtual byte[] GetValue()
{
if (_directoryControlValue == null)
{
return Array.Empty<byte>();
}
byte[] tempValue = new byte[_directoryControlValue.Length];
for (int i = 0; i < _directoryControlValue.Length; i++)
{
tempValue[i] = _directoryControlValue[i];
}
return tempValue;
}
public string Type { get; }
public bool IsCritical { get; set; }
public bool ServerSide { get; set; }
internal static void TransformControls(DirectoryControl[] controls)
{
for (int i = 0; i < controls.Length; i++)
{
Debug.Assert(controls[i] != null);
byte[] value = controls[i].GetValue();
if (controls[i].Type == "1.2.840.113556.1.4.319")
{
// The control is a PageControl.
object[] result = BerConverter.Decode("{iO}", value);
Debug.Assert((result != null) && (result.Length == 2));
int size = (int)result[0];
// user expects cookie with length 0 as paged search is done.
byte[] cookie = (byte[])result[1] ?? Array.Empty<byte>();
PageResultResponseControl pageControl = new PageResultResponseControl(size, cookie, controls[i].IsCritical, controls[i].GetValue());
controls[i] = pageControl;
}
else if (controls[i].Type == "1.2.840.113556.1.4.1504")
{
// The control is an AsqControl.
object[] o = BerConverter.Decode("{e}", value);
Debug.Assert((o != null) && (o.Length == 1));
int result = (int)o[0];
AsqResponseControl asq = new AsqResponseControl(result, controls[i].IsCritical, controls[i].GetValue());
controls[i] = asq;
}
else if (controls[i].Type == "1.2.840.113556.1.4.841")
{
// The control is a DirSyncControl.
object[] o = BerConverter.Decode("{iiO}", value);
Debug.Assert(o != null && o.Length == 3);
int moreData = (int)o[0];
int count = (int)o[1];
byte[] dirsyncCookie = (byte[])o[2];
DirSyncResponseControl dirsync = new DirSyncResponseControl(dirsyncCookie, (moreData == 0 ? false : true), count, controls[i].IsCritical, controls[i].GetValue());
controls[i] = dirsync;
}
else if (controls[i].Type == "1.2.840.113556.1.4.474")
{
// The control is a SortControl.
int result = 0;
string attribute = null;
object[] o = BerConverter.TryDecode("{ea}", value, out bool decodeSucceeded);
// decode might fail as AD for example never returns attribute name, we don't want to unnecessarily throw and catch exception
if (decodeSucceeded)
{
Debug.Assert(o != null && o.Length == 2);
result = (int)o[0];
attribute = (string)o[1];
}
else
{
// decoding might fail as attribute is optional
o = BerConverter.Decode("{e}", value);
Debug.Assert(o != null && o.Length == 1);
result = (int)o[0];
}
SortResponseControl sort = new SortResponseControl((ResultCode)result, attribute, controls[i].IsCritical, controls[i].GetValue());
controls[i] = sort;
}
else if (controls[i].Type == "2.16.840.1.113730.3.4.10")
{
// The control is a VlvResponseControl.
int position;
int count;
int result;
byte[] context = null;
object[] o = BerConverter.TryDecode("{iieO}", value, out bool decodeSucceeded);
if (decodeSucceeded)
{
Debug.Assert(o != null && o.Length == 4);
position = (int)o[0];
count = (int)o[1];
result = (int)o[2];
context = (byte[])o[3];
}
else
{
o = BerConverter.Decode("{iie}", value);
Debug.Assert(o != null && o.Length == 3);
position = (int)o[0];
count = (int)o[1];
result = (int)o[2];
}
VlvResponseControl vlv = new VlvResponseControl(position, count, context, (ResultCode)result, controls[i].IsCritical, controls[i].GetValue());
controls[i] = vlv;
}
}
}
}
public class AsqRequestControl : DirectoryControl
{
public AsqRequestControl() : base("1.2.840.113556.1.4.1504", null, true, true)
{
}
public AsqRequestControl(string attributeName) : this()
{
AttributeName = attributeName;
}
public string AttributeName { get; set; }
public override byte[] GetValue()
{
_directoryControlValue = BerConverter.Encode("{s}", new object[] { AttributeName });
return base.GetValue();
}
}
public class AsqResponseControl : DirectoryControl
{
internal AsqResponseControl(int result, bool criticality, byte[] controlValue) : base("1.2.840.113556.1.4.1504", controlValue, criticality, true)
{
Result = (ResultCode)result;
}
public ResultCode Result { get; }
}
public class CrossDomainMoveControl : DirectoryControl
{
public CrossDomainMoveControl() : base("1.2.840.113556.1.4.521", null, true, true)
{
}
public CrossDomainMoveControl(string targetDomainController) : this()
{
TargetDomainController = targetDomainController;
}
public string TargetDomainController { get; set; }
public override byte[] GetValue()
{
if (TargetDomainController != null)
{
UTF8Encoding encoder = new UTF8Encoding();
byte[] bytes = encoder.GetBytes(TargetDomainController);
// Allocate large enough space for the '\0' character.
_directoryControlValue = new byte[bytes.Length + 2];
for (int i = 0; i < bytes.Length; i++)
{
_directoryControlValue[i] = bytes[i];
}
}
return base.GetValue();
}
}
public class DomainScopeControl : DirectoryControl
{
public DomainScopeControl() : base("1.2.840.113556.1.4.1339", null, true, true)
{
}
}
public class ExtendedDNControl : DirectoryControl
{
private ExtendedDNFlag _flag = ExtendedDNFlag.HexString;
public ExtendedDNControl() : base("1.2.840.113556.1.4.529", null, true, true)
{
}
public ExtendedDNControl(ExtendedDNFlag flag) : this()
{
Flag = flag;
}
public ExtendedDNFlag Flag
{
get => _flag;
set
{
if (value < ExtendedDNFlag.HexString || value > ExtendedDNFlag.StandardString)
throw new InvalidEnumArgumentException(nameof(value), (int)value, typeof(ExtendedDNFlag));
_flag = value;
}
}
public override byte[] GetValue()
{
_directoryControlValue = BerConverter.Encode("{i}", new object[] { (int)Flag });
return base.GetValue();
}
}
public class LazyCommitControl : DirectoryControl
{
public LazyCommitControl() : base("1.2.840.113556.1.4.619", null, true, true) { }
}
public class DirectoryNotificationControl : DirectoryControl
{
public DirectoryNotificationControl() : base("1.2.840.113556.1.4.528", null, true, true) { }
}
public class PermissiveModifyControl : DirectoryControl
{
public PermissiveModifyControl() : base("1.2.840.113556.1.4.1413", null, true, true) { }
}
public class SecurityDescriptorFlagControl : DirectoryControl
{
public SecurityDescriptorFlagControl() : base("1.2.840.113556.1.4.801", null, true, true) { }
public SecurityDescriptorFlagControl(SecurityMasks masks) : this()
{
SecurityMasks = masks;
}
// We don't do validation to the dirsync flag here as underneath API does not check for it and we don't want to put
// unnecessary limitation on it.
public SecurityMasks SecurityMasks { get; set; }
public override byte[] GetValue()
{
_directoryControlValue = BerConverter.Encode("{i}", new object[] { (int)SecurityMasks });
return base.GetValue();
}
}
public class SearchOptionsControl : DirectoryControl
{
private SearchOption _searchOption = SearchOption.DomainScope;
public SearchOptionsControl() : base("1.2.840.113556.1.4.1340", null, true, true) { }
public SearchOptionsControl(SearchOption flags) : this()
{
SearchOption = flags;
}
public SearchOption SearchOption
{
get => _searchOption;
set
{
if (value < SearchOption.DomainScope || value > SearchOption.PhantomRoot)
throw new InvalidEnumArgumentException(nameof(value), (int)value, typeof(SearchOption));
_searchOption = value;
}
}
public override byte[] GetValue()
{
_directoryControlValue = BerConverter.Encode("{i}", new object[] { (int)SearchOption });
return base.GetValue();
}
}
public class ShowDeletedControl : DirectoryControl
{
public ShowDeletedControl() : base("1.2.840.113556.1.4.417", null, true, true) { }
}
public class TreeDeleteControl : DirectoryControl
{
public TreeDeleteControl() : base("1.2.840.113556.1.4.805", null, true, true) { }
}
public class VerifyNameControl : DirectoryControl
{
private string _serverName;
public VerifyNameControl() : base("1.2.840.113556.1.4.1338", null, true, true) { }
public VerifyNameControl(string serverName) : this()
{
_serverName = serverName ?? throw new ArgumentNullException(nameof(serverName));
}
public VerifyNameControl(string serverName, int flag) : this(serverName)
{
Flag = flag;
}
public string ServerName
{
get => _serverName;
set => _serverName = value ?? throw new ArgumentNullException(nameof(value));
}
public int Flag { get; set; }
public override byte[] GetValue()
{
byte[] tmpValue = null;
if (ServerName != null)
{
UnicodeEncoding unicode = new UnicodeEncoding();
tmpValue = unicode.GetBytes(ServerName);
}
_directoryControlValue = BerConverter.Encode("{io}", new object[] { Flag, tmpValue });
return base.GetValue();
}
}
public class DirSyncRequestControl : DirectoryControl
{
private byte[] _dirsyncCookie;
private int _count = 1048576;
public DirSyncRequestControl() : base("1.2.840.113556.1.4.841", null, true, true) { }
public DirSyncRequestControl(byte[] cookie) : this()
{
_dirsyncCookie = cookie;
}
public DirSyncRequestControl(byte[] cookie, DirectorySynchronizationOptions option) : this(cookie)
{
Option = option;
}
public DirSyncRequestControl(byte[] cookie, DirectorySynchronizationOptions option, int attributeCount) : this(cookie, option)
{
AttributeCount = attributeCount;
}
public byte[] Cookie
{
get
{
if (_dirsyncCookie == null)
{
return Array.Empty<byte>();
}
byte[] tempCookie = new byte[_dirsyncCookie.Length];
for (int i = 0; i < tempCookie.Length; i++)
{
tempCookie[i] = _dirsyncCookie[i];
}
return tempCookie;
}
set => _dirsyncCookie = value;
}
// We don't do validation to the dirsync flag here as underneath API does not check for it and we don't want to put
// unnecessary limitation on it.
public DirectorySynchronizationOptions Option { get; set; }
public int AttributeCount
{
get => _count;
set
{
if (value < 0)
{
throw new ArgumentException(SR.ValidValue, nameof(value));
}
_count = value;
}
}
public override byte[] GetValue()
{
object[] o = new object[] { (int)Option, AttributeCount, _dirsyncCookie };
_directoryControlValue = BerConverter.Encode("{iio}", o);
return base.GetValue();
}
}
public class DirSyncResponseControl : DirectoryControl
{
private byte[] _dirsyncCookie;
internal DirSyncResponseControl(byte[] cookie, bool moreData, int resultSize, bool criticality, byte[] controlValue) : base("1.2.840.113556.1.4.841", controlValue, criticality, true)
{
_dirsyncCookie = cookie;
MoreData = moreData;
ResultSize = resultSize;
}
public byte[] Cookie
{
get
{
if (_dirsyncCookie == null)
{
return Array.Empty<byte>();
}
byte[] tempCookie = new byte[_dirsyncCookie.Length];
for (int i = 0; i < tempCookie.Length; i++)
{
tempCookie[i] = _dirsyncCookie[i];
}
return tempCookie;
}
}
public bool MoreData { get; }
public int ResultSize { get; }
}
public class PageResultRequestControl : DirectoryControl
{
private int _size = 512;
private byte[] _pageCookie;
public PageResultRequestControl() : base("1.2.840.113556.1.4.319", null, true, true) { }
public PageResultRequestControl(int pageSize) : this()
{
PageSize = pageSize;
}
public PageResultRequestControl(byte[] cookie) : this()
{
_pageCookie = cookie;
}
public int PageSize
{
get => _size;
set
{
if (value < 0)
{
throw new ArgumentException(SR.ValidValue, nameof(value));
}
_size = value;
}
}
public byte[] Cookie
{
get
{
if (_pageCookie == null)
{
return Array.Empty<byte>();
}
byte[] tempCookie = new byte[_pageCookie.Length];
for (int i = 0; i < _pageCookie.Length; i++)
{
tempCookie[i] = _pageCookie[i];
}
return tempCookie;
}
set => _pageCookie = value;
}
public override byte[] GetValue()
{
object[] o = new object[] { PageSize, _pageCookie };
_directoryControlValue = BerConverter.Encode("{io}", o);
return base.GetValue();
}
}
public class PageResultResponseControl : DirectoryControl
{
private byte[] _pageCookie;
internal PageResultResponseControl(int count, byte[] cookie, bool criticality, byte[] controlValue) : base("1.2.840.113556.1.4.319", controlValue, criticality, true)
{
TotalCount = count;
_pageCookie = cookie;
}
public byte[] Cookie
{
get
{
if (_pageCookie == null)
{
return Array.Empty<byte>();
}
byte[] tempCookie = new byte[_pageCookie.Length];
for (int i = 0; i < _pageCookie.Length; i++)
{
tempCookie[i] = _pageCookie[i];
}
return tempCookie;
}
}
public int TotalCount { get; }
}
public class SortRequestControl : DirectoryControl
{
private SortKey[] _keys = Array.Empty<SortKey>();
public SortRequestControl(params SortKey[] sortKeys) : base("1.2.840.113556.1.4.473", null, true, true)
{
if (sortKeys == null)
{
throw new ArgumentNullException(nameof(sortKeys));
}
for (int i = 0; i < sortKeys.Length; i++)
{
if (sortKeys[i] == null)
{
throw new ArgumentException(SR.NullValueArray, nameof(sortKeys));
}
}
_keys = new SortKey[sortKeys.Length];
for (int i = 0; i < sortKeys.Length; i++)
{
_keys[i] = new SortKey(sortKeys[i].AttributeName, sortKeys[i].MatchingRule, sortKeys[i].ReverseOrder);
}
}
public SortRequestControl(string attributeName, bool reverseOrder) : this(attributeName, null, reverseOrder)
{
}
public SortRequestControl(string attributeName, string matchingRule, bool reverseOrder) : base("1.2.840.113556.1.4.473", null, true, true)
{
SortKey key = new SortKey(attributeName, matchingRule, reverseOrder);
_keys = new SortKey[] { key };
}
public SortKey[] SortKeys
{
get
{
if (_keys == null)
{
return Array.Empty<SortKey>();
}
SortKey[] tempKeys = new SortKey[_keys.Length];
for (int i = 0; i < _keys.Length; i++)
{
tempKeys[i] = new SortKey(_keys[i].AttributeName, _keys[i].MatchingRule, _keys[i].ReverseOrder);
}
return tempKeys;
}
set
{
if (value == null)
{
throw new ArgumentNullException(nameof(value));
}
for (int i = 0; i < value.Length; i++)
{
if (value[i] == null)
{
throw new ArgumentException(SR.NullValueArray, nameof(value));
}
}
_keys = new SortKey[value.Length];
for (int i = 0; i < value.Length; i++)
{
_keys[i] = new SortKey(value[i].AttributeName, value[i].MatchingRule, value[i].ReverseOrder);
}
}
}
public override byte[] GetValue()
{
IntPtr control = IntPtr.Zero;
int structSize = Marshal.SizeOf(typeof(SortKey));
int keyCount = _keys.Length;
IntPtr memHandle = Utility.AllocHGlobalIntPtrArray(keyCount + 1);
try
{
IntPtr tempPtr = IntPtr.Zero;
IntPtr sortPtr = IntPtr.Zero;
int i = 0;
for (i = 0; i < keyCount; i++)
{
sortPtr = Marshal.AllocHGlobal(structSize);
Marshal.StructureToPtr(_keys[i], sortPtr, false);
tempPtr = (IntPtr)((long)memHandle + IntPtr.Size * i);
Marshal.WriteIntPtr(tempPtr, sortPtr);
}
tempPtr = (IntPtr)((long)memHandle + IntPtr.Size * i);
Marshal.WriteIntPtr(tempPtr, IntPtr.Zero);
bool critical = IsCritical;
int error = Wldap32.ldap_create_sort_control(UtilityHandle.GetHandle(), memHandle, critical ? (byte)1 : (byte)0, ref control);
if (error != 0)
{
if (Utility.IsLdapError((LdapError)error))
{
string errorMessage = LdapErrorMappings.MapResultCode(error);
throw new LdapException(error, errorMessage);
}
else
{
throw new LdapException(error);
}
}
LdapControl managedControl = new LdapControl();
Marshal.PtrToStructure(control, managedControl);
berval value = managedControl.ldctl_value;
// reinitialize the value
_directoryControlValue = null;
if (value != null)
{
_directoryControlValue = new byte[value.bv_len];
Marshal.Copy(value.bv_val, _directoryControlValue, 0, value.bv_len);
}
}
finally
{
if (control != IntPtr.Zero)
{
Wldap32.ldap_control_free(control);
}
if (memHandle != IntPtr.Zero)
{
//release the memory from the heap
for (int i = 0; i < keyCount; i++)
{
IntPtr tempPtr = Marshal.ReadIntPtr(memHandle, IntPtr.Size * i);
if (tempPtr != IntPtr.Zero)
{
// free the marshalled name
IntPtr ptr = Marshal.ReadIntPtr(tempPtr);
if (ptr != IntPtr.Zero)
{
Marshal.FreeHGlobal(ptr);
}
// free the marshalled rule
ptr = Marshal.ReadIntPtr(tempPtr, IntPtr.Size);
if (ptr != IntPtr.Zero)
{
Marshal.FreeHGlobal(ptr);
}
Marshal.FreeHGlobal(tempPtr);
}
}
Marshal.FreeHGlobal(memHandle);
}
}
return base.GetValue();
}
}
public class SortResponseControl : DirectoryControl
{
internal SortResponseControl(ResultCode result, string attributeName, bool critical, byte[] value) : base("1.2.840.113556.1.4.474", value, critical, true)
{
Result = result;
AttributeName = attributeName;
}
public ResultCode Result { get; }
public string AttributeName { get; }
}
public class VlvRequestControl : DirectoryControl
{
private int _before = 0;
private int _after = 0;
private int _offset = 0;
private int _estimateCount = 0;
private byte[] _target;
private byte[] _context;
public VlvRequestControl() : base("2.16.840.1.113730.3.4.9", null, true, true) { }
public VlvRequestControl(int beforeCount, int afterCount, int offset) : this()
{
BeforeCount = beforeCount;
AfterCount = afterCount;
Offset = offset;
}
public VlvRequestControl(int beforeCount, int afterCount, string target) : this()
{
BeforeCount = beforeCount;
AfterCount = afterCount;
if (target != null)
{
UTF8Encoding encoder = new UTF8Encoding();
_target = encoder.GetBytes(target);
}
}
public VlvRequestControl(int beforeCount, int afterCount, byte[] target) : this()
{
BeforeCount = beforeCount;
AfterCount = afterCount;
Target = target;
}
public int BeforeCount
{
get => _before;
set
{
if (value < 0)
{
throw new ArgumentException(SR.ValidValue, nameof(value));
}
_before = value;
}
}
public int AfterCount
{
get => _after;
set
{
if (value < 0)
{
throw new ArgumentException(SR.ValidValue, nameof(value));
}
_after = value;
}
}
public int Offset
{
get => _offset;
set
{
if (value < 0)
{
throw new ArgumentException(SR.ValidValue, nameof(value));
}
_offset = value;
}
}
public int EstimateCount
{
get => _estimateCount;
set
{
if (value < 0)
{
throw new ArgumentException(SR.ValidValue, nameof(value));
}
_estimateCount = value;
}
}
public byte[] Target
{
get
{
if (_target == null)
{
return Array.Empty<byte>();
}
byte[] tempContext = new byte[_target.Length];
for (int i = 0; i < tempContext.Length; i++)
{
tempContext[i] = _target[i];
}
return tempContext;
}
set => _target = value;
}
public byte[] ContextId
{
get
{
if (_context == null)
{
return Array.Empty<byte>();
}
byte[] tempContext = new byte[_context.Length];
for (int i = 0; i < tempContext.Length; i++)
{
tempContext[i] = _context[i];
}
return tempContext;
}
set => _context = value;
}
public override byte[] GetValue()
{
var seq = new StringBuilder(10);
var objList = new ArrayList();
// first encode the before and the after count.
seq.Append("{ii");
objList.Add(BeforeCount);
objList.Add(AfterCount);
// encode Target if it is not null
if (Target.Length != 0)
{
seq.Append("t");
objList.Add(0x80 | 0x1);
seq.Append("o");
objList.Add(Target);
}
else
{
seq.Append("t{");
objList.Add(0xa0);
seq.Append("ii");
objList.Add(Offset);
objList.Add(EstimateCount);
seq.Append("}");
}
// encode the contextID if present
if (ContextId.Length != 0)
{
seq.Append("o");
objList.Add(ContextId);
}
seq.Append("}");
object[] values = new object[objList.Count];
for (int i = 0; i < objList.Count; i++)
{
values[i] = objList[i];
}
_directoryControlValue = BerConverter.Encode(seq.ToString(), values);
return base.GetValue();
}
}
public class VlvResponseControl : DirectoryControl
{
private byte[] _context;
internal VlvResponseControl(int targetPosition, int count, byte[] context, ResultCode result, bool criticality, byte[] value) : base("2.16.840.1.113730.3.4.10", value, criticality, true)
{
TargetPosition = targetPosition;
ContentCount = count;
_context = context;
Result = result;
}
public int TargetPosition { get; }
public int ContentCount { get; }
public byte[] ContextId
{
get
{
if (_context == null)
{
return Array.Empty<byte>();
}
byte[] tempContext = new byte[_context.Length];
for (int i = 0; i < tempContext.Length; i++)
{
tempContext[i] = _context[i];
}
return tempContext;
}
}
public ResultCode Result { get; }
}
public class QuotaControl : DirectoryControl
{
private byte[] _sid;
public QuotaControl() : base("1.2.840.113556.1.4.1852", null, true, true) { }
public QuotaControl(SecurityIdentifier querySid) : this()
{
QuerySid = querySid;
}
public SecurityIdentifier QuerySid
{
get => _sid == null ? null : new SecurityIdentifier(_sid, 0);
set
{
if (value == null)
{
_sid = null;
}
else
{
_sid = new byte[value.BinaryLength];
value.GetBinaryForm(_sid, 0);
}
}
}
public override byte[] GetValue()
{
_directoryControlValue = BerConverter.Encode("{o}", new object[] { _sid });
return base.GetValue();
}
}
public class DirectoryControlCollection : CollectionBase
{
public DirectoryControlCollection()
{
}
public DirectoryControl this[int index]
{
get => (DirectoryControl)List[index];
set => List[index] = value ?? throw new ArgumentNullException(nameof(value));
}
public int Add(DirectoryControl control)
{
if (control == null)
{
throw new ArgumentNullException(nameof(control));
}
return List.Add(control);
}
public void AddRange(DirectoryControl[] controls)
{
if (controls == null)
{
throw new ArgumentNullException(nameof(controls));
}
foreach (DirectoryControl control in controls)
{
if (control == null)
{
throw new ArgumentException(SR.ContainNullControl, nameof(controls));
}
}
InnerList.AddRange(controls);
}
public void AddRange(DirectoryControlCollection controlCollection)
{
if (controlCollection == null)
{
throw new ArgumentNullException(nameof(controlCollection));
}
int currentCount = controlCollection.Count;
for (int i = 0; i < currentCount; i = ((i) + (1)))
{
Add(controlCollection[i]);
}
}
public bool Contains(DirectoryControl value) => List.Contains(value);
public void CopyTo(DirectoryControl[] array, int index) => List.CopyTo(array, index);
public int IndexOf(DirectoryControl value) => List.IndexOf(value);
public void Insert(int index, DirectoryControl value)
{
if (value == null)
{
throw new ArgumentNullException(nameof(value));
}
List.Insert(index, value);
}
public void Remove(DirectoryControl value) => List.Remove(value);
protected override void OnValidate(object value)
{
if (value == null)
{
throw new ArgumentNullException(nameof(value));
}
if (!(value is DirectoryControl))
{
throw new ArgumentException(SR.Format(SR.InvalidValueType, nameof(DirectoryControl)), nameof(value));
}
}
}
}
| |
// ------------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information.
// ------------------------------------------------------------------------------
// **NOTE** This file was generated by a tool and any changes will be overwritten.
// Template Source: Templates\CSharp\Requests\EntityCollectionRequest.cs.tt
namespace Microsoft.Graph
{
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Threading;
using System.Linq.Expressions;
/// <summary>
/// The type SiteDrivesCollectionRequest.
/// </summary>
public partial class SiteDrivesCollectionRequest : BaseRequest, ISiteDrivesCollectionRequest
{
/// <summary>
/// Constructs a new SiteDrivesCollectionRequest.
/// </summary>
/// <param name="requestUrl">The URL for the built request.</param>
/// <param name="client">The <see cref="IBaseClient"/> for handling requests.</param>
/// <param name="options">Query and header option name value pairs for the request.</param>
public SiteDrivesCollectionRequest(
string requestUrl,
IBaseClient client,
IEnumerable<Option> options)
: base(requestUrl, client, options)
{
}
/// <summary>
/// Adds the specified Drive to the collection via POST.
/// </summary>
/// <param name="drive">The Drive to add.</param>
/// <returns>The created Drive.</returns>
public System.Threading.Tasks.Task<Drive> AddAsync(Drive drive)
{
return this.AddAsync(drive, CancellationToken.None);
}
/// <summary>
/// Adds the specified Drive to the collection via POST.
/// </summary>
/// <param name="drive">The Drive to add.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param>
/// <returns>The created Drive.</returns>
public System.Threading.Tasks.Task<Drive> AddAsync(Drive drive, CancellationToken cancellationToken)
{
this.ContentType = "application/json";
this.Method = "POST";
return this.SendAsync<Drive>(drive, cancellationToken);
}
/// <summary>
/// Gets the collection page.
/// </summary>
/// <returns>The collection page.</returns>
public System.Threading.Tasks.Task<ISiteDrivesCollectionPage> GetAsync()
{
return this.GetAsync(CancellationToken.None);
}
/// <summary>
/// Gets the collection page.
/// </summary>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param>
/// <returns>The collection page.</returns>
public async System.Threading.Tasks.Task<ISiteDrivesCollectionPage> GetAsync(CancellationToken cancellationToken)
{
this.Method = "GET";
var response = await this.SendAsync<SiteDrivesCollectionResponse>(null, cancellationToken).ConfigureAwait(false);
if (response != null && response.Value != null && response.Value.CurrentPage != null)
{
if (response.AdditionalData != null)
{
object nextPageLink;
response.AdditionalData.TryGetValue("@odata.nextLink", out nextPageLink);
var nextPageLinkString = nextPageLink as string;
if (!string.IsNullOrEmpty(nextPageLinkString))
{
response.Value.InitializeNextPageRequest(
this.Client,
nextPageLinkString);
}
// Copy the additional data collection to the page itself so that information is not lost
response.Value.AdditionalData = response.AdditionalData;
}
return response.Value;
}
return null;
}
/// <summary>
/// Adds the specified expand value to the request.
/// </summary>
/// <param name="value">The expand value.</param>
/// <returns>The request object to send.</returns>
public ISiteDrivesCollectionRequest Expand(string value)
{
this.QueryOptions.Add(new QueryOption("$expand", value));
return this;
}
/// <summary>
/// Adds the specified expand value to the request.
/// </summary>
/// <param name="expandExpression">The expression from which to calculate the expand value.</param>
/// <returns>The request object to send.</returns>
public ISiteDrivesCollectionRequest Expand(Expression<Func<Drive, object>> expandExpression)
{
if (expandExpression == null)
{
throw new ArgumentNullException(nameof(expandExpression));
}
string error;
string value = ExpressionExtractHelper.ExtractMembers(expandExpression, out error);
if (value == null)
{
throw new ArgumentException(error, nameof(expandExpression));
}
else
{
this.QueryOptions.Add(new QueryOption("$expand", value));
}
return this;
}
/// <summary>
/// Adds the specified select value to the request.
/// </summary>
/// <param name="value">The select value.</param>
/// <returns>The request object to send.</returns>
public ISiteDrivesCollectionRequest Select(string value)
{
this.QueryOptions.Add(new QueryOption("$select", value));
return this;
}
/// <summary>
/// Adds the specified select value to the request.
/// </summary>
/// <param name="selectExpression">The expression from which to calculate the select value.</param>
/// <returns>The request object to send.</returns>
public ISiteDrivesCollectionRequest Select(Expression<Func<Drive, object>> selectExpression)
{
if (selectExpression == null)
{
throw new ArgumentNullException(nameof(selectExpression));
}
string error;
string value = ExpressionExtractHelper.ExtractMembers(selectExpression, out error);
if (value == null)
{
throw new ArgumentException(error, nameof(selectExpression));
}
else
{
this.QueryOptions.Add(new QueryOption("$select", value));
}
return this;
}
/// <summary>
/// Adds the specified top value to the request.
/// </summary>
/// <param name="value">The top value.</param>
/// <returns>The request object to send.</returns>
public ISiteDrivesCollectionRequest Top(int value)
{
this.QueryOptions.Add(new QueryOption("$top", value.ToString()));
return this;
}
/// <summary>
/// Adds the specified filter value to the request.
/// </summary>
/// <param name="value">The filter value.</param>
/// <returns>The request object to send.</returns>
public ISiteDrivesCollectionRequest Filter(string value)
{
this.QueryOptions.Add(new QueryOption("$filter", value));
return this;
}
/// <summary>
/// Adds the specified skip value to the request.
/// </summary>
/// <param name="value">The skip value.</param>
/// <returns>The request object to send.</returns>
public ISiteDrivesCollectionRequest Skip(int value)
{
this.QueryOptions.Add(new QueryOption("$skip", value.ToString()));
return this;
}
/// <summary>
/// Adds the specified orderby value to the request.
/// </summary>
/// <param name="value">The orderby value.</param>
/// <returns>The request object to send.</returns>
public ISiteDrivesCollectionRequest OrderBy(string value)
{
this.QueryOptions.Add(new QueryOption("$orderby", value));
return this;
}
}
}
| |
//http://www.whydoidoit.com
//Copyright (C) 2012 Mike Talbot
//
//Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
//The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
//
//THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//#define US_LOGGING
using UnityEngine;
using UnityEngine.SceneManagement;
using System.Collections;
using System;
using System.Linq;
using System.Collections.Generic;
using Serialization;
using System.Reflection;
using System.IO;
using Object = UnityEngine.Object;
using System.Net;
/// <summary>
/// Declares a class that serializes a derivation of Component
/// </summary>
[AttributeUsage(AttributeTargets.Class, AllowMultiple = true)]
public class ComponentSerializerFor : Attribute {
public Type SerializesType;
public ComponentSerializerFor(Type serializesType) {
SerializesType = serializesType;
}
}
[AttributeUsage(AttributeTargets.Class, AllowMultiple = true)]
public class SerializerPlugIn : Attribute { }
[AttributeUsage(AttributeTargets.Class)]
public class SuspendLevelSerialization : Attribute { }
public interface IComponentSerializer {
/// <summary>
/// Serialize the specified component to a byte array
/// </summary>
/// <param name='component'> Component to be serialized </param>
byte[] Serialize(Component component);
/// <summary>
/// Deserialize the specified data into the instance.
/// </summary>
/// <param name='data'> The data that represents the component, produced by Serialize </param>
/// <param name='instance'> The instance to target </param>
void Deserialize(byte[] data, Component instance);
}
public interface IControlSerialization {
bool ShouldSave();
}
public interface IControlSerializationEx : IControlSerialization {
bool ShouldSaveWholeObject();
}
/// <summary>
/// Level serializer - this class is the main interaction point for
/// saving and loading Unity objects and whole scenes.
/// </summary>
public static class LevelSerializer {
#region Delegates
/// <summary>
/// Used when querying if an item should be stored.
/// </summary>
public delegate void StoreQuery(GameObject go, ref bool store);
public delegate void StoreComponentQuery(Component component, ref bool store);
#endregion
#region SerializationModes enum
/// <summary>
/// Serialization modes.
/// </summary>
public enum SerializationModes {
/// <summary>
/// Serialize when suspended
/// </summary>
SerializeWhenFree,
/// <summary>
/// Ensure that there is serialization data
/// when suspending
/// </summary>
CacheSerialization
}
#endregion
private static Dictionary<string, GameObject> allPrefabs = new Dictionary<string, GameObject>();
/// <summary>
/// The types which should be ignored for serialization
/// </summary>
public static HashSet<string> IgnoreTypes = new HashSet<string>();
public static Dictionary<Type, IComponentSerializer> CustomSerializers =
new Dictionary<Type, IComponentSerializer>();
internal static int lastFrame;
/// <summary>
/// The name of the player.
/// </summary>
public static string PlayerName = string.Empty;
/// <summary>
/// Whether resume information should be saved when saving the level
/// </summary>
public static bool SaveResumeInformation = true;
private static int _suspensionCount;
private static SaveEntry _cachedState;
/// <summary>
/// The serialization caching mode
/// </summary>
public static SerializationModes SerializationMode = SerializationModes.CacheSerialization;
/// <summary>
/// The max games that will be stored.
/// </summary>
public static int MaxGames = 20;
/// <summary>
/// The saved games.
/// </summary>
public static Lookup<string, List<SaveEntry>> SavedGames = new Index<string, List<SaveEntry>>();
//Stop cases
private static readonly List<Type> _stopCases = new List<Type>();
/// <summary>
/// Indicates whether the system is deserializing a level
/// </summary>
public static bool IsDeserializing;
public static readonly List<object> createdPlugins = new List<object>();
/// <summary>
/// Should the system use compression
/// </summary>
public static bool useCompression = false;
static WebClient webClient = new WebClient();
#region Extended methods
static void HandleWebClientUploadStringCompleted(object sender, UploadStringCompletedEventArgs e) {
lock (Guard) {
uploadCount--;
}
Loom.QueueOnMainThread(() => {
if (e.UserState is Action<Exception>) {
(e.UserState as Action<Exception>)(e.Error);
}
});
}
static void HandleWebClientUploadDataCompleted(object sender, UploadDataCompletedEventArgs e) {
lock (Guard) {
uploadCount--;
}
Loom.QueueOnMainThread(() => {
if (e.UserState is Action<Exception>) {
(e.UserState as Action<Exception>)(e.Error);
}
});
}
/// <summary>
/// Saves a particular object tree to a file. The file will be
/// saved beneath Application.persistentDataPath
/// </summary>
/// <param name='filename'>
/// The filename to save the object tree into
/// </param>
/// <param name='rootOfTree'>
/// The root of the tree
/// </param>
public static void SaveObjectTreeToFile(string filename, GameObject rootOfTree) {
var data = SaveObjectTree(rootOfTree);
data.WriteToFile(Application.persistentDataPath + "/" + filename);
}
/// <summary>
/// Loads an object tree into the current scene from a file
/// </summary>
/// <param name='filename'>
/// The file that should be loaded (from within Application.persistentDataPath)
/// </param>
/// <param name='onComplete'>
/// A method call to make when loading is complete
/// </param>
public static void LoadObjectTreeFromFile(string filename, Action<LevelLoader> onComplete = null) {
var x = File.Open(Application.persistentDataPath + "/" + filename, FileMode.Open);
var data = new byte[x.Length];
x.Read(data, 0, (int)x.Length);
x.Close();
LoadObjectTree(data, onComplete);
}
/// <summary>
/// Serializes the level to a file
/// </summary>
/// <param name='filename'>
/// The filename to use
/// </param>
/// <param name="usePersistentDataPath">
/// Is filename just a filename in Application.persistentDataPath or a whole path?
/// </param>
public static void SerializeLevelToFile(string filename, bool usePersistentDataPath = true) {
var data = SerializeLevel();
if (usePersistentDataPath) {
data.WriteToFile(Application.persistentDataPath + "/" + filename);
}
else {
#if US_LOGGING
Debug.LogFormat("Trying to write file to {0}", filename);
#endif
data.WriteToFile(filename);
#if US_LOGGING
Debug.LogErrorFormat("ERROR: {0} cannot be open for saving!", filename);
#endif
}
}
/// <summary>
/// Loads a level from a file
/// </summary>
/// <param name='filename'>
/// The filename to use
/// </param>
/// <param name="usePersistentDataPath">
/// Is filename just a filename in Application.persistentDataPath or a whole path?
/// </param>
/// <param name="showGUI">
/// Should the screen fade?
/// </param>
public static void LoadSavedLevelFromFile(string filename, bool usePersistentDataPath = true, bool showGUI = true) {
StreamReader reader;
string data = null;
if (usePersistentDataPath) {
reader = File.OpenText(Application.persistentDataPath + "/" + filename);
data = reader.ReadToEnd();
reader.Close();
}
else {
#if US_LOGGING
Debug.LogFormat("Trying to write file to {0}", filename);
#endif
reader = File.OpenText(filename);
data = reader.ReadToEnd();
reader.Close();
#if US_LOGGING
Debug.LogErrorFormat("ERROR: {0} cannot be open for loading!", filename);
#endif
}
if (data != null) {
LoadSavedLevel(data, showGUI);
}
else {
Debug.LogErrorFormat("No data was loaded from {0}", filename);
}
}
static readonly object Guard = new object();
/// <summary>
/// Saves an object tree to a server using POST or STOR
/// </summary>
/// <param name='uri'>
/// The url to save the tree to e.g. ftp://whydoidoit.net/Downloads/someFile.txt
/// </param>
/// <param name='rootOfTree'>
/// The object to be saved
/// </param>
/// <param name='userName'>
/// The user name (if required)
/// </param>
/// <param name='password'>
/// The password (if required)
/// </param>
/// <param name='onComplete'>
/// A function to call when the upload is complete
/// </param>
public static void SaveObjectTreeToServer(string uri, GameObject rootOfTree, string userName = "", string password = "", Action<Exception> onComplete = null) {
onComplete = onComplete ?? delegate { };
Action execute = () => {
var data = SaveObjectTree(rootOfTree);
Action doIt = () => {
uploadCount++;
webClient.Credentials = new NetworkCredential(userName, password);
webClient.UploadDataAsync(new Uri(uri), null, data, onComplete);
};
DoWhenReady(doIt);
};
execute();
}
static void DoWhenReady(Action upload) {
lock (Guard) {
if (uploadCount > 0) {
Loom.QueueOnMainThread(() => DoWhenReady(upload), 0.4f);
}
else {
upload();
}
}
}
/// <summary>
/// Loads an object tree from a server
/// </summary>
/// <param name='uri'>
/// The url to load the object tree from
/// </param>
/// <param name='onComplete'>
/// A method to call when the load is complete
/// </param>
public static void LoadObjectTreeFromServer(string uri, Action<LevelLoader> onComplete = null) {
onComplete = onComplete ?? delegate { };
RadicalRoutineHelper.Current.StartCoroutine(DownloadFromServer(uri, onComplete));
}
static int uploadCount;
/// <summary>
/// Serializes the level to a server.
/// </summary>
/// <param name='uri'>
/// The url of the location for the stored data. ftp://whydoidoit.net/Downloads/someFile.dat
/// </param>
/// <param name='userName'>
/// User name if required
/// </param>
/// <param name='password'>
/// Password if required
/// </param>
/// <param name='onComplete'>
/// A method to call when the serialization is complete
/// </param>
public static void SerializeLevelToServer(string uri, string userName = "", string password = "", Action<Exception> onComplete = null) {
lock (Guard) {
if (uploadCount > 0) {
Loom.QueueOnMainThread(() => SerializeLevelToServer(uri, userName, password, onComplete), 0.5f);
return;
}
uploadCount++;
onComplete = onComplete ?? delegate { };
var data = SerializeLevel();
webClient.Credentials = new NetworkCredential(userName, password);
webClient.UploadStringAsync(new Uri(uri), null, data, onComplete);
}
}
/// <summary>
/// Loads the saved level from a server url.
/// </summary>
/// <param name='uri'>
/// The url of the server to load the data from
/// </param>
public static void LoadSavedLevelFromServer(string uri) {
RadicalRoutineHelper.Current.StartCoroutine(DownloadLevelFromServer(uri));
}
static IEnumerator DownloadFromServer(string uri, Action<LevelLoader> onComplete) {
var www = new WWW(uri);
yield return www;
LoadObjectTree(www.bytes, onComplete);
}
static IEnumerator DownloadLevelFromServer(string uri) {
var www = new WWW(uri);
yield return www;
LoadSavedLevel(www.text);
}
#endregion
static LevelSerializer()
{
webClient.UploadDataCompleted += HandleWebClientUploadDataCompleted;
webClient.UploadStringCompleted += HandleWebClientUploadStringCompleted;
//Basic plug in configuration and special cases
_stopCases.Add(typeof(PrefabIdentifier));
//UnitySerializer.AddPrivateType(typeof(AnimationClip));
/* //Other initialization
foreach (var asm in AppDomain.CurrentDomain.GetAssemblies())
{
UnitySerializer.ScanAllTypesForAttribute((tp, attr) =>
createdPlugins.Add(Activator.CreateInstance(tp)), asm, typeof(SerializerPlugIn));
UnitySerializer.ScanAllTypesForAttribute((tp, attr) =>
{
CustomSerializers[((ComponentSerializerFor)attr).SerializesType] = Activator.CreateInstance(tp) as IComponentSerializer;
}, asm, typeof(ComponentSerializerFor));
}*/
AllPrefabs = Resources.FindObjectsOfTypeAll(typeof(GameObject)).Cast<GameObject>()
.Where(go => {
var pf = go.GetComponent<PrefabIdentifier>();
return pf != null && !pf.IsInScene();
})
.Distinct(CompareGameObjects.Instance)
.ToDictionary(go => go.GetComponent<PrefabIdentifier>().ClassId, go => go);
/*try {
var stored = FilePrefs.GetString("_Save_Game_Data_");
if (!string.IsNullOrEmpty(stored)) {
try {
SavedGames = UnitySerializer.Deserialize<Lookup<string, List<SaveEntry>>>(Convert.FromBase64String(stored));
}
catch {
SavedGames = null;
}
}
if (SavedGames == null) {
SavedGames = new Index<string, List<SaveEntry>>();
SaveDataToFilePrefs();
}
}
catch {
SavedGames = new Index<string, List<SaveEntry>>();
}*/
}
internal static Dictionary<string, GameObject> AllPrefabs {
get {
if (Time.frameCount != lastFrame) {
allPrefabs = allPrefabs.Where(p => p.Value).ToDictionary(p => p.Key, p => p.Value);
lastFrame = Time.frameCount;
}
return allPrefabs;
}
set { allPrefabs = value; }
}
/// <summary>
/// Gets a value indicating whether this instance can resume (there is resume data)
/// </summary>
/// <value>
/// <c>true</c> if this instance can resume; otherwise, <c>false</c>.
/// </value>
public static bool CanResume {
get { return !string.IsNullOrEmpty(FilePrefs.GetString(PlayerName + "__RESUME__")); }
}
/// <summary>
/// Gets a value indicating whether this instance is suspended.
/// </summary>
/// <value> <c>true</c> if this instance is suspended; otherwise, <c>false</c> . </value>
public static bool IsSuspended {
get { return _suspensionCount > 0; }
}
/// <summary>
/// Gets the serialization suspension count.
/// </summary>
/// <value> The suspension count. </value>
public static int SuspensionCount {
get { return _suspensionCount; }
}
/// <summary>
/// Occurs when the level was deserialized
/// </summary>
public static event Action Deserialized = delegate { };
/// <summary>
/// Occurs when the level was serialized.
/// </summary>
public static event Action GameSaved = delegate { };
/// <summary>
/// Occurs when suspending serialization.
/// </summary>
public static event Action SuspendingSerialization = delegate { };
/// <summary>
/// Occurs when resuming serialization.
/// </summary>
public static event Action ResumingSerialization = delegate { };
internal static void InvokeDeserialized() {
_suspensionCount = 0;
if (Deserialized != null) {
Deserialized();
}
foreach (var go in Object.FindObjectsOfType(typeof(GameObject)).Cast<GameObject>()) {
go.SendMessage("OnDeserialized", null, SendMessageOptions.DontRequireReceiver);
}
}
/// <summary>
/// Raised to check whehter a particular item should be stored
/// </summary>
public static event StoreQuery Store;
public static event StoreComponentQuery StoreComponent = delegate { };
/// <summary>
/// Resume for a stored game state that wasn't directly saved
/// </summary>
public static void Resume() {
var data = FilePrefs.GetString(PlayerName + "__RESUME__");
if (!string.IsNullOrEmpty(data)) {
var se = UnitySerializer.Deserialize<SaveEntry>(Convert.FromBase64String(data));
se.Load();
}
}
/// <summary>
/// Create a resumption checkpoint
/// </summary>
public static void Checkpoint() {
SaveGame("Resume", false, PerformSaveCheckPoint);
}
private static void PerformSaveCheckPoint(string name, bool urgent) {
var newGame = CreateSaveEntry(name, urgent);
FilePrefs.SetString(PlayerName + "__RESUME__", Convert.ToBase64String(UnitySerializer.Serialize(newGame)));
FilePrefs.Save();
}
public static void ClearCheckpoint() {
ClearCheckpoint(true);
}
public static void ClearCheckpoint(bool store) {
FilePrefs.DeleteKey(PlayerName + "__RESUME__");
if (store) {
FilePrefs.Save();
}
}
/// <summary>
/// Suspends the serialization. Must resume as many times as you suspend
/// </summary>
public static void SuspendSerialization() {
if (_suspensionCount == 0) {
SuspendingSerialization();
if (SerializationMode == SerializationModes.CacheSerialization) {
_cachedState = CreateSaveEntry("resume", true);
if (SaveResumeInformation) {
FilePrefs.SetString(PlayerName + "__RESUME__",
Convert.ToBase64String(UnitySerializer.Serialize(_cachedState)));
FilePrefs.Save();
}
}
}
_suspensionCount++;
}
/// <summary>
/// Resumes the serialization. Must be balanced with calls to SuspendSerialization
/// </summary>
public static void ResumeSerialization() {
_suspensionCount--;
if (_suspensionCount == 0) {
ResumingSerialization();
}
}
/// <summary>
/// Ignores the type of component when saving games.
/// </summary>
/// <param name='typename'> Typename of the component to ignore </param>
public static void IgnoreType(string typename) {
IgnoreTypes.Add(typename);
}
/// <summary>
/// Remove a type from the ignore list
/// </summary>
/// <param name='typename'>
/// Typename to remove
/// </param>
public static void UnIgnoreType(string typename) {
IgnoreTypes.Remove(typename);
}
/// <summary>
/// Ignores the type of component when saving games.
/// </summary>
/// <param name='tp'> The type of the component to ignore </param>
public static void IgnoreType(Type tp) {
if (tp.FullName != null) {
IgnoreTypes.Add(tp.FullName);
}
}
/// <summary>
/// Creates a saved game for the current position
/// </summary>
/// <returns> The new save entry. </returns>
/// <param name='name'> A name for the save entry </param>
/// <param name='urgent'> An urgent save will store the current state, even if suspended. In this case it is likely that clean up will be necessary by handing Deserialized messages or responding to the LevelSerializer.Deserialized event </param>
public static SaveEntry CreateSaveEntry(string name, bool urgent) {
return new SaveEntry() {
Name = name,
When = DateTime.Now,
Level = SceneManager.GetActiveScene().name,
Data = SerializeLevel(urgent)
};
}
/// <summary>
/// Saves the game.
/// </summary>
/// <param name='name'> The name to use for the game </param>
public static void SaveGame(string name) {
SaveGame(name, false, null);
}
public static void SaveGame(string name, bool urgent, Action<string, bool> perform) {
perform = perform ?? PerformSave;
//See if we need to serialize later
if (!urgent && (IsSuspended && SerializationMode == SerializationModes.SerializeWhenFree)) {
//Are we already waiting for serialization to occur
if (GameObject.Find("/SerializationHelper") != null) {
return;
}
//Create a helper
var go = new GameObject("SerializationHelper");
var helper = go.AddComponent(typeof(SerializationHelper)) as SerializationHelper;
helper.gameName = name;
helper.perform = perform;
return;
}
perform(name, urgent);
}
private static void PerformSave(string name, bool urgent) {
var newGame = CreateSaveEntry(name, urgent);
SavedGames[PlayerName].Insert(0, newGame);
while (SavedGames[PlayerName].Count > MaxGames) {
SavedGames[PlayerName].RemoveAt(SavedGames.Count - 1);
}
SaveDataToFilePrefs();
FilePrefs.SetString(PlayerName + "__RESUME__", Convert.ToBase64String(UnitySerializer.Serialize(newGame)));
FilePrefs.Save();
GameSaved();
}
/// <summary>
/// Saves the stored game data to player prefs.
/// </summary>
public static void SaveDataToFilePrefs() {
FilePrefs.SetString("_Save_Game_Data_", Convert.ToBase64String(UnitySerializer.Serialize(SavedGames)));
FilePrefs.Save();
}
/// <summary>
/// Registers the calling assembly as one providing serialization extensions.
/// </summary>
public static void RegisterAssembly() {
UnitySerializer.ScanAllTypesForAttribute(
(tp, attr) => {
CustomSerializers[((ComponentSerializerFor)attr).SerializesType] =
Activator.CreateInstance(tp) as IComponentSerializer;
}, Assembly.GetCallingAssembly(),
typeof(ComponentSerializerFor));
}
/// <summary>
/// Adds the prefab path.
/// </summary>
/// <param name='path'> A resource path that contains prefabs to be created for the game </param>
public static void AddPrefabPath(string path) {
foreach (var pair in Resources.LoadAll(path, typeof(GameObject))
.Cast<GameObject>()
.Where(go => go.GetComponent<UniqueIdentifier>() != null)
.ToDictionary(go => go.GetComponent<UniqueIdentifier>().ClassId, go => go).Where(
pair => !AllPrefabs.ContainsKey(pair.Key))) {
AllPrefabs.Add(pair.Key, pair.Value);
}
}
/// <summary>
/// Dont garbage collect during deserialization
/// </summary>
public static void DontCollect() {
_collectionCount++;
}
/// <summary>
/// Enable garbage collection during deserialization
/// </summary>
public static void Collect() {
_collectionCount--;
}
static int _collectionCount = 0;
/// <summary>
/// Gets a value indicating whether this <see cref="LevelSerializer"/> should garbage collect.
/// </summary>
/// <value>
/// <c>true</c> if should collect; otherwise, <c>false</c>.
/// </value>
public static bool ShouldCollect {
get {
return _collectionCount <= 0;
}
}
/// <summary>
/// Serializes the level to a string
/// </summary>
/// <returns> The level data as a string </returns>
/// <exception>Is thrown when the serization was suspended
/// <cref>SerizationSuspendedException</cref>
/// </exception>
public static string SerializeLevel() {
return SerializeLevel(false);
}
/// <summary>
/// Serializes the level.
/// </summary>
/// <returns> The level stored as a string. </returns>
/// <param name='urgent'> Whether to ignore an suspension of serialization </param>
/// <exception cref='SerializationSuspendedException'>Is thrown when the serialization was suspended and urgent was not specified</exception>
public static string SerializeLevel(bool urgent) {
//using(new Timing("Save Level"))
{
if (IsSuspended && !urgent) {
if (SerializationMode == SerializationModes.CacheSerialization) {
return _cachedState.Data;
}
else {
throw new SerializationSuspendedException();
}
}
//Try to get as much memory as possible
Resources.UnloadUnusedAssets();
if (ShouldCollect) GC.Collect();
var data = SerializeLevel(false, null);
//Free up memory that has been used during serialization
if (ShouldCollect) GC.Collect();
if (useCompression) {
return
CompressionHelper.Compress(data);
}
else {
return "NOCOMPRESSION" + Convert.ToBase64String(data);
}
}
}
internal static void RaiseProgress(string section, float complete) {
Progress(section, complete);
}
internal static bool HasParent(UniqueIdentifier i, string id) {
var scan = UniqueIdentifier.GetByName(i.Id).transform;
while (scan != null) {
UniqueIdentifier ui;
if ((ui = scan.GetComponent<UniqueIdentifier>()) != null) {
if (id == ui.Id) {
return true;
}
}
scan = scan.parent;
}
return false;
}
private static void GetComponentsInChildrenWithClause(Transform t, List<StoreInformation> components) {
foreach (var c in t.Cast<Transform>()) {
var s = c.GetComponent<StoreInformation>();
if (s != null) {
if (!(s is PrefabIdentifier)) {
components.Add(s);
GetComponentsInChildrenWithClause(c, components);
}
}
else {
GetComponentsInChildrenWithClause(c, components);
}
}
}
/// <summary>
/// Internal function
/// </summary>
public static List<StoreInformation> GetComponentsInChildrenWithClause(GameObject go) {
var components = new List<StoreInformation>();
GetComponentsInChildrenWithClause(go.transform, components);
return components;
}
/// <summary>
/// Occurs when progress occurs during the deserialization/serialization process
/// </summary>
public static event Action<string, float> Progress = delegate { };
/// <summary>
/// Save an objects tree so it can be reloaded later
/// </summary>
/// <param name="rootOfTree">The object at the root of the tree</param>
/// <returns></returns>
public static byte[] SaveObjectTree(this GameObject rootOfTree) {
if (!rootOfTree.GetComponent<UniqueIdentifier>()) {
EmptyObjectIdentifier.FlagAll(rootOfTree);
}
return SerializeLevel(false, rootOfTree.GetComponent<UniqueIdentifier>().Id);
}
/// <summary>
/// Occurs before any loading is done.
/// </summary>
public static event Action BeginLoad = delegate { };
/// <summary>
/// Serializes the level to a byte array, with an optional root item. The root item
/// and its children, if specified, will be the only things saved
/// </summary>
/// <returns> The level data as a byte array </returns>
/// <param name='urgent'> Whether to save even if serialization is suspended </param>
/// <param name='id'> Identifier (or null) of an object to be the root of the data serialization </param>
public static byte[] SerializeLevel(bool urgent, string id) {
LevelData ld;
using (new Radical.Logging()) {
//First we need to know the name of the last level loaded
using (new UnitySerializer.SerializationScope()) {
ld = new LevelData() {
//The level to reload
Name = SceneManager.GetActiveScene().name,
rootObject = string.IsNullOrEmpty(id) ? null : id
};
//All of the currently active uniquely identified objects
ld.StoredObjectNames = UniqueIdentifier
.AllIdentifiers
.Where(i => string.IsNullOrEmpty(id) || i.Id == id || HasParent(i, id))
.Select(i => i.gameObject)
.Where(go => go != null)
.Where(go => {
var shouldSerialize = go.FindInterface<IControlSerializationEx>();
return shouldSerialize == null || shouldSerialize.ShouldSaveWholeObject();
})
.Where(go => {
if (Store == null) {
return true;
}
var result = true;
Store(go, ref result);
return result;
})
.Select(n => {
try {
var si = new StoredItem() {
createEmptyObject = n.GetComponent<EmptyObjectIdentifier>() != null,
layer = n.layer,
tag = n.tag,
setExtraData = true,
Active = n.activeSelf,
Components =
n.GetComponents<Component>().Where(c => c != null).Select(
c => c.GetType().FullName).Distinct()
.ToDictionary(v => v, v => true),
Name = n.GetComponent<UniqueIdentifier>().Id,
GameObjectName = n.name,
ParentName =
(n.transform.parent == null ||
n.transform.parent.GetComponent<UniqueIdentifier>() ==
null)
? null
: (n.transform.parent.GetComponent<UniqueIdentifier>().
Id),
ClassId = n.GetComponent<PrefabIdentifier>() != null
? n.GetComponent<PrefabIdentifier>().ClassId
: string.Empty
};
if (n.GetComponent<StoreInformation>()) {
n.SendMessage("OnSerializing", SendMessageOptions.DontRequireReceiver);
}
var pf = n.GetComponent<PrefabIdentifier>();
if (pf != null) {
var components = GetComponentsInChildrenWithClause(n);
si.Children = components.GroupBy(c => c.ClassId).ToDictionary(c => c.Key,
c =>
c.Select(
i => i.Id)
.ToList());
}
return si;
}
catch (Exception e) {
Debug.LogWarning("Failed to serialize status of " + n.name + " with error " +
e.ToString());
return null;
}
})
.Where(si => si != null)
.ToList();
//All of the data for the items to be stored
var toBeProcessed = UniqueIdentifier
.AllIdentifiers
.Where(o => o.GetComponent<StoreInformation>() != null || o.GetComponent<PrefabIdentifier>() != null)
.Where(i => string.IsNullOrEmpty(id) || i.Id == id || HasParent(i, id))
.Where(i => i != null)
.Select(i => i.gameObject)
.Where(i => i != null)
.Where(go => {
var shouldSerialize = go.FindInterface<IControlSerializationEx>();
return shouldSerialize == null || shouldSerialize.ShouldSaveWholeObject();
})
.Distinct()
.Where(go => {
if (Store == null) {
return true;
}
var result = true;
Store(go, ref result);
return result;
})
.SelectMany(o => o.GetComponents<Component>())
.Where(c => {
if (c == null) {
return false;
}
var tp = c.GetType();
var store = true;
StoreComponent(c, ref store);
return store && (!(c is IControlSerialization) || (c as IControlSerialization).ShouldSave()) &&
!tp.IsDefined(typeof(DontStoreAttribute), true)
&& !IgnoreTypes.Contains(tp.FullName) && tp.FullName != "UnityEngine.Animator";
})
.Select(c => new {
Identifier =
(StoreInformation)c.gameObject.GetComponent(typeof(StoreInformation)),
Component = c
})
.Where(cp =>
(cp.Identifier.StoreAllComponents ||
cp.Identifier.Components.Contains(cp.Component.GetType().FullName)))
.OrderBy(cp => cp.Identifier.Id)
.ThenBy(cp => cp.Component.GetType().FullName).ToList();
var processed = 0;
ld.StoredItems = toBeProcessed
.Select(cp => {
try {
if (Radical.IsLogging()) {
Radical.Log("<{0} : {1} - {2}>", cp.Component.gameObject.GetFullName(),
cp.Component.GetType().Name,
cp.Component.GetComponent<UniqueIdentifier>().Id);
Radical.IndentLog();
}
var sd = new StoredData() {
Type = cp.Component.GetType().FullName,
ClassId = cp.Identifier.ClassId,
Name = cp.Component.GetComponent<UniqueIdentifier>().Id
};
if (CustomSerializers.ContainsKey(cp.Component.GetType())) {
sd.Data = CustomSerializers[cp.Component.GetType()].Serialize(cp.Component);
}
else {
sd.Data = UnitySerializer.SerializeForDeserializeInto(cp.Component);
}
if (Radical.IsLogging()) {
Radical.OutdentLog();
Radical.Log("</{0} : {1}>", cp.Component.gameObject.GetFullName(),
cp.Component.GetType().Name);
}
processed++;
Progress("Storing", (float)processed / (float)toBeProcessed.Count);
return sd;
}
catch (Exception e) {
processed++;
Debug.LogWarning("Failed to serialize data (" +
cp.Component.GetType().AssemblyQualifiedName + ") of " +
cp.Component.name + " with error " + e.ToString());
return null;
}
})
.Where(s => s != null)
.ToList();
}
}
var data = UnitySerializer.Serialize(ld);
return data;
}
/// <summary>
/// Reload an object tree
/// </summary>
/// <param name="data">The data for the tree to be loaded</param>
/// <param name="onComplete">A function to call when the load is complete</param>
public static void LoadObjectTree(this byte[] data, Action<LevelLoader> onComplete = null) {
onComplete = onComplete ?? delegate { };
LoadNow(data, true, false, onComplete);
}
public static void LoadNow(object data) {
LoadNow(data, false, true, null);
}
public static void LoadNow(object data, bool dontDeleteExistingItems) {
LoadNow(data, dontDeleteExistingItems, true, null);
}
public static void LoadNow(object data, bool dontDeleteExistingItems, bool showLoadingGUI) {
LoadNow(data, dontDeleteExistingItems, showLoadingGUI, null);
}
public static void LoadNow(object data, bool dontDeleteExistingItems, bool showLoadingGUI, Action<LevelLoader> complete) {
if (BeginLoad != null) {
BeginLoad();
}
byte[] levelData = null;
if (data is byte[]) {
levelData = (byte[])data;
}
if (data is string) {
var str = (string)data;
if (str.StartsWith("NOCOMPRESSION")) {
levelData = Convert.FromBase64String(str.Substring(13));
}
else {
levelData = CompressionHelper.Decompress(str);
}
}
if (levelData == null) {
throw new ArgumentException("data parameter must be either a byte[] or a base64 encoded string");
}
//Create a level loader
var l = new GameObject();
var loader = l.AddComponent<LevelLoader>();
loader.showGUI = showLoadingGUI;
var ld = UnitySerializer.Deserialize<LevelSerializer.LevelData>(levelData);
loader.Data = ld;
loader.DontDelete = dontDeleteExistingItems;
//Get the loader to do its job
loader.StartCoroutine(PerformLoad(loader, complete));
}
static IEnumerator PerformLoad(LevelLoader loader, Action<LevelLoader> complete) {
yield return loader.StartCoroutine(loader.Load(0, Time.timeScale));
if (complete != null) {
complete(loader);
}
}
/// <summary>
/// Loads the saved level.
/// </summary>
/// <param name='data'> The data describing the level to load </param>
/// <param name="showGUI"> Should the screen fade? </param>
public static LevelLoader LoadSavedLevel(string data, bool showGUI = true) {
if (BeginLoad != null) {
BeginLoad();
}
LevelData ld;
IsDeserializing = true;
if (data.StartsWith("NOCOMPRESSION")) {
ld = UnitySerializer.Deserialize<LevelData>(Convert.FromBase64String(data.Substring(13)));
}
else {
ld =
UnitySerializer.Deserialize<LevelData>(CompressionHelper.Decompress(data));
}
SaveGameManager.Loaded();
var go = new GameObject();
Object.DontDestroyOnLoad(go);
var loader = go.AddComponent<LevelLoader>();
loader.Data = ld;
loader.showGUI = showGUI;
SceneManager.LoadScene(ld.Name);
return loader;
}
#region Nested type: CompareGameObjects
private class CompareGameObjects : IEqualityComparer<GameObject> {
#region IEqualityComparer[GameObject] implementation
public bool Equals(GameObject x, GameObject y) {
return System.String.Compare(x.GetComponent<PrefabIdentifier>().ClassId, y.GetComponent<PrefabIdentifier>().ClassId, System.StringComparison.Ordinal) == 0;
}
public int GetHashCode(GameObject obj) {
return obj.GetComponent<PrefabIdentifier>().ClassId.GetHashCode();
}
#endregion
public static readonly CompareGameObjects Instance = new CompareGameObjects();
}
#endregion
#region Nested type: LevelData
/// <summary>
/// The data stored for a level
/// </summary>
public class LevelData {
/// <summary>
/// The name of the level that was saved
/// </summary>
public string Name;
/// <summary>
/// All of the items that were saved
/// </summary>
public List<StoredData> StoredItems;
/// <summary>
/// All of the names of items saved
/// </summary>
public List<StoredItem> StoredObjectNames;
public string rootObject;
}
#endregion
#region Nested type: ProgressHelper
private class ProgressHelper {
#region ICodeProgress implementation
public void SetProgress(long inSize, long outSize) {
RaiseProgress("Compression", 05f);
}
#endregion
}
#endregion
#region Nested type: SaveEntry
/// <summary>
/// A saved game entry
/// </summary>
public class SaveEntry {
/// <summary>
/// The data about the saved game
/// </summary>
public string Data;
/// <summary>
/// The name of the unity scene
/// </summary>
public string Level;
/// <summary>
/// The name provided for the saved game.
/// </summary>
public string Name;
/// <summary>
/// The time that the game was saved
/// </summary>
public DateTime When;
/// <summary>
/// Initializes a new instance of the <see cref="LevelSerializer.SaveEntry" /> class.
/// </summary>
/// <param name='contents'> The string representing the data of the saved game (use .ToString()) </param>
public SaveEntry(string contents) {
UnitySerializer.DeserializeInto(Convert.FromBase64String(contents), this);
}
public SaveEntry() {
}
/// <summary>
/// Gets the caption.
/// </summary>
/// <value> The caption which is a combination of the name, the level and the time that the game was saved </value>
public string Caption {
get { return string.Format("{0} - {1} - {2:g}", Name, Level, When); }
}
/// <summary>
/// Load this saved game
/// </summary>
public void Load() {
LoadSavedLevel(Data);
}
/// <summary>
/// Delete this saved game
/// </summary>
public void Delete() {
var owner = SavedGames.FirstOrDefault(p => p.Value.Contains(this));
if (owner.Value != null) {
owner.Value.Remove(this);
SaveDataToFilePrefs();
}
}
/// <summary>
/// Returns a <see cref="System.String" /> that represents the current <see cref="LevelSerializer.SaveEntry" />.
/// </summary>
/// <returns> A <see cref="System.String" /> that represents the current <see cref="LevelSerializer.SaveEntry" /> . </returns>
public override string ToString() {
return Convert.ToBase64String(UnitySerializer.Serialize(this));
}
}
#endregion
#region Nested type: SerializationHelper
/// <summary>
/// Checks for the ability to serialize
/// </summary>
public class SerializationHelper : MonoBehaviour {
public string gameName;
public Action<string, bool> perform;
private void Update() {
//Check to see if we are still suspended
if (IsSuspended == false) {
if (perform != null) {
perform(gameName, false);
}
DestroyImmediate(gameObject);
}
}
}
#endregion
#region Nested type: SerializationSuspendedException
public class SerializationSuspendedException : Exception {
public SerializationSuspendedException() : base("Serialization was suspended: " + _suspensionCount + " times") { }
}
#endregion
#region Nested type: StoredData
public class StoredData {
public string ClassId;
public byte[] Data;
public string Name;
public string Type;
}
#endregion
#region Nested type: StoredItem
public class StoredItem {
public bool Active;
public int layer;
public string tag;
public bool setExtraData;
public readonly List<string> ChildIds = new List<string>();
public Dictionary<string, List<string>> Children = new Dictionary<string, List<string>>();
public string ClassId;
public Dictionary<string, bool> Components;
[DoNotSerialize]
public GameObject GameObject;
public string GameObjectName;
public string Name;
public string ParentName;
public bool createEmptyObject;
public override string ToString() {
return string.Format("{0} child of {2} - ({1})", Name, ClassId, ParentName);
}
}
#endregion
}
[ComponentSerializerFor(typeof(Animation))]
public class SerializeAnimations : IComponentSerializer {
#region Nested type: StoredState
public class StoredState {
public byte[] data;
public string name;
public SaveGameManager.AssetReference asset;
}
#endregion
#region IComponentSerializer implementation
public byte[] Serialize(Component component) {
return
UnitySerializer.Serialize(
((Animation)component).Cast<AnimationState>().Select(
a => new StoredState() { data = UnitySerializer.SerializeForDeserializeInto(a), name = a.name, asset = SaveGameManager.Instance.GetAssetId(a.clip) }).
ToList());
}
public void Deserialize(byte[] data, Component instance) {
UnitySerializer.AddFinalAction(() => {
var animation = (Animation)instance;
animation.Stop();
var current = animation.Cast<AnimationState>().ToDictionary(a => a.name);
var list = UnitySerializer.Deserialize<List<StoredState>>(data);
foreach (var entry in list) {
if (entry.asset != null && !current.ContainsKey(entry.name)) {
animation.AddClip(SaveGameManager.Instance.GetAsset(entry.asset) as AnimationClip, entry.name);
}
if (entry.name.Contains(" - Queued Clone")) {
var newState = animation.PlayQueued(entry.name.Replace(" - Queued Clone", ""));
UnitySerializer.DeserializeInto(entry.data, newState);
}
else {
UnitySerializer.DeserializeInto(entry.data, animation[entry.name]);
}
}
});
}
#endregion
}
public static class FieldSerializer {
public static void SerializeFields(Dictionary<string, object> storage, object obj, params string[] names) {
var tp = obj.GetType();
foreach (var name in names) {
var fld = tp.GetField(name,
BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic |
BindingFlags.SetField);
if (fld != null) {
storage[name] = fld.GetValue(obj);
}
}
}
public static void DeserializeFields(Dictionary<string, object> storage, object obj) {
var tp = obj.GetType();
foreach (var p in storage) {
var fld = tp.GetField(p.Key,
BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic |
BindingFlags.SetField);
if (fld != null) {
fld.SetValue(obj, p.Value);
}
}
}
}
| |
/// Copyright (C) 2012-2014 Soomla Inc.
///
/// Licensed under the Apache License, Version 2.0 (the "License");
/// you may not use this file except in compliance with the License.
/// You may obtain a copy of the License at
///
/// http://www.apache.org/licenses/LICENSE-2.0
///
/// Unless required by applicable law or agreed to in writing, software
/// distributed under the License is distributed on an "AS IS" BASIS,
/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
/// See the License for the specific language governing permissions and
/// limitations under the License.
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System;
using System.IO;
using Soomla;
using Soomla.Profile;
using Soomla.Example;
/// <summary>
/// This class contains functions that initialize the game and that display the different screens of the game.
/// </summary>
public class ExampleWindow : MonoBehaviour {
private static ExampleWindow instance = null;
public string fontSuffix = "";
private static bool isVisible = false;
private bool isInit = false;
private Provider targetProvider = Provider.FACEBOOK;
private Reward exampleReward = new BadgeReward("example_reward", "Example Social Reward");
/// <summary>
/// Initializes the game state before the game starts.
/// </summary>
void Awake(){
if(instance == null){ //making sure we only initialize one instance.
instance = this;
GameObject.DontDestroyOnLoad(this.gameObject);
} else { //Destroying unused instances.
GameObject.Destroy(this);
}
//FONT
//using max to be certain we have the longest side of the screen, even if we are in portrait.
if(Mathf.Max(Screen.width, Screen.height) > 640){
fontSuffix = "_2X"; //a nice suffix to show the fonts are twice as big as the original
}
}
private Texture2D tBackground;
private Texture2D tShed;
private Texture2D tBGBar;
private Texture2D tShareDisable;
private Texture2D tShare;
private Texture2D tSharePress;
private Texture2D tShareStoryDisable;
private Texture2D tShareStory;
private Texture2D tShareStoryPress;
private Texture2D tUploadDisable;
private Texture2D tUpload;
private Texture2D tUploadPress;
private Texture2D tConnect;
private Texture2D tConnectPress;
private Texture2D tLogout;
private Texture2D tLogoutPress;
private Font fgoodDog;
// private bool bScreenshot = false;
/// <summary>
/// Starts this instance.
/// Use this for initialization.
/// </summary>
void Start () {
fgoodDog = (Font)Resources.Load("Fonts/GoodDog" + fontSuffix);
tBackground = (Texture2D)Resources.Load("Profile/BG");
tShed = (Texture2D)Resources.Load("Profile/Headline");
tBGBar = (Texture2D)Resources.Load("Profile/BG-Bar");
tShareDisable = (Texture2D)Resources.Load("Profile/BTN-Share-Disable");
tShare = (Texture2D)Resources.Load("Profile/BTN-Share-Normal");
tSharePress = (Texture2D)Resources.Load("Profile/BTN-Share-Press");
tShareStoryDisable = (Texture2D)Resources.Load("Profile/BTN-ShareStory-Disable");
tShareStory = (Texture2D)Resources.Load("Profile/BTN-ShareStory-Normal");
tShareStoryPress = (Texture2D)Resources.Load("Profile/BTN-ShareStory-Press");
tUploadDisable = (Texture2D)Resources.Load("Profile/BTN-Upload-Disable");
tUpload = (Texture2D)Resources.Load("Profile/BTN-Upload-Normal");
tUploadPress = (Texture2D)Resources.Load("Profile/BTN-Upload-Press");
tConnect = (Texture2D)Resources.Load("Profile/BTN-Connect");
tConnectPress = (Texture2D)Resources.Load("Profile/BTN-Connect-Press");
tLogout = (Texture2D)Resources.Load("Profile/BTN-LogOut");
tLogoutPress = (Texture2D)Resources.Load("Profile/BTN-LogOut-Press");
// examples of catching fired events
ProfileEvents.OnSoomlaProfileInitialized += () => {
Soomla.SoomlaUtils.LogDebug("ExampleWindow", "SoomlaProfile Initialized !");
isInit = true;
};
ProfileEvents.OnUserRatingEvent += () => {
Soomla.SoomlaUtils.LogDebug("ExampleWindow", "User opened rating page");
};
ProfileEvents.OnGetScoresFinished += (GetScoresFinishedEvent ev) => {
foreach (Score score in ev.Scores.PageData) {
SoomlaUtils.LogDebug("ExampleWindow", score.Player.ProfileId);
}
};
ProfileEvents.OnGetLeaderboardsFinished += (GetLeaderboardsFinishedEvent ev) => {
SoomlaUtils.LogDebug("ExampleWindow", "leaderboard 1: " + ev.Leaderboards.PageData[0].ID);
SoomlaProfile.GetScores(Provider.GAME_CENTER, ev.Leaderboards.PageData[0]);
};
ProfileEvents.OnLoginFinished += (UserProfile UserProfile, bool autoLogin, string payload) => {
SoomlaUtils.LogDebug("ExampleWindow", "logged in");
SoomlaProfile.GetLeaderboards(Provider.GAME_CENTER);
};
ProfileEvents.OnGetContactsFinished += (Provider provider, SocialPageData<UserProfile> contactsData, string payload) => {
Soomla.SoomlaUtils.LogDebug("ExampleWindow", "get contacts for: " + contactsData.PageData.Count + " page: " + contactsData.PageNumber + " More? " + contactsData.HasMore);
foreach (var profile in contactsData.PageData) {
Soomla.SoomlaUtils.LogDebug("ExampleWindow", "Contact: " + profile.toJSONObject().print());
}
if (contactsData.HasMore) {
SoomlaProfile.GetContacts(targetProvider);
}
};
SoomlaProfile.Initialize();
// SoomlaProfile.OpenAppRatingPage();
#if UNITY_IPHONE
Handheld.SetActivityIndicatorStyle(UnityEngine.iOS.ActivityIndicatorStyle.Gray);
#elif UNITY_ANDROID
Handheld.SetActivityIndicatorStyle(AndroidActivityIndicatorStyle.Small);
#endif
}
/// <summary>
/// Sets the window to open, and sets the GUI state to welcome.
/// </summary>
public static void OpenWindow(){
isVisible = true;
}
/// <summary>
/// Sets the window to closed.
/// </summary>
public static void CloseWindow(){
isVisible = false;
}
/// <summary>
/// Implements the game behavior of MuffinRush.
/// Overrides the superclass function in order to provide functionality for our game.
/// </summary>
void Update () {
if (Application.platform == RuntimePlatform.Android) {
if (Input.GetKeyUp(KeyCode.Escape)) {
//quit application on back button
Application.Quit();
return;
}
}
}
/// <summary>
/// Calls the relevant function to display the correct screen of the game.
/// </summary>
void OnGUI(){
if(!isVisible){
return;
}
GUI.skin.horizontalScrollbar = GUIStyle.none;
GUI.skin.verticalScrollbar = GUIStyle.none;
welcomeScreen();
}
/// <summary>
/// Displays the welcome screen of the game.
/// </summary>
void welcomeScreen()
{
Color backupColor = GUI.color;
float vertGap = 80f;
//drawing background, just using a white pixel here
GUI.DrawTexture(new Rect(0,0,Screen.width,Screen.height),tBackground);
GUI.DrawTexture(new Rect(0,0,Screen.width,timesH(240f)), tShed, ScaleMode.StretchToFill, true);
float rowsTop = 300.0f;
float rowsHeight = 120.0f;
GUI.DrawTexture(new Rect(timesW(65.0f),timesH(rowsTop+10f),timesW(516.0f),timesH(102.0f)), tBGBar, ScaleMode.StretchToFill, true);
if (SoomlaProfile.IsLoggedIn(targetProvider)) {
GUI.skin.button.normal.background = tShare;
GUI.skin.button.hover.background = tShare;
GUI.skin.button.active.background = tSharePress;
if(GUI.Button(new Rect(timesW(50.0f),timesH(rowsTop),timesW(212.0f),timesH(120.0f)), "")){
SoomlaProfile.UpdateStatus(targetProvider, "I LOVE SOOMLA ! http://www.soom.la", null, exampleReward);
}
} else {
GUI.DrawTexture(new Rect(timesW(50.0f),timesH(rowsTop),timesW(212.0f),timesH(120.0f)), tShareDisable,
ScaleMode.StretchToFill, true);
}
GUI.color = Color.black;
GUI.skin.label.font = fgoodDog;
GUI.skin.label.fontSize = 30;
GUI.skin.label.alignment = TextAnchor.MiddleCenter;
GUI.Label(new Rect(timesW(270.0f),timesH(rowsTop),timesW(516.0f-212.0f),timesH(120.0f)),"I Love SOOMLA!");
GUI.color = backupColor;
rowsTop += vertGap + rowsHeight;
GUI.DrawTexture(new Rect(timesW(65.0f),timesH(rowsTop+10f),timesW(516.0f),timesH(102.0f)), tBGBar, ScaleMode.StretchToFill, true);
if (SoomlaProfile.IsLoggedIn(targetProvider)) {
GUI.skin.button.normal.background = tShareStory;
GUI.skin.button.hover.background = tShareStory;
GUI.skin.button.active.background = tShareStoryPress;
if(GUI.Button(new Rect(timesW(50.0f),timesH(rowsTop),timesW(212.0f),timesH(120.0f)), "")){
SoomlaProfile.UpdateStory(targetProvider,
"The story of SOOMBOT (Profile Test App)",
"The story of SOOMBOT (Profile Test App)",
"SOOMBOT Story",
"DESCRIPTION",
"http://about.soom.la/soombots",
"http://about.soom.la/wp-content/uploads/2014/05/330x268-spockbot.png",
null,
exampleReward);
}
} else {
GUI.DrawTexture(new Rect(timesW(50.0f),timesH(rowsTop),timesW(212.0f),timesH(120.0f)), tShareStoryDisable,
ScaleMode.StretchToFill, true);
}
GUI.color = Color.black;
GUI.skin.label.font = fgoodDog;
GUI.skin.label.fontSize = 25;
GUI.skin.label.alignment = TextAnchor.MiddleCenter;
GUI.Label(new Rect(timesW(270.0f),timesH(rowsTop),timesW(516.0f-212.0f),timesH(120.0f)),"Full story of The SOOMBOT!");
GUI.color = backupColor;
rowsTop += vertGap + rowsHeight;
GUI.DrawTexture(new Rect(timesW(65.0f),timesH(rowsTop+10f),timesW(516.0f),timesH(102.0f)), tBGBar, ScaleMode.StretchToFill, true);
if (SoomlaProfile.IsLoggedIn(targetProvider)) {
GUI.skin.button.normal.background = tUpload;
GUI.skin.button.hover.background = tUpload;
GUI.skin.button.active.background = tUploadPress;
if(GUI.Button(new Rect(timesW(50.0f),timesH(rowsTop),timesW(212.0f),timesH(120.0f)), "")){
// string fileName = "soom.jpg";
// string path = "";
//
// #if UNITY_IOS
// path = Application.dataPath + "/Raw/" + fileName;
// #elif UNITY_ANDROID
// path = "jar:file://" + Application.dataPath + "!/assets/" + fileName;
// #endif
//
// byte[] bytes = File.ReadAllBytes(path);
// SoomlaProfile.UploadImage(targetProvider, "Awesome Test App of SOOMLA Profile!", fileName, bytes, 10, null, exampleReward);
SoomlaProfile.UploadCurrentScreenShot(this, targetProvider, "Awesome Test App of SOOMLA Profile!", "This a screenshot of the current state of SOOMLA's test app on my computer.", null);
}
} else {
GUI.DrawTexture(new Rect(timesW(50.0f),timesH(rowsTop),timesW(212.0f),timesH(120.0f)), tUploadDisable,
ScaleMode.StretchToFill, true);
}
GUI.color = Color.black;
GUI.skin.label.font = fgoodDog;
GUI.skin.label.fontSize = 28;
GUI.skin.label.alignment = TextAnchor.MiddleCenter;
GUI.Label(new Rect(timesW(270.0f),timesH(rowsTop),timesW(516.0f-212.0f),timesH(120.0f)),"Current Screenshot");
GUI.color = backupColor;
if (SoomlaProfile.IsLoggedIn(targetProvider)) {
GUI.skin.button.normal.background = tLogout;
GUI.skin.button.hover.background = tLogout;
GUI.skin.button.active.background = tLogoutPress;
if(GUI.Button(new Rect(timesW(20.0f),timesH(950f),timesW(598.0f),timesH(141.0f)), "")){
SoomlaProfile.Logout(targetProvider);
}
} else if (isInit) {
GUI.skin.button.normal.background = tConnect;
GUI.skin.button.hover.background = tConnect;
GUI.skin.button.active.background = tConnectPress;
if(GUI.Button(new Rect(timesW(20.0f),timesH(950f),timesW(598.0f),timesH(141.0f)), "")){
//SoomlaProfile.GetLeaderboards(Provider.GAME_CENTER);
SoomlaProfile.Login(targetProvider, null, exampleReward);
}
}
}
private static string ScreenShotName(int width, int height) {
return string.Format("{0}/screen_{1}x{2}_{3}.png",
Application.persistentDataPath,
width, height,
System.DateTime.Now.ToString("yyyy-MM-dd_HH-mm-ss"));
}
private float timesW(float f) {
return (float)(f/640.0)*Screen.width;
}
private float timesH(float f) {
return (float)(f/1136.0)*Screen.height;
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using log4net;
using Mono.Addins;
using Nini.Config;
using Nwc.XmlRpc;
using OpenSim.Framework.Servers;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Net;
using System.Reflection;
namespace OpenSim.Region.OptionalModules.Avatar.Chat
{
[Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "IRCBridgeModule")]
public class IRCBridgeModule : INonSharedRegionModule
{
internal static bool Enabled = false;
internal static List<ChannelState> m_channels = new List<ChannelState>();
internal static IConfig m_config = null;
internal static string m_password = String.Empty;
internal static List<RegionState> m_regions = new List<RegionState>();
internal RegionState m_region = null;
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
#region INonSharedRegionModule Members
public string Name
{
get { return "IRCBridgeModule"; }
}
public Type ReplaceableInterface
{
get { return null; }
}
public void AddRegion(Scene scene)
{
if (Enabled)
{
try
{
m_log.InfoFormat("[IRC-Bridge] Connecting region {0}", scene.RegionInfo.RegionName);
if (!String.IsNullOrEmpty(m_password))
MainServer.Instance.AddXmlRPCHandler("irc_admin", XmlRpcAdminMethod, false);
m_region = new RegionState(scene, m_config);
lock (m_regions) m_regions.Add(m_region);
m_region.Open();
}
catch (Exception e)
{
m_log.WarnFormat("[IRC-Bridge] Region {0} not connected to IRC : {1}", scene.RegionInfo.RegionName, e.Message);
m_log.Debug(e);
}
}
else
{
//m_log.DebugFormat("[IRC-Bridge] Not enabled. Connect for region {0} ignored", scene.RegionInfo.RegionName);
}
}
public void Close()
{
}
public void Initialise(IConfigSource config)
{
m_config = config.Configs["IRC"];
if (m_config == null)
{
// m_log.InfoFormat("[IRC-Bridge] module not configured");
return;
}
if (!m_config.GetBoolean("enabled", false))
{
// m_log.InfoFormat("[IRC-Bridge] module disabled in configuration");
return;
}
if (config.Configs["RemoteAdmin"] != null)
{
m_password = config.Configs["RemoteAdmin"].GetString("access_password", m_password);
}
Enabled = true;
m_log.InfoFormat("[IRC-Bridge]: Module is enabled");
}
public void RegionLoaded(Scene scene)
{
}
public void RemoveRegion(Scene scene)
{
if (!Enabled)
return;
if (m_region == null)
return;
if (!String.IsNullOrEmpty(m_password))
MainServer.Instance.RemoveXmlRPCHandler("irc_admin");
m_region.Close();
if (m_regions.Contains(m_region))
{
lock (m_regions) m_regions.Remove(m_region);
}
}
#endregion INonSharedRegionModule Members
public static XmlRpcResponse XmlRpcAdminMethod(XmlRpcRequest request, IPEndPoint remoteClient)
{
m_log.Debug("[IRC-Bridge]: XML RPC Admin Entry");
XmlRpcResponse response = new XmlRpcResponse();
Hashtable responseData = new Hashtable();
try
{
Hashtable requestData = (Hashtable)request.Params[0];
bool found = false;
string region = String.Empty;
if (m_password != String.Empty)
{
if (!requestData.ContainsKey("password"))
throw new Exception("Invalid request");
if ((string)requestData["password"] != m_password)
throw new Exception("Invalid request");
}
if (!requestData.ContainsKey("region"))
throw new Exception("No region name specified");
region = (string)requestData["region"];
foreach (RegionState rs in m_regions)
{
if (rs.Region == region)
{
responseData["server"] = rs.cs.Server;
responseData["port"] = (int)rs.cs.Port;
responseData["user"] = rs.cs.User;
responseData["channel"] = rs.cs.IrcChannel;
responseData["enabled"] = rs.cs.irc.Enabled;
responseData["connected"] = rs.cs.irc.Connected;
responseData["nickname"] = rs.cs.irc.Nick;
found = true;
break;
}
}
if (!found) throw new Exception(String.Format("Region <{0}> not found", region));
responseData["success"] = true;
}
catch (Exception e)
{
m_log.ErrorFormat("[IRC-Bridge] XML RPC Admin request failed : {0}", e.Message);
responseData["success"] = "false";
responseData["error"] = e.Message;
}
finally
{
response.Value = responseData;
}
m_log.Debug("[IRC-Bridge]: XML RPC Admin Exit");
return response;
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator 0.17.0.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Management.MachineLearning.WebServices
{
using System.Threading.Tasks;
using Microsoft.Rest.Azure;
using Models;
/// <summary>
/// Extension methods for WebServicesOperations.
/// </summary>
public static partial class WebServicesOperationsExtensions
{
/// <summary>
/// Creates or updates a new Azure ML web service or update an existing one.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='createOrUpdatePayload'>
/// The payload to create or update the Azure ML web service.
/// </param>
/// <param name='resourceGroupName'>
/// Name of the resource group.
/// </param>
/// <param name='webServiceName'>
/// The Azure ML web service name which you want to reach.
/// </param>
public static WebService CreateOrUpdate(this IWebServicesOperations operations, WebService createOrUpdatePayload, string resourceGroupName, string webServiceName)
{
return System.Threading.Tasks.Task.Factory.StartNew(s => ((IWebServicesOperations)s).CreateOrUpdateAsync(createOrUpdatePayload, resourceGroupName, webServiceName), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Creates or updates a new Azure ML web service or update an existing one.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='createOrUpdatePayload'>
/// The payload to create or update the Azure ML web service.
/// </param>
/// <param name='resourceGroupName'>
/// Name of the resource group.
/// </param>
/// <param name='webServiceName'>
/// The Azure ML web service name which you want to reach.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async System.Threading.Tasks.Task<WebService> CreateOrUpdateAsync(this IWebServicesOperations operations, WebService createOrUpdatePayload, string resourceGroupName, string webServiceName, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
using (var _result = await operations.CreateOrUpdateWithHttpMessagesAsync(createOrUpdatePayload, resourceGroupName, webServiceName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Creates or updates a new Azure ML web service or update an existing one.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='createOrUpdatePayload'>
/// The payload to create or update the Azure ML web service.
/// </param>
/// <param name='resourceGroupName'>
/// Name of the resource group.
/// </param>
/// <param name='webServiceName'>
/// The Azure ML web service name which you want to reach.
/// </param>
public static WebService BeginCreateOrUpdate(this IWebServicesOperations operations, WebService createOrUpdatePayload, string resourceGroupName, string webServiceName)
{
return System.Threading.Tasks.Task.Factory.StartNew(s => ((IWebServicesOperations)s).BeginCreateOrUpdateAsync(createOrUpdatePayload, resourceGroupName, webServiceName), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Creates or updates a new Azure ML web service or update an existing one.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='createOrUpdatePayload'>
/// The payload to create or update the Azure ML web service.
/// </param>
/// <param name='resourceGroupName'>
/// Name of the resource group.
/// </param>
/// <param name='webServiceName'>
/// The Azure ML web service name which you want to reach.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async System.Threading.Tasks.Task<WebService> BeginCreateOrUpdateAsync(this IWebServicesOperations operations, WebService createOrUpdatePayload, string resourceGroupName, string webServiceName, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
using (var _result = await operations.BeginCreateOrUpdateWithHttpMessagesAsync(createOrUpdatePayload, resourceGroupName, webServiceName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Retrieve an Azure ML web service definition by its subscription, resource
/// group and name.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// Name of the resource group.
/// </param>
/// <param name='webServiceName'>
/// The Azure ML web service name which you want to reach.
/// </param>
public static WebService Get(this IWebServicesOperations operations, string resourceGroupName, string webServiceName)
{
return System.Threading.Tasks.Task.Factory.StartNew(s => ((IWebServicesOperations)s).GetAsync(resourceGroupName, webServiceName), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Retrieve an Azure ML web service definition by its subscription, resource
/// group and name.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// Name of the resource group.
/// </param>
/// <param name='webServiceName'>
/// The Azure ML web service name which you want to reach.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async System.Threading.Tasks.Task<WebService> GetAsync(this IWebServicesOperations operations, string resourceGroupName, string webServiceName, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
using (var _result = await operations.GetWithHttpMessagesAsync(resourceGroupName, webServiceName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Patch an existing Azure ML web service resource.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='patchPayload'>
/// The payload to patch the Azure ML web service with.
/// </param>
/// <param name='resourceGroupName'>
/// Name of the resource group.
/// </param>
/// <param name='webServiceName'>
/// The Azure ML web service name which you want to reach.
/// </param>
public static WebService Patch(this IWebServicesOperations operations, WebService patchPayload, string resourceGroupName, string webServiceName)
{
return System.Threading.Tasks.Task.Factory.StartNew(s => ((IWebServicesOperations)s).PatchAsync(patchPayload, resourceGroupName, webServiceName), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Patch an existing Azure ML web service resource.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='patchPayload'>
/// The payload to patch the Azure ML web service with.
/// </param>
/// <param name='resourceGroupName'>
/// Name of the resource group.
/// </param>
/// <param name='webServiceName'>
/// The Azure ML web service name which you want to reach.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async System.Threading.Tasks.Task<WebService> PatchAsync(this IWebServicesOperations operations, WebService patchPayload, string resourceGroupName, string webServiceName, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
using (var _result = await operations.PatchWithHttpMessagesAsync(patchPayload, resourceGroupName, webServiceName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Patch an existing Azure ML web service resource.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='patchPayload'>
/// The payload to patch the Azure ML web service with.
/// </param>
/// <param name='resourceGroupName'>
/// Name of the resource group.
/// </param>
/// <param name='webServiceName'>
/// The Azure ML web service name which you want to reach.
/// </param>
public static WebService BeginPatch(this IWebServicesOperations operations, WebService patchPayload, string resourceGroupName, string webServiceName)
{
return System.Threading.Tasks.Task.Factory.StartNew(s => ((IWebServicesOperations)s).BeginPatchAsync(patchPayload, resourceGroupName, webServiceName), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Patch an existing Azure ML web service resource.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='patchPayload'>
/// The payload to patch the Azure ML web service with.
/// </param>
/// <param name='resourceGroupName'>
/// Name of the resource group.
/// </param>
/// <param name='webServiceName'>
/// The Azure ML web service name which you want to reach.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async System.Threading.Tasks.Task<WebService> BeginPatchAsync(this IWebServicesOperations operations, WebService patchPayload, string resourceGroupName, string webServiceName, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
using (var _result = await operations.BeginPatchWithHttpMessagesAsync(patchPayload, resourceGroupName, webServiceName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Remove an existing Azure ML web service.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// Name of the resource group.
/// </param>
/// <param name='webServiceName'>
/// The Azure ML web service name which you want to reach.
/// </param>
public static void Remove(this IWebServicesOperations operations, string resourceGroupName, string webServiceName)
{
System.Threading.Tasks.Task.Factory.StartNew(s => ((IWebServicesOperations)s).RemoveAsync(resourceGroupName, webServiceName), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Remove an existing Azure ML web service.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// Name of the resource group.
/// </param>
/// <param name='webServiceName'>
/// The Azure ML web service name which you want to reach.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async System.Threading.Tasks.Task RemoveAsync(this IWebServicesOperations operations, string resourceGroupName, string webServiceName, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
await operations.RemoveWithHttpMessagesAsync(resourceGroupName, webServiceName, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Remove an existing Azure ML web service.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// Name of the resource group.
/// </param>
/// <param name='webServiceName'>
/// The Azure ML web service name which you want to reach.
/// </param>
public static void BeginRemove(this IWebServicesOperations operations, string resourceGroupName, string webServiceName)
{
System.Threading.Tasks.Task.Factory.StartNew(s => ((IWebServicesOperations)s).BeginRemoveAsync(resourceGroupName, webServiceName), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Remove an existing Azure ML web service.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// Name of the resource group.
/// </param>
/// <param name='webServiceName'>
/// The Azure ML web service name which you want to reach.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async System.Threading.Tasks.Task BeginRemoveAsync(this IWebServicesOperations operations, string resourceGroupName, string webServiceName, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
await operations.BeginRemoveWithHttpMessagesAsync(resourceGroupName, webServiceName, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Get the access keys of a particular Azure ML web service
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// Name of the resource group.
/// </param>
/// <param name='webServiceName'>
/// The Azure ML web service name which you want to reach.
/// </param>
public static WebServiceKeys ListKeys(this IWebServicesOperations operations, string resourceGroupName, string webServiceName)
{
return System.Threading.Tasks.Task.Factory.StartNew(s => ((IWebServicesOperations)s).ListKeysAsync(resourceGroupName, webServiceName), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Get the access keys of a particular Azure ML web service
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// Name of the resource group.
/// </param>
/// <param name='webServiceName'>
/// The Azure ML web service name which you want to reach.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async System.Threading.Tasks.Task<WebServiceKeys> ListKeysAsync(this IWebServicesOperations operations, string resourceGroupName, string webServiceName, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
using (var _result = await operations.ListKeysWithHttpMessagesAsync(resourceGroupName, webServiceName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Retrieve all Azure ML web services in a given resource group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// Name of the resource group.
/// </param>
/// <param name='skiptoken'>
/// Continuation token for pagination.
/// </param>
public static PaginatedWebServicesList ListInResourceGroup(this IWebServicesOperations operations, string resourceGroupName, string skiptoken = default(string))
{
return System.Threading.Tasks.Task.Factory.StartNew(s => ((IWebServicesOperations)s).ListInResourceGroupAsync(resourceGroupName, skiptoken), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Retrieve all Azure ML web services in a given resource group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// Name of the resource group.
/// </param>
/// <param name='skiptoken'>
/// Continuation token for pagination.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async System.Threading.Tasks.Task<PaginatedWebServicesList> ListInResourceGroupAsync(this IWebServicesOperations operations, string resourceGroupName, string skiptoken = default(string), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
using (var _result = await operations.ListInResourceGroupWithHttpMessagesAsync(resourceGroupName, skiptoken, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Retrieve all Azure ML web services in the current Azure subscription.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='skiptoken'>
/// Continuation token for pagination.
/// </param>
public static PaginatedWebServicesList List(this IWebServicesOperations operations, string skiptoken = default(string))
{
return System.Threading.Tasks.Task.Factory.StartNew(s => ((IWebServicesOperations)s).ListAsync(skiptoken), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Retrieve all Azure ML web services in the current Azure subscription.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='skiptoken'>
/// Continuation token for pagination.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async System.Threading.Tasks.Task<PaginatedWebServicesList> ListAsync(this IWebServicesOperations operations, string skiptoken = default(string), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
using (var _result = await operations.ListWithHttpMessagesAsync(skiptoken, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
}
}
| |
namespace RunfileEditor
{
partial class frmContainer
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.tabControl1 = new System.Windows.Forms.TabControl();
this.tabPage1 = new System.Windows.Forms.TabPage();
this.label4 = new System.Windows.Forms.Label();
this.label2 = new System.Windows.Forms.Label();
this.listViewErrors = new System.Windows.Forms.ListView();
this.pictureBox1 = new System.Windows.Forms.PictureBox();
this.label3 = new System.Windows.Forms.Label();
this.label1 = new System.Windows.Forms.Label();
this.OpenXMLRunfile = new System.Windows.Forms.Button();
this.OpenFile = new System.Windows.Forms.Button();
this.SendFileXMLToEFI = new System.Windows.Forms.Button();
this.SaveXMLRunfile = new System.Windows.Forms.Button();
this.menuStrip2 = new System.Windows.Forms.MenuStrip();
this.toolStripMenuItem2 = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripMenuItem3 = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripMenuItem4 = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripMenuItem5 = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripMenuItem6 = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripMenuItem13 = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripMenuItem14 = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripMenuItem15 = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripMenuItem16 = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripMenuItem17 = new System.Windows.Forms.ToolStripMenuItem();
this.tabControl1.SuspendLayout();
this.tabPage1.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).BeginInit();
this.menuStrip2.SuspendLayout();
this.SuspendLayout();
//
// tabControl1
//
this.tabControl1.AllowDrop = true;
this.tabControl1.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.tabControl1.Controls.Add(this.tabPage1);
this.tabControl1.Location = new System.Drawing.Point(12, 27);
this.tabControl1.Name = "tabControl1";
this.tabControl1.SelectedIndex = 0;
this.tabControl1.Size = new System.Drawing.Size(1024, 512);
this.tabControl1.TabIndex = 0;
//
// tabPage1
//
this.tabPage1.Controls.Add(this.label4);
this.tabPage1.Controls.Add(this.label2);
this.tabPage1.Controls.Add(this.listViewErrors);
this.tabPage1.Controls.Add(this.pictureBox1);
this.tabPage1.Controls.Add(this.label3);
this.tabPage1.Controls.Add(this.label1);
this.tabPage1.Controls.Add(this.OpenXMLRunfile);
this.tabPage1.Controls.Add(this.OpenFile);
this.tabPage1.Controls.Add(this.SendFileXMLToEFI);
this.tabPage1.Controls.Add(this.SaveXMLRunfile);
this.tabPage1.Location = new System.Drawing.Point(4, 22);
this.tabPage1.Name = "tabPage1";
this.tabPage1.Padding = new System.Windows.Forms.Padding(3);
this.tabPage1.Size = new System.Drawing.Size(1016, 486);
this.tabPage1.TabIndex = 0;
this.tabPage1.Text = "GUI Home";
this.tabPage1.UseVisualStyleBackColor = true;
//
// label4
//
this.label4.AutoSize = true;
this.label4.Location = new System.Drawing.Point(56, 249);
this.label4.Name = "label4";
this.label4.Size = new System.Drawing.Size(35, 13);
this.label4.TabIndex = 19;
this.label4.Text = "label4";
//
// label2
//
this.label2.AutoSize = true;
this.label2.Location = new System.Drawing.Point(393, 37);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(35, 13);
this.label2.TabIndex = 18;
this.label2.Text = "label2";
//
// listViewErrors
//
this.listViewErrors.Location = new System.Drawing.Point(16, 281);
this.listViewErrors.MultiSelect = false;
this.listViewErrors.Name = "listViewErrors";
this.listViewErrors.Size = new System.Drawing.Size(994, 200);
this.listViewErrors.TabIndex = 0;
this.listViewErrors.UseCompatibleStateImageBehavior = false;
this.listViewErrors.View = System.Windows.Forms.View.List;
//
// pictureBox1
//
this.pictureBox1.Location = new System.Drawing.Point(698, 37);
this.pictureBox1.Name = "pictureBox1";
this.pictureBox1.Size = new System.Drawing.Size(252, 187);
this.pictureBox1.TabIndex = 17;
this.pictureBox1.TabStop = false;
this.pictureBox1.Click += new System.EventHandler(this.pictureBox1_Click);
//
// label3
//
this.label3.AutoSize = true;
this.label3.Location = new System.Drawing.Point(754, 4);
this.label3.Name = "label3";
this.label3.Size = new System.Drawing.Size(130, 13);
this.label3.TabIndex = 15;
this.label3.Text = "Small Picture of the Model";
//
// label1
//
this.label1.AutoSize = true;
this.label1.Location = new System.Drawing.Point(56, 37);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(173, 13);
this.label1.TabIndex = 11;
this.label1.Text = "Open XML Runfile document from :";
//
// OpenXMLRunfile
//
this.OpenXMLRunfile.Cursor = System.Windows.Forms.Cursors.Arrow;
this.OpenXMLRunfile.Location = new System.Drawing.Point(16, 70);
this.OpenXMLRunfile.Name = "OpenXMLRunfile";
this.OpenXMLRunfile.Size = new System.Drawing.Size(254, 53);
this.OpenXMLRunfile.TabIndex = 7;
this.OpenXMLRunfile.Text = "Open Runfile Document";
this.OpenXMLRunfile.UseVisualStyleBackColor = true;
this.OpenXMLRunfile.Click += new System.EventHandler(this.OpenFile_Click);
//
// OpenFile
//
this.OpenFile.Location = new System.Drawing.Point(17, 185);
this.OpenFile.Name = "OpenFile";
this.OpenFile.Size = new System.Drawing.Size(254, 50);
this.OpenFile.TabIndex = 3;
this.OpenFile.Text = "Exit Runfile Editor";
this.OpenFile.UseVisualStyleBackColor = true;
this.OpenFile.Click += new System.EventHandler(this.Exit_Click);
//
// SendFileXMLToEFI
//
this.SendFileXMLToEFI.Location = new System.Drawing.Point(288, 70);
this.SendFileXMLToEFI.Name = "SendFileXMLToEFI";
this.SendFileXMLToEFI.Size = new System.Drawing.Size(254, 53);
this.SendFileXMLToEFI.TabIndex = 2;
this.SendFileXMLToEFI.Text = "Send Runfile to Earlab";
this.SendFileXMLToEFI.UseVisualStyleBackColor = true;
this.SendFileXMLToEFI.Click += new System.EventHandler(this.SendFileXMLToEFI_Click);
//
// SaveXMLRunfile
//
this.SaveXMLRunfile.Location = new System.Drawing.Point(16, 129);
this.SaveXMLRunfile.Name = "SaveXMLRunfile";
this.SaveXMLRunfile.Size = new System.Drawing.Size(254, 50);
this.SaveXMLRunfile.TabIndex = 1;
this.SaveXMLRunfile.Text = "Save XML Runfile";
this.SaveXMLRunfile.UseVisualStyleBackColor = true;
this.SaveXMLRunfile.Click += new System.EventHandler(this.SaveXMLFile_Click);
//
// menuStrip2
//
this.menuStrip2.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.toolStripMenuItem2,
this.toolStripMenuItem6,
this.toolStripMenuItem16});
this.menuStrip2.Location = new System.Drawing.Point(0, 0);
this.menuStrip2.Name = "menuStrip2";
this.menuStrip2.Size = new System.Drawing.Size(1048, 24);
this.menuStrip2.TabIndex = 2;
this.menuStrip2.Text = "menuStrip2";
//
// toolStripMenuItem2
//
this.toolStripMenuItem2.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.toolStripMenuItem3,
this.toolStripMenuItem4,
this.toolStripMenuItem5});
this.toolStripMenuItem2.Name = "toolStripMenuItem2";
this.toolStripMenuItem2.Size = new System.Drawing.Size(70, 20);
this.toolStripMenuItem2.Text = "Earlab GUI";
//
// toolStripMenuItem3
//
this.toolStripMenuItem3.Name = "toolStripMenuItem3";
this.toolStripMenuItem3.Size = new System.Drawing.Size(139, 22);
this.toolStripMenuItem3.Text = "About";
//
// toolStripMenuItem4
//
this.toolStripMenuItem4.Name = "toolStripMenuItem4";
this.toolStripMenuItem4.Size = new System.Drawing.Size(139, 22);
this.toolStripMenuItem4.Text = "Online Help";
//
// toolStripMenuItem5
//
this.toolStripMenuItem5.Name = "toolStripMenuItem5";
this.toolStripMenuItem5.Size = new System.Drawing.Size(139, 22);
this.toolStripMenuItem5.Text = "Exit";
this.toolStripMenuItem5.Click += new System.EventHandler(this.exitToolStripMenuItem_Click);
//
// toolStripMenuItem6
//
this.toolStripMenuItem6.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.toolStripMenuItem13,
this.toolStripMenuItem14,
this.toolStripMenuItem15});
this.toolStripMenuItem6.Name = "toolStripMenuItem6";
this.toolStripMenuItem6.Size = new System.Drawing.Size(35, 20);
this.toolStripMenuItem6.Text = "File";
//
// toolStripMenuItem13
//
this.toolStripMenuItem13.Name = "toolStripMenuItem13";
this.toolStripMenuItem13.Size = new System.Drawing.Size(197, 22);
this.toolStripMenuItem13.Text = "Open Saved Run File...";
this.toolStripMenuItem13.Click += new System.EventHandler(this.openSavedRunfileToolStripMenuItem_Click);
//
// toolStripMenuItem14
//
this.toolStripMenuItem14.Name = "toolStripMenuItem14";
this.toolStripMenuItem14.Size = new System.Drawing.Size(197, 22);
this.toolStripMenuItem14.Text = "Save";
//
// toolStripMenuItem15
//
this.toolStripMenuItem15.Name = "toolStripMenuItem15";
this.toolStripMenuItem15.Size = new System.Drawing.Size(197, 22);
this.toolStripMenuItem15.Text = "Save As...";
//
// toolStripMenuItem16
//
this.toolStripMenuItem16.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.toolStripMenuItem17});
this.toolStripMenuItem16.Name = "toolStripMenuItem16";
this.toolStripMenuItem16.Size = new System.Drawing.Size(40, 20);
this.toolStripMenuItem16.Text = "Help";
//
// toolStripMenuItem17
//
this.toolStripMenuItem17.Name = "toolStripMenuItem17";
this.toolStripMenuItem17.Size = new System.Drawing.Size(139, 22);
this.toolStripMenuItem17.Text = "Earlab Help";
//
// frmContainer
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(1048, 564);
this.Controls.Add(this.menuStrip2);
this.Controls.Add(this.tabControl1);
this.IsMdiContainer = true;
this.Name = "frmContainer";
this.Text = "Earlab GUI version .7";
this.tabControl1.ResumeLayout(false);
this.tabPage1.ResumeLayout(false);
this.tabPage1.PerformLayout();
((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).EndInit();
this.menuStrip2.ResumeLayout(false);
this.menuStrip2.PerformLayout();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
public void button_create_if_no_errors()
{
this.button1 = new System.Windows.Forms.Button();
//
// button1
//
this.tabPage1.Controls.Add(this.button1);
this.button1.Location = new System.Drawing.Point(288, 185);
this.button1.Name = "button1";
this.button1.Size = new System.Drawing.Size(254, 50);
this.button1.TabIndex = 18;
this.button1.Text = "Only Appear if No Errors";
this.button1.UseVisualStyleBackColor = true;
this.button1.Click += new System.EventHandler(this.DesktopEarlabLaunch_Click);
}
public void remove_button()
{
this.tabPage1.Controls.Remove(this.button1);
}
//private void create_abstract_tab()
//{
// this.tabPage2 = new System.Windows.Forms.TabPage();
// this.tabPage2.SuspendLayout();
// ((System.ComponentModel.ISupportInitialize)(this.pictureBox2)).BeginInit();
// //
// // tabPage2
// //
// this.tabPage2.Controls.Add(this.label5);
// this.tabPage2.Controls.Add(this.label4);
// this.tabPage2.Controls.Add(this.textBox1);
// this.tabPage2.Controls.Add(this.pictureBox2);
// this.tabPage2.Location = new System.Drawing.Point(4, 22);
// this.tabPage2.Name = "tabPage2";
// this.tabPage2.Padding = new System.Windows.Forms.Padding(3);
// this.tabPage2.Size = new System.Drawing.Size(1016, 486);
// this.tabPage2.TabIndex = 1;
// this.tabPage2.Text = "tabPage2";
// this.tabPage2.UseVisualStyleBackColor = true;
// this.label5 = new System.Windows.Forms.Label();
// this.label4 = new System.Windows.Forms.Label();
//System.Windows.Forms.TabPage tabPage2;
//System.Windows.Forms.TextBox textBox1;
//System.Windows.Forms.PictureBox pictureBox2;
//System.Windows.Forms.Label label5;
//System.Windows.Forms.Label label4;
////
//// label5
////
//this.label5.AutoSize = true;
//this.label5.Location = new System.Drawing.Point(579, 42);
//this.label5.Name = "label5";
//this.label5.Size = new System.Drawing.Size(35, 13);
//this.label5.TabIndex = 8;
//this.label5.Text = "label5";
////
//// label4
////
//this.label4.AutoSize = true;
//this.label4.Location = new System.Drawing.Point(579, 16);
//this.label4.Name = "label4";
//this.label4.Size = new System.Drawing.Size(35, 13);
//this.label4.TabIndex = 7;
//this.label4.Text = "label4";
////
//// textBox1
////
//this.textBox1.Location = new System.Drawing.Point(579, 102);
//this.textBox1.Multiline = true;
//this.textBox1.Name = "textBox1";
//this.textBox1.Size = new System.Drawing.Size(359, 345);
//this.textBox1.TabIndex = 6;
////
//// pictureBox2
////
//this.pictureBox2.Location = new System.Drawing.Point(23, 16);
//this.pictureBox2.Name = "pictureBox2";
//this.pictureBox2.Size = new System.Drawing.Size(524, 437);
//this.pictureBox2.TabIndex = 4;
//this.pictureBox2.TabStop = false;
//this.tabPage2.ResumeLayout(false);
//this.tabPage2.PerformLayout();
//((System.ComponentModel.ISupportInitialize)(this.pictureBox2)).EndInit();
//}
private System.Windows.Forms.TabControl tabControl1;
private System.Windows.Forms.TabPage tabPage1;
private System.Windows.Forms.Button OpenFile;
private System.Windows.Forms.Button SendFileXMLToEFI;
private System.Windows.Forms.Button SaveXMLRunfile;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.Button OpenXMLRunfile;
private System.Windows.Forms.Label label3;
private System.Windows.Forms.PictureBox pictureBox1;
private System.Windows.Forms.MenuStrip menuStrip2;
private System.Windows.Forms.ToolStripMenuItem toolStripMenuItem2;
private System.Windows.Forms.ToolStripMenuItem toolStripMenuItem3;
private System.Windows.Forms.ToolStripMenuItem toolStripMenuItem4;
private System.Windows.Forms.ToolStripMenuItem toolStripMenuItem5;
private System.Windows.Forms.ToolStripMenuItem toolStripMenuItem6;
private System.Windows.Forms.ToolStripMenuItem toolStripMenuItem13;
private System.Windows.Forms.ToolStripMenuItem toolStripMenuItem14;
private System.Windows.Forms.ToolStripMenuItem toolStripMenuItem15;
private System.Windows.Forms.ToolStripMenuItem toolStripMenuItem16;
private System.Windows.Forms.ToolStripMenuItem toolStripMenuItem17;
public System.Windows.Forms.Button button1;
private System.Windows.Forms.Label label2;
private System.Windows.Forms.Label label4;
}
}
| |
/*
* Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;
namespace Amazon.RDS.Model
{
/// <summary>
/// <para> This data type is used as a response element in the action DescribeDBEngineVersions. </para>
/// </summary>
public class DBEngineVersion
{
private string engine;
private string engineVersion;
private string dBParameterGroupFamily;
private string dBEngineDescription;
private string dBEngineVersionDescription;
private CharacterSet defaultCharacterSet;
private List<CharacterSet> supportedCharacterSets = new List<CharacterSet>();
/// <summary>
/// The name of the database engine.
///
/// </summary>
public string Engine
{
get { return this.engine; }
set { this.engine = value; }
}
/// <summary>
/// Sets the Engine property
/// </summary>
/// <param name="engine">The value to set for the Engine property </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public DBEngineVersion WithEngine(string engine)
{
this.engine = engine;
return this;
}
// Check to see if Engine property is set
internal bool IsSetEngine()
{
return this.engine != null;
}
/// <summary>
/// The version number of the database engine.
///
/// </summary>
public string EngineVersion
{
get { return this.engineVersion; }
set { this.engineVersion = value; }
}
/// <summary>
/// Sets the EngineVersion property
/// </summary>
/// <param name="engineVersion">The value to set for the EngineVersion property </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public DBEngineVersion WithEngineVersion(string engineVersion)
{
this.engineVersion = engineVersion;
return this;
}
// Check to see if EngineVersion property is set
internal bool IsSetEngineVersion()
{
return this.engineVersion != null;
}
/// <summary>
/// The name of the DBParameterGroupFamily for the database engine.
///
/// </summary>
public string DBParameterGroupFamily
{
get { return this.dBParameterGroupFamily; }
set { this.dBParameterGroupFamily = value; }
}
/// <summary>
/// Sets the DBParameterGroupFamily property
/// </summary>
/// <param name="dBParameterGroupFamily">The value to set for the DBParameterGroupFamily property </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public DBEngineVersion WithDBParameterGroupFamily(string dBParameterGroupFamily)
{
this.dBParameterGroupFamily = dBParameterGroupFamily;
return this;
}
// Check to see if DBParameterGroupFamily property is set
internal bool IsSetDBParameterGroupFamily()
{
return this.dBParameterGroupFamily != null;
}
/// <summary>
/// The description of the database engine.
///
/// </summary>
public string DBEngineDescription
{
get { return this.dBEngineDescription; }
set { this.dBEngineDescription = value; }
}
/// <summary>
/// Sets the DBEngineDescription property
/// </summary>
/// <param name="dBEngineDescription">The value to set for the DBEngineDescription property </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public DBEngineVersion WithDBEngineDescription(string dBEngineDescription)
{
this.dBEngineDescription = dBEngineDescription;
return this;
}
// Check to see if DBEngineDescription property is set
internal bool IsSetDBEngineDescription()
{
return this.dBEngineDescription != null;
}
/// <summary>
/// The description of the database engine version.
///
/// </summary>
public string DBEngineVersionDescription
{
get { return this.dBEngineVersionDescription; }
set { this.dBEngineVersionDescription = value; }
}
/// <summary>
/// Sets the DBEngineVersionDescription property
/// </summary>
/// <param name="dBEngineVersionDescription">The value to set for the DBEngineVersionDescription property </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public DBEngineVersion WithDBEngineVersionDescription(string dBEngineVersionDescription)
{
this.dBEngineVersionDescription = dBEngineVersionDescription;
return this;
}
// Check to see if DBEngineVersionDescription property is set
internal bool IsSetDBEngineVersionDescription()
{
return this.dBEngineVersionDescription != null;
}
/// <summary>
/// The default character set for new instances of this engine version, if the <c>CharacterSetName</c> parameter of the CreateDBInstance API is
/// not specified.
///
/// </summary>
public CharacterSet DefaultCharacterSet
{
get { return this.defaultCharacterSet; }
set { this.defaultCharacterSet = value; }
}
/// <summary>
/// Sets the DefaultCharacterSet property
/// </summary>
/// <param name="defaultCharacterSet">The value to set for the DefaultCharacterSet property </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public DBEngineVersion WithDefaultCharacterSet(CharacterSet defaultCharacterSet)
{
this.defaultCharacterSet = defaultCharacterSet;
return this;
}
// Check to see if DefaultCharacterSet property is set
internal bool IsSetDefaultCharacterSet()
{
return this.defaultCharacterSet != null;
}
/// <summary>
/// A list of the character sets supported by this engine for the <c>CharacterSetName</c> parameter of the CreateDBInstance API.
///
/// </summary>
public List<CharacterSet> SupportedCharacterSets
{
get { return this.supportedCharacterSets; }
set { this.supportedCharacterSets = value; }
}
/// <summary>
/// Adds elements to the SupportedCharacterSets collection
/// </summary>
/// <param name="supportedCharacterSets">The values to add to the SupportedCharacterSets collection </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public DBEngineVersion WithSupportedCharacterSets(params CharacterSet[] supportedCharacterSets)
{
foreach (CharacterSet element in supportedCharacterSets)
{
this.supportedCharacterSets.Add(element);
}
return this;
}
/// <summary>
/// Adds elements to the SupportedCharacterSets collection
/// </summary>
/// <param name="supportedCharacterSets">The values to add to the SupportedCharacterSets collection </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public DBEngineVersion WithSupportedCharacterSets(IEnumerable<CharacterSet> supportedCharacterSets)
{
foreach (CharacterSet element in supportedCharacterSets)
{
this.supportedCharacterSets.Add(element);
}
return this;
}
// Check to see if SupportedCharacterSets property is set
internal bool IsSetSupportedCharacterSets()
{
return this.supportedCharacterSets.Count > 0;
}
}
}
| |
/*
Copyright 2006 - 2010 Intel Corporation
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
using System;
using System.Collections;
using OpenSource.UPnP;
namespace UPnPValidator
{
public sealed class TestQueue
{
public TestQueue(ICollection subTests, ISubTestArgument arg)
{
foreach (ISubTest sub in subTests)
{
AddTest(sub);
}
Arg = arg;
}
public void RunQueue()
{
Arg.TestGroup.state = UPnPTestStates.Running;
UPnPService[] services = Arg.Device.Services;
UPnPServiceWatcher[] watchers = new UPnPServiceWatcher[services.Length];
for (int i=0; i < services.Length; i++)
{
//watchers[i] = new UPnPServiceWatcher(services[i], null, new UPnPServiceWatcher.SniffPacketHandler(this.SniffPacketSink));
}
foreach (ISubTest sub in Q.Values)
{
Arg.TestGroup.SetState(sub.Name, UPnPTestStates.Running);
bool cont = true;
foreach (SubTest pre1 in sub.Prerequisites)
{
pre1.CalculateExpectedTestingTime(Q.Values, Arg);
ISubTest pre = null;
foreach (ISubTest pre2 in Q.Values)
{
if (pre2.Name == pre1.Name)
{
pre = pre2;
}
}
if (
(!
(pre.TestState == UPnPTestStates.Pass) ||
(pre.TestState == UPnPTestStates.Warn)
)
)
{
cont = false;
}
}
this.UpdateTimeAndProgress(0);
if (cont)
{
UPnPTestStates result = sub.Run(Q.Values, Arg);
Arg.TestGroup.SetState(sub.Name, result);
if (sub.TestState != result)
{
throw new ApplicationException("Test state does not match the set value.");
}
}
this.UpdateTimeAndProgress(0);
}
UPnPTestStates MasterResult = UPnPTestStates.Pass;
foreach (ISubTest done in Q.Values)
{
if (done.TestState > MasterResult)
{
MasterResult = done.TestState;
break;
}
}
for (int i=0; i < services.Length; i++)
{
//watchers[i].OnSniffPacket -= new UPnPServiceWatcher.SniffPacketHandler(this.SniffPacketSink);
}
Arg.TestGroup.state = MasterResult;
}
/// <summary>
/// Logs packets.
/// </summary>
/// <param name="sender"></param>
/// <param name="MSG"></param>
private void SniffPacketSink(UPnPServiceWatcher sender, HTTPMessage MSG)
{
this.Arg.TestGroup.AddPacket(MSG);
}
/// <summary>
/// <see cref="ISubTest"/> objects can call this method
/// to start a countdown timer and progress bar info. The
/// method should be called regularly after the completion
/// of a subtest and also when a subtest wants to update its
/// progress with finer granularity.
///
/// <para>
/// Method updates the TotalTime property using the <see cref="ISubTest.TestingTime"/>
/// values of all tests in the group.
/// </para>
///
/// <para>
/// Progress is determined by the sum of <see cref="ISubTest.TestingTime"/>
/// values of completed subtests and the "secondOffsetForCurrentSubTest"
/// value.
/// </para>
/// </summary>
/// <param name="secondOffsetForCurrentSubTest">
/// This value should be zero unless an actively executing subtest wants to report
/// additional progress within itself, in which case the value should reflect
/// the total number of elapsed seconds (in terms of total test time).
/// </param>
public void UpdateTimeAndProgress(int secondOffsetForCurrentSubTest)
{
int elapsed = 0;
m_TotalTime = 0;
foreach (ISubTest test in this.Q.Values)
{
if (test.Enabled)
{
m_TotalTime += test.ExpectedTestingTime;
}
// calculate elapsed time
if (
(
(test.TestState == UPnPTestStates.Pass) ||
(test.TestState == UPnPTestStates.Warn)
)
&&
test.Enabled
)
{
elapsed += test.ExpectedTestingTime;
}
}
elapsed += secondOffsetForCurrentSubTest;
Arg.TestGroup.AbortCountDown();
Arg.TestGroup.StartCountDown(elapsed, m_TotalTime);
}
/// <summary>
/// Total expected time until completion of the test.
/// This value may grow during execution of subtests.
/// </summary>
private int m_TotalTime = 0;
/// <summary>
/// Total time expected for this entire test group. This value
/// may change as the test progresses.
/// </summary>
public int TotalTime { get { return this.m_TotalTime; } }
private void AddTest (ISubTest sub)
{
bool found = false;
foreach (ISubTest st in Q.Values)
{
if (st.Name == sub.Name)
{
found = true;
break;
}
}
if (!found)
{
foreach (ISubTest pre in sub.Prerequisites)
{
AddTest(pre);
}
Q.Add(sub, sub);
}
}
private SortedList Q = new SortedList(new SubTestOrderer());
private ISubTestArgument Arg;
}
}
| |
namespace Microsoft.Protocols.TestSuites.Common
{
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net;
using System.Reflection;
using System.Text;
using System.Web.Services.Protocols;
using System.Xml;
using System.Xml.Linq;
using System.Xml.Schema;
using System.Xml.Serialization;
using System.Xml.XPath;
using Microsoft.Protocols.TestTools;
/// <summary>
/// Partial class of proxy class.
/// </summary>
public partial class ExchangeServiceBinding
{
/// <summary>
/// The paths of xsd files.
/// </summary>
private static string[] xsdPaths = new string[]
{
"MS-OXWSDLGM-message.xsd",
"MS-OXWSDLGM-types.xsd",
"MS-OXWSATT-messages.xsd",
"MS-OXWSATT-types.xsd",
"MS-OXWSBTRF-messages.xsd",
"MS-OXWSBTRF-types.xsd",
"MS-OXWSCDATA-messages.xsd",
"MS-OXWSCDATA-types.xsd",
"MS-OXWSCEXT-messages.xsd",
"MS-OXWSCEXT-types.xsd",
"MS-OXWSCONT-types.xsd",
"MS-OXWSCONV-messages.xsd",
"MS-OXWSCONV-types.xsd",
"MS-OXWSCORE-messages.xsd",
"MS-OXWSCORE-types.xsd",
"MS-OXWSCVTID-messages.xsd",
"MS-OXWSCVTID-types.xsd",
"MS-OXWSDLIST-messages.xsd",
"MS-OXWSDLIST-types.xsd",
"MS-OXWSEDISC-messages.xsd",
"MS-OXWSEDISC-types.xsd",
"MS-OXWSFOLD-messages.xsd",
"MS-OXWSFOLD-types.xsd",
"MS-OXWSGNI-messages.xsd",
"MS-OXWSGNI-types.xsd",
"MS-OXWSGTRM-messages.xsd",
"MS-OXWSGTRM-types.xsd",
"MS-OXWSGTZ-messages.xsd",
"MS-OXWSGTZ-types.xsd",
"MS-OXWSMSG-types.xsd",
"MS-OXWSMSHR-messages.xsd",
"MS-OXWSMSHR-types.xsd",
"MS-OXWSMTGS-messages.xsd",
"MS-OXWSMTGS-types.xsd",
"MS-OXWSNTIF-messages.xsd",
"MS-OXWSNTIF-types.xsd",
"MS-OXWSPED-messages.xsd",
"MS-OXWSPERS-messages.xsd",
"MS-OXWSPERS-types.xsd",
"MS-OXWSPOST-types.xsd",
"MS-OXWSPSNTIF-messages.xsd",
"MS-OXWSPSNTIF-types.xsd",
"MS-OXWSRSLNM-messages.xsd",
"MS-OXWSRSLNM-types.xsd",
"MS-OXWSSRCH-messages.xsd",
"MS-OXWSSRCH-types.xsd",
"MS-OXWSSYNC-messages.xsd",
"MS-OXWSSYNC-types.xsd",
"MS-OXWSTASK-types.xsd",
"MS-OXWSURPT-messages.xsd",
"MS-OXWSURPT-types.xsd",
"MS-OXWSXPROP-types.xsd",
"MS-OXWSUSRCFG-messages.xsd",
"MS-OXWSUSRCFG-types.xsd",
"MS-OXWSCONT-messages.xsd"
};
/// <summary>
/// ITestSite object to use ITestSite's functions.
/// </summary>
private ITestSite site;
/// <summary>
/// An XmlReaderSettings that is used to validate the schema.
/// </summary>
private XmlReaderSettings xmlReaderSettings;
/// <summary>
/// Get Uri property of SoapHttpClientProtocol.
/// </summary>
private PropertyInfo baseURI = typeof(ExchangeServiceBinding).GetProperty("Uri", BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.InvokeMethod);
/// <summary>
/// Get PendingSyncRequest property of SoapHttpClientProtocol.
/// </summary>
private PropertyInfo basePendingSyncRequest = typeof(ExchangeServiceBinding).GetProperty("PendingSyncRequest", BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.InvokeMethod);
/// <summary>
/// Get SetStream method of SoapClientMessage.
/// </summary>
private MethodInfo setStream = typeof(SoapClientMessage).GetMethod("SetStream", BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.InvokeMethod);
/// <summary>
/// Represents the callback method that will handle XML schema validation events and the System.Xml.Schema.ValidationEventArgs.
/// </summary>
private ValidationEventHandler itemStackValidationEventHandler;
/// <summary>
/// An xmlWriterHook that is used to hook actual request xml in the request stream.
/// </summary>
private XmlWriterInjector xmlWriterHookInstance;
/// <summary>
/// The raw XML request to server
/// </summary>
private IXPathNavigable rawRequestXml;
/// <summary>
/// The raw XML response from server
/// </summary>
private IXPathNavigable rawResponseXml;
/// <summary>
/// The warning collection of schema validation.
/// </summary>
private Collection<ValidationEventArgs> schemaValidationWarnings = new Collection<ValidationEventArgs>();
/// <summary>
/// The error collection of schema validation.
/// </summary>
private Collection<ValidationEventArgs> schemaValidationErrors = new Collection<ValidationEventArgs>();
/// <summary>
/// Initializes a new instance of the ExchangeServiceBinding class with the specified parameter.
/// </summary>
/// <param name="url">The base URL of the XML Web service the client is requesting.</param>
/// <param name="userName">The user name associated with the credentials.</param>
/// <param name="password">The password for the user name associated with the credentials.</param>
/// <param name="domain">The domain associated with these credentials.</param>
/// <param name="testSite">The test site instance.</param>
public ExchangeServiceBinding(string url, string userName, string password, string domain, ITestSite testSite)
{
this.Url = url;
this.Credentials = new NetworkCredential(userName, password, domain);
this.itemStackValidationEventHandler = this.ValidationCallBack;
this.InitialXmlReaderSettings();
if (this.site == null)
{
this.site = testSite;
}
}
/// <summary>
/// Handle the server response.
/// </summary>
/// <param name="request">The request messages.</param>
/// <param name="response">The response messages.</param>
/// <param name="isSchemaValidated">The schema validation result.</param>
public delegate void ServiceResponseDelegate(BaseRequestType request, BaseResponseMessageType response, bool isSchemaValidated);
/// <summary>
/// Handle the server response. Invoked when a response received from server.
/// </summary>
public static event ServiceResponseDelegate ServiceResponseEvent;
/// <summary>
/// Gets the warning collection of schema validation.
/// </summary>
public Collection<ValidationEventArgs> SchemaValidationWarnings
{
get
{
return this.schemaValidationWarnings;
}
}
/// <summary>
/// Gets the error collection of schema validation.
/// </summary>
public Collection<ValidationEventArgs> SchemaValidationErrors
{
get
{
return this.schemaValidationErrors;
}
}
/// <summary>
/// Gets a value indicating whether the schema validation is successful.
/// </summary>
public bool IsSchemaValidated
{
get;
private set;
}
/// <summary>
/// Gets the raw XML request sent to protocol SUT
/// </summary>
public IXPathNavigable LastRawRequestXml
{
get
{
return this.rawRequestXml;
}
}
/// <summary>
/// Gets the raw XML response received from protocol SUT
/// </summary>
public IXPathNavigable LastRawResponseXml
{
get
{
return this.rawResponseXml;
}
}
/// <summary>
/// Overload .NET framework Invoke method to provide extra XML schema validation function.
/// </summary>
/// <param name="methodName">The name of the XML Web service method.</param>
/// <param name="parameters">An array of objects that contains the parameters to pass to the XML Web service. The order of the values in the array corresponds to the order of the parameters in the calling method of the derived class.</param>
/// <returns>An array of objects that contains the return value and any reference or out parameters of the derived class method.</returns>
public new object[] Invoke(string methodName, object[] parameters)
{
this.rawRequestXml = null;
this.rawResponseXml = null;
WebResponse webResponse = null;
WebRequest webRequest = null;
object[] objArray;
StringBuilder sb = new StringBuilder();
using (StringWriter sw = new StringWriter(sb))
{
Assembly assembly = Assembly.GetAssembly(typeof(ItemType));
BaseRequestType requestInfo = (BaseRequestType)parameters[0];
Type type = typeof(BaseRequestType);
Type[] types = assembly.GetTypes();
foreach (Type t in types)
{
if (requestInfo.GetType().Equals(t))
{
type = t;
}
}
// Serialize the request.
XmlSerializer xs = new XmlSerializer(type);
xs.Serialize(sw, requestInfo);
}
try
{
// Creates a WebRequest for the specified uri.
webRequest = this.GetWebRequest(this.baseURI.GetValue(this, null) as Uri);
webRequest.PreAuthenticate = true;
// Check PropertyInfo is null or not.
Trace.Assert(this.basePendingSyncRequest != null, "PropertyInfo can not be NULL");
// Sets the value of PendingSyncRequest.
this.basePendingSyncRequest.SetValue(this, webRequest, null);
// Invoke method of HttpWebClientProtocol.
SoapClientMessage message = this.InstanceInvokeBase("BeforeSerialize", webRequest, methodName, parameters) as SoapClientMessage;
Stream requestStream = webRequest.GetRequestStream();
try
{
Trace.Assert(this.setStream != null, "MethodInfo can not be NULL");
this.setStream.Invoke(message, new object[] { requestStream });
this.InstanceInvokeBase("Serialize", message);
}
finally
{
requestStream.Close();
}
// Get the actual request xml by using xmlWriterHookInstance. The xmlWriterHookInstance is appended to the GetWriterForMessage method of the proxy class.
string requestXmlString = this.xmlWriterHookInstance.Xml.ToString();
// Load the actual request xml to an XmlElement
if (!string.IsNullOrEmpty(requestXmlString))
{
XmlDocument xmlDocOfReadRequest = new XmlDocument();
xmlDocOfReadRequest.LoadXml(requestXmlString);
this.rawRequestXml = xmlDocOfReadRequest.DocumentElement;
this.site.Log.Add(LogEntryKind.Debug, "The raw xml request message is:\r\n{0}", ((XmlElement)this.rawRequestXml).OuterXml);
}
webResponse = this.GetWebResponse(webRequest);
HttpWebResponse httpWebResponse = (HttpWebResponse)webResponse;
if (httpWebResponse.StatusCode != HttpStatusCode.OK)
{
throw new WebException(httpWebResponse.StatusDescription);
}
Stream responseStream = null;
try
{
responseStream = webResponse.GetResponseStream();
string streamString = string.Empty;
using (StreamReader sr = new StreamReader(responseStream))
{
responseStream = null;
StringBuilder xmlString = new StringBuilder();
while (sr.Peek() > -1)
{
string strInput = sr.ReadLine();
xmlString.Append(strInput);
}
streamString = xmlString.ToString();
Trace.TraceInformation(streamString);
}
using (Stream streamObjRawXmlResponse = new MemoryStream(ASCIIEncoding.Default.GetBytes(streamString)))
{
XmlDocument responseXml = new XmlDocument();
responseXml.LoadXml(streamString);
this.rawResponseXml = responseXml.DocumentElement;
this.site.Log.Add(LogEntryKind.Debug, "The raw xml response message is:\r\n{0}", ((XmlElement)this.rawResponseXml).OuterXml);
objArray = this.InstanceInvoke("ReadResponse", message, webResponse, streamObjRawXmlResponse, false) as object[];
// Gets SOAP header from the response.
string soapHeader = this.GetSoapElement(responseXml, "Header");
// Gets SOAP body from the response.
string soapBody = this.GetSoapElement(responseXml, "Body");
this.XmlValidater(soapHeader, soapBody);
if (ExchangeServiceBinding.ServiceResponseEvent != null)
{
if (objArray[0] is BaseResponseMessageType)
{
ExchangeServiceBinding.ServiceResponseEvent(
(BaseRequestType)parameters[0],
(BaseResponseMessageType)objArray[0],
this.IsSchemaValidated);
}
}
}
}
catch (XmlException exception)
{
if (exception.Message.Contains("The following elements are not closed"))
{
throw new InvalidOperationException("The xml is not complete.", exception);
}
else
{
throw new InvalidOperationException("WebResponseBadXml", exception);
}
}
finally
{
if (responseStream != null)
{
responseStream.Dispose();
}
}
}
finally
{
if (webRequest == this.basePendingSyncRequest.GetValue(this, null) as WebRequest)
{
if (this.basePendingSyncRequest.CanWrite)
{
this.basePendingSyncRequest.SetValue(this, null, null);
}
}
}
return objArray;
}
#region Override implementation, append the xmlWriterHookInstance into the GetWriterForMessage method
/// <summary>
/// Override implementation, append the xmlWriterHookInstance into the GetWriterForMessage method
/// </summary>
/// <param name="message">The SOAP client message</param>
/// <param name="bufferSize">The size of the buffer for the xml writer</param>
/// <returns>An instance of the XmlWriterHook</returns>
protected override XmlWriter GetWriterForMessage(SoapClientMessage message, int bufferSize)
{
XmlWriter originalXmlWriterImplementation = base.GetWriterForMessage(message, bufferSize);
this.xmlWriterHookInstance = new XmlWriterInjector(originalXmlWriterImplementation);
return this.xmlWriterHookInstance;
}
#endregion
/// <summary>
/// Initialize an instance of XmlReaderSettings.
/// </summary>
private void InitialXmlReaderSettings()
{
this.xmlReaderSettings = new XmlReaderSettings();
foreach (string schemaFilePath in xsdPaths)
{
string xsd = this.ReadSchema(schemaFilePath);
string targetNamespace = this.GetTargetNamespace(xsd);
StringReader reader = null;
try
{
reader = new StringReader(xsd);
using (XmlReader schemaReader = XmlReader.Create(reader))
{
reader = null;
this.xmlReaderSettings.Schemas.Add(targetNamespace, schemaReader);
}
}
finally
{
if (reader != null)
{
reader.Dispose();
}
}
}
this.xmlReaderSettings.ValidationType = ValidationType.Schema;
this.xmlReaderSettings.ConformanceLevel = ConformanceLevel.Document;
this.xmlReaderSettings.ValidationFlags |= XmlSchemaValidationFlags.ReportValidationWarnings;
this.xmlReaderSettings.ValidationEventHandler += new ValidationEventHandler(this.itemStackValidationEventHandler);
}
/// <summary>
/// Gets the SOAP header or SOAP body from response.
/// </summary>
/// <param name="responseXml">The response xml</param>
/// <param name="element">The element's name, Header or Body.</param>
/// <returns>The SOAP element.</returns>
private string GetSoapElement(XmlDocument responseXml, string element)
{
XmlNode nodesForSoapElement;
XNamespace soapNamespace = @"http://schemas.xmlsoap.org/soap/envelope/";
XName elementName = soapNamespace + element;
XDocument doc;
using (XmlNodeReader nodeReader = new XmlNodeReader(responseXml))
{
doc = XDocument.Load(nodeReader, LoadOptions.None);
}
// Select elements.
IEnumerable<XElement> elements = from x in doc.Root.Elements(elementName)
select x;
// If there is no SOAP header, return null.
if (elements.Count() == 0 && element.Equals("Header"))
{
return null;
}
using (XmlReader reader = elements.First().CreateReader())
{
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(reader);
nodesForSoapElement = xmlDoc;
}
// There is only one SOAP header or body element, return the first child's xml.
return nodesForSoapElement.FirstChild.InnerXml;
}
/// <summary>
/// Reads schema from an XSD file.
/// </summary>
/// <param name="xsdFile">An XSD file name.</param>
/// <returns>The schema string used to validate server response.</returns>
private string ReadSchema(string xsdFile)
{
using (FileStream stream = new FileStream(xsdFile, FileMode.Open, FileAccess.Read))
{
// Creates a new XDocument instance by using the specified stream.
XDocument xsd = XDocument.Load(stream);
XNamespace namespaceW3 = @"http://www.w3.org/2001/XMLSchema";
XName includeElementName = namespaceW3 + "include";
// Selects elements.
IEnumerable<XElement> includeElements = from x in xsd.Root.Elements(includeElementName)
select x;
includeElements = new List<XElement>(includeElements);
foreach (XElement includeElement in includeElements)
{
// Removes this node from its parent.
includeElement.Remove();
}
XName importElementName = namespaceW3 + "import";
XName schemaLocationName = "schemaLocation";
// Selects attributes.
IEnumerable<XAttribute> schemaLocationAttributes = from x in xsd.Root.Elements(importElementName)
where x.Attribute(schemaLocationName) != null
select x.Attribute(schemaLocationName);
schemaLocationAttributes = new List<XAttribute>(schemaLocationAttributes);
foreach (XAttribute schemaLocationAttribute in schemaLocationAttributes)
{
// Removes this attribute from its parent element.
schemaLocationAttribute.Remove();
}
return xsd.ToString();
}
}
/// <summary>
/// Gets the target namespace.
/// </summary>
/// <param name="fullSchema">Full schema content.</param>
/// <returns>The target namespace.</returns>
private string GetTargetNamespace(string fullSchema)
{
XNamespace namespaceW3 = @"http://www.w3.org/2001/XMLSchema";
XName schemaElementName = namespaceW3 + "schema";
XDocument doc = XDocument.Parse(fullSchema);
XElement schemaElement = doc.Element(schemaElementName);
if (schemaElement != null)
{
XAttribute targetAttribute = schemaElement.Attribute("targetNamespace");
if (targetAttribute != null)
{
return targetAttribute.Value;
}
}
return null;
}
/// <summary>
/// Validate a piece of Xml fragment according the given Xml Schema.
/// </summary>
/// <param name="xmlHeader">The xml fragment of SOAP header.</param>
/// <param name="xmlBody">The xml fragment of SOAP body.</param>
/// <returns>A Boolean value of the validate result.</returns>
private bool XmlValidater(string xmlHeader, string xmlBody)
{
this.IsSchemaValidated = false;
if (xmlHeader == null)
{
return this.IsSchemaValidated = this.ElementValidater(xmlBody);
}
else
{
return this.IsSchemaValidated = this.ElementValidater(xmlHeader) && this.ElementValidater(xmlBody);
}
}
/// <summary>
/// Validate a piece of Xml fragment according the given Xml Schema.
/// </summary>
/// <param name="elementXml">The xml fragment.</param>
/// <returns>A Boolean value of the validate result.</returns>
private bool ElementValidater(string elementXml)
{
this.schemaValidationErrors.Clear();
this.schemaValidationWarnings.Clear();
bool isValidated = false;
StringReader stringReader = null;
try
{
stringReader = new StringReader(elementXml);
using (XmlReader xmlReader = XmlReader.Create(stringReader, this.xmlReaderSettings))
{
stringReader = null;
while (xmlReader.Read())
{
}
isValidated = this.schemaValidationErrors.Count == 0 && this.schemaValidationWarnings.Count == 0;
}
}
finally
{
if (stringReader != null)
{
stringReader.Dispose();
}
}
return isValidated;
}
/// <summary>
/// Display any warnings or errors.
/// </summary>
/// <param name="sender">The source of the event. Note Determine the type of a sender before using it in your code. You cannot assume that the sender is an instance of a particular type. The sender is also not guaranteed to not be null. Always surround your casts with failure handling logic.</param>
/// <param name="args">The event data.</param>
private void ValidationCallBack(object sender, ValidationEventArgs args)
{
if (args.Severity == XmlSeverityType.Warning)
{
this.schemaValidationWarnings.Add(args);
}
if (args.Severity == XmlSeverityType.Error)
{
this.schemaValidationErrors.Add(args);
}
}
/// <summary>
/// Invoke method of HttpWebClientProtocol.
/// </summary>
/// <param name="name">Invokes the method or constructor represented by the current instance, using the specified parameters.</param>
/// <param name="parameters">An argument list for the invoked method or constructor.</param>
/// <returns>An object containing the return value of the invoked method, or null in the case of a constructor.</returns>
private object InstanceInvokeBase(string name, params object[] parameters)
{
try
{
BindingFlags bfs = BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.InvokeMethod;
MethodInfo mi = typeof(ExchangeServiceBinding).BaseType.GetMethod(name, bfs);
Trace.Assert(mi != null, "MethodInfo can not be NULL");
return mi.Invoke(this, parameters);
}
catch (TargetInvocationException ex)
{
if (ex.InnerException != null)
{
throw ex.InnerException;
}
else
{
throw;
}
}
}
/// <summary>
/// Invoke method of HttpWebClientProtocol.
/// </summary>
/// <param name="name">Invokes the method or constructor represented by the current instance, using the specified parameters.</param>
/// <param name="parameters">An argument list for the invoked method or constructor.</param>
/// <returns>An object containing the return value of the invoked method, or null in the case of a constructor.</returns>
private object InstanceInvoke(string name, params object[] parameters)
{
try
{
BindingFlags bfs = BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.InvokeMethod;
MethodInfo mi = typeof(SoapHttpClientProtocol).GetMethod(name, bfs);
Trace.Assert(mi != null, "MethodInfo can not be NULL");
return mi.Invoke(this, parameters);
}
catch (TargetInvocationException ex)
{
if (ex.InnerException != null)
{
throw ex.InnerException;
}
else
{
throw;
}
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
/******************************************************************************
* This file is auto-generated from a template file by the GenerateTests.csx *
* script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make *
* changes, please update the corresponding template and run according to the *
* directions listed in the file. *
******************************************************************************/
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics;
using System.Runtime.Intrinsics.X86;
namespace JIT.HardwareIntrinsics.X86
{
public static partial class Program
{
private static void ShiftRightArithmeticInt1616()
{
var test = new SimpleUnaryOpTest__ShiftRightArithmeticInt1616();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
if (Avx.IsSupported)
{
// Validates basic functionality works, using Load
test.RunBasicScenario_Load();
// Validates basic functionality works, using LoadAligned
test.RunBasicScenario_LoadAligned();
}
// Validates calling via reflection works, using Unsafe.Read
test.RunReflectionScenario_UnsafeRead();
if (Avx.IsSupported)
{
// Validates calling via reflection works, using Load
test.RunReflectionScenario_Load();
// Validates calling via reflection works, using LoadAligned
test.RunReflectionScenario_LoadAligned();
}
// Validates passing a static member works
test.RunClsVarScenario();
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario_UnsafeRead();
if (Avx.IsSupported)
{
// Validates passing a local works, using Load
test.RunLclVarScenario_Load();
// Validates passing a local works, using LoadAligned
test.RunLclVarScenario_LoadAligned();
}
// Validates passing the field of a local works
test.RunLclFldScenario();
// Validates passing an instance member works
test.RunFldScenario();
}
else
{
// Validates we throw on unsupported hardware
test.RunUnsupportedScenario();
}
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class SimpleUnaryOpTest__ShiftRightArithmeticInt1616
{
private const int VectorSize = 32;
private const int Op1ElementCount = VectorSize / sizeof(Int16);
private const int RetElementCount = VectorSize / sizeof(Int16);
private static Int16[] _data = new Int16[Op1ElementCount];
private static Vector256<Int16> _clsVar;
private Vector256<Int16> _fld;
private SimpleUnaryOpTest__DataTable<Int16, Int16> _dataTable;
static SimpleUnaryOpTest__ShiftRightArithmeticInt1616()
{
var random = new Random();
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = (short)(random.Next(0, short.MaxValue)); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int16>, byte>(ref _clsVar), ref Unsafe.As<Int16, byte>(ref _data[0]), VectorSize);
}
public SimpleUnaryOpTest__ShiftRightArithmeticInt1616()
{
Succeeded = true;
var random = new Random();
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = (short)(random.Next(0, short.MaxValue)); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int16>, byte>(ref _fld), ref Unsafe.As<Int16, byte>(ref _data[0]), VectorSize);
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = (short)(random.Next(0, short.MaxValue)); }
_dataTable = new SimpleUnaryOpTest__DataTable<Int16, Int16>(_data, new Int16[RetElementCount], VectorSize);
}
public bool IsSupported => Avx2.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
var result = Avx2.ShiftRightArithmetic(
Unsafe.Read<Vector256<Int16>>(_dataTable.inArrayPtr),
16
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
var result = Avx2.ShiftRightArithmetic(
Avx.LoadVector256((Int16*)(_dataTable.inArrayPtr)),
16
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_LoadAligned()
{
var result = Avx2.ShiftRightArithmetic(
Avx.LoadAlignedVector256((Int16*)(_dataTable.inArrayPtr)),
16
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
var result = typeof(Avx2).GetMethod(nameof(Avx2.ShiftRightArithmetic), new Type[] { typeof(Vector256<Int16>), typeof(byte) })
.Invoke(null, new object[] {
Unsafe.Read<Vector256<Int16>>(_dataTable.inArrayPtr),
(byte)16
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Int16>)(result));
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
var result = typeof(Avx2).GetMethod(nameof(Avx2.ShiftRightArithmetic), new Type[] { typeof(Vector256<Int16>), typeof(byte) })
.Invoke(null, new object[] {
Avx.LoadVector256((Int16*)(_dataTable.inArrayPtr)),
(byte)16
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Int16>)(result));
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_LoadAligned()
{
var result = typeof(Avx2).GetMethod(nameof(Avx2.ShiftRightArithmetic), new Type[] { typeof(Vector256<Int16>), typeof(byte) })
.Invoke(null, new object[] {
Avx.LoadAlignedVector256((Int16*)(_dataTable.inArrayPtr)),
(byte)16
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Int16>)(result));
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
var result = Avx2.ShiftRightArithmetic(
_clsVar,
16
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_UnsafeRead()
{
var firstOp = Unsafe.Read<Vector256<Int16>>(_dataTable.inArrayPtr);
var result = Avx2.ShiftRightArithmetic(firstOp, 16);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(firstOp, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
var firstOp = Avx.LoadVector256((Int16*)(_dataTable.inArrayPtr));
var result = Avx2.ShiftRightArithmetic(firstOp, 16);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(firstOp, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_LoadAligned()
{
var firstOp = Avx.LoadAlignedVector256((Int16*)(_dataTable.inArrayPtr));
var result = Avx2.ShiftRightArithmetic(firstOp, 16);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(firstOp, _dataTable.outArrayPtr);
}
public void RunLclFldScenario()
{
var test = new SimpleUnaryOpTest__ShiftRightArithmeticInt1616();
var result = Avx2.ShiftRightArithmetic(test._fld, 16);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld, _dataTable.outArrayPtr);
}
public void RunFldScenario()
{
var result = Avx2.ShiftRightArithmetic(_fld, 16);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld, _dataTable.outArrayPtr);
}
public void RunUnsupportedScenario()
{
Succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
Succeeded = true;
}
}
private void ValidateResult(Vector256<Int16> firstOp, void* result, [CallerMemberName] string method = "")
{
Int16[] inArray = new Int16[Op1ElementCount];
Int16[] outArray = new Int16[RetElementCount];
Unsafe.Write(Unsafe.AsPointer(ref inArray[0]), firstOp);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize);
ValidateResult(inArray, outArray, method);
}
private void ValidateResult(void* firstOp, void* result, [CallerMemberName] string method = "")
{
Int16[] inArray = new Int16[Op1ElementCount];
Int16[] outArray = new Int16[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref inArray[0]), ref Unsafe.AsRef<byte>(firstOp), VectorSize);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize);
ValidateResult(inArray, outArray, method);
}
private void ValidateResult(Int16[] firstOp, Int16[] result, [CallerMemberName] string method = "")
{
if ((short)(firstOp[0] >> 15) != result[0])
{
Succeeded = false;
}
else
{
for (var i = 1; i < RetElementCount; i++)
{
if ((short)(firstOp[i] >> 15) != result[i])
{
Succeeded = false;
break;
}
}
}
if (!Succeeded)
{
Console.WriteLine($"{nameof(Avx2)}.{nameof(Avx2.ShiftRightArithmetic)}<Int16>(Vector256<Int16><9>): {method} failed:");
Console.WriteLine($" firstOp: ({string.Join(", ", firstOp)})");
Console.WriteLine($" result: ({string.Join(", ", result)})");
Console.WriteLine();
}
}
}
}
| |
/********************************************************************
The Multiverse Platform is made available under the MIT License.
Copyright (c) 2012 The Multiverse Foundation
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without restriction,
including without limitation the rights to use, copy, modify,
merge, publish, distribute, sublicense, and/or sell copies
of the Software, and to permit persons to whom the Software
is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE
OR OTHER DEALINGS IN THE SOFTWARE.
*********************************************************************/
namespace MVImportTool
{
partial class MVImportToolForm
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager( typeof( MVImportToolForm ) );
this.StartButton = new System.Windows.Forms.Button();
this.StopButton = new System.Windows.Forms.Button();
this.ExitButton = new System.Windows.Forms.Button();
this.menuStrip1 = new System.Windows.Forms.MenuStrip();
this.toolStripMenuItem1 = new System.Windows.Forms.ToolStripMenuItem();
this.configurationToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.helpToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.launchOnlineHelpToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.releaseNotesToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.submitFeedbackOrABugToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.commandFlagsToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.aboutCOLLADAImportToolToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.splitContainer1 = new System.Windows.Forms.SplitContainer();
this.tabControl1 = new System.Windows.Forms.TabControl();
this.ColladaTabPage = new System.Windows.Forms.TabPage();
this.sourceFileSelector1 = new MVImportTool.SourceFileSelector();
this.RepositoriesTabPage = new System.Windows.Forms.TabPage();
this.repositoryControl1 = new MVImportTool.RepositoryControl();
this.ExecutionTabControl = new System.Windows.Forms.TabControl();
this.CommandTabPage = new System.Windows.Forms.TabPage();
this.commandControl1 = new MVImportTool.CommandControl();
this.LogTabPage = new System.Windows.Forms.TabPage();
this.logPanel1 = new MVImportTool.LogPanel();
this.menuStrip1.SuspendLayout();
this.splitContainer1.Panel1.SuspendLayout();
this.splitContainer1.Panel2.SuspendLayout();
this.splitContainer1.SuspendLayout();
this.tabControl1.SuspendLayout();
this.ColladaTabPage.SuspendLayout();
this.RepositoriesTabPage.SuspendLayout();
this.ExecutionTabControl.SuspendLayout();
this.CommandTabPage.SuspendLayout();
this.LogTabPage.SuspendLayout();
this.SuspendLayout();
//
// StartButton
//
this.StartButton.Anchor = ((System.Windows.Forms.AnchorStyles) ((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.StartButton.Location = new System.Drawing.Point( 575, 335 );
this.StartButton.Name = "StartButton";
this.StartButton.Size = new System.Drawing.Size( 75, 23 );
this.StartButton.TabIndex = 1;
this.StartButton.Text = "Start";
this.StartButton.UseVisualStyleBackColor = true;
this.StartButton.Click += new System.EventHandler( this.StartButton_Click );
//
// StopButton
//
this.StopButton.Anchor = ((System.Windows.Forms.AnchorStyles) ((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.StopButton.Location = new System.Drawing.Point( 656, 335 );
this.StopButton.Name = "StopButton";
this.StopButton.Size = new System.Drawing.Size( 75, 23 );
this.StopButton.TabIndex = 2;
this.StopButton.Text = "Stop";
this.StopButton.UseVisualStyleBackColor = true;
this.StopButton.Click += new System.EventHandler( this.StopButton_Click );
//
// ExitButton
//
this.ExitButton.Anchor = ((System.Windows.Forms.AnchorStyles) ((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.ExitButton.Location = new System.Drawing.Point( 737, 335 );
this.ExitButton.Name = "ExitButton";
this.ExitButton.Size = new System.Drawing.Size( 75, 23 );
this.ExitButton.TabIndex = 3;
this.ExitButton.Text = "Exit";
this.ExitButton.UseVisualStyleBackColor = true;
this.ExitButton.Click += new System.EventHandler( this.ExitButton_Click );
//
// menuStrip1
//
this.menuStrip1.Items.AddRange( new System.Windows.Forms.ToolStripItem[] {
this.toolStripMenuItem1,
this.helpToolStripMenuItem} );
this.menuStrip1.Location = new System.Drawing.Point( 0, 0 );
this.menuStrip1.Name = "menuStrip1";
this.menuStrip1.Size = new System.Drawing.Size( 814, 24 );
this.menuStrip1.TabIndex = 4;
this.menuStrip1.Text = "menuStrip1";
//
// toolStripMenuItem1
//
this.toolStripMenuItem1.DropDownItems.AddRange( new System.Windows.Forms.ToolStripItem[] {
this.configurationToolStripMenuItem} );
this.toolStripMenuItem1.Name = "toolStripMenuItem1";
this.toolStripMenuItem1.Size = new System.Drawing.Size( 84, 20 );
this.toolStripMenuItem1.Text = "Configuration";
//
// configurationToolStripMenuItem
//
this.configurationToolStripMenuItem.Name = "configurationToolStripMenuItem";
this.configurationToolStripMenuItem.Size = new System.Drawing.Size( 132, 22 );
this.configurationToolStripMenuItem.Text = "Configure";
this.configurationToolStripMenuItem.Click += new System.EventHandler( this.configurationToolStripMenuItem_Click );
//
// helpToolStripMenuItem
//
this.helpToolStripMenuItem.DropDownItems.AddRange( new System.Windows.Forms.ToolStripItem[] {
this.launchOnlineHelpToolStripMenuItem,
this.releaseNotesToolStripMenuItem,
this.submitFeedbackOrABugToolStripMenuItem,
this.commandFlagsToolStripMenuItem,
this.aboutCOLLADAImportToolToolStripMenuItem} );
this.helpToolStripMenuItem.Name = "helpToolStripMenuItem";
this.helpToolStripMenuItem.Size = new System.Drawing.Size( 40, 20 );
this.helpToolStripMenuItem.Text = "Help";
//
// launchOnlineHelpToolStripMenuItem
//
this.launchOnlineHelpToolStripMenuItem.Name = "launchOnlineHelpToolStripMenuItem";
this.launchOnlineHelpToolStripMenuItem.Size = new System.Drawing.Size( 221, 22 );
this.launchOnlineHelpToolStripMenuItem.Text = "Launch Online Help";
this.launchOnlineHelpToolStripMenuItem.Click += new System.EventHandler( this.launchOnlineHelpToolStripMenuItem_Click );
//
// releaseNotesToolStripMenuItem
//
this.releaseNotesToolStripMenuItem.Name = "releaseNotesToolStripMenuItem";
this.releaseNotesToolStripMenuItem.Size = new System.Drawing.Size( 221, 22 );
this.releaseNotesToolStripMenuItem.Text = "Release Notes";
this.releaseNotesToolStripMenuItem.Click += new System.EventHandler( this.releaseNotesToolStripMenuItem_Click );
//
// submitFeedbackOrABugToolStripMenuItem
//
this.submitFeedbackOrABugToolStripMenuItem.Name = "submitFeedbackOrABugToolStripMenuItem";
this.submitFeedbackOrABugToolStripMenuItem.Size = new System.Drawing.Size( 221, 22 );
this.submitFeedbackOrABugToolStripMenuItem.Text = "Submit Feedback or a Bug";
this.submitFeedbackOrABugToolStripMenuItem.Click += new System.EventHandler( this.submitFeedbackOrABugToolStripMenuItem_Click );
//
// commandFlagsToolStripMenuItem
//
this.commandFlagsToolStripMenuItem.Name = "commandFlagsToolStripMenuItem";
this.commandFlagsToolStripMenuItem.Size = new System.Drawing.Size( 221, 22 );
this.commandFlagsToolStripMenuItem.Text = "Command Flags";
this.commandFlagsToolStripMenuItem.Click += new System.EventHandler( this.commandFlagsToolStripMenuItem_Click );
//
// aboutCOLLADAImportToolToolStripMenuItem
//
this.aboutCOLLADAImportToolToolStripMenuItem.Name = "aboutCOLLADAImportToolToolStripMenuItem";
this.aboutCOLLADAImportToolToolStripMenuItem.Size = new System.Drawing.Size( 221, 22 );
this.aboutCOLLADAImportToolToolStripMenuItem.Text = "About COLLADA Import Tool";
this.aboutCOLLADAImportToolToolStripMenuItem.Click += new System.EventHandler( this.aboutCOLLADAImportToolToolStripMenuItem_Click );
//
// splitContainer1
//
this.splitContainer1.Anchor = ((System.Windows.Forms.AnchorStyles) ((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.splitContainer1.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D;
this.splitContainer1.FixedPanel = System.Windows.Forms.FixedPanel.Panel1;
this.splitContainer1.Location = new System.Drawing.Point( 0, 23 );
this.splitContainer1.MinimumSize = new System.Drawing.Size( 650, 310 );
this.splitContainer1.Name = "splitContainer1";
//
// splitContainer1.Panel1
//
this.splitContainer1.Panel1.Controls.Add( this.tabControl1 );
this.splitContainer1.Panel1MinSize = 200;
//
// splitContainer1.Panel2
//
this.splitContainer1.Panel2.Controls.Add( this.ExecutionTabControl );
this.splitContainer1.Panel2MinSize = 415;
this.splitContainer1.Size = new System.Drawing.Size( 814, 310 );
this.splitContainer1.SplitterDistance = 262;
this.splitContainer1.TabIndex = 0;
//
// tabControl1
//
this.tabControl1.Controls.Add( this.ColladaTabPage );
this.tabControl1.Controls.Add( this.RepositoriesTabPage );
this.tabControl1.Dock = System.Windows.Forms.DockStyle.Fill;
this.tabControl1.Location = new System.Drawing.Point( 0, 0 );
this.tabControl1.Name = "tabControl1";
this.tabControl1.SelectedIndex = 0;
this.tabControl1.ShowToolTips = true;
this.tabControl1.Size = new System.Drawing.Size( 258, 306 );
this.tabControl1.TabIndex = 0;
//
// ColladaTabPage
//
this.ColladaTabPage.Controls.Add( this.sourceFileSelector1 );
this.ColladaTabPage.Location = new System.Drawing.Point( 4, 22 );
this.ColladaTabPage.Name = "ColladaTabPage";
this.ColladaTabPage.Padding = new System.Windows.Forms.Padding( 3 );
this.ColladaTabPage.Size = new System.Drawing.Size( 250, 280 );
this.ColladaTabPage.TabIndex = 0;
this.ColladaTabPage.Text = "COLLADA Files";
this.ColladaTabPage.ToolTipText = "Set up which COLLADA files to import";
this.ColladaTabPage.UseVisualStyleBackColor = true;
//
// sourceFileSelector1
//
this.sourceFileSelector1.Dock = System.Windows.Forms.DockStyle.Fill;
this.sourceFileSelector1.FileFilter = "*.dae";
this.sourceFileSelector1.Folder = "";
this.sourceFileSelector1.Location = new System.Drawing.Point( 3, 3 );
this.sourceFileSelector1.Name = "sourceFileSelector1";
this.sourceFileSelector1.Size = new System.Drawing.Size( 244, 274 );
this.sourceFileSelector1.TabIndex = 0;
//
// RepositoriesTabPage
//
this.RepositoriesTabPage.Controls.Add( this.repositoryControl1 );
this.RepositoriesTabPage.Location = new System.Drawing.Point( 4, 22 );
this.RepositoriesTabPage.Name = "RepositoriesTabPage";
this.RepositoriesTabPage.Padding = new System.Windows.Forms.Padding( 3 );
this.RepositoriesTabPage.Size = new System.Drawing.Size( 250, 280 );
this.RepositoriesTabPage.TabIndex = 1;
this.RepositoriesTabPage.Text = "Repositories";
this.RepositoriesTabPage.ToolTipText = "Select the repositories into which you are importing files";
this.RepositoriesTabPage.UseVisualStyleBackColor = true;
//
// repositoryControl1
//
this.repositoryControl1.CheckedRespositoryPaths = ((System.Collections.Generic.List<string>) (resources.GetObject( "repositoryControl1.CheckedRespositoryPaths" )));
this.repositoryControl1.Dock = System.Windows.Forms.DockStyle.Fill;
this.repositoryControl1.Location = new System.Drawing.Point( 3, 3 );
this.repositoryControl1.Name = "repositoryControl1";
this.repositoryControl1.Size = new System.Drawing.Size( 244, 274 );
this.repositoryControl1.TabIndex = 0;
//
// ExecutionTabControl
//
this.ExecutionTabControl.Controls.Add( this.CommandTabPage );
this.ExecutionTabControl.Controls.Add( this.LogTabPage );
this.ExecutionTabControl.Dock = System.Windows.Forms.DockStyle.Fill;
this.ExecutionTabControl.Location = new System.Drawing.Point( 0, 0 );
this.ExecutionTabControl.Name = "ExecutionTabControl";
this.ExecutionTabControl.SelectedIndex = 0;
this.ExecutionTabControl.ShowToolTips = true;
this.ExecutionTabControl.Size = new System.Drawing.Size( 544, 306 );
this.ExecutionTabControl.TabIndex = 0;
//
// CommandTabPage
//
this.CommandTabPage.Controls.Add( this.commandControl1 );
this.CommandTabPage.Location = new System.Drawing.Point( 4, 22 );
this.CommandTabPage.Name = "CommandTabPage";
this.CommandTabPage.Padding = new System.Windows.Forms.Padding( 3 );
this.CommandTabPage.Size = new System.Drawing.Size( 536, 280 );
this.CommandTabPage.TabIndex = 0;
this.CommandTabPage.Text = "Command Controls";
this.CommandTabPage.ToolTipText = "Controls for Conversion and Copying";
this.CommandTabPage.UseVisualStyleBackColor = true;
//
// commandControl1
//
this.commandControl1.Dock = System.Windows.Forms.DockStyle.Fill;
this.commandControl1.Location = new System.Drawing.Point( 3, 3 );
this.commandControl1.MinimumSize = new System.Drawing.Size( 210, 250 );
this.commandControl1.Name = "commandControl1";
this.commandControl1.Size = new System.Drawing.Size( 530, 274 );
this.commandControl1.TabIndex = 0;
//
// LogTabPage
//
this.LogTabPage.Controls.Add( this.logPanel1 );
this.LogTabPage.Location = new System.Drawing.Point( 4, 22 );
this.LogTabPage.Name = "LogTabPage";
this.LogTabPage.Padding = new System.Windows.Forms.Padding( 3 );
this.LogTabPage.Size = new System.Drawing.Size( 536, 280 );
this.LogTabPage.TabIndex = 1;
this.LogTabPage.Text = "Execution Log";
this.LogTabPage.ToolTipText = "Displays output from the Import commands";
this.LogTabPage.UseVisualStyleBackColor = true;
//
// logPanel1
//
this.logPanel1.Dock = System.Windows.Forms.DockStyle.Fill;
this.logPanel1.Location = new System.Drawing.Point( 3, 3 );
this.logPanel1.Name = "logPanel1";
this.logPanel1.Size = new System.Drawing.Size( 530, 274 );
this.logPanel1.TabIndex = 0;
//
// MVImportToolForm
//
this.AutoScaleDimensions = new System.Drawing.SizeF( 6F, 13F );
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size( 814, 361 );
this.Controls.Add( this.ExitButton );
this.Controls.Add( this.StopButton );
this.Controls.Add( this.StartButton );
this.Controls.Add( this.splitContainer1 );
this.Controls.Add( this.menuStrip1 );
this.Icon = ((System.Drawing.Icon) (resources.GetObject( "$this.Icon" )));
this.MainMenuStrip = this.menuStrip1;
this.MinimumSize = new System.Drawing.Size( 690, 395 );
this.Name = "MVImportToolForm";
this.Text = "Multiverse COLLADA Import Tool";
this.Load += new System.EventHandler( this.MVImportToolForm_Load );
this.menuStrip1.ResumeLayout( false );
this.menuStrip1.PerformLayout();
this.splitContainer1.Panel1.ResumeLayout( false );
this.splitContainer1.Panel2.ResumeLayout( false );
this.splitContainer1.ResumeLayout( false );
this.tabControl1.ResumeLayout( false );
this.ColladaTabPage.ResumeLayout( false );
this.RepositoriesTabPage.ResumeLayout( false );
this.ExecutionTabControl.ResumeLayout( false );
this.CommandTabPage.ResumeLayout( false );
this.LogTabPage.ResumeLayout( false );
this.ResumeLayout( false );
this.PerformLayout();
}
#endregion
private System.Windows.Forms.SplitContainer splitContainer1;
private CommandControl commandControl1;
// private ImporterConfiguration importerConfiguration1;
private System.Windows.Forms.TabControl ExecutionTabControl;
private System.Windows.Forms.TabPage CommandTabPage;
private System.Windows.Forms.TabPage LogTabPage;
private LogPanel logPanel1;
private System.Windows.Forms.Button StartButton;
private System.Windows.Forms.Button StopButton;
private System.Windows.Forms.Button ExitButton;
private System.Windows.Forms.MenuStrip menuStrip1;
private System.Windows.Forms.ToolStripMenuItem toolStripMenuItem1;
private System.Windows.Forms.ToolStripMenuItem configurationToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem helpToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem launchOnlineHelpToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem releaseNotesToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem submitFeedbackOrABugToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem commandFlagsToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem aboutCOLLADAImportToolToolStripMenuItem;
private System.Windows.Forms.TabControl tabControl1;
private System.Windows.Forms.TabPage ColladaTabPage;
private SourceFileSelector sourceFileSelector1;
private System.Windows.Forms.TabPage RepositoriesTabPage;
private RepositoryControl repositoryControl1;
}
}
| |
/*
* Copyright (c) 2006-2014, openmetaverse.org
* All rights reserved.
*
* - Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* - Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* - Neither the name of the openmetaverse.org nor the names
* of its contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Runtime.InteropServices;
using System.Globalization;
namespace OpenMetaverse
{
/// <summary>
/// A three-dimensional vector with floating-point values
/// </summary>
[Serializable]
[StructLayout(LayoutKind.Sequential)]
public struct Vector3 : IComparable<Vector3>, IEquatable<Vector3>
{
/// <summary>X value</summary>
public float X;
/// <summary>Y value</summary>
public float Y;
/// <summary>Z value</summary>
public float Z;
#region Constructors
public Vector3(float x, float y, float z)
{
X = x;
Y = y;
Z = z;
}
public Vector3(float value)
{
X = value;
Y = value;
Z = value;
}
public Vector3(Vector2 value, float z)
{
X = value.X;
Y = value.Y;
Z = z;
}
public Vector3(Vector3d vector)
{
X = (float)vector.X;
Y = (float)vector.Y;
Z = (float)vector.Z;
}
/// <summary>
/// Constructor, builds a vector from a byte array
/// </summary>
/// <param name="byteArray">Byte array containing three four-byte floats</param>
/// <param name="pos">Beginning position in the byte array</param>
public Vector3(byte[] byteArray, int pos)
{
X = Y = Z = 0f;
FromBytes(byteArray, pos);
}
public Vector3(Vector3 vector)
{
X = vector.X;
Y = vector.Y;
Z = vector.Z;
}
#endregion Constructors
#region Public Methods
public float Length()
{
return (float)Math.Sqrt(DistanceSquared(this, Zero));
}
public float LengthSquared()
{
return DistanceSquared(this, Zero);
}
public void Normalize()
{
this = Normalize(this);
}
/// <summary>
/// Test if this vector is equal to another vector, within a given
/// tolerance range
/// </summary>
/// <param name="vec">Vector to test against</param>
/// <param name="tolerance">The acceptable magnitude of difference
/// between the two vectors</param>
/// <returns>True if the magnitude of difference between the two vectors
/// is less than the given tolerance, otherwise false</returns>
public bool ApproxEquals(Vector3 vec, float tolerance)
{
Vector3 diff = this - vec;
return (diff.LengthSquared() <= tolerance * tolerance);
}
/// <summary>
/// IComparable.CompareTo implementation
/// </summary>
public int CompareTo(Vector3 vector)
{
return Length().CompareTo(vector.Length());
}
/// <summary>
/// Test if this vector is composed of all finite numbers
/// </summary>
public bool IsFinite()
{
return (Utils.IsFinite(X) && Utils.IsFinite(Y) && Utils.IsFinite(Z));
}
/// <summary>
/// Builds a vector from a byte array
/// </summary>
/// <param name="byteArray">Byte array containing a 12 byte vector</param>
/// <param name="pos">Beginning position in the byte array</param>
public void FromBytes(byte[] byteArray, int pos)
{
if (!BitConverter.IsLittleEndian)
{
// Big endian architecture
byte[] conversionBuffer = new byte[12];
Buffer.BlockCopy(byteArray, pos, conversionBuffer, 0, 12);
Array.Reverse(conversionBuffer, 0, 4);
Array.Reverse(conversionBuffer, 4, 4);
Array.Reverse(conversionBuffer, 8, 4);
X = BitConverter.ToSingle(conversionBuffer, 0);
Y = BitConverter.ToSingle(conversionBuffer, 4);
Z = BitConverter.ToSingle(conversionBuffer, 8);
}
else
{
// Little endian architecture
X = BitConverter.ToSingle(byteArray, pos);
Y = BitConverter.ToSingle(byteArray, pos + 4);
Z = BitConverter.ToSingle(byteArray, pos + 8);
}
}
/// <summary>
/// Returns the raw bytes for this vector
/// </summary>
/// <returns>A 12 byte array containing X, Y, and Z</returns>
public byte[] GetBytes()
{
byte[] byteArray = new byte[12];
ToBytes(byteArray, 0);
return byteArray;
}
/// <summary>
/// Writes the raw bytes for this vector to a byte array
/// </summary>
/// <param name="dest">Destination byte array</param>
/// <param name="pos">Position in the destination array to start
/// writing. Must be at least 12 bytes before the end of the array</param>
public void ToBytes(byte[] dest, int pos)
{
Buffer.BlockCopy(BitConverter.GetBytes(X), 0, dest, pos + 0, 4);
Buffer.BlockCopy(BitConverter.GetBytes(Y), 0, dest, pos + 4, 4);
Buffer.BlockCopy(BitConverter.GetBytes(Z), 0, dest, pos + 8, 4);
if (!BitConverter.IsLittleEndian)
{
Array.Reverse(dest, pos + 0, 4);
Array.Reverse(dest, pos + 4, 4);
Array.Reverse(dest, pos + 8, 4);
}
}
#endregion Public Methods
#region Static Methods
public static Vector3 Add(Vector3 value1, Vector3 value2)
{
value1.X += value2.X;
value1.Y += value2.Y;
value1.Z += value2.Z;
return value1;
}
public static Vector3 Clamp(Vector3 value1, Vector3 min, Vector3 max)
{
return new Vector3(
Utils.Clamp(value1.X, min.X, max.X),
Utils.Clamp(value1.Y, min.Y, max.Y),
Utils.Clamp(value1.Z, min.Z, max.Z));
}
public static Vector3 Cross(Vector3 value1, Vector3 value2)
{
return new Vector3(
value1.Y * value2.Z - value2.Y * value1.Z,
value1.Z * value2.X - value2.Z * value1.X,
value1.X * value2.Y - value2.X * value1.Y);
}
public static float Distance(Vector3 value1, Vector3 value2)
{
return (float)Math.Sqrt(DistanceSquared(value1, value2));
}
public static float DistanceSquared(Vector3 value1, Vector3 value2)
{
return
(value1.X - value2.X) * (value1.X - value2.X) +
(value1.Y - value2.Y) * (value1.Y - value2.Y) +
(value1.Z - value2.Z) * (value1.Z - value2.Z);
}
public static Vector3 Divide(Vector3 value1, Vector3 value2)
{
value1.X /= value2.X;
value1.Y /= value2.Y;
value1.Z /= value2.Z;
return value1;
}
public static Vector3 Divide(Vector3 value1, float value2)
{
float factor = 1f / value2;
value1.X *= factor;
value1.Y *= factor;
value1.Z *= factor;
return value1;
}
public static float Dot(Vector3 value1, Vector3 value2)
{
return value1.X * value2.X + value1.Y * value2.Y + value1.Z * value2.Z;
}
public static Vector3 Lerp(Vector3 value1, Vector3 value2, float amount)
{
return new Vector3(
Utils.Lerp(value1.X, value2.X, amount),
Utils.Lerp(value1.Y, value2.Y, amount),
Utils.Lerp(value1.Z, value2.Z, amount));
}
public static float Mag(Vector3 value)
{
return (float)Math.Sqrt((value.X * value.X) + (value.Y * value.Y) + (value.Z * value.Z));
}
public static Vector3 Max(Vector3 value1, Vector3 value2)
{
return new Vector3(
Math.Max(value1.X, value2.X),
Math.Max(value1.Y, value2.Y),
Math.Max(value1.Z, value2.Z));
}
public static Vector3 Min(Vector3 value1, Vector3 value2)
{
return new Vector3(
Math.Min(value1.X, value2.X),
Math.Min(value1.Y, value2.Y),
Math.Min(value1.Z, value2.Z));
}
public static Vector3 Multiply(Vector3 value1, Vector3 value2)
{
value1.X *= value2.X;
value1.Y *= value2.Y;
value1.Z *= value2.Z;
return value1;
}
public static Vector3 Multiply(Vector3 value1, float scaleFactor)
{
value1.X *= scaleFactor;
value1.Y *= scaleFactor;
value1.Z *= scaleFactor;
return value1;
}
public static Vector3 Negate(Vector3 value)
{
value.X = -value.X;
value.Y = -value.Y;
value.Z = -value.Z;
return value;
}
public static Vector3 Normalize(Vector3 value)
{
const float MAG_THRESHOLD = 0.0000001f;
float factor = Distance(value, Zero);
if (factor > MAG_THRESHOLD)
{
factor = 1f / factor;
value.X *= factor;
value.Y *= factor;
value.Z *= factor;
}
else
{
value.X = 0f;
value.Y = 0f;
value.Z = 0f;
}
return value;
}
/// <summary>
/// Parse a vector from a string
/// </summary>
/// <param name="val">A string representation of a 3D vector, enclosed
/// in arrow brackets and separated by commas</param>
public static Vector3 Parse(string val)
{
char[] splitChar = { ',' };
string[] split = val.Replace("<", String.Empty).Replace(">", String.Empty).Split(splitChar);
return new Vector3(
Single.Parse(split[0].Trim(), Utils.EnUsCulture),
Single.Parse(split[1].Trim(), Utils.EnUsCulture),
Single.Parse(split[2].Trim(), Utils.EnUsCulture));
}
public static bool TryParse(string val, out Vector3 result)
{
try
{
result = Parse(val);
return true;
}
catch (Exception)
{
result = Vector3.Zero;
return false;
}
}
/// <summary>
/// Calculate the rotation between two vectors
/// </summary>
/// <param name="a">Normalized directional vector (such as 1,0,0 for forward facing)</param>
/// <param name="b">Normalized target vector</param>
public static Quaternion RotationBetween(Vector3 a, Vector3 b)
{
float dotProduct = Dot(a, b);
Vector3 crossProduct = Cross(a, b);
float magProduct = a.Length() * b.Length();
double angle = Math.Acos(dotProduct / magProduct);
Vector3 axis = Normalize(crossProduct);
float s = (float)Math.Sin(angle / 2d);
return new Quaternion(
axis.X * s,
axis.Y * s,
axis.Z * s,
(float)Math.Cos(angle / 2d));
}
/// <summary>
/// Interpolates between two vectors using a cubic equation
/// </summary>
public static Vector3 SmoothStep(Vector3 value1, Vector3 value2, float amount)
{
return new Vector3(
Utils.SmoothStep(value1.X, value2.X, amount),
Utils.SmoothStep(value1.Y, value2.Y, amount),
Utils.SmoothStep(value1.Z, value2.Z, amount));
}
public static Vector3 Subtract(Vector3 value1, Vector3 value2)
{
value1.X -= value2.X;
value1.Y -= value2.Y;
value1.Z -= value2.Z;
return value1;
}
public static Vector3 Transform(Vector3 position, Matrix4 matrix)
{
return new Vector3(
(position.X * matrix.M11) + (position.Y * matrix.M21) + (position.Z * matrix.M31) + matrix.M41,
(position.X * matrix.M12) + (position.Y * matrix.M22) + (position.Z * matrix.M32) + matrix.M42,
(position.X * matrix.M13) + (position.Y * matrix.M23) + (position.Z * matrix.M33) + matrix.M43);
}
public static Vector3 TransformNormal(Vector3 position, Matrix4 matrix)
{
return new Vector3(
(position.X * matrix.M11) + (position.Y * matrix.M21) + (position.Z * matrix.M31),
(position.X * matrix.M12) + (position.Y * matrix.M22) + (position.Z * matrix.M32),
(position.X * matrix.M13) + (position.Y * matrix.M23) + (position.Z * matrix.M33));
}
#endregion Static Methods
#region Overrides
public override bool Equals(object obj)
{
return (obj is Vector3) ? this == (Vector3)obj : false;
}
public bool Equals(Vector3 other)
{
return this == other;
}
public override int GetHashCode()
{
int hash = X.GetHashCode();
hash = hash * 31 + Y.GetHashCode();
hash = hash * 31 + Z.GetHashCode();
return hash;
}
/// <summary>
/// Get a formatted string representation of the vector
/// </summary>
/// <returns>A string representation of the vector</returns>
public override string ToString()
{
return String.Format(Utils.EnUsCulture, "<{0}, {1}, {2}>", X, Y, Z);
}
/// <summary>
/// Get a string representation of the vector elements with up to three
/// decimal digits and separated by spaces only
/// </summary>
/// <returns>Raw string representation of the vector</returns>
public string ToRawString()
{
CultureInfo enUs = new CultureInfo("en-us");
enUs.NumberFormat.NumberDecimalDigits = 3;
return String.Format(enUs, "{0} {1} {2}", X, Y, Z);
}
#endregion Overrides
#region Operators
public static bool operator ==(Vector3 value1, Vector3 value2)
{
return value1.X == value2.X
&& value1.Y == value2.Y
&& value1.Z == value2.Z;
}
public static bool operator !=(Vector3 value1, Vector3 value2)
{
return !(value1 == value2);
}
public static Vector3 operator +(Vector3 value1, Vector3 value2)
{
value1.X += value2.X;
value1.Y += value2.Y;
value1.Z += value2.Z;
return value1;
}
public static Vector3 operator -(Vector3 value)
{
value.X = -value.X;
value.Y = -value.Y;
value.Z = -value.Z;
return value;
}
public static Vector3 operator -(Vector3 value1, Vector3 value2)
{
value1.X -= value2.X;
value1.Y -= value2.Y;
value1.Z -= value2.Z;
return value1;
}
public static Vector3 operator *(Vector3 value1, Vector3 value2)
{
value1.X *= value2.X;
value1.Y *= value2.Y;
value1.Z *= value2.Z;
return value1;
}
public static Vector3 operator *(Vector3 value, float scaleFactor)
{
value.X *= scaleFactor;
value.Y *= scaleFactor;
value.Z *= scaleFactor;
return value;
}
public static Vector3 operator *(Vector3 vec, Quaternion rot)
{
float rw = -rot.X * vec.X - rot.Y * vec.Y - rot.Z * vec.Z;
float rx = rot.W * vec.X + rot.Y * vec.Z - rot.Z * vec.Y;
float ry = rot.W * vec.Y + rot.Z * vec.X - rot.X * vec.Z;
float rz = rot.W * vec.Z + rot.X * vec.Y - rot.Y * vec.X;
vec.X = -rw * rot.X + rx * rot.W - ry * rot.Z + rz * rot.Y;
vec.Y = -rw * rot.Y + ry * rot.W - rz * rot.X + rx * rot.Z;
vec.Z = -rw * rot.Z + rz * rot.W - rx * rot.Y + ry * rot.X;
return vec;
}
public static Vector3 operator *(Vector3 vector, Matrix4 matrix)
{
return Transform(vector, matrix);
}
public static Vector3 operator /(Vector3 value1, Vector3 value2)
{
value1.X /= value2.X;
value1.Y /= value2.Y;
value1.Z /= value2.Z;
return value1;
}
public static Vector3 operator /(Vector3 value, float divider)
{
float factor = 1f / divider;
value.X *= factor;
value.Y *= factor;
value.Z *= factor;
return value;
}
/// <summary>
/// Cross product between two vectors
/// </summary>
public static Vector3 operator %(Vector3 value1, Vector3 value2)
{
return Cross(value1, value2);
}
/// <summary>
/// Explicit casting for Vector3d > Vector3
/// </summary>
/// <param name="value"></param>
/// <returns></returns>
public static explicit operator Vector3(Vector3d value)
{
Vector3d foo = (Vector3d)Vector3.Zero;
return new Vector3(value);
}
#endregion Operators
/// <summary>A vector with a value of 0,0,0</summary>
public readonly static Vector3 Zero = new Vector3();
/// <summary>A vector with a value of 1,1,1</summary>
public readonly static Vector3 One = new Vector3(1f, 1f, 1f);
/// <summary>A unit vector facing forward (X axis), value 1,0,0</summary>
public readonly static Vector3 UnitX = new Vector3(1f, 0f, 0f);
/// <summary>A unit vector facing left (Y axis), value 0,1,0</summary>
public readonly static Vector3 UnitY = new Vector3(0f, 1f, 0f);
/// <summary>A unit vector facing up (Z axis), value 0,0,1</summary>
public readonly static Vector3 UnitZ = new Vector3(0f, 0f, 1f);
}
}
| |
using System;
using System.Globalization;
using System.Linq;
using System.Threading;
using Microsoft.SharePoint.Client;
namespace Core.ListRatingSettings
{
public enum VotingExperience
{
None,
Ratings,
Likes
}
public class RatingsEnabler
{
private readonly ILogger _logger;
private readonly ClientContext _context;
private List _library;
public RatingsEnabler(ClientContext context) : this(context, new ConsoleLogger())
{
}
public RatingsEnabler(ClientContext context, ILogger logger)
{
if (context == null) throw new ArgumentNullException("context");
if (logger == null) throw new ArgumentNullException("logger");
_context = context;
_logger = logger;
}
#region Rating Field
private readonly Guid RatingsFieldGuid_AverageRating = new Guid("5a14d1ab-1513-48c7-97b3-657a5ba6c742");
private readonly Guid RatingsFieldGuid_RatingCount = new Guid("b1996002-9167-45e5-a4df-b2c41c6723c7");
private readonly Guid RatingsFieldGuid_RatedBy = new Guid("4D64B067-08C3-43DC-A87B-8B8E01673313");
private readonly Guid RatingsFieldGuid_Ratings = new Guid("434F51FB-FFD2-4A0E-A03B-CA3131AC67BA");
private readonly Guid LikeFieldGuid_LikedBy = new Guid("2cdcd5eb-846d-4f4d-9aaf-73e8e73c7312");
private readonly Guid LikeFieldGuid_LikeCount = new Guid("6e4d832b-f610-41a8-b3e0-239608efda41");
#endregion
public void Disable(string listName)
{
var web = _context.Web;
_context.Load(_context.Web, p => p.Url);
_context.ExecuteQuery();
// Fetch Library
try
{
_library = web.Lists.GetByTitle(listName);
_context.Load(_library);
_context.ExecuteQuery();
_logger.WriteSuccess("Found list/library : " + _library.Title);
}
catch (ServerException e)
{
_logger.WriteException(string.Format("Error: {0} \nMessage: {1} \nStack: {2}", web.Url, e.Message, e.StackTrace));
return;
}
// Add to property Root Folder of Pages Library
AddProperty(VotingExperience.None);
}
/// <summary>
/// Enable Social Settings Likes/Ratings on given list
/// </summary>
/// <param name="listName">List Name</param>
/// <param name="experience">Likes/Ratings</param>
public void Enable(string listName,VotingExperience experience)
{
/* Get root Web
* Validate if current web is publishing web
* Find List/Library library
* Add property to RootFolder of List/Library : key: Ratings_VotingExperience value:Likes
* Add rating fields
* Add fields to default view
* */
var web = _context.Site.RootWeb;
_context.Load(_context.Site.RootWeb, p => p.Url);
_context.ExecuteQuery();
try
{
_logger.WriteInfo("Processing: " + web.Url);
EnsureReputation(web, listName,experience);
}
catch (Exception e)
{
_logger.WriteException(string.Format("Error: {0} \nMessage: {1} \nStack: {2}", web.Url, e.Message, e.StackTrace));
}
}
private void EnsureReputation(Web web,string listName,VotingExperience experience)
{
// only process publishing web
if (!IsPublishingWeb(web))
{
_logger.WriteWarning("Is publishing site : No");
return;
}
_logger.WriteInfo("Is publishing site : Yes");
SetCulture(GetWebCulture(web));
// Fetch Library
try
{
_library = web.Lists.GetByTitle(listName);
_context.Load(_library);
_context.ExecuteQuery();
_logger.WriteSuccess("Found list/library : " + _library.Title);
}
catch (ServerException e)
{
_logger.WriteException(string.Format("Error: {0} \nMessage: {1} \nStack: {2}", web.Url, e.Message, e.StackTrace));
return;
}
// Add to property Root Folder of Pages Library
AddProperty(experience);
AddListFields();
AddViewFields(experience);
_logger.WriteSuccess(string.Format("Enabled {0} on list/library {1}", experience,_library.Title));
}
/// <summary>
/// Checks if the web is Publishing Web
/// </summary>
/// <param name="web"></param>
/// <returns></returns>
private bool IsPublishingWeb(Web web)
{
_context.Load(web, p => p.AllProperties);
_context.ExecuteQuery();
return web.AllProperties.FieldValues.ContainsKey("__PublishingFeatureActivated");
}
/// <summary>
/// Add Ratings/Likes related fields to List
/// </summary>
private void AddListFields()
{
//NOTE: The method returns the field, which can be used if required, for the sake of simplicity i removed it
EnsureField(_library, RatingsFieldGuid_RatingCount);
EnsureField(_library, RatingsFieldGuid_RatedBy);
EnsureField(_library, RatingsFieldGuid_Ratings);
EnsureField(_library, RatingsFieldGuid_AverageRating);
EnsureField(_library, LikeFieldGuid_LikedBy);
EnsureField(_library, LikeFieldGuid_LikeCount);
_library.Update();
_context.ExecuteQuery();
_logger.WriteSuccess("Ensured fields in library.");
}
/// <summary>
/// Add/Remove Ratings/Likes field in default view depending on exerpeince selected
/// </summary>
/// <param name="experience"></param>
private void AddViewFields(VotingExperience experience)
{
// Add LikesCount and LikeBy (Explicit) to view fields
_context.Load(_library.DefaultView, p => p.ViewFields);
_context.ExecuteQuery();
var defaultView = _library.DefaultView;
switch (experience)
{
case VotingExperience.Ratings:
// Remove Likes Fields
if(defaultView.ViewFields.Contains("LikesCount"))
defaultView.ViewFields.Remove("LikesCount");
defaultView.ViewFields.Add("AverageRating");
// Add Ratings related field
break;
case VotingExperience.Likes:
// Remove Ratings Fields
// Add Likes related field
if (defaultView.ViewFields.Contains("AverageRating"))
defaultView.ViewFields.Remove("AverageRating");
defaultView.ViewFields.Add("LikesCount");
break;
default:
throw new ArgumentOutOfRangeException("experience");
}
defaultView.Update();
_context.ExecuteQuery();
_logger.WriteSuccess("Ensured view-field.");
}
/// <summary>
/// Check for Ratings/Likes field and add to ListField if doesn't exists.
/// </summary>
/// <param name="list">List</param>
/// <param name="fieldId">Field Id</param>
/// <returns></returns>
private Field EnsureField(List list, Guid fieldId)
{
FieldCollection fields = list.Fields;
FieldCollection availableFields = list.ParentWeb.AvailableFields;
Field field = availableFields.GetById(fieldId);
_context.Load(fields);
_context.Load(field, p => p.SchemaXmlWithResourceTokens, p => p.Id, p => p.InternalName, p => p.StaticName);
_context.ExecuteQuery();
if (!fields.Any(p => p.Id == fieldId))
{
var newField = fields.AddFieldAsXml(field.SchemaXmlWithResourceTokens, false, AddFieldOptions.AddFieldInternalNameHint | AddFieldOptions.AddToAllContentTypes);
return newField;
}
return field;
}
/// <summary>
/// Add required key/value settings on List Root-Folder
/// </summary>
/// <param name="experience"></param>
private void AddProperty(VotingExperience experience)
{
_context.Load(_library.RootFolder, p => p.Properties);
_context.ExecuteQuery();
if (experience != VotingExperience.None)
{
_library.RootFolder.Properties["Ratings_VotingExperience"] = experience.ToString();
}
else
{
_library.RootFolder.Properties["Ratings_VotingExperience"] = "";
}
_library.RootFolder.Update();
_context.ExecuteQuery();
_logger.WriteSuccess(string.Format("Ensured {0} Property.",experience));
}
private uint GetWebCulture(Web web)
{
_context.Load(web, p => p.Language);
_context.ExecuteQuery();
return web.Language;
}
private void SetCulture(uint culture)
{
Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture(CultureInfo.GetCultureInfo((int)culture).ToString());
Thread.CurrentThread.CurrentUICulture = CultureInfo.CreateSpecificCulture(CultureInfo.GetCultureInfo((int)culture).ToString());
}
}
}
| |
using System;
using KSP.Localization;
using UnityEngine;
namespace Starstrider42.CustomAsteroids
{
/// <summary>
/// Represents a set of asteroids aimed at a celestial body's sphere of influence.
/// </summary>
///
/// <remarks>To avoid breaking the persistence code, Flyby may not have subclasses.</remarks>
internal sealed class Flyby : AbstractAsteroidSet
{
/// <summary>The name of the celestial object the asteroids will approach.</summary>
[Persistent]
readonly string targetBody;
/// <summary>
/// The distance by which the asteroid would miss <c>targetBody</c> without gravitational
/// focusing.
/// </summary>
[Persistent]
readonly ApproachRange approach;
/// <summary>The time to closest approach (again, ignoring <c>targetBody</c>'s gravity).</summary>
[Persistent]
readonly ValueRange warnTime;
/// <summary>The speed relative to <c>targetBody</c>, ignoring its gravity.</summary>
[Persistent]
readonly ValueRange vSoi;
/// <summary>
/// Creates a dummy flyby group. The object is initialized to a state in which it will not
/// be expected to generate orbits. Any orbits that <em>are</em> generated will be located
/// inside Kerbin, causing the game to immediately delete the object with the orbit. Does
/// not throw exceptions.
/// </summary>
internal Flyby ()
{
targetBody = "Kerbin";
approach = new ApproachRange (ValueRange.Distribution.Uniform,
ApproachRange.Type.Periapsis, min: 0);
warnTime = new ValueRange (ValueRange.Distribution.Uniform);
vSoi = new ValueRange (ValueRange.Distribution.LogNormal, avg: 300, stdDev: 100);
}
public override Orbit drawOrbit ()
{
CelestialBody body = AsteroidManager.getPlanetByName (targetBody);
Debug.Log ("[CustomAsteroids]: "
+ Localizer.Format ("#autoLOC_CustomAsteroids_LogOrbitDraw", getName ()));
double deltaV = wrappedDraw (vSoi, getName (), "vSoi");
double deltaT = wrappedDraw (warnTime, getName (), "warnTime");
if (deltaV <= 0.0) {
throw new InvalidOperationException (
Localizer.Format ("#autoLOC_CustomAsteroids_ErrorFlybyBadVInf",
getName (), deltaV));
}
// Negative deltaT is allowed
double peri;
switch (approach.getParam ()) {
case ApproachRange.Type.ImpactParameter:
double b = wrappedDraw (approach, getName (), "approach");
if (b < 0.0) {
throw new InvalidOperationException (
Localizer.Format ("#autoLOC_CustomAsteroids_ErrorFlybyBadB", getName (), b));
}
double a = -body.gravParameter / (deltaV * deltaV);
double x = b / a;
peri = a * (1.0 - Math.Sqrt (x * x + 1.0));
break;
case ApproachRange.Type.Periapsis:
peri = wrappedDraw (approach, getName (), "approach");
if (peri < 0.0) {
throw new InvalidOperationException (
Localizer.Format ("#autoLOC_CustomAsteroids_ErrorFlybyBadPeri",
getName (), peri));
}
break;
default:
throw new InvalidOperationException (
Localizer.Format ("#autoLOC_CustomAsteroids_ErrorFlybyBadApproach",
getName (), approach.getParam ()));
}
#if DEBUG
Debug.Log ($"[CustomAsteroids]: "
+ Localizer.Format ("#autoLOC_CustomAsteroids_LogFlyby",
peri, targetBody, deltaT / (6.0 * 3600.0), deltaV)
);
#endif
Orbit newOrbit = createHyperbolicOrbit (body, peri, deltaV,
Planetarium.GetUniversalTime () + deltaT);
// Sun has sphereOfInfluence = +Infinity, so condition will always fail for Sun-centric
// orbit. No special treatment needed for the case where the orbit lies entirely outside
// the SoI
while (needsSoITransition (newOrbit)) {
newOrbit = patchToParent (newOrbit);
}
newOrbit.UpdateFromUT (Planetarium.GetUniversalTime ());
return newOrbit;
}
/// <summary>
/// Creates a hyperbolic orbit around the given celestial body.
/// </summary>
/// <returns>The newly created orbit, with state vectors anchored to its periapsis.</returns>
/// <param name="body">The celestial body at the focus of the orbit.</param>
/// <param name="periapsis">The periapsis (from the body center), in meters. Must not be
/// negative.</param>
/// <param name="vInf">The excess speed associated with the orbit, in meters per second.
/// Must be positive.</param>
/// <param name="utPeri">The absolute time of periapsis passage.</param>
///
/// <exception cref="ArgumentException">Thrown if either <c>periapsis</c> or <c>vInf</c>
/// are out of bounds.</exception>
static Orbit createHyperbolicOrbit (CelestialBody body, double periapsis, double vInf,
double utPeri)
{
if (vInf <= 0.0) {
throw new ArgumentException (
Localizer.Format ("#autoLOC_CustomAsteroids_ErrorHyperBadVInf", vInf),
nameof (vInf));
}
if (periapsis < 0.0) {
throw new ArgumentException (
Localizer.Format ("#autoLOC_CustomAsteroids_ErrorHyperBadPeri", periapsis),
nameof (periapsis));
}
double a = -body.gravParameter / (vInf * vInf);
double e = 1.0 - periapsis / a;
// Random orientation, to be consistent with CreateRandomOrbitFlyBy
double i = RandomDist.drawIsotropic ();
double lAn = RandomDist.drawAngle ();
double aPe = RandomDist.drawAngle ();
Debug.Log ($"[CustomAsteroids]: "
+ Localizer.Format ("#autoLOC_CustomAsteroids_LogHyperOrbit", body.bodyName,
a, e, i, aPe, lAn));
return new Orbit (i, e, a, lAn, aPe, 0.0, utPeri, body);
}
/// <summary>
/// Returns the orbit adjacent to the given orbit. <c>oldOrbit</c> must leave its reference
/// body' SoI. If the orbit's epoch of periapsis is in the future, the returned orbit will
/// precede <c>oldOrbit</c>; if it is in the past, the returned orbit will follow
/// <c>oldOrbit</c>.
/// </summary>
/// <returns>An orbit around the parent body of <c>oldOrbit</c>'s body, that patches
/// seamlessly with <c>oldOrbit</c> at its body' SoI boundary. See main description for
/// whether it's an incoming or outgoing patch.</returns>
/// <param name="oldOrbit">The orbit to use as a reference for patching. The time interval
/// in which the orbit is inside the indicated SoI must not include the current time.</param>
///
/// <exception cref="ArgumentException">Thrown if <c>oldOrbit</c> does not intersect a sphere
/// of influence.</exception>
/// <exception cref="InvalidOperationException">Thrown if an object following <c>oldOrbit</c>
/// would be inside its parent body's sphere of influence at the current time.</exception>
static Orbit patchToParent (Orbit oldOrbit)
{
if (!needsSoITransition (oldOrbit)) {
throw new InvalidOperationException (
Localizer.Format ("#autoLOC_CustomAsteroids_ErrorSoiInvalid",
oldOrbit.referenceBody));
}
if (oldOrbit.referenceBody.GetOrbitDriver () == null) {
throw new ArgumentException (
Localizer.Format ("#autoLOC_CustomAsteroids_ErrorSoiNoParent",
oldOrbit.referenceBody));
}
CelestialBody oldParent = oldOrbit.referenceBody;
CelestialBody newParent = oldParent.orbit.referenceBody;
double utSoi = getSoiCrossing (oldOrbit);
#if DEBUG
Debug.Log (Localizer.Format ("#autoLOC_CustomAsteroids_LogSoi",
oldParent, newParent, utSoi));
#endif
// Need position/velocity relative to newParent, not oldParent or absolute
Vector3d xNewParent = oldOrbit.getRelativePositionAtUT (utSoi)
+ oldParent.orbit.getRelativePositionAtUT (utSoi);
Vector3d vNewParent = oldOrbit.getOrbitalVelocityAtUT (utSoi)
+ oldParent.orbit.getOrbitalVelocityAtUT (utSoi);
Orbit newOrbit = new Orbit ();
newOrbit.UpdateFromStateVectors (xNewParent, vNewParent, newParent, utSoi);
return newOrbit;
}
/// <summary>
/// Returns whether the given orbit undergoes any SoI transitions between its
/// characteristic epoch and the current time. Does not throw exceptions.
/// </summary>
/// <returns><c>true</c>, if the orbit needs to be corrected for an SoI transition,
/// <c>false</c> otherwise.</returns>
/// <param name="orbit">The orbit to test</param>
static bool needsSoITransition (Orbit orbit)
{
double now = Planetarium.GetUniversalTime ();
double soi = orbit.referenceBody.sphereOfInfluence;
if (orbit.eccentricity >= 1.0) {
return orbit.getRelativePositionAtUT (now).magnitude > soi;
}
// If an elliptical orbit leaves the SoI, then getRelativePositionAtUT gives
// misleading results after the SoI transition.
return (orbit.ApR > soi)
&& ((Math.Abs (now - orbit.epoch) > 0.5 * orbit.period)
|| (orbit.getRelativePositionAtUT (now).magnitude > soi));
}
/// <summary>
/// Returns the time at which the given orbit enters its parent body's sphere of influence
/// (if in the future) or exits it (if in the past). If the orbit is always outside the
/// sphere of influence, returns the nominal time of periapsis.
/// </summary>
/// <returns>The UT of SoI entry/exit, to within 1 second.</returns>
/// <param name="hyperbolic">An unbound orbit. MUST have a parent body with a sphere of
/// influence.</param>
///
/// <exception cref="ArgumentException">Thrown if orbit does not intersect a sphere of
/// influence.</exception>
static double getSoiCrossing (Orbit hyperbolic)
{
// Desired accuracy of result, in seconds
const double PRECISION = 1.0;
double soi = hyperbolic.referenceBody.sphereOfInfluence;
if (double.IsInfinity (soi) || double.IsNaN (soi)) {
throw new ArgumentException (
Localizer.Format ("#autoLOC_CustomAsteroids_ErrorSoiNoSoi",
hyperbolic.referenceBody),
nameof (hyperbolic));
}
if (hyperbolic.eccentricity < 1.0 && hyperbolic.ApR < soi) {
throw new ArgumentException (
Localizer.Format ("#autoLOC_CustomAsteroids_ErrorSoiNoExit", hyperbolic),
nameof (hyperbolic));
}
double innerUT = hyperbolic.epoch - hyperbolic.ObTAtEpoch;
double outerUT = innerUT;
double pseudoPeriod = Math.Abs (2.0 * Math.PI
/ hyperbolic.GetMeanMotion (hyperbolic.semiMajorAxis));
if (innerUT > Planetarium.GetUniversalTime ()) {
// Search for SoI entry
while (hyperbolic.getRelativePositionAtUT (outerUT).magnitude < soi) {
outerUT -= 0.5 * pseudoPeriod;
}
} else {
// Search for SoI exit
while (hyperbolic.getRelativePositionAtUT (outerUT).magnitude < soi) {
outerUT += 0.5 * pseudoPeriod;
}
}
// Pinpoint SoI entry/exit
while (Math.Abs (outerUT - innerUT) > PRECISION) {
double ut = 0.5 * (innerUT + outerUT);
if (hyperbolic.getRelativePositionAtUT (ut).magnitude < soi) {
// Too close; look higher
innerUT = ut;
} else {
// Too far; look lower
outerUT = ut;
}
}
return 0.5 * (innerUT + outerUT);
}
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Linq;
using System.IO;
using Roslyn.Test.Utilities;
using Microsoft.CodeAnalysis.Test.Utilities;
using Xunit;
using Microsoft.CodeAnalysis;
using System.Collections.Immutable;
using Roslyn.Utilities;
using System.Runtime.InteropServices;
namespace Microsoft.CodeAnalysis.Scripting.Hosting.UnitTests
{
// TODO: clean up and move to portable tests
public class MetadataShadowCopyProviderTests : TestBase, IDisposable
{
private readonly MetadataShadowCopyProvider _provider;
private static readonly ImmutableArray<string> s_systemNoShadowCopyDirectories = ImmutableArray.Create(
FileUtilities.NormalizeDirectoryPath(Environment.GetFolderPath(Environment.SpecialFolder.Windows)),
FileUtilities.NormalizeDirectoryPath(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles)),
FileUtilities.NormalizeDirectoryPath(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFilesX86)),
FileUtilities.NormalizeDirectoryPath(RuntimeEnvironment.GetRuntimeDirectory()));
public MetadataShadowCopyProviderTests()
{
_provider = new MetadataShadowCopyProvider(TempRoot.Root, s_systemNoShadowCopyDirectories);
}
public override void Dispose()
{
_provider.Dispose();
Assert.False(Directory.Exists(_provider.ShadowCopyDirectory), "Shadow copy directory should have been deleted");
base.Dispose();
}
[Fact]
public void Errors()
{
Assert.Throws<ArgumentNullException>(() => _provider.NeedsShadowCopy(null));
Assert.Throws<ArgumentException>(() => _provider.NeedsShadowCopy("c:foo.dll"));
Assert.Throws<ArgumentException>(() => _provider.NeedsShadowCopy("bar.dll"));
Assert.Throws<ArgumentException>(() => _provider.NeedsShadowCopy(@"\bar.dll"));
Assert.Throws<ArgumentException>(() => _provider.NeedsShadowCopy(@"../bar.dll"));
Assert.Throws<ArgumentNullException>(() => _provider.SuppressShadowCopy(null));
Assert.Throws<ArgumentException>(() => _provider.SuppressShadowCopy("c:foo.dll"));
Assert.Throws<ArgumentException>(() => _provider.SuppressShadowCopy("bar.dll"));
Assert.Throws<ArgumentException>(() => _provider.SuppressShadowCopy(@"\bar.dll"));
Assert.Throws<ArgumentException>(() => _provider.SuppressShadowCopy(@"../bar.dll"));
Assert.Throws<ArgumentNullException>(() => _provider.GetReference(null));
Assert.Throws<ArgumentException>(() => _provider.GetReference("c:foo.dll"));
Assert.Throws<ArgumentException>(() => _provider.GetReference("bar.dll"));
Assert.Throws<ArgumentException>(() => _provider.GetReference(@"\bar.dll"));
Assert.Throws<ArgumentException>(() => _provider.GetReference(@"../bar.dll"));
Assert.Throws<ArgumentOutOfRangeException>(() => _provider.GetMetadataShadowCopy(@"c:\foo.dll", (MetadataImageKind)Byte.MaxValue));
Assert.Throws<ArgumentNullException>(() => _provider.GetMetadataShadowCopy(null, MetadataImageKind.Assembly));
Assert.Throws<ArgumentException>(() => _provider.GetMetadataShadowCopy("c:foo.dll", MetadataImageKind.Assembly));
Assert.Throws<ArgumentException>(() => _provider.GetMetadataShadowCopy("bar.dll", MetadataImageKind.Assembly));
Assert.Throws<ArgumentException>(() => _provider.GetMetadataShadowCopy(@"\bar.dll", MetadataImageKind.Assembly));
Assert.Throws<ArgumentException>(() => _provider.GetMetadataShadowCopy(@"../bar.dll", MetadataImageKind.Assembly));
Assert.Throws<ArgumentOutOfRangeException>(() => _provider.GetMetadata(@"c:\foo.dll", (MetadataImageKind)Byte.MaxValue));
Assert.Throws<ArgumentNullException>(() => _provider.GetMetadata(null, MetadataImageKind.Assembly));
Assert.Throws<ArgumentException>(() => _provider.GetMetadata("c:foo.dll", MetadataImageKind.Assembly));
}
[Fact]
public void Copy()
{
var dir = Temp.CreateDirectory();
var dll = dir.CreateFile("a.dll").WriteAllBytes(TestResources.MetadataTests.InterfaceAndClass.CSClasses01);
var doc = dir.CreateFile("a.xml").WriteAllText("<hello>");
var sc1 = _provider.GetMetadataShadowCopy(dll.Path, MetadataImageKind.Assembly);
var sc2 = _provider.GetMetadataShadowCopy(dll.Path, MetadataImageKind.Assembly);
Assert.Equal(sc2, sc1);
Assert.Equal(dll.Path, sc1.PrimaryModule.OriginalPath);
Assert.NotEqual(dll.Path, sc1.PrimaryModule.FullPath);
Assert.False(sc1.Metadata.IsImageOwner, "Copy expected");
Assert.Equal(File.ReadAllBytes(dll.Path), File.ReadAllBytes(sc1.PrimaryModule.FullPath));
Assert.Equal(File.ReadAllBytes(doc.Path), File.ReadAllBytes(sc1.DocumentationFile.FullPath));
}
[Fact]
public void SuppressCopy1()
{
var dll = Temp.CreateFile().WriteAllText("blah");
_provider.SuppressShadowCopy(dll.Path);
var sc1 = _provider.GetMetadataShadowCopy(dll.Path, MetadataImageKind.Assembly);
Assert.Null(sc1);
}
[Fact]
public void SuppressCopy_Framework()
{
// framework assemblies not copied:
string mscorlib = typeof(object).Assembly.Location;
var sc2 = _provider.GetMetadataShadowCopy(mscorlib, MetadataImageKind.Assembly);
Assert.Null(sc2);
}
[Fact]
public void SuppressCopy_ShadowCopyDirectory()
{
// shadow copies not copied:
var dll = Temp.CreateFile("a.dll").WriteAllBytes(TestResources.MetadataTests.InterfaceAndClass.CSClasses01);
// copy:
var sc1 = _provider.GetMetadataShadowCopy(dll.Path, MetadataImageKind.Assembly);
Assert.NotEqual(dll.Path, sc1.PrimaryModule.FullPath);
// file not copied:
var sc2 = _provider.GetMetadataShadowCopy(sc1.PrimaryModule.FullPath, MetadataImageKind.Assembly);
Assert.Null(sc2);
}
[Fact]
public void Modules()
{
// modules: { MultiModule.dll, mod2.netmodule, mod3.netmodule }
var dir = Temp.CreateDirectory();
string path0 = dir.CreateFile("MultiModule.dll").WriteAllBytes(TestResources.SymbolsTests.MultiModule.MultiModuleDll).Path;
string path1 = dir.CreateFile("mod2.netmodule").WriteAllBytes(TestResources.SymbolsTests.MultiModule.mod2).Path;
string path2 = dir.CreateFile("mod3.netmodule").WriteAllBytes(TestResources.SymbolsTests.MultiModule.mod3).Path;
var reference1 = _provider.GetReference(path0);
Assert.NotNull(reference1);
Assert.Equal(0, _provider.CacheSize);
Assert.Equal(path0, reference1.FilePath);
var metadata1 = reference1.GetMetadata() as AssemblyMetadata;
Assert.NotNull(metadata1);
Assert.Equal(3, metadata1.GetModules().Length);
var scDir = Directory.GetFileSystemEntries(_provider.ShadowCopyDirectory).Single();
Assert.True(Directory.Exists(scDir));
var scFiles = Directory.GetFileSystemEntries(scDir);
AssertEx.SetEqual(new[] { "MultiModule.dll", "mod2.netmodule", "mod3.netmodule" }, scFiles.Select(p => Path.GetFileName(p)));
foreach (var sc in scFiles)
{
Assert.True(_provider.IsShadowCopy(sc));
// files should be locked:
Assert.Throws<IOException>(() => File.Delete(sc));
}
// should get the same metadata:
var metadata2 = reference1.GetMetadata() as AssemblyMetadata;
Assert.Same(metadata1, metadata2);
// a new reference is created:
var reference2 = _provider.GetReference(path0);
Assert.NotNull(reference2);
Assert.Equal(path0, reference2.FilePath);
Assert.NotSame(reference1, reference2);
// the original file wasn't modified so we still get the same metadata:
var metadata3 = reference2.GetMetadata() as AssemblyMetadata;
Assert.Same(metadata3, metadata2);
// modify the file:
File.SetLastWriteTimeUtc(path0, DateTime.Now + TimeSpan.FromHours(1));
// the reference doesn't own the metadata, so we get an updated image if we ask again:
var modifiedMetadata3 = reference2.GetMetadata() as AssemblyMetadata;
Assert.NotSame(modifiedMetadata3, metadata2);
// a new reference is created, again we get the modified image (which is copied to the shadow copy directory):
var reference4 = _provider.GetReference(path0);
Assert.NotNull(reference4);
Assert.Equal(path0, reference4.FilePath);
Assert.NotSame(reference2, reference4);
// the file has been modified - we get new metadata:
var metadata4 = reference4.GetMetadata() as AssemblyMetadata;
Assert.NotSame(metadata4, metadata3);
for (int i = 0; i < metadata4.GetModules().Length; i++)
{
Assert.NotSame(metadata4.GetModules()[i], metadata3.GetModules()[i]);
}
}
[Fact]
public unsafe void DisposalOnFailure()
{
var f0 = Temp.CreateFile().WriteAllText("bogus").Path;
var r0 = _provider.GetReference(f0);
Assert.Throws<BadImageFormatException>(() => r0.GetMetadata());
string f1 = Temp.CreateFile().WriteAllBytes(TestResources.SymbolsTests.MultiModule.MultiModuleDll).Path;
var r1 = _provider.GetReference(f1);
Assert.Throws<FileNotFoundException>(() => r1.GetMetadata());
}
[Fact]
public void GetMetadata()
{
var dir = Temp.CreateDirectory();
var dll = dir.CreateFile("a.dll").WriteAllBytes(TestResources.MetadataTests.InterfaceAndClass.CSClasses01);
var doc = dir.CreateFile("a.xml").WriteAllText("<hello>");
var sc1 = _provider.GetMetadataShadowCopy(dll.Path, MetadataImageKind.Assembly);
var sc2 = _provider.GetMetadataShadowCopy(dll.Path, MetadataImageKind.Assembly);
var md1 = _provider.GetMetadata(dll.Path, MetadataImageKind.Assembly);
Assert.NotNull(md1);
Assert.Equal(MetadataImageKind.Assembly, md1.Kind);
// This needs to be in different folder from referencesdir to cause the other code path
// to be triggered for NeedsShadowCopy method
var dir2 = System.IO.Path.GetTempPath();
string dll2 = System.IO.Path.Combine(dir2, "a2.dll");
System.IO.File.WriteAllBytes(dll2, TestResources.MetadataTests.InterfaceAndClass.CSClasses01);
Assert.Equal(1, _provider.CacheSize);
var sc3a = _provider.GetMetadataShadowCopy(dll2, MetadataImageKind.Module);
Assert.Equal(2, _provider.CacheSize);
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections;
using System.Collections.Generic;
using Xunit;
namespace System.Net.Primitives.Functional.Tests
{
public static class CredentialCacheTest
{
private static readonly Uri uriPrefix1 = new Uri("http://microsoft:80");
private static readonly Uri uriPrefix2 = new Uri("http://softmicro:80");
private static readonly string host1 = "host1";
private static readonly string host2 = "host2";
private static readonly int port1 = 500;
private static readonly int port2 = 700;
private static readonly string authenticationType1 = "authenticationType1";
private static readonly string authenticationType2 = "authenticationType2";
private static readonly NetworkCredential credential1 = new NetworkCredential("username1", "password");
private static readonly NetworkCredential credential2 = new NetworkCredential("username2", "password");
private static readonly NetworkCredential credential3 = new NetworkCredential("username3", "password");
private static readonly NetworkCredential credential4 = new NetworkCredential("username4", "password");
private static readonly NetworkCredential credential5 = new NetworkCredential("username5", "password");
private static readonly NetworkCredential credential6 = new NetworkCredential("username6", "password");
private static readonly NetworkCredential credential7 = new NetworkCredential("username7", "password");
private static readonly NetworkCredential credential8 = new NetworkCredential("username8", "password");
private struct CredentialCacheCount
{
public CredentialCacheCount(CredentialCache cc, int count)
{
CredentialCache = cc;
Count = count;
}
public CredentialCache CredentialCache { get; }
public int Count { get; }
}
private static CredentialCache CreateUriCredentialCache() =>
CreateUriCredentialCacheCount().CredentialCache;
private static CredentialCacheCount CreateUriCredentialCacheCount(CredentialCache cc = null, int count = 0)
{
cc = cc ?? new CredentialCache();
cc.Add(uriPrefix1, authenticationType1, credential1); count++;
cc.Add(uriPrefix1, authenticationType2, credential2); count++;
cc.Add(uriPrefix2, authenticationType1, credential3); count++;
cc.Add(uriPrefix2, authenticationType2, credential4); count++;
return new CredentialCacheCount(cc, count);
}
private static CredentialCache CreateHostPortCredentialCache() =>
CreateHostPortCredentialCacheCount().CredentialCache;
private static CredentialCacheCount CreateHostPortCredentialCacheCount(CredentialCache cc = null, int count = 0)
{
cc = cc ?? new CredentialCache();
cc.Add(host1, port1, authenticationType1, credential1); count++;
cc.Add(host1, port1, authenticationType2, credential2); count++;
cc.Add(host1, port2, authenticationType1, credential3); count++;
cc.Add(host1, port2, authenticationType2, credential4); count++;
cc.Add(host2, port1, authenticationType1, credential5); count++;
cc.Add(host2, port1, authenticationType2, credential6); count++;
cc.Add(host2, port2, authenticationType1, credential7); count++;
cc.Add(host2, port2, authenticationType2, credential8); count++;
return new CredentialCacheCount(cc, count);
}
private static CredentialCacheCount CreateUriAndHostPortCredentialCacheCount()
{
CredentialCacheCount uri = CreateUriCredentialCacheCount();
return CreateHostPortCredentialCacheCount(uri.CredentialCache, uri.Count);
}
private static IEnumerable<CredentialCacheCount> GetCredentialCacheCounts()
{
yield return new CredentialCacheCount(new CredentialCache(), 0);
yield return CreateUriCredentialCacheCount();
yield return CreateHostPortCredentialCacheCount();
yield return CreateUriAndHostPortCredentialCacheCount();
}
[Fact]
public static void Ctor_Empty_Success()
{
CredentialCache cc = new CredentialCache();
}
[Fact]
public static void Add_UriAuthenticationTypeCredential_Success()
{
CredentialCache cc = CreateUriCredentialCache();
Assert.Equal(credential1, cc.GetCredential(uriPrefix1, authenticationType1));
Assert.Equal(credential2, cc.GetCredential(uriPrefix1, authenticationType2));
Assert.Equal(credential3, cc.GetCredential(uriPrefix2, authenticationType1));
Assert.Equal(credential4, cc.GetCredential(uriPrefix2, authenticationType2));
}
[Fact]
public static void Add_UriAuthenticationTypeCredential_Invalid()
{
CredentialCache cc = CreateUriCredentialCache();
Assert.Null(cc.GetCredential(new Uri("http://invalid.uri"), authenticationType1)); //No such uriPrefix
Assert.Null(cc.GetCredential(uriPrefix1, "invalid-authentication-type")); //No such authenticationType
AssertExtensions.Throws<ArgumentNullException>("uriPrefix", () => cc.Add(null, "some", new NetworkCredential())); //Null uriPrefix
AssertExtensions.Throws<ArgumentNullException>("authType", () => cc.Add(new Uri("http://microsoft:80"), null, new NetworkCredential())); //Null authenticationType
}
[Fact]
public static void Add_UriAuthenticationTypeCredential_DuplicateItem_Throws()
{
CredentialCache cc = new CredentialCache();
cc.Add(uriPrefix1, authenticationType1, credential1);
Assert.Throws<ArgumentException>(() => cc.Add(uriPrefix1, authenticationType1, credential1));
}
[Fact]
public static void Add_HostPortAuthenticationTypeCredential_Success()
{
CredentialCache cc = CreateHostPortCredentialCache();
Assert.Equal(credential1, cc.GetCredential(host1, port1, authenticationType1));
Assert.Equal(credential2, cc.GetCredential(host1, port1, authenticationType2));
Assert.Equal(credential3, cc.GetCredential(host1, port2, authenticationType1));
Assert.Equal(credential4, cc.GetCredential(host1, port2, authenticationType2));
Assert.Equal(credential5, cc.GetCredential(host2, port1, authenticationType1));
Assert.Equal(credential6, cc.GetCredential(host2, port1, authenticationType2));
Assert.Equal(credential7, cc.GetCredential(host2, port2, authenticationType1));
Assert.Equal(credential8, cc.GetCredential(host2, port2, authenticationType2));
}
[Fact]
public static void Add_HostPortAuthenticationTypeCredential_Invalid()
{
CredentialCache cc = CreateHostPortCredentialCache();
Assert.Null(cc.GetCredential("invalid-host", port1, authenticationType1)); //No such host
Assert.Null(cc.GetCredential(host1, 900, authenticationType1)); //No such port
Assert.Null(cc.GetCredential(host1, port1, "invalid-authentication-type")); //No such authenticationType
AssertExtensions.Throws<ArgumentNullException>("host", () => cc.Add(null, 500, "authenticationType", new NetworkCredential())); //Null host
AssertExtensions.Throws<ArgumentNullException>("authenticationType", () => cc.Add("host", 500, null, new NetworkCredential())); //Null authenticationType
var exception = Record.Exception(() => cc.Add("", 500, "authenticationType", new NetworkCredential()));
// On full framework we get exception.ParamName as null while it is "host" on netcore
Assert.NotNull(exception);
Assert.True(exception is ArgumentException);
ArgumentException ae = exception as ArgumentException;
Assert.True(ae.ParamName == "host" || ae.ParamName == null);
AssertExtensions.Throws<ArgumentOutOfRangeException>("port", () => cc.Add("host", -1, "authenticationType", new NetworkCredential())); //Port < 0
}
[Fact]
public static void Add_HostPortAuthenticationTypeCredential_DuplicateItem_Throws()
{
CredentialCache cc = new CredentialCache();
cc.Add(host1, port1, authenticationType1, credential1);
Assert.Throws<ArgumentException>(() => cc.Add(host1, port1, authenticationType1, credential1));
}
[Fact]
public static void Remove_UriAuthenticationType_Success()
{
CredentialCache cc = CreateUriCredentialCache();
cc.Remove(uriPrefix1, authenticationType1);
Assert.Null(cc.GetCredential(uriPrefix1, authenticationType1));
}
[Fact]
public static void Remove_UriAuthenticationType_Invalid()
{
CredentialCache cc = new CredentialCache();
//Doesn't throw, just returns
cc.Remove(null, "authenticationType");
cc.Remove(new Uri("http://some.com"), null);
cc.Remove(new Uri("http://some.com"), "authenticationType");
}
[Fact]
public static void Remove_HostPortAuthenticationType_Success()
{
CredentialCache cc = CreateHostPortCredentialCache();
cc.Remove(host1, port1, authenticationType1);
Assert.Null(cc.GetCredential(host1, port1, authenticationType1));
}
[Fact]
public static void Remove_HostPortAuthenticationType_Invalid()
{
CredentialCache cc = new CredentialCache();
//Doesn't throw, just returns
cc.Remove(null, 500, "authenticationType");
cc.Remove("host", 500, null);
cc.Remove("host", -1, "authenticationType");
cc.Remove("host", 500, "authenticationType");
}
[Fact]
public static void GetCredential_SimilarUriAuthenticationType_GetLongestUriPrefix()
{
CredentialCache cc = new CredentialCache();
cc.Add(new Uri("http://microsoft:80/greaterpath"), authenticationType1, credential2);
cc.Add(new Uri("http://microsoft:80/"), authenticationType1, credential1);
NetworkCredential nc = cc.GetCredential(new Uri("http://microsoft:80"), authenticationType1);
Assert.Equal(nc, credential2);
}
[Fact]
public static void GetCredential_UriAuthenticationType_Invalid()
{
CredentialCache cc = new CredentialCache();
AssertExtensions.Throws<ArgumentNullException>("uriPrefix", () => cc.GetCredential(null, "authenticationType")); //Null uriPrefix
AssertExtensions.Throws<ArgumentNullException>("authType", () => cc.GetCredential(new Uri("http://microsoft:80"), null)); //Null authenticationType
}
[Fact]
public static void GetCredential_HostPortAuthenticationType_Invalid()
{
CredentialCache cc = new CredentialCache();
AssertExtensions.Throws<ArgumentNullException>("host", () => cc.GetCredential(null, 500, "authenticationType")); //Null host
AssertExtensions.Throws<ArgumentNullException>("authenticationType", () => cc.GetCredential("host", 500, null)); //Null authenticationType
var exception = Record.Exception(() => cc.GetCredential("", 500, "authenticationType")); //Empty host
// On full framework we get exception.ParamName as null while it is "host" on netcore
Assert.NotNull(exception);
Assert.True(exception is ArgumentException);
ArgumentException ae = exception as ArgumentException;
Assert.True(ae.ParamName == "host" || ae.ParamName == null);
AssertExtensions.Throws<ArgumentOutOfRangeException>("port", () => cc.GetCredential("host", -1, "authenticationType")); //Port < 0
}
public static IEnumerable<object[]> GetEnumeratorWithCountTestData
{
get
{
foreach (CredentialCacheCount ccc in GetCredentialCacheCounts())
{
yield return new object[] { ccc.CredentialCache, ccc.Count };
}
}
}
[Theory]
[MemberData(nameof(GetEnumeratorWithCountTestData))]
public static void GetEnumerator_Enumerate_Success(CredentialCache cc, int count)
{
IEnumerator enumerator = cc.GetEnumerator();
Assert.NotNull(enumerator);
for (int iterations = 0; iterations < 2; iterations++)
{
Assert.Throws<InvalidOperationException>(() => enumerator.Current);
for (int i = 0; i < count; i++)
{
Assert.True(enumerator.MoveNext());
Assert.NotNull(enumerator.Current);
}
Assert.False(enumerator.MoveNext());
Assert.Throws<InvalidOperationException>(() => enumerator.Current);
enumerator.Reset();
}
}
public static IEnumerable<object[]> GetEnumeratorThenAddTestData
{
get
{
foreach (bool addUri in new[] { true, false })
{
foreach (CredentialCacheCount ccc in GetCredentialCacheCounts())
{
yield return new object[] { ccc.CredentialCache, addUri };
}
}
}
}
[Theory]
[MemberData(nameof(GetEnumeratorThenAddTestData))]
public static void GetEnumerator_MoveNextSynchronization_Invalid(CredentialCache cc, bool addUri)
{
//An InvalidOperationException is thrown when moving the enumerator
//when a credential is added to the cache after getting the enumerator
IEnumerator enumerator = cc.GetEnumerator();
if (addUri)
{
cc.Add(new Uri("http://whatever:80"), authenticationType1, credential1);
}
else
{
cc.Add("whatever", 80, authenticationType1, credential1);
}
Assert.Throws<InvalidOperationException>(() => enumerator.MoveNext());
}
[Theory]
[MemberData(nameof(GetEnumeratorThenAddTestData))]
public static void GetEnumerator_CurrentSynchronization_Invalid(CredentialCache cc, bool addUri)
{
//An InvalidOperationException is thrown when getting the current enumerated object
//when a credential is added to the cache after getting the enumerator
IEnumerator enumerator = cc.GetEnumerator();
enumerator.MoveNext();
if (addUri)
{
cc.Add(new Uri("http://whatever:80"), authenticationType1, credential1);
}
else
{
cc.Add("whatever", 80, authenticationType1, credential1);
}
Assert.Throws<InvalidOperationException>(() => enumerator.Current);
}
public static IEnumerable<object[]> GetEnumeratorTestData
{
get
{
foreach (CredentialCacheCount ccc in GetCredentialCacheCounts())
{
yield return new object[] { ccc.CredentialCache };
}
}
}
[Theory]
[MemberData(nameof(GetEnumeratorTestData))]
public static void GetEnumerator_ResetIndexGetCurrent_Invalid(CredentialCache cc)
{
IEnumerator enumerator = cc.GetEnumerator();
enumerator.Reset();
Assert.Throws<InvalidOperationException>(() => enumerator.Current);
}
[Fact]
public static void GetEnumerator_MoveNextIndex_Invalid()
{
CredentialCache cc = new CredentialCache();
IEnumerator enumerator = cc.GetEnumerator();
enumerator.MoveNext();
Assert.Throws<InvalidOperationException>(() => enumerator.Current);
}
[Fact]
public static void DefaultCredentials_Get_Success()
{
NetworkCredential c = CredentialCache.DefaultCredentials as NetworkCredential;
Assert.NotNull(c);
Assert.Equal(String.Empty, c.UserName);
Assert.Equal(String.Empty, c.Password);
Assert.Equal(String.Empty, c.Domain);
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.Netcoreapp | TargetFrameworkMonikers.Uap)]
public static void AddRemove_UriAuthenticationTypeDefaultCredentials_Success_net46()
{
NetworkCredential nc = CredentialCache.DefaultNetworkCredentials as NetworkCredential;
CredentialCache cc = new CredentialCache();
// The full framework throw System.ArgumentException with the message
// 'Default credentials cannot be supplied for the authenticationType1 authentication scheme.'
AssertExtensions.Throws<ArgumentException>("authType", () => cc.Add(uriPrefix1, authenticationType1, nc));
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework)]
public static void AddRemove_UriAuthenticationTypeDefaultCredentials_Success()
{
NetworkCredential nc = CredentialCache.DefaultNetworkCredentials as NetworkCredential;
CredentialCache cc = new CredentialCache();
cc.Add(uriPrefix1, authenticationType1, nc);
Assert.Equal(nc, cc.GetCredential(uriPrefix1, authenticationType1));
cc.Remove(uriPrefix1, authenticationType1);
Assert.Null(cc.GetCredential(uriPrefix1, authenticationType1));
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework)]
public static void AddRemove_HostPortAuthenticationTypeDefaultCredentials_Success()
{
NetworkCredential nc = CredentialCache.DefaultNetworkCredentials as NetworkCredential;
CredentialCache cc = new CredentialCache();
cc.Add(host1, port1, authenticationType1, nc);
Assert.Equal(nc, cc.GetCredential(host1, port1, authenticationType1));
cc.Remove(host1, port1, authenticationType1);
Assert.Null(cc.GetCredential(host1, port1, authenticationType1));
}
[Fact]
public static void DefaultNetworkCredentials_Get_Success()
{
NetworkCredential nc = CredentialCache.DefaultNetworkCredentials as NetworkCredential;
Assert.NotNull(nc);
Assert.Equal(String.Empty, nc.UserName);
Assert.Equal(String.Empty, nc.Password);
Assert.Equal(String.Empty, nc.Domain);
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Reflection;
using System.Reflection.Emit;
using System.Runtime.InteropServices.Tests.Common;
using Xunit;
namespace System.Runtime.InteropServices.Tests
{
public partial class GetComInterfaceForObjectTests
{
[Fact]
[PlatformSpecific(TestPlatforms.Windows)]
public void GetComInterfaceForObject_GenericWithValidClass_ReturnsExpected()
{
var o = new ClassWithInterface();
IntPtr iUnknown = Marshal.GetComInterfaceForObject<ClassWithInterface, NonGenericInterface>(o);
try
{
Assert.NotEqual(IntPtr.Zero, iUnknown);
}
finally
{
Marshal.Release(iUnknown);
}
}
[Fact]
[PlatformSpecific(TestPlatforms.Windows)]
public void GetComInterfaceForObject_GenericWithValidStruct_ReturnsExpected()
{
var o = new StructWithInterface();
IntPtr iUnknown = Marshal.GetComInterfaceForObject<StructWithInterface, NonGenericInterface>(o);
try
{
Assert.NotEqual(IntPtr.Zero, iUnknown);
}
finally
{
Marshal.Release(iUnknown);
}
}
[Fact]
[PlatformSpecific(TestPlatforms.Windows)]
public void GetComInterfaceForObject_NonGenericWithValidClass_ReturnsExpected()
{
var o = new ClassWithInterface();
IntPtr iUnknown = Marshal.GetComInterfaceForObject(o, typeof(NonGenericInterface));
try
{
Assert.NotEqual(IntPtr.Zero, iUnknown);
}
finally
{
Marshal.Release(iUnknown);
}
}
[Fact]
[PlatformSpecific(TestPlatforms.Windows)]
public void GetComInterfaceForObject_NonGenericWithValidStruct_ReturnsExpected()
{
var o = new StructWithInterface();
IntPtr iUnknown = Marshal.GetComInterfaceForObject(o, typeof(NonGenericInterface));
try
{
Assert.NotEqual(IntPtr.Zero, iUnknown);
}
finally
{
Marshal.Release(iUnknown);
}
}
[Theory]
[InlineData(CustomQueryInterfaceMode.Allow)]
[InlineData(CustomQueryInterfaceMode.Ignore)]
[InlineData(CustomQueryInterfaceMode.Allow + 1)]
[InlineData(CustomQueryInterfaceMode.Ignore - 1)]
[PlatformSpecific(TestPlatforms.Windows)]
public void GetComInterfaceForObject_NonGenericCustomQueryInterfaceModeWithValidClass_ReturnsExpected(CustomQueryInterfaceMode mode)
{
var o = new ClassWithInterface();
IntPtr iUnknown = Marshal.GetComInterfaceForObject(o, typeof(NonGenericInterface));
try
{
Assert.NotEqual(IntPtr.Zero, iUnknown);
}
finally
{
Marshal.Release(iUnknown);
}
}
[Theory]
[InlineData(CustomQueryInterfaceMode.Allow)]
[InlineData(CustomQueryInterfaceMode.Ignore)]
[InlineData(CustomQueryInterfaceMode.Allow + 1)]
[InlineData(CustomQueryInterfaceMode.Ignore - 1)]
[PlatformSpecific(TestPlatforms.Windows)]
public void GetComInterfaceForObject_NonGenericCustomQueryInterfaceModeWithValidStruct_ReturnsExpected(CustomQueryInterfaceMode mode)
{
var o = new StructWithInterface();
IntPtr iUnknown = Marshal.GetComInterfaceForObject(o, typeof(NonGenericInterface), mode);
try
{
Assert.NotEqual(IntPtr.Zero, iUnknown);
}
finally
{
Marshal.Release(iUnknown);
}
}
public class ClassWithInterface : NonGenericInterface { }
public class StructWithInterface : NonGenericInterface { }
[Fact]
[PlatformSpecific(TestPlatforms.AnyUnix)]
public void GetComInterfaceForObject_Unix_ThrowsPlatformNotSupportedException()
{
Assert.Throws<PlatformNotSupportedException>(() => Marshal.GetComInterfaceForObject(null, null));
Assert.Throws<PlatformNotSupportedException>(() => Marshal.GetComInterfaceForObject(null, null, CustomQueryInterfaceMode.Allow));
Assert.Throws<PlatformNotSupportedException>(() => Marshal.GetComInterfaceForObject<int, int>(1));
}
[Fact]
[PlatformSpecific(TestPlatforms.Windows)]
public void GetComInterfaceForObject_NullObject_ThrowsArgumentNullException()
{
AssertExtensions.Throws<ArgumentNullException>("o", () => Marshal.GetComInterfaceForObject(null, typeof(NonGenericInterface)));
AssertExtensions.Throws<ArgumentNullException>("o", () => Marshal.GetComInterfaceForObject(null, typeof(NonGenericInterface), CustomQueryInterfaceMode.Allow));
AssertExtensions.Throws<ArgumentNullException>("o", () => Marshal.GetComInterfaceForObject<string, string>(null));
}
[Fact]
[PlatformSpecific(TestPlatforms.Windows)]
public void GetComInterfaceForObject_NullType_ThrowsArgumentNullException()
{
AssertExtensions.Throws<ArgumentNullException>("t", () => Marshal.GetComInterfaceForObject(new object(), null));
AssertExtensions.Throws<ArgumentNullException>("t", () => Marshal.GetComInterfaceForObject(new object(), null, CustomQueryInterfaceMode.Allow));
}
public static IEnumerable<object[]> GetComInterfaceForObject_InvalidType_TestData()
{
yield return new object[] { typeof(int).MakeByRefType() };
yield return new object[] { typeof(int).MakePointerType() };
yield return new object[] { typeof(string) };
yield return new object[] { typeof(NonGenericClass) };
yield return new object[] { typeof(GenericClass<>) };
yield return new object[] { typeof(GenericClass<string>) };
yield return new object[] { typeof(AbstractClass) };
yield return new object[] { typeof(GenericStruct<>) };
yield return new object[] { typeof(GenericStruct<string>) };
yield return new object[] { typeof(GenericInterface<>) };
yield return new object[] { typeof(GenericInterface<string>) };
yield return new object[] { typeof(GenericClass<>).GetTypeInfo().GenericTypeParameters[0] };
AssemblyBuilder assemblyBuilder = AssemblyBuilder.DefineDynamicAssembly(new AssemblyName("Assembly"), AssemblyBuilderAccess.Run);
ModuleBuilder moduleBuilder = assemblyBuilder.DefineDynamicModule("Module");
TypeBuilder typeBuilder = moduleBuilder.DefineType("Type");
yield return new object[] { typeBuilder };
yield return new object[] { typeof(NonComVisibleClass) };
yield return new object[] { typeof(NonComVisibleStruct) };
yield return new object[] { typeof(NonComVisibleInterface) };
AssemblyBuilder collectibleAssemblyBuilder = AssemblyBuilder.DefineDynamicAssembly(new AssemblyName("Assembly"), AssemblyBuilderAccess.RunAndCollect);
ModuleBuilder collectibleModuleBuilder = collectibleAssemblyBuilder.DefineDynamicModule("Module");
TypeBuilder collectibleTypeBuilder = collectibleModuleBuilder.DefineType("Type", TypeAttributes.Interface | TypeAttributes.Abstract);
Type collectibleType = collectibleTypeBuilder.CreateType();
yield return new object[] { collectibleType };
}
[Theory]
[MemberData(nameof(GetComInterfaceForObject_InvalidType_TestData))]
[PlatformSpecific(TestPlatforms.Windows)]
public void GetComInterfaceForObject_InvalidType_ThrowsArgumentException(Type type)
{
AssertExtensions.Throws<ArgumentException>("t", () => Marshal.GetComInterfaceForObject(new object(), type));
AssertExtensions.Throws<ArgumentException>("t", () => Marshal.GetComInterfaceForObject(new object(), type, CustomQueryInterfaceMode.Allow));
}
public static IEnumerable<object[]> GetComInterfaceForObject_InvalidObject_TestData()
{
yield return new object[] { new GenericClass<string>() };
yield return new object[] { new GenericStruct<string>() };
}
[Theory]
[MemberData(nameof(GetComInterfaceForObject_InvalidObject_TestData))]
[PlatformSpecific(TestPlatforms.Windows)]
public void GetComInterfaceForObject_InvalidObject_ThrowsArgumentException(object o)
{
AssertExtensions.Throws<ArgumentException>("o", () => Marshal.GetComInterfaceForObject(o, typeof(NonGenericInterface)));
AssertExtensions.Throws<ArgumentException>("o", () => Marshal.GetComInterfaceForObject(o, typeof(NonGenericInterface), CustomQueryInterfaceMode.Allow));
AssertExtensions.Throws<ArgumentException>("o", () => Marshal.GetComInterfaceForObject<object, NonGenericInterface>(o));
}
[Fact]
[PlatformSpecific(TestPlatforms.Windows)]
public void GetTypedObjectForIUnknown_UncastableType_ThrowsInvalidCastException()
{
Assert.Throws<InvalidCastException>(() => Marshal.GetComInterfaceForObject(new object(), typeof(NonGenericInterface)));
Assert.Throws<InvalidCastException>(() => Marshal.GetComInterfaceForObject(new object(), typeof(NonGenericInterface), CustomQueryInterfaceMode.Allow));
Assert.Throws<InvalidCastException>(() => Marshal.GetComInterfaceForObject<object, NonGenericInterface>(new object()));
}
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Composition;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading;
using Microsoft.CodeAnalysis.Collections;
using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.FindSymbols;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.LanguageServices;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp
{
[ExportLanguageService(typeof(ISyntaxFactsService), LanguageNames.CSharp), Shared]
internal class CSharpSyntaxFactsService : ISyntaxFactsService
{
public bool IsAwaitKeyword(SyntaxToken token)
{
return token.IsKind(SyntaxKind.AwaitKeyword);
}
public bool IsIdentifier(SyntaxToken token)
{
return token.IsKind(SyntaxKind.IdentifierToken);
}
public bool IsGlobalNamespaceKeyword(SyntaxToken token)
{
return token.IsKind(SyntaxKind.GlobalKeyword);
}
public bool IsVerbatimIdentifier(SyntaxToken token)
{
return token.IsVerbatimIdentifier();
}
public bool IsOperator(SyntaxToken token)
{
var kind = token.Kind();
return
(SyntaxFacts.IsAnyUnaryExpression(kind) &&
(token.Parent is PrefixUnaryExpressionSyntax || token.Parent is PostfixUnaryExpressionSyntax || token.Parent is OperatorDeclarationSyntax)) ||
(SyntaxFacts.IsBinaryExpression(kind) && (token.Parent is BinaryExpressionSyntax || token.Parent is OperatorDeclarationSyntax)) ||
(SyntaxFacts.IsAssignmentExpressionOperatorToken(kind) && token.Parent is AssignmentExpressionSyntax);
}
public bool IsKeyword(SyntaxToken token)
{
var kind = (SyntaxKind)token.RawKind;
return
SyntaxFacts.IsKeywordKind(kind); // both contextual and reserved keywords
}
public bool IsContextualKeyword(SyntaxToken token)
{
var kind = (SyntaxKind)token.RawKind;
return
SyntaxFacts.IsContextualKeyword(kind);
}
public bool IsPreprocessorKeyword(SyntaxToken token)
{
var kind = (SyntaxKind)token.RawKind;
return
SyntaxFacts.IsPreprocessorKeyword(kind);
}
public bool IsHashToken(SyntaxToken token)
{
return (SyntaxKind)token.RawKind == SyntaxKind.HashToken;
}
public bool IsInInactiveRegion(SyntaxTree syntaxTree, int position, CancellationToken cancellationToken)
{
var csharpTree = syntaxTree as SyntaxTree;
if (csharpTree == null)
{
return false;
}
return csharpTree.IsInInactiveRegion(position, cancellationToken);
}
public bool IsInNonUserCode(SyntaxTree syntaxTree, int position, CancellationToken cancellationToken)
{
var csharpTree = syntaxTree as SyntaxTree;
if (csharpTree == null)
{
return false;
}
return csharpTree.IsInNonUserCode(position, cancellationToken);
}
public bool IsEntirelyWithinStringOrCharOrNumericLiteral(SyntaxTree syntaxTree, int position, CancellationToken cancellationToken)
{
var csharpTree = syntaxTree as SyntaxTree;
if (csharpTree == null)
{
return false;
}
return csharpTree.IsEntirelyWithinStringOrCharLiteral(position, cancellationToken);
}
public bool IsDirective(SyntaxNode node)
{
return node is DirectiveTriviaSyntax;
}
public bool TryGetExternalSourceInfo(SyntaxNode node, out ExternalSourceInfo info)
{
var lineDirective = node as LineDirectiveTriviaSyntax;
if (lineDirective != null)
{
if (lineDirective.Line.Kind() == SyntaxKind.DefaultKeyword)
{
info = new ExternalSourceInfo(null, ends: true);
return true;
}
else if (lineDirective.Line.Kind() == SyntaxKind.NumericLiteralToken &&
lineDirective.Line.Value is int)
{
info = new ExternalSourceInfo((int)lineDirective.Line.Value, false);
return true;
}
}
info = default(ExternalSourceInfo);
return false;
}
public bool IsRightSideOfQualifiedName(SyntaxNode node)
{
var name = node as SimpleNameSyntax;
return name.IsRightSideOfQualifiedName();
}
public bool IsMemberAccessExpressionName(SyntaxNode node)
{
var name = node as SimpleNameSyntax;
return name.IsMemberAccessExpressionName();
}
public bool IsObjectCreationExpressionType(SyntaxNode node)
{
return node.IsParentKind(SyntaxKind.ObjectCreationExpression) &&
((ObjectCreationExpressionSyntax)node.Parent).Type == node;
}
public bool IsAttributeName(SyntaxNode node)
{
return SyntaxFacts.IsAttributeName(node);
}
public bool IsInvocationExpression(SyntaxNode node)
{
return node is InvocationExpressionSyntax;
}
public bool IsAnonymousFunction(SyntaxNode node)
{
return node is ParenthesizedLambdaExpressionSyntax ||
node is SimpleLambdaExpressionSyntax ||
node is AnonymousMethodExpressionSyntax;
}
public bool IsGenericName(SyntaxNode node)
{
return node is GenericNameSyntax;
}
public bool IsNamedParameter(SyntaxNode node)
{
return node.CheckParent<NameColonSyntax>(p => p.Name == node);
}
public bool IsSkippedTokensTrivia(SyntaxNode node)
{
return node is SkippedTokensTriviaSyntax;
}
public bool HasIncompleteParentMember(SyntaxNode node)
{
return node.IsParentKind(SyntaxKind.IncompleteMember);
}
public SyntaxToken GetIdentifierOfGenericName(SyntaxNode genericName)
{
var csharpGenericName = genericName as GenericNameSyntax;
return csharpGenericName != null
? csharpGenericName.Identifier
: default(SyntaxToken);
}
public bool IsCaseSensitive
{
get
{
return true;
}
}
public bool IsUsingDirectiveName(SyntaxNode node)
{
return
node.IsParentKind(SyntaxKind.UsingDirective) &&
((UsingDirectiveSyntax)node.Parent).Name == node;
}
public bool IsForEachStatement(SyntaxNode node)
{
return node is ForEachStatementSyntax;
}
public bool IsLockStatement(SyntaxNode node)
{
return node is LockStatementSyntax;
}
public bool IsUsingStatement(SyntaxNode node)
{
return node is UsingStatementSyntax;
}
public bool IsThisConstructorInitializer(SyntaxToken token)
{
return token.Parent.IsKind(SyntaxKind.ThisConstructorInitializer) &&
((ConstructorInitializerSyntax)token.Parent).ThisOrBaseKeyword == token;
}
public bool IsBaseConstructorInitializer(SyntaxToken token)
{
return token.Parent.IsKind(SyntaxKind.BaseConstructorInitializer) &&
((ConstructorInitializerSyntax)token.Parent).ThisOrBaseKeyword == token;
}
public bool IsQueryExpression(SyntaxNode node)
{
return node is QueryExpressionSyntax;
}
public bool IsPredefinedType(SyntaxToken token)
{
PredefinedType actualType;
return TryGetPredefinedType(token, out actualType) && actualType != PredefinedType.None;
}
public bool IsPredefinedType(SyntaxToken token, PredefinedType type)
{
PredefinedType actualType;
return TryGetPredefinedType(token, out actualType) && actualType == type;
}
public bool TryGetPredefinedType(SyntaxToken token, out PredefinedType type)
{
type = GetPredefinedType(token);
return type != PredefinedType.None;
}
private PredefinedType GetPredefinedType(SyntaxToken token)
{
switch ((SyntaxKind)token.RawKind)
{
case SyntaxKind.BoolKeyword:
return PredefinedType.Boolean;
case SyntaxKind.ByteKeyword:
return PredefinedType.Byte;
case SyntaxKind.SByteKeyword:
return PredefinedType.SByte;
case SyntaxKind.IntKeyword:
return PredefinedType.Int32;
case SyntaxKind.UIntKeyword:
return PredefinedType.UInt32;
case SyntaxKind.ShortKeyword:
return PredefinedType.Int16;
case SyntaxKind.UShortKeyword:
return PredefinedType.UInt16;
case SyntaxKind.LongKeyword:
return PredefinedType.Int64;
case SyntaxKind.ULongKeyword:
return PredefinedType.UInt64;
case SyntaxKind.FloatKeyword:
return PredefinedType.Single;
case SyntaxKind.DoubleKeyword:
return PredefinedType.Double;
case SyntaxKind.DecimalKeyword:
return PredefinedType.Decimal;
case SyntaxKind.StringKeyword:
return PredefinedType.String;
case SyntaxKind.CharKeyword:
return PredefinedType.Char;
case SyntaxKind.ObjectKeyword:
return PredefinedType.Object;
case SyntaxKind.VoidKeyword:
return PredefinedType.Void;
default:
return PredefinedType.None;
}
}
public bool IsPredefinedOperator(SyntaxToken token)
{
PredefinedOperator actualOperator;
return TryGetPredefinedOperator(token, out actualOperator) && actualOperator != PredefinedOperator.None;
}
public bool IsPredefinedOperator(SyntaxToken token, PredefinedOperator op)
{
PredefinedOperator actualOperator;
return TryGetPredefinedOperator(token, out actualOperator) && actualOperator == op;
}
public bool TryGetPredefinedOperator(SyntaxToken token, out PredefinedOperator op)
{
op = GetPredefinedOperator(token);
return op != PredefinedOperator.None;
}
private PredefinedOperator GetPredefinedOperator(SyntaxToken token)
{
switch ((SyntaxKind)token.RawKind)
{
case SyntaxKind.PlusToken:
case SyntaxKind.PlusEqualsToken:
return PredefinedOperator.Addition;
case SyntaxKind.MinusToken:
case SyntaxKind.MinusEqualsToken:
return PredefinedOperator.Subtraction;
case SyntaxKind.AmpersandToken:
case SyntaxKind.AmpersandEqualsToken:
return PredefinedOperator.BitwiseAnd;
case SyntaxKind.BarToken:
case SyntaxKind.BarEqualsToken:
return PredefinedOperator.BitwiseOr;
case SyntaxKind.MinusMinusToken:
return PredefinedOperator.Decrement;
case SyntaxKind.PlusPlusToken:
return PredefinedOperator.Increment;
case SyntaxKind.SlashToken:
case SyntaxKind.SlashEqualsToken:
return PredefinedOperator.Division;
case SyntaxKind.EqualsEqualsToken:
return PredefinedOperator.Equality;
case SyntaxKind.CaretToken:
case SyntaxKind.CaretEqualsToken:
return PredefinedOperator.ExclusiveOr;
case SyntaxKind.GreaterThanToken:
return PredefinedOperator.GreaterThan;
case SyntaxKind.GreaterThanEqualsToken:
return PredefinedOperator.GreaterThanOrEqual;
case SyntaxKind.ExclamationEqualsToken:
return PredefinedOperator.Inequality;
case SyntaxKind.LessThanLessThanToken:
case SyntaxKind.LessThanLessThanEqualsToken:
return PredefinedOperator.LeftShift;
case SyntaxKind.LessThanEqualsToken:
return PredefinedOperator.LessThanOrEqual;
case SyntaxKind.AsteriskToken:
case SyntaxKind.AsteriskEqualsToken:
return PredefinedOperator.Multiplication;
case SyntaxKind.PercentToken:
case SyntaxKind.PercentEqualsToken:
return PredefinedOperator.Modulus;
case SyntaxKind.ExclamationToken:
case SyntaxKind.TildeToken:
return PredefinedOperator.Complement;
case SyntaxKind.GreaterThanGreaterThanToken:
case SyntaxKind.GreaterThanGreaterThanEqualsToken:
return PredefinedOperator.RightShift;
}
return PredefinedOperator.None;
}
public string GetText(int kind)
{
return SyntaxFacts.GetText((SyntaxKind)kind);
}
public bool IsIdentifierStartCharacter(char c)
{
return SyntaxFacts.IsIdentifierStartCharacter(c);
}
public bool IsIdentifierPartCharacter(char c)
{
return SyntaxFacts.IsIdentifierPartCharacter(c);
}
public bool IsIdentifierEscapeCharacter(char c)
{
return c == '@';
}
public bool IsValidIdentifier(string identifier)
{
var token = SyntaxFactory.ParseToken(identifier);
return IsIdentifier(token) && !token.ContainsDiagnostics && token.ToString().Length == identifier.Length;
}
public bool IsVerbatimIdentifier(string identifier)
{
var token = SyntaxFactory.ParseToken(identifier);
return IsIdentifier(token) && !token.ContainsDiagnostics && token.ToString().Length == identifier.Length && token.IsVerbatimIdentifier();
}
public bool IsTypeCharacter(char c)
{
return false;
}
public bool IsStartOfUnicodeEscapeSequence(char c)
{
return c == '\\';
}
public bool IsLiteral(SyntaxToken token)
{
switch (token.Kind())
{
case SyntaxKind.NumericLiteralToken:
case SyntaxKind.CharacterLiteralToken:
case SyntaxKind.StringLiteralToken:
case SyntaxKind.NullKeyword:
case SyntaxKind.TrueKeyword:
case SyntaxKind.FalseKeyword:
case SyntaxKind.InterpolatedStringStartToken:
case SyntaxKind.InterpolatedStringEndToken:
case SyntaxKind.InterpolatedVerbatimStringStartToken:
case SyntaxKind.InterpolatedStringTextToken:
case SyntaxKind.TranslatableStringStartToken:
case SyntaxKind.TranslatableVerbatimStringStartToken:
return true;
}
return false;
}
public bool IsStringLiteral(SyntaxToken token)
{
return token.IsKind(SyntaxKind.StringLiteralToken, SyntaxKind.InterpolatedStringTextToken);
}
public bool IsTypeNamedVarInVariableOrFieldDeclaration(SyntaxToken token, SyntaxNode parent)
{
var typedToken = token;
var typedParent = parent;
if (typedParent.IsKind(SyntaxKind.IdentifierName))
{
TypeSyntax declaredType = null;
if (typedParent.IsParentKind(SyntaxKind.VariableDeclaration))
{
declaredType = ((VariableDeclarationSyntax)typedParent.Parent).Type;
}
else if (typedParent.IsParentKind(SyntaxKind.FieldDeclaration))
{
declaredType = ((FieldDeclarationSyntax)typedParent.Parent).Declaration.Type;
}
return declaredType == typedParent && typedToken.ValueText == "var";
}
return false;
}
public bool IsTypeNamedDynamic(SyntaxToken token, SyntaxNode parent)
{
var typedParent = parent as ExpressionSyntax;
if (typedParent != null)
{
if (SyntaxFacts.IsInTypeOnlyContext(typedParent) &&
typedParent.IsKind(SyntaxKind.IdentifierName) &&
token.ValueText == "dynamic")
{
return true;
}
}
return false;
}
public bool IsBindableToken(SyntaxToken token)
{
if (this.IsWord(token) || this.IsLiteral(token) || this.IsOperator(token))
{
switch ((SyntaxKind)token.RawKind)
{
case SyntaxKind.DelegateKeyword:
case SyntaxKind.VoidKeyword:
return false;
}
return true;
}
return false;
}
public bool IsMemberAccessExpression(SyntaxNode node)
{
return node is MemberAccessExpressionSyntax &&
((MemberAccessExpressionSyntax)node).Kind() == SyntaxKind.SimpleMemberAccessExpression;
}
public bool IsConditionalMemberAccessExpression(SyntaxNode node)
{
return node is ConditionalAccessExpressionSyntax;
}
public bool IsPointerMemberAccessExpression(SyntaxNode node)
{
return node is MemberAccessExpressionSyntax &&
((MemberAccessExpressionSyntax)node).Kind() == SyntaxKind.PointerMemberAccessExpression;
}
public void GetNameAndArityOfSimpleName(SyntaxNode node, out string name, out int arity)
{
name = null;
arity = 0;
var simpleName = node as SimpleNameSyntax;
if (simpleName != null)
{
name = simpleName.Identifier.ValueText;
arity = simpleName.Arity;
}
}
public SyntaxNode GetExpressionOfMemberAccessExpression(SyntaxNode node)
{
return node.IsKind(SyntaxKind.MemberBindingExpression)
? GetExpressionOfConditionalMemberAccessExpression(node.GetParentConditionalAccessExpression())
: (node as MemberAccessExpressionSyntax)?.Expression;
}
public SyntaxNode GetExpressionOfConditionalMemberAccessExpression(SyntaxNode node)
{
return (node as ConditionalAccessExpressionSyntax)?.Expression;
}
public bool IsInStaticContext(SyntaxNode node)
{
return node.IsInStaticContext();
}
public bool IsInNamespaceOrTypeContext(SyntaxNode node)
{
return SyntaxFacts.IsInNamespaceOrTypeContext(node as ExpressionSyntax);
}
public SyntaxNode GetExpressionOfArgument(SyntaxNode node)
{
return ((ArgumentSyntax)node).Expression;
}
public RefKind GetRefKindOfArgument(SyntaxNode node)
{
return (node as ArgumentSyntax).GetRefKind();
}
public bool IsInConstantContext(SyntaxNode node)
{
return (node as ExpressionSyntax).IsInConstantContext();
}
public bool IsInConstructor(SyntaxNode node)
{
return node.GetAncestor<ConstructorDeclarationSyntax>() != null;
}
public bool IsUnsafeContext(SyntaxNode node)
{
return node.IsUnsafeContext();
}
public SyntaxNode GetNameOfAttribute(SyntaxNode node)
{
return ((AttributeSyntax)node).Name;
}
public bool IsAttribute(SyntaxNode node)
{
return node is AttributeSyntax;
}
public bool IsAttributeNamedArgumentIdentifier(SyntaxNode node)
{
var identifier = node as IdentifierNameSyntax;
return
identifier != null &&
identifier.IsParentKind(SyntaxKind.NameEquals) &&
identifier.Parent.IsParentKind(SyntaxKind.AttributeArgument);
}
public SyntaxNode GetContainingTypeDeclaration(SyntaxNode root, int position)
{
if (root == null)
{
throw new ArgumentNullException(nameof(root));
}
if (position < 0 || position > root.Span.End)
{
throw new ArgumentOutOfRangeException(nameof(position));
}
return root
.FindToken(position)
.GetAncestors<SyntaxNode>()
.FirstOrDefault(n => n is BaseTypeDeclarationSyntax || n is DelegateDeclarationSyntax);
}
public SyntaxNode GetContainingVariableDeclaratorOfFieldDeclaration(SyntaxNode node)
{
throw ExceptionUtilities.Unreachable;
}
public SyntaxToken FindTokenOnLeftOfPosition(
SyntaxNode node, int position, bool includeSkipped, bool includeDirectives, bool includeDocumentationComments)
{
return node.FindTokenOnLeftOfPosition(position, includeSkipped, includeDirectives, includeDocumentationComments);
}
public SyntaxToken FindTokenOnRightOfPosition(
SyntaxNode node, int position, bool includeSkipped, bool includeDirectives, bool includeDocumentationComments)
{
return node.FindTokenOnRightOfPosition(position, includeSkipped, includeDirectives, includeDocumentationComments);
}
public bool IsObjectCreationExpression(SyntaxNode node)
{
return node is ObjectCreationExpressionSyntax;
}
public bool IsObjectInitializerNamedAssignmentIdentifier(SyntaxNode node)
{
var identifier = node as IdentifierNameSyntax;
return
identifier != null &&
identifier.IsLeftSideOfAssignExpression() &&
identifier.Parent.IsParentKind(SyntaxKind.ObjectInitializerExpression);
}
public bool IsElementAccessExpression(SyntaxNode node)
{
return node.Kind() == SyntaxKind.ElementAccessExpression;
}
public SyntaxNode ConvertToSingleLine(SyntaxNode node)
{
return node.ConvertToSingleLine();
}
public SyntaxToken ToIdentifierToken(string name)
{
return name.ToIdentifierToken();
}
public SyntaxNode Parenthesize(SyntaxNode expression, bool includeElasticTrivia)
{
return ((ExpressionSyntax)expression).Parenthesize(includeElasticTrivia);
}
public bool IsIndexerMemberCRef(SyntaxNode node)
{
return node.Kind() == SyntaxKind.IndexerMemberCref;
}
public SyntaxNode GetContainingMemberDeclaration(SyntaxNode root, int position, bool useFullSpan = true)
{
Contract.ThrowIfNull(root, "root");
Contract.ThrowIfTrue(position < 0 || position > root.FullSpan.End, "position");
var end = root.FullSpan.End;
if (end == 0)
{
// empty file
return null;
}
// make sure position doesn't touch end of root
position = Math.Min(position, end - 1);
var node = root.FindToken(position).Parent;
while (node != null)
{
if (useFullSpan || node.Span.Contains(position))
{
var kind = node.Kind();
if ((kind != SyntaxKind.GlobalStatement) && (kind != SyntaxKind.IncompleteMember) && (node is MemberDeclarationSyntax))
{
return node;
}
}
node = node.Parent;
}
return null;
}
public bool IsMethodLevelMember(SyntaxNode node)
{
return node is BaseMethodDeclarationSyntax || node is BasePropertyDeclarationSyntax || node is EnumMemberDeclarationSyntax || node is BaseFieldDeclarationSyntax;
}
public bool IsTopLevelNodeWithMembers(SyntaxNode node)
{
return node is NamespaceDeclarationSyntax ||
node is TypeDeclarationSyntax ||
node is EnumDeclarationSyntax;
}
public bool TryGetDeclaredSymbolInfo(SyntaxNode node, out DeclaredSymbolInfo declaredSymbolInfo)
{
switch (node.Kind())
{
case SyntaxKind.ClassDeclaration:
var classDecl = (ClassDeclarationSyntax)node;
declaredSymbolInfo = new DeclaredSymbolInfo(classDecl.Identifier.ValueText,
GetContainerDisplayName(node.Parent),
GetFullyQualifiedContainerName(node.Parent),
DeclaredSymbolInfoKind.Class, classDecl.Identifier.Span);
return true;
case SyntaxKind.ConstructorDeclaration:
var ctorDecl = (ConstructorDeclarationSyntax)node;
declaredSymbolInfo = new DeclaredSymbolInfo(
ctorDecl.Identifier.ValueText,
GetContainerDisplayName(node.Parent),
GetFullyQualifiedContainerName(node.Parent),
DeclaredSymbolInfoKind.Constructor,
ctorDecl.Identifier.Span,
parameterCount: (ushort)(ctorDecl.ParameterList?.Parameters.Count ?? 0));
return true;
case SyntaxKind.DelegateDeclaration:
var delegateDecl = (DelegateDeclarationSyntax)node;
declaredSymbolInfo = new DeclaredSymbolInfo(delegateDecl.Identifier.ValueText,
GetContainerDisplayName(node.Parent),
GetFullyQualifiedContainerName(node.Parent),
DeclaredSymbolInfoKind.Delegate, delegateDecl.Identifier.Span);
return true;
case SyntaxKind.EnumDeclaration:
var enumDecl = (EnumDeclarationSyntax)node;
declaredSymbolInfo = new DeclaredSymbolInfo(enumDecl.Identifier.ValueText,
GetContainerDisplayName(node.Parent),
GetFullyQualifiedContainerName(node.Parent),
DeclaredSymbolInfoKind.Enum, enumDecl.Identifier.Span);
return true;
case SyntaxKind.EnumMemberDeclaration:
var enumMember = (EnumMemberDeclarationSyntax)node;
declaredSymbolInfo = new DeclaredSymbolInfo(enumMember.Identifier.ValueText,
GetContainerDisplayName(node.Parent),
GetFullyQualifiedContainerName(node.Parent),
DeclaredSymbolInfoKind.EnumMember, enumMember.Identifier.Span);
return true;
case SyntaxKind.EventDeclaration:
var eventDecl = (EventDeclarationSyntax)node;
declaredSymbolInfo = new DeclaredSymbolInfo(ExpandExplicitInterfaceName(eventDecl.Identifier.ValueText, eventDecl.ExplicitInterfaceSpecifier),
GetContainerDisplayName(node.Parent),
GetFullyQualifiedContainerName(node.Parent),
DeclaredSymbolInfoKind.Event, eventDecl.Identifier.Span);
return true;
case SyntaxKind.IndexerDeclaration:
var indexerDecl = (IndexerDeclarationSyntax)node;
declaredSymbolInfo = new DeclaredSymbolInfo(WellKnownMemberNames.Indexer,
GetContainerDisplayName(node.Parent),
GetFullyQualifiedContainerName(node.Parent),
DeclaredSymbolInfoKind.Indexer, indexerDecl.ThisKeyword.Span);
return true;
case SyntaxKind.InterfaceDeclaration:
var interfaceDecl = (InterfaceDeclarationSyntax)node;
declaredSymbolInfo = new DeclaredSymbolInfo(interfaceDecl.Identifier.ValueText,
GetContainerDisplayName(node.Parent),
GetFullyQualifiedContainerName(node.Parent),
DeclaredSymbolInfoKind.Interface, interfaceDecl.Identifier.Span);
return true;
case SyntaxKind.MethodDeclaration:
var method = (MethodDeclarationSyntax)node;
declaredSymbolInfo = new DeclaredSymbolInfo(
ExpandExplicitInterfaceName(method.Identifier.ValueText, method.ExplicitInterfaceSpecifier),
GetContainerDisplayName(node.Parent),
GetFullyQualifiedContainerName(node.Parent),
DeclaredSymbolInfoKind.Method,
method.Identifier.Span,
parameterCount: (ushort)(method.ParameterList?.Parameters.Count ?? 0),
typeParameterCount: (ushort)(method.TypeParameterList?.Parameters.Count ?? 0));
return true;
case SyntaxKind.PropertyDeclaration:
var property = (PropertyDeclarationSyntax)node;
declaredSymbolInfo = new DeclaredSymbolInfo(ExpandExplicitInterfaceName(property.Identifier.ValueText, property.ExplicitInterfaceSpecifier),
GetContainerDisplayName(node.Parent),
GetFullyQualifiedContainerName(node.Parent),
DeclaredSymbolInfoKind.Property, property.Identifier.Span);
return true;
case SyntaxKind.StructDeclaration:
var structDecl = (StructDeclarationSyntax)node;
declaredSymbolInfo = new DeclaredSymbolInfo(structDecl.Identifier.ValueText,
GetContainerDisplayName(node.Parent),
GetFullyQualifiedContainerName(node.Parent),
DeclaredSymbolInfoKind.Struct, structDecl.Identifier.Span);
return true;
case SyntaxKind.VariableDeclarator:
// could either be part of a field declaration or an event field declaration
var variableDeclarator = (VariableDeclaratorSyntax)node;
var variableDeclaration = variableDeclarator.Parent as VariableDeclarationSyntax;
var fieldDeclaration = variableDeclaration?.Parent as BaseFieldDeclarationSyntax;
if (fieldDeclaration != null)
{
var kind = fieldDeclaration is EventFieldDeclarationSyntax
? DeclaredSymbolInfoKind.Event
: fieldDeclaration.Modifiers.Any(m => m.Kind() == SyntaxKind.ConstKeyword)
? DeclaredSymbolInfoKind.Constant
: DeclaredSymbolInfoKind.Field;
declaredSymbolInfo = new DeclaredSymbolInfo(variableDeclarator.Identifier.ValueText,
GetContainerDisplayName(fieldDeclaration.Parent),
GetFullyQualifiedContainerName(fieldDeclaration.Parent),
kind, variableDeclarator.Identifier.Span);
return true;
}
break;
}
declaredSymbolInfo = default(DeclaredSymbolInfo);
return false;
}
private static string ExpandExplicitInterfaceName(string identifier, ExplicitInterfaceSpecifierSyntax explicitInterfaceSpecifier)
{
if (explicitInterfaceSpecifier == null)
{
return identifier;
}
else
{
var builder = new StringBuilder();
ExpandTypeName(explicitInterfaceSpecifier.Name, builder);
builder.Append('.');
builder.Append(identifier);
return builder.ToString();
}
}
private static void ExpandTypeName(TypeSyntax type, StringBuilder builder)
{
switch (type.Kind())
{
case SyntaxKind.AliasQualifiedName:
var alias = (AliasQualifiedNameSyntax)type;
builder.Append(alias.Alias.Identifier.ValueText);
break;
case SyntaxKind.ArrayType:
var array = (ArrayTypeSyntax)type;
ExpandTypeName(array.ElementType, builder);
for (int i = 0; i < array.RankSpecifiers.Count; i++)
{
var rankSpecifier = array.RankSpecifiers[i];
builder.Append(rankSpecifier.OpenBracketToken.Text);
for (int j = 1; j < rankSpecifier.Sizes.Count; j++)
{
builder.Append(',');
}
builder.Append(rankSpecifier.CloseBracketToken.Text);
}
break;
case SyntaxKind.GenericName:
var generic = (GenericNameSyntax)type;
builder.Append(generic.Identifier.ValueText);
if (generic.TypeArgumentList != null)
{
var arguments = generic.TypeArgumentList.Arguments;
builder.Append(generic.TypeArgumentList.LessThanToken.Text);
for (int i = 0; i < arguments.Count; i++)
{
if (i != 0)
{
builder.Append(',');
}
ExpandTypeName(arguments[i], builder);
}
builder.Append(generic.TypeArgumentList.GreaterThanToken.Text);
}
break;
case SyntaxKind.IdentifierName:
var identifierName = (IdentifierNameSyntax)type;
builder.Append(identifierName.Identifier.ValueText);
break;
case SyntaxKind.NullableType:
var nullable = (NullableTypeSyntax)type;
ExpandTypeName(nullable.ElementType, builder);
builder.Append(nullable.QuestionToken.Text);
break;
case SyntaxKind.OmittedTypeArgument:
// do nothing since it was omitted, but don't reach the default block
break;
case SyntaxKind.PointerType:
var pointer = (PointerTypeSyntax)type;
ExpandTypeName(pointer.ElementType, builder);
builder.Append(pointer.AsteriskToken.Text);
break;
case SyntaxKind.PredefinedType:
var predefined = (PredefinedTypeSyntax)type;
builder.Append(predefined.Keyword.Text);
break;
case SyntaxKind.QualifiedName:
var qualified = (QualifiedNameSyntax)type;
ExpandTypeName(qualified.Left, builder);
builder.Append(qualified.DotToken.Text);
ExpandTypeName(qualified.Right, builder);
break;
default:
Debug.Assert(false, "Unexpected type syntax " + type.Kind());
break;
}
}
private string GetContainerDisplayName(SyntaxNode node)
{
return GetDisplayName(node, DisplayNameOptions.IncludeTypeParameters);
}
private string GetFullyQualifiedContainerName(SyntaxNode node)
{
return GetDisplayName(node, DisplayNameOptions.IncludeNamespaces);
}
private const string dotToken = ".";
public string GetDisplayName(SyntaxNode node, DisplayNameOptions options, string rootNamespace = null)
{
if (node == null)
{
return string.Empty;
}
var pooled = PooledStringBuilder.GetInstance();
var builder = pooled.Builder;
// return type
var memberDeclaration = node as MemberDeclarationSyntax;
if ((options & DisplayNameOptions.IncludeType) != 0)
{
var type = memberDeclaration.GetMemberType();
if (type != null && !type.IsMissing)
{
builder.Append(type);
builder.Append(' ');
}
}
var names = ArrayBuilder<string>.GetInstance();
// containing type(s)
var parent = node.GetAncestor<TypeDeclarationSyntax>() ?? node.Parent;
while (parent is TypeDeclarationSyntax)
{
names.Push(GetName(parent, options));
parent = parent.Parent;
}
// containing namespace(s) in source (if any)
if ((options & DisplayNameOptions.IncludeNamespaces) != 0)
{
while (parent != null && parent.Kind() == SyntaxKind.NamespaceDeclaration)
{
names.Add(GetName(parent, options));
parent = parent.Parent;
}
}
while (!names.IsEmpty())
{
var name = names.Pop();
if (name != null)
{
builder.Append(name);
builder.Append(dotToken);
}
}
// name (including generic type parameters)
builder.Append(GetName(node, options));
// parameter list (if any)
if ((options & DisplayNameOptions.IncludeParameters) != 0)
{
builder.Append(memberDeclaration.GetParameterList());
}
return pooled.ToStringAndFree();
}
private static string GetName(SyntaxNode node, DisplayNameOptions options)
{
const string missingTokenPlaceholder = "?";
switch (node.Kind())
{
case SyntaxKind.CompilationUnit:
return null;
case SyntaxKind.IdentifierName:
var identifier = ((IdentifierNameSyntax)node).Identifier;
return identifier.IsMissing ? missingTokenPlaceholder : identifier.Text;
case SyntaxKind.IncompleteMember:
return missingTokenPlaceholder;
case SyntaxKind.NamespaceDeclaration:
return GetName(((NamespaceDeclarationSyntax)node).Name, options);
case SyntaxKind.QualifiedName:
var qualified = (QualifiedNameSyntax)node;
return GetName(qualified.Left, options) + dotToken + GetName(qualified.Right, options);
}
string name = null;
var memberDeclaration = node as MemberDeclarationSyntax;
if (memberDeclaration != null)
{
var nameToken = memberDeclaration.GetNameToken();
if (nameToken == default(SyntaxToken))
{
Debug.Assert(memberDeclaration.Kind() == SyntaxKind.ConversionOperatorDeclaration);
name = (memberDeclaration as ConversionOperatorDeclarationSyntax)?.Type.ToString();
}
else
{
name = nameToken.IsMissing ? missingTokenPlaceholder : nameToken.Text;
if (memberDeclaration.Kind() == SyntaxKind.DestructorDeclaration)
{
name = "~" + name;
}
if ((options & DisplayNameOptions.IncludeTypeParameters) != 0)
{
var pooled = PooledStringBuilder.GetInstance();
var builder = pooled.Builder;
builder.Append(name);
AppendTypeParameterList(builder, memberDeclaration.GetTypeParameterList());
name = pooled.ToStringAndFree();
}
}
}
else
{
var fieldDeclarator = node as VariableDeclaratorSyntax;
if (fieldDeclarator != null)
{
var nameToken = fieldDeclarator.Identifier;
if (nameToken != default(SyntaxToken))
{
name = nameToken.IsMissing ? missingTokenPlaceholder : nameToken.Text;
}
}
}
Debug.Assert(name != null, "Unexpected node type " + node.Kind());
return name;
}
private static void AppendTypeParameterList(StringBuilder builder, TypeParameterListSyntax typeParameterList)
{
if (typeParameterList != null && typeParameterList.Parameters.Count > 0)
{
builder.Append('<');
builder.Append(typeParameterList.Parameters[0].Identifier.ValueText);
for (int i = 1; i < typeParameterList.Parameters.Count; i++)
{
builder.Append(", ");
builder.Append(typeParameterList.Parameters[i].Identifier.ValueText);
}
builder.Append('>');
}
}
public List<SyntaxNode> GetMethodLevelMembers(SyntaxNode root)
{
var list = new List<SyntaxNode>();
AppendMethodLevelMembers(root, list);
return list;
}
private void AppendMethodLevelMembers(SyntaxNode node, List<SyntaxNode> list)
{
foreach (var member in node.GetMembers())
{
if (IsTopLevelNodeWithMembers(member))
{
AppendMethodLevelMembers(member, list);
continue;
}
if (IsMethodLevelMember(member))
{
list.Add(member);
}
}
}
public TextSpan GetMemberBodySpanForSpeculativeBinding(SyntaxNode node)
{
if (node.Span.IsEmpty)
{
return default(TextSpan);
}
var member = GetContainingMemberDeclaration(node, node.SpanStart);
if (member == null)
{
return default(TextSpan);
}
// TODO: currently we only support method for now
var method = member as BaseMethodDeclarationSyntax;
if (method != null)
{
if (method.Body == null)
{
return default(TextSpan);
}
return GetBlockBodySpan(method.Body);
}
return default(TextSpan);
}
public bool ContainsInMemberBody(SyntaxNode node, TextSpan span)
{
var constructor = node as ConstructorDeclarationSyntax;
if (constructor != null)
{
return (constructor.Body != null && GetBlockBodySpan(constructor.Body).Contains(span)) ||
(constructor.Initializer != null && constructor.Initializer.Span.Contains(span));
}
var method = node as BaseMethodDeclarationSyntax;
if (method != null)
{
return method.Body != null && GetBlockBodySpan(method.Body).Contains(span);
}
var property = node as BasePropertyDeclarationSyntax;
if (property != null)
{
return property.AccessorList != null && property.AccessorList.Span.Contains(span);
}
var @enum = node as EnumMemberDeclarationSyntax;
if (@enum != null)
{
return @enum.EqualsValue != null && @enum.EqualsValue.Span.Contains(span);
}
var field = node as BaseFieldDeclarationSyntax;
if (field != null)
{
return field.Declaration != null && field.Declaration.Span.Contains(span);
}
return false;
}
private TextSpan GetBlockBodySpan(BlockSyntax body)
{
return TextSpan.FromBounds(body.OpenBraceToken.Span.End, body.CloseBraceToken.SpanStart);
}
public int GetMethodLevelMemberId(SyntaxNode root, SyntaxNode node)
{
Contract.Requires(root.SyntaxTree == node.SyntaxTree);
int currentId = 0;
SyntaxNode currentNode;
Contract.ThrowIfFalse(TryGetMethodLevelMember(root, (n, i) => n == node, ref currentId, out currentNode));
Contract.ThrowIfFalse(currentId >= 0);
CheckMemberId(root, node, currentId);
return currentId;
}
public SyntaxNode GetMethodLevelMember(SyntaxNode root, int memberId)
{
int currentId = 0;
SyntaxNode currentNode;
if (!TryGetMethodLevelMember(root, (n, i) => i == memberId, ref currentId, out currentNode))
{
return null;
}
Contract.ThrowIfNull(currentNode);
CheckMemberId(root, currentNode, memberId);
return currentNode;
}
private bool TryGetMethodLevelMember(
SyntaxNode node, Func<SyntaxNode, int, bool> predicate, ref int currentId, out SyntaxNode currentNode)
{
foreach (var member in node.GetMembers())
{
if (IsTopLevelNodeWithMembers(member))
{
if (TryGetMethodLevelMember(member, predicate, ref currentId, out currentNode))
{
return true;
}
continue;
}
if (IsMethodLevelMember(member))
{
if (predicate(member, currentId))
{
currentNode = member;
return true;
}
currentId++;
}
}
currentNode = null;
return false;
}
[Conditional("DEBUG")]
private void CheckMemberId(SyntaxNode root, SyntaxNode node, int memberId)
{
var list = GetMethodLevelMembers(root);
var index = list.IndexOf(node);
Contract.ThrowIfFalse(index == memberId);
}
public SyntaxNode GetBindableParent(SyntaxToken token)
{
var node = token.Parent;
while (node != null)
{
var parent = node.Parent;
// If this node is on the left side of a member access expression, don't ascend
// further or we'll end up binding to something else.
var memberAccess = parent as MemberAccessExpressionSyntax;
if (memberAccess != null)
{
if (memberAccess.Expression == node)
{
break;
}
}
// If this node is on the left side of a qualified name, don't ascend
// further or we'll end up binding to something else.
var qualifiedName = parent as QualifiedNameSyntax;
if (qualifiedName != null)
{
if (qualifiedName.Left == node)
{
break;
}
}
// If this node is on the left side of a alias-qualified name, don't ascend
// further or we'll end up binding to something else.
var aliasQualifiedName = parent as AliasQualifiedNameSyntax;
if (aliasQualifiedName != null)
{
if (aliasQualifiedName.Alias == node)
{
break;
}
}
// If this node is the type of an object creation expression, return the
// object creation expression.
var objectCreation = parent as ObjectCreationExpressionSyntax;
if (objectCreation != null)
{
if (objectCreation.Type == node)
{
node = parent;
break;
}
}
// The inside of an interpolated string is treated as its own token so we
// need to force navigation to the parent expression syntax.
if (node is InterpolatedStringTextSyntax && parent is InterpolatedStringExpressionSyntax)
{
node = parent;
break;
}
// If this node is not parented by a name, we're done.
var name = parent as NameSyntax;
if (name == null)
{
break;
}
node = parent;
}
return node;
}
public IEnumerable<SyntaxNode> GetConstructors(SyntaxNode root, CancellationToken cancellationToken)
{
var compilationUnit = root as CompilationUnitSyntax;
if (compilationUnit == null)
{
return SpecializedCollections.EmptyEnumerable<SyntaxNode>();
}
var constructors = new List<SyntaxNode>();
AppendConstructors(compilationUnit.Members, constructors, cancellationToken);
return constructors;
}
private void AppendConstructors(SyntaxList<MemberDeclarationSyntax> members, List<SyntaxNode> constructors, CancellationToken cancellationToken)
{
foreach (var member in members)
{
cancellationToken.ThrowIfCancellationRequested();
var constructor = member as ConstructorDeclarationSyntax;
if (constructor != null)
{
constructors.Add(constructor);
continue;
}
var @namespace = member as NamespaceDeclarationSyntax;
if (@namespace != null)
{
AppendConstructors(@namespace.Members, constructors, cancellationToken);
}
var @class = member as ClassDeclarationSyntax;
if (@class != null)
{
AppendConstructors(@class.Members, constructors, cancellationToken);
}
var @struct = member as StructDeclarationSyntax;
if (@struct != null)
{
AppendConstructors(@struct.Members, constructors, cancellationToken);
}
}
}
public bool TryGetCorrespondingOpenBrace(SyntaxToken token, out SyntaxToken openBrace)
{
if (token.Kind() == SyntaxKind.CloseBraceToken)
{
var tuple = token.Parent.GetBraces();
openBrace = tuple.Item1;
return openBrace.Kind() == SyntaxKind.OpenBraceToken;
}
openBrace = default(SyntaxToken);
return false;
}
public TextSpan GetInactiveRegionSpanAroundPosition(SyntaxTree syntaxTree, int position, CancellationToken cancellationToken)
{
var trivia = syntaxTree.GetRoot(cancellationToken).FindTrivia(position, findInsideTrivia: false);
if (trivia.Kind() == SyntaxKind.DisabledTextTrivia)
{
return trivia.FullSpan;
}
var token = syntaxTree.FindTokenOrEndToken(position, cancellationToken);
if (token.Kind() == SyntaxKind.EndOfFileToken)
{
var triviaList = token.LeadingTrivia;
foreach (var triviaTok in triviaList.Reverse())
{
if (triviaTok.Span.Contains(position))
{
return default(TextSpan);
}
if (triviaTok.Span.End < position)
{
if (!triviaTok.HasStructure)
{
return default(TextSpan);
}
var structure = triviaTok.GetStructure();
if (structure is BranchingDirectiveTriviaSyntax)
{
var branch = (BranchingDirectiveTriviaSyntax)structure;
return !branch.IsActive || !branch.BranchTaken ? TextSpan.FromBounds(branch.FullSpan.Start, position) : default(TextSpan);
}
}
}
}
return default(TextSpan);
}
}
}
| |
// Copyright (c) The Avalonia Project. All rights reserved.
// Licensed under the MIT license. See licence.md file in the project root for full license information.
using System;
using System.Diagnostics.CodeAnalysis;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Text;
// ReSharper disable InconsistentNaming
#pragma warning disable 169, 649
namespace Avalonia.Win32.Interop
{
[SuppressMessage("Microsoft.StyleCop.CSharp.NamingRules", "SA1305:FieldNamesMustNotUseHungarianNotation", Justification = "Using Win32 naming for consistency.")]
[SuppressMessage("Microsoft.StyleCop.CSharp.NamingRules", "SA1307:AccessibleFieldsMustBeginWithUpperCaseLetter", Justification = "Using Win32 naming for consistency.")]
[SuppressMessage("Microsoft.StyleCop.CSharp.NamingRules", "SA1310:FieldNamesMustNotContainUnderscore", Justification = "Using Win32 naming for consistency.")]
[SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:Elements must be documented", Justification = "Look in Win32 docs.")]
[SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1602:Enumeration items must be documented", Justification = "Look in Win32 docs.")]
internal static class UnmanagedMethods
{
public const int CW_USEDEFAULT = unchecked((int)0x80000000);
public delegate void TimerProc(IntPtr hWnd, uint uMsg, IntPtr nIDEvent, uint dwTime);
public delegate IntPtr WndProc(IntPtr hWnd, uint msg, IntPtr wParam, IntPtr lParam);
public enum Cursor
{
IDC_ARROW = 32512,
IDC_IBEAM = 32513,
IDC_WAIT = 32514,
IDC_CROSS = 32515,
IDC_UPARROW = 32516,
IDC_SIZE = 32640,
IDC_ICON = 32641,
IDC_SIZENWSE = 32642,
IDC_SIZENESW = 32643,
IDC_SIZEWE = 32644,
IDC_SIZENS = 32645,
IDC_SIZEALL = 32646,
IDC_NO = 32648,
IDC_HAND = 32649,
IDC_APPSTARTING = 32650,
IDC_HELP = 32651
}
public enum MouseActivate : int
{
MA_ACTIVATE = 1,
MA_ACTIVATEANDEAT = 2,
MA_NOACTIVATE = 3,
MA_NOACTIVATEANDEAT = 4
}
[Flags]
public enum SetWindowPosFlags : uint
{
SWP_ASYNCWINDOWPOS = 0x4000,
SWP_DEFERERASE = 0x2000,
SWP_DRAWFRAME = 0x0020,
SWP_FRAMECHANGED = 0x0020,
SWP_HIDEWINDOW = 0x0080,
SWP_NOACTIVATE = 0x0010,
SWP_NOCOPYBITS = 0x0100,
SWP_NOMOVE = 0x0002,
SWP_NOOWNERZORDER = 0x0200,
SWP_NOREDRAW = 0x0008,
SWP_NOREPOSITION = 0x0200,
SWP_NOSENDCHANGING = 0x0400,
SWP_NOSIZE = 0x0001,
SWP_NOZORDER = 0x0004,
SWP_SHOWWINDOW = 0x0040,
SWP_RESIZE = SWP_NOACTIVATE | SWP_NOMOVE | SWP_NOZORDER
}
public enum ShowWindowCommand
{
Hide = 0,
Normal = 1,
ShowMinimized = 2,
Maximize = 3,
ShowMaximized = 3,
ShowNoActivate = 4,
Show = 5,
Minimize = 6,
ShowMinNoActive = 7,
ShowNA = 8,
Restore = 9,
ShowDefault = 10,
ForceMinimize = 11
}
public enum SystemMetric
{
SM_CXSCREEN = 0, // 0x00
SM_CYSCREEN = 1, // 0x01
SM_CXVSCROLL = 2, // 0x02
SM_CYHSCROLL = 3, // 0x03
SM_CYCAPTION = 4, // 0x04
SM_CXBORDER = 5, // 0x05
SM_CYBORDER = 6, // 0x06
SM_CXDLGFRAME = 7, // 0x07
SM_CXFIXEDFRAME = 7, // 0x07
SM_CYDLGFRAME = 8, // 0x08
SM_CYFIXEDFRAME = 8, // 0x08
SM_CYVTHUMB = 9, // 0x09
SM_CXHTHUMB = 10, // 0x0A
SM_CXICON = 11, // 0x0B
SM_CYICON = 12, // 0x0C
SM_CXCURSOR = 13, // 0x0D
SM_CYCURSOR = 14, // 0x0E
SM_CYMENU = 15, // 0x0F
SM_CXFULLSCREEN = 16, // 0x10
SM_CYFULLSCREEN = 17, // 0x11
SM_CYKANJIWINDOW = 18, // 0x12
SM_MOUSEPRESENT = 19, // 0x13
SM_CYVSCROLL = 20, // 0x14
SM_CXHSCROLL = 21, // 0x15
SM_DEBUG = 22, // 0x16
SM_SWAPBUTTON = 23, // 0x17
SM_CXMIN = 28, // 0x1C
SM_CYMIN = 29, // 0x1D
SM_CXSIZE = 30, // 0x1E
SM_CYSIZE = 31, // 0x1F
SM_CXSIZEFRAME = 32, // 0x20
SM_CXFRAME = 32, // 0x20
SM_CYSIZEFRAME = 33, // 0x21
SM_CYFRAME = 33, // 0x21
SM_CXMINTRACK = 34, // 0x22
SM_CYMINTRACK = 35, // 0x23
SM_CXDOUBLECLK = 36, // 0x24
SM_CYDOUBLECLK = 37, // 0x25
SM_CXICONSPACING = 38, // 0x26
SM_CYICONSPACING = 39, // 0x27
SM_MENUDROPALIGNMENT = 40, // 0x28
SM_PENWINDOWS = 41, // 0x29
SM_DBCSENABLED = 42, // 0x2A
SM_CMOUSEBUTTONS = 43, // 0x2B
SM_SECURE = 44, // 0x2C
SM_CXEDGE = 45, // 0x2D
SM_CYEDGE = 46, // 0x2E
SM_CXMINSPACING = 47, // 0x2F
SM_CYMINSPACING = 48, // 0x30
SM_CXSMICON = 49, // 0x31
SM_CYSMICON = 50, // 0x32
SM_CYSMCAPTION = 51, // 0x33
SM_CXSMSIZE = 52, // 0x34
SM_CYSMSIZE = 53, // 0x35
SM_CXMENUSIZE = 54, // 0x36
SM_CYMENUSIZE = 55, // 0x37
SM_ARRANGE = 56, // 0x38
SM_CXMINIMIZED = 57, // 0x39
SM_CYMINIMIZED = 58, // 0x3A
SM_CXMAXTRACK = 59, // 0x3B
SM_CYMAXTRACK = 60, // 0x3C
SM_CXMAXIMIZED = 61, // 0x3D
SM_CYMAXIMIZED = 62, // 0x3E
SM_NETWORK = 63, // 0x3F
SM_CLEANBOOT = 67, // 0x43
SM_CXDRAG = 68, // 0x44
SM_CYDRAG = 69, // 0x45
SM_SHOWSOUNDS = 70, // 0x46
SM_CXMENUCHECK = 71, // 0x47
SM_CYMENUCHECK = 72, // 0x48
SM_SLOWMACHINE = 73, // 0x49
SM_MIDEASTENABLED = 74, // 0x4A
SM_MOUSEWHEELPRESENT = 75, // 0x4B
SM_XVIRTUALSCREEN = 76, // 0x4C
SM_YVIRTUALSCREEN = 77, // 0x4D
SM_CXVIRTUALSCREEN = 78, // 0x4E
SM_CYVIRTUALSCREEN = 79, // 0x4F
SM_CMONITORS = 80, // 0x50
SM_SAMEDISPLAYFORMAT = 81, // 0x51
SM_IMMENABLED = 82, // 0x52
SM_CXFOCUSBORDER = 83, // 0x53
SM_CYFOCUSBORDER = 84, // 0x54
SM_TABLETPC = 86, // 0x56
SM_MEDIACENTER = 87, // 0x57
SM_STARTER = 88, // 0x58
SM_SERVERR2 = 89, // 0x59
SM_MOUSEHORIZONTALWHEELPRESENT = 91, // 0x5B
SM_CXPADDEDBORDER = 92, // 0x5C
SM_DIGITIZER = 94, // 0x5E
SM_MAXIMUMTOUCHES = 95, // 0x5F
SM_REMOTESESSION = 0x1000, // 0x1000
SM_SHUTTINGDOWN = 0x2000, // 0x2000
SM_REMOTECONTROL = 0x2001, // 0x2001
SM_CONVERTABLESLATEMODE = 0x2003,
SM_SYSTEMDOCKED = 0x2004,
}
[Flags]
public enum ModifierKeys
{
MK_CONTROL = 0x0008,
MK_LBUTTON = 0x0001,
MK_MBUTTON = 0x0010,
MK_RBUTTON = 0x0002,
MK_SHIFT = 0x0004,
MK_XBUTTON1 = 0x0020,
MK_XBUTTON2 = 0x0040
}
public enum WindowActivate
{
WA_INACTIVE,
WA_ACTIVE,
WA_CLICKACTIVE,
}
public enum HitTestValues
{
HTERROR = -2,
HTTRANSPARENT = -1,
HTNOWHERE = 0,
HTCLIENT = 1,
HTCAPTION = 2,
HTSYSMENU = 3,
HTGROWBOX = 4,
HTMENU = 5,
HTHSCROLL = 6,
HTVSCROLL = 7,
HTMINBUTTON = 8,
HTMAXBUTTON = 9,
HTLEFT = 10,
HTRIGHT = 11,
HTTOP = 12,
HTTOPLEFT = 13,
HTTOPRIGHT = 14,
HTBOTTOM = 15,
HTBOTTOMLEFT = 16,
HTBOTTOMRIGHT = 17,
HTBORDER = 18,
HTOBJECT = 19,
HTCLOSE = 20,
HTHELP = 21
}
[Flags]
public enum WindowStyles : uint
{
WS_BORDER = 0x800000,
WS_CAPTION = 0xc00000,
WS_CHILD = 0x40000000,
WS_CLIPCHILDREN = 0x2000000,
WS_CLIPSIBLINGS = 0x4000000,
WS_DISABLED = 0x8000000,
WS_DLGFRAME = 0x400000,
WS_GROUP = 0x20000,
WS_HSCROLL = 0x100000,
WS_MAXIMIZE = 0x1000000,
WS_MAXIMIZEBOX = 0x10000,
WS_MINIMIZE = 0x20000000,
WS_MINIMIZEBOX = 0x20000,
WS_OVERLAPPED = 0x0,
WS_OVERLAPPEDWINDOW = WS_OVERLAPPED | WS_CAPTION | WS_SYSMENU | WS_SIZEFRAME | WS_MINIMIZEBOX | WS_MAXIMIZEBOX,
WS_POPUP = 0x80000000u,
WS_POPUPWINDOW = WS_POPUP | WS_BORDER | WS_SYSMENU,
WS_SIZEFRAME = 0x40000,
WS_SYSMENU = 0x80000,
WS_TABSTOP = 0x10000,
WS_VISIBLE = 0x10000000,
WS_VSCROLL = 0x200000,
WS_EX_DLGMODALFRAME = 0x00000001,
WS_EX_NOPARENTNOTIFY = 0x00000004,
WS_EX_TOPMOST = 0x00000008,
WS_EX_ACCEPTFILES = 0x00000010,
WS_EX_TRANSPARENT = 0x00000020,
WS_EX_MDICHILD = 0x00000040,
WS_EX_TOOLWINDOW = 0x00000080,
WS_EX_WINDOWEDGE = 0x00000100,
WS_EX_CLIENTEDGE = 0x00000200,
WS_EX_CONTEXTHELP = 0x00000400,
WS_EX_RIGHT = 0x00001000,
WS_EX_LEFT = 0x00000000,
WS_EX_RTLREADING = 0x00002000,
WS_EX_LTRREADING = 0x00000000,
WS_EX_LEFTSCROLLBAR = 0x00004000,
WS_EX_RIGHTSCROLLBAR = 0x00000000,
WS_EX_CONTROLPARENT = 0x00010000,
WS_EX_STATICEDGE = 0x00020000,
WS_EX_APPWINDOW = 0x00040000,
WS_EX_OVERLAPPEDWINDOW = WS_EX_WINDOWEDGE | WS_EX_CLIENTEDGE,
WS_EX_PALETTEWINDOW = WS_EX_WINDOWEDGE | WS_EX_TOOLWINDOW | WS_EX_TOPMOST,
WS_EX_LAYERED = 0x00080000,
WS_EX_NOINHERITLAYOUT = 0x00100000,
WS_EX_LAYOUTRTL = 0x00400000,
WS_EX_COMPOSITED = 0x02000000,
WS_EX_NOACTIVATE = 0x08000000
}
public enum WindowsMessage : uint
{
WM_NULL = 0x0000,
WM_CREATE = 0x0001,
WM_DESTROY = 0x0002,
WM_MOVE = 0x0003,
WM_SIZE = 0x0005,
WM_ACTIVATE = 0x0006,
WM_SETFOCUS = 0x0007,
WM_KILLFOCUS = 0x0008,
WM_ENABLE = 0x000A,
WM_SETREDRAW = 0x000B,
WM_SETTEXT = 0x000C,
WM_GETTEXT = 0x000D,
WM_GETTEXTLENGTH = 0x000E,
WM_PAINT = 0x000F,
WM_CLOSE = 0x0010,
WM_QUERYENDSESSION = 0x0011,
WM_QUERYOPEN = 0x0013,
WM_ENDSESSION = 0x0016,
WM_QUIT = 0x0012,
WM_ERASEBKGND = 0x0014,
WM_SYSCOLORCHANGE = 0x0015,
WM_SHOWWINDOW = 0x0018,
WM_WININICHANGE = 0x001A,
WM_SETTINGCHANGE = WM_WININICHANGE,
WM_DEVMODECHANGE = 0x001B,
WM_ACTIVATEAPP = 0x001C,
WM_FONTCHANGE = 0x001D,
WM_TIMECHANGE = 0x001E,
WM_CANCELMODE = 0x001F,
WM_SETCURSOR = 0x0020,
WM_MOUSEACTIVATE = 0x0021,
WM_CHILDACTIVATE = 0x0022,
WM_QUEUESYNC = 0x0023,
WM_GETMINMAXINFO = 0x0024,
WM_PAINTICON = 0x0026,
WM_ICONERASEBKGND = 0x0027,
WM_NEXTDLGCTL = 0x0028,
WM_SPOOLERSTATUS = 0x002A,
WM_DRAWITEM = 0x002B,
WM_MEASUREITEM = 0x002C,
WM_DELETEITEM = 0x002D,
WM_VKEYTOITEM = 0x002E,
WM_CHARTOITEM = 0x002F,
WM_SETFONT = 0x0030,
WM_GETFONT = 0x0031,
WM_SETHOTKEY = 0x0032,
WM_GETHOTKEY = 0x0033,
WM_QUERYDRAGICON = 0x0037,
WM_COMPAREITEM = 0x0039,
WM_GETOBJECT = 0x003D,
WM_COMPACTING = 0x0041,
WM_WINDOWPOSCHANGING = 0x0046,
WM_WINDOWPOSCHANGED = 0x0047,
WM_COPYDATA = 0x004A,
WM_CANCELJOURNAL = 0x004B,
WM_NOTIFY = 0x004E,
WM_INPUTLANGCHANGEREQUEST = 0x0050,
WM_INPUTLANGCHANGE = 0x0051,
WM_TCARD = 0x0052,
WM_HELP = 0x0053,
WM_USERCHANGED = 0x0054,
WM_NOTIFYFORMAT = 0x0055,
WM_CONTEXTMENU = 0x007B,
WM_STYLECHANGING = 0x007C,
WM_STYLECHANGED = 0x007D,
WM_DISPLAYCHANGE = 0x007E,
WM_GETICON = 0x007F,
WM_SETICON = 0x0080,
WM_NCCREATE = 0x0081,
WM_NCDESTROY = 0x0082,
WM_NCCALCSIZE = 0x0083,
WM_NCHITTEST = 0x0084,
WM_NCPAINT = 0x0085,
WM_NCACTIVATE = 0x0086,
WM_GETDLGCODE = 0x0087,
WM_SYNCPAINT = 0x0088,
WM_NCMOUSEMOVE = 0x00A0,
WM_NCLBUTTONDOWN = 0x00A1,
WM_NCLBUTTONUP = 0x00A2,
WM_NCLBUTTONDBLCLK = 0x00A3,
WM_NCRBUTTONDOWN = 0x00A4,
WM_NCRBUTTONUP = 0x00A5,
WM_NCRBUTTONDBLCLK = 0x00A6,
WM_NCMBUTTONDOWN = 0x00A7,
WM_NCMBUTTONUP = 0x00A8,
WM_NCMBUTTONDBLCLK = 0x00A9,
WM_NCXBUTTONDOWN = 0x00AB,
WM_NCXBUTTONUP = 0x00AC,
WM_NCXBUTTONDBLCLK = 0x00AD,
WM_INPUT_DEVICE_CHANGE = 0x00FE,
WM_INPUT = 0x00FF,
WM_KEYFIRST = 0x0100,
WM_KEYDOWN = 0x0100,
WM_KEYUP = 0x0101,
WM_CHAR = 0x0102,
WM_DEADCHAR = 0x0103,
WM_SYSKEYDOWN = 0x0104,
WM_SYSKEYUP = 0x0105,
WM_SYSCHAR = 0x0106,
WM_SYSDEADCHAR = 0x0107,
WM_UNICHAR = 0x0109,
WM_KEYLAST = 0x0109,
WM_IME_STARTCOMPOSITION = 0x010D,
WM_IME_ENDCOMPOSITION = 0x010E,
WM_IME_COMPOSITION = 0x010F,
WM_IME_KEYLAST = 0x010F,
WM_INITDIALOG = 0x0110,
WM_COMMAND = 0x0111,
WM_SYSCOMMAND = 0x0112,
WM_TIMER = 0x0113,
WM_HSCROLL = 0x0114,
WM_VSCROLL = 0x0115,
WM_INITMENU = 0x0116,
WM_INITMENUPOPUP = 0x0117,
WM_MENUSELECT = 0x011F,
WM_MENUCHAR = 0x0120,
WM_ENTERIDLE = 0x0121,
WM_MENURBUTTONUP = 0x0122,
WM_MENUDRAG = 0x0123,
WM_MENUGETOBJECT = 0x0124,
WM_UNINITMENUPOPUP = 0x0125,
WM_MENUCOMMAND = 0x0126,
WM_CHANGEUISTATE = 0x0127,
WM_UPDATEUISTATE = 0x0128,
WM_QUERYUISTATE = 0x0129,
WM_CTLCOLORMSGBOX = 0x0132,
WM_CTLCOLOREDIT = 0x0133,
WM_CTLCOLORLISTBOX = 0x0134,
WM_CTLCOLORBTN = 0x0135,
WM_CTLCOLORDLG = 0x0136,
WM_CTLCOLORSCROLLBAR = 0x0137,
WM_CTLCOLORSTATIC = 0x0138,
WM_MOUSEFIRST = 0x0200,
WM_MOUSEMOVE = 0x0200,
WM_LBUTTONDOWN = 0x0201,
WM_LBUTTONUP = 0x0202,
WM_LBUTTONDBLCLK = 0x0203,
WM_RBUTTONDOWN = 0x0204,
WM_RBUTTONUP = 0x0205,
WM_RBUTTONDBLCLK = 0x0206,
WM_MBUTTONDOWN = 0x0207,
WM_MBUTTONUP = 0x0208,
WM_MBUTTONDBLCLK = 0x0209,
WM_MOUSEWHEEL = 0x020A,
WM_XBUTTONDOWN = 0x020B,
WM_XBUTTONUP = 0x020C,
WM_XBUTTONDBLCLK = 0x020D,
WM_MOUSEHWHEEL = 0x020E,
WM_MOUSELAST = 0x020E,
WM_PARENTNOTIFY = 0x0210,
WM_ENTERMENULOOP = 0x0211,
WM_EXITMENULOOP = 0x0212,
WM_NEXTMENU = 0x0213,
WM_SIZING = 0x0214,
WM_CAPTURECHANGED = 0x0215,
WM_MOVING = 0x0216,
WM_POWERBROADCAST = 0x0218,
WM_DEVICECHANGE = 0x0219,
WM_MDICREATE = 0x0220,
WM_MDIDESTROY = 0x0221,
WM_MDIACTIVATE = 0x0222,
WM_MDIRESTORE = 0x0223,
WM_MDINEXT = 0x0224,
WM_MDIMAXIMIZE = 0x0225,
WM_MDITILE = 0x0226,
WM_MDICASCADE = 0x0227,
WM_MDIICONARRANGE = 0x0228,
WM_MDIGETACTIVE = 0x0229,
WM_MDISETMENU = 0x0230,
WM_ENTERSIZEMOVE = 0x0231,
WM_EXITSIZEMOVE = 0x0232,
WM_DROPFILES = 0x0233,
WM_MDIREFRESHMENU = 0x0234,
WM_IME_SETCONTEXT = 0x0281,
WM_IME_NOTIFY = 0x0282,
WM_IME_CONTROL = 0x0283,
WM_IME_COMPOSITIONFULL = 0x0284,
WM_IME_SELECT = 0x0285,
WM_IME_CHAR = 0x0286,
WM_IME_REQUEST = 0x0288,
WM_IME_KEYDOWN = 0x0290,
WM_IME_KEYUP = 0x0291,
WM_MOUSEHOVER = 0x02A1,
WM_MOUSELEAVE = 0x02A3,
WM_NCMOUSEHOVER = 0x02A0,
WM_NCMOUSELEAVE = 0x02A2,
WM_WTSSESSION_CHANGE = 0x02B1,
WM_TABLET_FIRST = 0x02c0,
WM_TABLET_LAST = 0x02df,
WM_DPICHANGED = 0x02E0,
WM_CUT = 0x0300,
WM_COPY = 0x0301,
WM_PASTE = 0x0302,
WM_CLEAR = 0x0303,
WM_UNDO = 0x0304,
WM_RENDERFORMAT = 0x0305,
WM_RENDERALLFORMATS = 0x0306,
WM_DESTROYCLIPBOARD = 0x0307,
WM_DRAWCLIPBOARD = 0x0308,
WM_PAINTCLIPBOARD = 0x0309,
WM_VSCROLLCLIPBOARD = 0x030A,
WM_SIZECLIPBOARD = 0x030B,
WM_ASKCBFORMATNAME = 0x030C,
WM_CHANGECBCHAIN = 0x030D,
WM_HSCROLLCLIPBOARD = 0x030E,
WM_QUERYNEWPALETTE = 0x030F,
WM_PALETTEISCHANGING = 0x0310,
WM_PALETTECHANGED = 0x0311,
WM_HOTKEY = 0x0312,
WM_PRINT = 0x0317,
WM_PRINTCLIENT = 0x0318,
WM_APPCOMMAND = 0x0319,
WM_THEMECHANGED = 0x031A,
WM_CLIPBOARDUPDATE = 0x031D,
WM_DWMCOMPOSITIONCHANGED = 0x031E,
WM_DWMNCRENDERINGCHANGED = 0x031F,
WM_DWMCOLORIZATIONCOLORCHANGED = 0x0320,
WM_DWMWINDOWMAXIMIZEDCHANGE = 0x0321,
WM_GETTITLEBARINFOEX = 0x033F,
WM_HANDHELDFIRST = 0x0358,
WM_HANDHELDLAST = 0x035F,
WM_AFXFIRST = 0x0360,
WM_AFXLAST = 0x037F,
WM_PENWINFIRST = 0x0380,
WM_PENWINLAST = 0x038F,
WM_APP = 0x8000,
WM_USER = 0x0400,
WM_DISPATCH_WORK_ITEM = WM_USER,
}
public enum BitmapCompressionMode : uint
{
BI_RGB = 0,
BI_RLE8 = 1,
BI_RLE4 = 2,
BI_BITFIELDS = 3,
BI_JPEG = 4,
BI_PNG = 5
}
public enum DIBColorTable
{
DIB_RGB_COLORS = 0, /* color table in RGBs */
DIB_PAL_COLORS /* color table in palette indices */
};
[StructLayout(LayoutKind.Sequential)]
public struct RGBQUAD
{
public byte rgbBlue;
public byte rgbGreen;
public byte rgbRed;
public byte rgbReserved;
}
[StructLayout(LayoutKind.Sequential)]
public struct BITMAPINFO
{
// C# cannot inlay structs in structs so must expand directly here
//
//[StructLayout(LayoutKind.Sequential)]
//public struct BITMAPINFOHEADER
//{
public uint biSize;
public int biWidth;
public int biHeight;
public ushort biPlanes;
public ushort biBitCount;
public BitmapCompressionMode biCompression;
public uint biSizeImage;
public int biXPelsPerMeter;
public int biYPelsPerMeter;
public uint biClrUsed;
public uint biClrImportant;
//}
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 256)]
public uint[] cols;
}
public const int SizeOf_BITMAPINFOHEADER = 40;
[DllImport("user32.dll", SetLastError = true)]
public static extern IntPtr GetDC(IntPtr hWnd);
[DllImport("gdi32.dll")]
public static extern int SetDIBitsToDevice(IntPtr hdc, int XDest, int YDest,
uint dwWidth, uint dwHeight,
int XSrc, int YSrc,
uint uStartScan, uint cScanLines,
IntPtr lpvBits, [In] ref BITMAPINFO lpbmi, uint fuColorUse);
[DllImport("user32.dll")]
public static extern bool ReleaseDC(IntPtr hWnd, IntPtr hDC);
[DllImport("user32.dll", SetLastError = true)]
public static extern bool AdjustWindowRectEx(ref RECT lpRect, uint dwStyle, bool bMenu, uint dwExStyle);
[DllImport("user32.dll")]
public static extern IntPtr BeginPaint(IntPtr hwnd, out PAINTSTRUCT lpPaint);
[DllImport("user32.dll")]
public static extern bool ClientToScreen(IntPtr hWnd, ref POINT lpPoint);
[DllImport("user32.dll", SetLastError = true)]
public static extern IntPtr CreateWindowEx(
int dwExStyle,
uint lpClassName,
string lpWindowName,
uint dwStyle,
int x,
int y,
int nWidth,
int nHeight,
IntPtr hWndParent,
IntPtr hMenu,
IntPtr hInstance,
IntPtr lpParam);
[DllImport("user32.dll", EntryPoint = "DefWindowProcW")]
public static extern IntPtr DefWindowProc(IntPtr hWnd, uint msg, IntPtr wParam, IntPtr lParam);
[DllImport("user32.dll", EntryPoint = "DispatchMessageW")]
public static extern IntPtr DispatchMessage(ref MSG lpmsg);
[DllImport("user32.dll", SetLastError = true)]
public static extern bool DestroyWindow(IntPtr hwnd);
[DllImport("user32.dll")]
public static extern bool EnableWindow(IntPtr hWnd, bool bEnable);
[DllImport("user32.dll")]
public static extern bool EndPaint(IntPtr hWnd, ref PAINTSTRUCT lpPaint);
[DllImport("user32.dll")]
public static extern uint GetCaretBlinkTime();
[DllImport("user32.dll")]
public static extern bool GetClientRect(IntPtr hwnd, out RECT lpRect);
[DllImport("user32.dll")]
public static extern bool GetCursorPos(out POINT lpPoint);
[DllImport("user32.dll")]
public static extern uint GetDoubleClickTime();
[DllImport("user32.dll")]
public static extern bool GetKeyboardState(byte[] lpKeyState);
[DllImport("user32.dll", EntryPoint = "GetMessageW")]
public static extern sbyte GetMessage(out MSG lpMsg, IntPtr hWnd, uint wMsgFilterMin, uint wMsgFilterMax);
[DllImport("user32.dll")]
public static extern int GetMessageTime();
[DllImport("kernel32.dll")]
public static extern IntPtr GetModuleHandle(string lpModuleName);
[DllImport("user32.dll")]
public static extern int GetSystemMetrics(SystemMetric smIndex);
[DllImport("user32.dll", SetLastError = true)]
public static extern uint GetWindowLong(IntPtr hWnd, int nIndex);
[DllImport("user32.dll", SetLastError = true)]
public static extern uint SetWindowLong(IntPtr hWnd, int nIndex, uint value);
[DllImport("user32.dll", SetLastError = true)]
public static extern bool GetWindowPlacement(IntPtr hWnd, ref WINDOWPLACEMENT lpwndpl);
[DllImport("user32.dll")]
public static extern bool GetWindowRect(IntPtr hwnd, out RECT lpRect);
[DllImport("user32.dll")]
public static extern bool GetUpdateRect(IntPtr hwnd, out RECT lpRect, bool bErase);
[DllImport("user32.dll")]
public static extern bool InvalidateRect(IntPtr hWnd, ref RECT lpRect, bool bErase);
[DllImport("user32.dll")]
public static extern bool IsWindowEnabled(IntPtr hWnd);
[DllImport("user32.dll")]
public static extern bool IsWindowUnicode(IntPtr hWnd);
[DllImport("user32.dll")]
public static extern bool IsWindowVisible(IntPtr hWnd);
[DllImport("user32.dll")]
public static extern bool KillTimer(IntPtr hWnd, IntPtr uIDEvent);
[DllImport("user32.dll")]
public static extern IntPtr LoadCursor(IntPtr hInstance, IntPtr lpCursorName);
[DllImport("user32.dll")]
public static extern bool PeekMessage(out MSG lpMsg, IntPtr hWnd, uint wMsgFilterMin, uint wMsgFilterMax, uint wRemoveMsg);
[DllImport("user32.dll")]
public static extern IntPtr PostMessage(IntPtr hWnd, int msg, IntPtr wParam, IntPtr lParam);
[DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Unicode, EntryPoint = "RegisterClassExW")]
public static extern ushort RegisterClassEx(ref WNDCLASSEX lpwcx);
[DllImport("user32.dll")]
public static extern bool ReleaseCapture();
[DllImport("user32.dll")]
public static extern bool ScreenToClient(IntPtr hWnd, ref POINT lpPoint);
[DllImport("user32.dll", SetLastError = true)]
public static extern IntPtr SetActiveWindow(IntPtr hWnd);
[DllImport("user32.dll")]
public static extern IntPtr SetCapture(IntPtr hWnd);
[DllImport("user32.dll")]
public static extern IntPtr SetTimer(IntPtr hWnd, IntPtr nIDEvent, uint uElapse, TimerProc lpTimerFunc);
[DllImport("user32.dll")]
public static extern bool SetWindowPos(IntPtr hWnd, IntPtr hWndInsertAfter, int x, int y, int cx, int cy, SetWindowPosFlags uFlags);
[DllImport("user32.dll")]
public static extern bool SetParent(IntPtr hWnd, IntPtr hWndNewParent);
[DllImport("user32.dll")]
public static extern bool ShowWindow(IntPtr hWnd, ShowWindowCommand nCmdShow);
[DllImport("user32.dll")]
public static extern int ToUnicode(
uint virtualKeyCode,
uint scanCode,
byte[] keyboardState,
[Out, MarshalAs(UnmanagedType.LPWStr, SizeConst = 64)]
StringBuilder receivingBuffer,
int bufferSize,
uint flags);
[DllImport("user32.dll", SetLastError = true)]
public static extern bool TrackMouseEvent(ref TRACKMOUSEEVENT lpEventTrack);
[DllImport("user32.dll")]
public static extern bool TranslateMessage(ref MSG lpMsg);
[DllImport("user32.dll")]
public static extern bool UnregisterClass(string lpClassName, IntPtr hInstance);
[DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Auto)]
public static extern bool SetWindowText(IntPtr hwnd, string lpString);
public enum ClassLongIndex : int
{
GCL_HCURSOR = -12,
GCL_HICON = -14
}
[DllImport("user32.dll", EntryPoint = "SetClassLongPtr")]
private static extern IntPtr SetClassLong64(IntPtr hWnd, ClassLongIndex nIndex, IntPtr dwNewLong);
[DllImport("user32.dll", EntryPoint = "SetClassLong")]
private static extern IntPtr SetClassLong32(IntPtr hWnd, ClassLongIndex nIndex, IntPtr dwNewLong);
public static IntPtr SetClassLong(IntPtr hWnd, ClassLongIndex nIndex, IntPtr dwNewLong)
{
if (IntPtr.Size == 4)
{
return SetClassLong32(hWnd, nIndex, dwNewLong);
}
return SetClassLong64(hWnd, nIndex, dwNewLong);
}
[ComImport, ClassInterface(ClassInterfaceType.None), TypeLibType(TypeLibTypeFlags.FCanCreate), Guid("DC1C5A9C-E88A-4DDE-A5A1-60F82A20AEF7")]
internal class FileOpenDialogRCW { }
[DllImport("shell32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
internal static extern int SHCreateItemFromParsingName([MarshalAs(UnmanagedType.LPWStr)] string pszPath, IntPtr pbc, ref Guid riid, [MarshalAs(UnmanagedType.Interface)] out IShellItem ppv);
[DllImport("user32.dll", SetLastError = true)]
public static extern bool OpenClipboard(IntPtr hWndOwner);
[DllImport("user32.dll", SetLastError = true)]
public static extern bool CloseClipboard();
[DllImport("user32.dll")]
public static extern bool EmptyClipboard();
[DllImport("user32.dll")]
public static extern IntPtr GetClipboardData(ClipboardFormat uFormat);
[DllImport("user32.dll")]
public static extern IntPtr SetClipboardData(ClipboardFormat uFormat, IntPtr hMem);
[DllImport("kernel32.dll", CharSet = CharSet.Auto, ExactSpelling = true)]
public static extern IntPtr GlobalLock(IntPtr handle);
[DllImport("kernel32.dll", CharSet = CharSet.Auto, ExactSpelling = true)]
public static extern bool GlobalUnlock(IntPtr handle);
[DllImport("kernel32.dll", CharSet = CharSet.Auto, ExactSpelling = true)]
public static extern IntPtr GlobalAlloc(int uFlags, int dwBytes);
[DllImport("kernel32.dll", CharSet = CharSet.Auto, ExactSpelling = true)]
public static extern IntPtr GlobalFree(IntPtr hMem);
[DllImport("kernel32.dll", SetLastError = true)]
public static extern IntPtr LoadLibrary(string fileName);
[DllImport("comdlg32.dll", CharSet = CharSet.Unicode, EntryPoint = "GetSaveFileNameW")]
public static extern bool GetSaveFileName(IntPtr lpofn);
[DllImport("comdlg32.dll", CharSet = CharSet.Unicode, EntryPoint = "GetOpenFileNameW")]
public static extern bool GetOpenFileName(IntPtr lpofn);
[DllImport("comdlg32.dll")]
public static extern int CommDlgExtendedError();
public static bool ShCoreAvailable => LoadLibrary("shcore.dll") != IntPtr.Zero;
[DllImport("shcore.dll")]
public static extern void SetProcessDpiAwareness(PROCESS_DPI_AWARENESS value);
[DllImport("shcore.dll")]
public static extern long GetDpiForMonitor(IntPtr hmonitor, MONITOR_DPI_TYPE dpiType, out uint dpiX, out uint dpiY);
[DllImport("shcore.dll")]
public static extern void GetScaleFactorForMonitor(IntPtr hMon, out uint pScale);
[DllImport("user32.dll")]
public static extern IntPtr MonitorFromPoint(POINT pt, MONITOR dwFlags);
[DllImport("user32.dll")]
public static extern IntPtr MonitorFromWindow(IntPtr hwnd, MONITOR dwFlags);
public enum MONITOR
{
MONITOR_DEFAULTTONULL = 0x00000000,
MONITOR_DEFAULTTOPRIMARY = 0x00000001,
MONITOR_DEFAULTTONEAREST = 0x00000002,
}
public enum PROCESS_DPI_AWARENESS
{
PROCESS_DPI_UNAWARE = 0,
PROCESS_SYSTEM_DPI_AWARE = 1,
PROCESS_PER_MONITOR_DPI_AWARE = 2
}
public enum MONITOR_DPI_TYPE
{
MDT_EFFECTIVE_DPI = 0,
MDT_ANGULAR_DPI = 1,
MDT_RAW_DPI = 2,
MDT_DEFAULT = MDT_EFFECTIVE_DPI
}
public enum ClipboardFormat
{
CF_TEXT = 1,
CF_UNICODETEXT = 13
}
public struct MSG
{
public IntPtr hwnd;
public uint message;
public IntPtr wParam;
public IntPtr lParam;
public uint time;
public POINT pt;
}
[StructLayout(LayoutKind.Sequential)]
public struct PAINTSTRUCT
{
public IntPtr hdc;
public bool fErase;
public RECT rcPaint;
public bool fRestore;
public bool fIncUpdate;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 32)]
public byte[] rgbReserved;
}
public struct POINT
{
public int X;
public int Y;
}
public struct RECT
{
public int left;
public int top;
public int right;
public int bottom;
}
public struct TRACKMOUSEEVENT
{
public int cbSize;
public uint dwFlags;
public IntPtr hwndTrack;
public int dwHoverTime;
}
[StructLayout(LayoutKind.Sequential)]
public struct WINDOWPLACEMENT
{
/// <summary>
/// The length of the structure, in bytes. Before calling the GetWindowPlacement or SetWindowPlacement functions, set this member to sizeof(WINDOWPLACEMENT).
/// <para>
/// GetWindowPlacement and SetWindowPlacement fail if this member is not set correctly.
/// </para>
/// </summary>
public int Length;
/// <summary>
/// Specifies flags that control the position of the minimized window and the method by which the window is restored.
/// </summary>
public int Flags;
/// <summary>
/// The current show state of the window.
/// </summary>
public ShowWindowCommand ShowCmd;
/// <summary>
/// The coordinates of the window's upper-left corner when the window is minimized.
/// </summary>
public POINT MinPosition;
/// <summary>
/// The coordinates of the window's upper-left corner when the window is maximized.
/// </summary>
public POINT MaxPosition;
/// <summary>
/// The window's coordinates when the window is in the restored position.
/// </summary>
public RECT NormalPosition;
/// <summary>
/// Gets the default (empty) value.
/// </summary>
public static WINDOWPLACEMENT Default
{
get
{
WINDOWPLACEMENT result = new WINDOWPLACEMENT();
result.Length = Marshal.SizeOf(result);
return result;
}
}
}
[StructLayout(LayoutKind.Sequential)]
public struct WNDCLASSEX
{
public int cbSize;
public int style;
public WndProc lpfnWndProc;
public int cbClsExtra;
public int cbWndExtra;
public IntPtr hInstance;
public IntPtr hIcon;
public IntPtr hCursor;
public IntPtr hbrBackground;
public string lpszMenuName;
public string lpszClassName;
public IntPtr hIconSm;
}
[Flags]
public enum OpenFileNameFlags
{
OFN_ALLOWMULTISELECT = 0x00000200,
OFN_EXPLORER = 0x00080000,
OFN_HIDEREADONLY = 0x00000004,
OFN_NOREADONLYRETURN = 0x00008000,
OFN_OVERWRITEPROMPT = 0x00000002
}
public enum HRESULT : long
{
S_FALSE = 0x0001,
S_OK = 0x0000,
E_INVALIDARG = 0x80070057,
E_OUTOFMEMORY = 0x8007000E
}
public const uint SIGDN_FILESYSPATH = 0x80058000;
[Flags]
internal enum FOS : uint
{
FOS_OVERWRITEPROMPT = 0x00000002,
FOS_STRICTFILETYPES = 0x00000004,
FOS_NOCHANGEDIR = 0x00000008,
FOS_PICKFOLDERS = 0x00000020,
FOS_FORCEFILESYSTEM = 0x00000040, // Ensure that items returned are filesystem items.
FOS_ALLNONSTORAGEITEMS = 0x00000080, // Allow choosing items that have no storage.
FOS_NOVALIDATE = 0x00000100,
FOS_ALLOWMULTISELECT = 0x00000200,
FOS_PATHMUSTEXIST = 0x00000800,
FOS_FILEMUSTEXIST = 0x00001000,
FOS_CREATEPROMPT = 0x00002000,
FOS_SHAREAWARE = 0x00004000,
FOS_NOREADONLYRETURN = 0x00008000,
FOS_NOTESTFILECREATE = 0x00010000,
FOS_HIDEMRUPLACES = 0x00020000,
FOS_HIDEPINNEDPLACES = 0x00040000,
FOS_NODEREFERENCELINKS = 0x00100000,
FOS_DONTADDTORECENT = 0x02000000,
FOS_FORCESHOWHIDDEN = 0x10000000,
FOS_DEFAULTNOMINIMODE = 0x20000000
}
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
public struct OpenFileName
{
public int lStructSize;
public IntPtr hwndOwner;
public IntPtr hInstance;
public IntPtr lpstrFilter;
public IntPtr lpstrCustomFilter;
public int nMaxCustFilter;
public int nFilterIndex;
public IntPtr lpstrFile;
public int nMaxFile;
public IntPtr lpstrFileTitle;
public int nMaxFileTitle;
public IntPtr lpstrInitialDir;
public IntPtr lpstrTitle;
public OpenFileNameFlags Flags;
private readonly ushort Unused;
private readonly ushort Unused2;
public IntPtr lpstrDefExt;
public IntPtr lCustData;
public IntPtr lpfnHook;
public IntPtr lpTemplateName;
public IntPtr reservedPtr;
public int reservedInt;
public int flagsEx;
}
}
[ComImport(), Guid("42F85136-DB7E-439C-85F1-E4075D135FC8"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
internal interface IFileDialog
{
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
[PreserveSig()]
uint Show([In, Optional] IntPtr hwndOwner); //IModalWindow
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
uint SetFileTypes([In] uint cFileTypes, [In, MarshalAs(UnmanagedType.LPArray)] IntPtr rgFilterSpec);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
uint SetFileTypeIndex([In] uint iFileType);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
uint GetFileTypeIndex(out uint piFileType);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
uint Advise([In, MarshalAs(UnmanagedType.Interface)] IntPtr pfde, out uint pdwCookie);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
uint Unadvise([In] uint dwCookie);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
uint SetOptions([In] uint fos);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
uint GetOptions(out uint fos);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
void SetDefaultFolder([In, MarshalAs(UnmanagedType.Interface)] IShellItem psi);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
uint SetFolder([In, MarshalAs(UnmanagedType.Interface)] IShellItem psi);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
uint GetFolder([MarshalAs(UnmanagedType.Interface)] out IShellItem ppsi);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
uint GetCurrentSelection([MarshalAs(UnmanagedType.Interface)] out IShellItem ppsi);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
uint SetFileName([In, MarshalAs(UnmanagedType.LPWStr)] string pszName);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
uint GetFileName([MarshalAs(UnmanagedType.LPWStr)] out string pszName);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
uint SetTitle([In, MarshalAs(UnmanagedType.LPWStr)] string pszTitle);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
uint SetOkButtonLabel([In, MarshalAs(UnmanagedType.LPWStr)] string pszText);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
uint SetFileNameLabel([In, MarshalAs(UnmanagedType.LPWStr)] string pszLabel);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
uint GetResult([MarshalAs(UnmanagedType.Interface)] out IShellItem ppsi);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
uint AddPlace([In, MarshalAs(UnmanagedType.Interface)] IShellItem psi, uint fdap);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
uint SetDefaultExtension([In, MarshalAs(UnmanagedType.LPWStr)] string pszDefaultExtension);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
uint Close([MarshalAs(UnmanagedType.Error)] uint hr);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
uint SetClientGuid([In] ref Guid guid);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
uint ClearClientData();
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
uint SetFilter([MarshalAs(UnmanagedType.Interface)] IntPtr pFilter);
}
[ComImport, Guid("43826D1E-E718-42EE-BC55-A1E261C37BFE"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
internal interface IShellItem
{
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
uint BindToHandler([In] IntPtr pbc, [In] ref Guid rbhid, [In] ref Guid riid, [Out, MarshalAs(UnmanagedType.Interface)] out IntPtr ppvOut);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
uint GetParent([MarshalAs(UnmanagedType.Interface)] out IShellItem ppsi);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
uint GetDisplayName([In] uint sigdnName, out IntPtr ppszName);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
uint GetAttributes([In] uint sfgaoMask, out uint psfgaoAttribs);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
uint Compare([In, MarshalAs(UnmanagedType.Interface)] IShellItem psi, [In] uint hint, out int piOrder);
}
}
| |
//
// DataEntry.cs
//
// Authors:
// Gabriel Burt <gburt@novell.com>
//
// Copyright (C) 2008 Novell, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.Globalization;
using System.Xml;
using System.Collections;
using System.Collections.Generic;
namespace Lastfm.Data
{
public class DataEntry
{
private XmlElement root;
public XmlElement Root {
get { return root; }
set { root = value; }
}
public DataEntry ()
{
}
public DataEntry (XmlElement root)
{
this.root = root;
}
public T Get<T> (string name)
{
try {
XmlElement node = root[name];
if (node != null) {
return (T) Convert.ChangeType (node.InnerText, typeof(T), CultureInfo.InvariantCulture);
} else if (root.HasAttribute (name)) {
return (T) Convert.ChangeType (root.GetAttribute (name), typeof(T));
}
} catch (Exception) {}
return default(T);
}
protected string GetUrl (string name)
{
return Uri.UnescapeDataString (Get<string> (name));
}
}
// Generic types
public class NamedEntry : DataEntry
{
public string Name { get { return Get<string> ("name"); } }
public string Url { get { return GetUrl ("url"); } }
}
public class TopTag : NamedEntry
{
public int Count { get { return Get<int> ("count"); } }
}
public class RssEntry : DataEntry
{
public string Title { get { return Get<string> ("title"); } }
public string Link { get { return Get<string> ("link"); } }
public DateTime PublicationDate { get { return Get<DateTime> ("pubDate"); } }
public string Guid { get { return Get<string> ("guid"); } }
public string Description { get { return Get<string> ("description"); } }
}
// User-specific types
public class ProfileEntry : DataEntry
{
public string Url { get { return GetUrl ("url"); } }
public string RealName { get { return Get<string> ("realname"); } }
public string Gender { get { return Get<string> ("gender"); } }
public string Country { get { return Get<string> ("country"); } }
public string AvatarUrl { get { return Get<string> ("avatar"); } }
public string IconUrl { get { return Get<string> ("icon"); } }
public DateTime Registered { get { return Get<DateTime> ("registered"); } }
public int Age { get { return Get<int> ("age"); } }
public int PlayCount { get { return Get<int> ("playcount"); } }
}
public class UserTopArtist : NamedEntry
{
public string MbId { get { return Get<string> ("mbid"); } }
public int Rank { get { return Get<int> ("rank"); } }
public int PlayCount { get { return Get<int> ("playcount"); } }
public string ThumbnailUrl { get { return Get<string> ("thumbnail"); } }
public string ImageUrl { get { return Get<string> ("image"); } }
}
public class UserTopAlbum : NamedEntry
{
public string Artist { get { return Get<string> ("artist"); } }
public string MbId { get { return Get<string> ("mbid"); } }
public int Rank { get { return Get<int> ("rank"); } }
public int PlayCount { get { return Get<int> ("playcount"); } }
}
public class UserTopTrack : NamedEntry
{
public string Artist { get { return Get<string> ("artist"); } }
public int Rank { get { return Get<int> ("rank"); } }
public int PlayCount { get { return Get<int> ("playcount"); } }
}
public class Friend : DataEntry
{
public string UserName { get { return Get<string> ("username"); } }
public string Url { get { return GetUrl ("url"); } }
public string ImageUrl { get { return Get<string> ("image"); } }
}
public class Neighbor : Friend
{
public double Match { get { return Get<double> ("match"); } }
public int MatchAsInt { get { return (int) Math.Round (Match); } }
}
public class RecentTrack : NamedEntry
{
public string Artist { get { return Get<string> ("artist"); } }
public string Album { get { return Get<string> ("album"); } }
public DateTime Date { get { return Get<DateTime> ("date"); } }
}
public class DateRangeEntry : DataEntry
{
public DateTime From { get { return Get<DateTime> ("from"); } }
public DateTime To { get { return Get<DateTime> ("to"); } }
}
public class ArtistChartEntry : NamedEntry
{
public string MbId { get { return Get<string> ("mbid"); } }
public int PlayCount { get { return Get<int> ("playcount"); } }
public int ChartPosition { get { return Get<int> ("chartposition"); } }
}
public class RecommendedArtistEntry : NamedEntry
{
public string MbId { get { return Get<string> ("mbid"); } }
}
public class EventEntry : RssEntry
{
public DateTime Begins { get { return Get<DateTime> ("xcal:dtstart"); } }
public DateTime Ends { get { return Get<DateTime> ("xcal:dtend"); } }
}
public class TasteArtist : RssEntry
{
public string Name { get { return Get<string> ("name"); } }
}
public class TasteEntry : DataEntry
{
public double Score { get { return Get<double> ("score"); } }
private DataEntryCollection<TasteArtist> artists;
public DataEntryCollection<TasteArtist> Artists {
get {
if (artists == null) {
artists = new DataEntryCollection<TasteArtist> (Root ["commonArtists"].ChildNodes);
}
return artists;
}
}
}
// Artist entries
public class SimilarArtist : NamedEntry
{
public string ImageUrl { get { return Get<string> ("image"); } }
public string SmallImageUrl { get { return Get<string> ("image_small"); } }
public double Match { get { return Get<double> ("match"); } }
public int MatchAsInt { get { return (int) Math.Round (Match); } }
}
public class ArtistFan : Friend
{
public int Weight { get { return Get<int> ("weight"); } }
}
public class ArtistTopTrack : NamedEntry
{
public int Reach { get { return Get<int> ("reach"); } }
}
public class ArtistTopAlbum : NamedEntry
{
public int Reach { get { return Get<int> ("reach"); } }
}
// Album Data
public class AlbumData : DataEntry
{
public string Reach { get { return Get<string> ("reach"); } }
public string LastfmUrl { get { return Get<string> ("url"); } }
public DateTime ReleaseDate { get { return Get<DateTime> ("releasedate"); } }
}
public class AlbumCoverUrls : DataEntry
{
public string Small { get { return Get<string> ("small"); } }
public string Medium { get { return Get<string> ("medium"); } }
public string Large { get { return Get<string> ("large"); } }
public string[] AllUrls() {
return (new string[] {Small, Medium, Large});
}
}
public class AlbumTrack : DataEntry
{
public string Title { get { return Get<string> ("title"); } }
public int Reach { get { return Get<int> ("reach"); } }
public string LastfmUrl { get { return Get<string> ("url"); } }
}
}
| |
// Copyright 2011 Microsoft Corporation
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
namespace Microsoft.Data.OData.Atom
{
#region Namespaces
using System;
using System.Collections.Generic;
using System.Diagnostics;
#endregion Namespaces
/// <summary>
/// Helper methods used to merge Atom metadata from EPM with those specified through annotations.
/// </summary>
internal static class ODataAtomWriterMetadataEpmMergeUtils
{
/// <summary>
/// Merges custom and EPM ATOM metadata.
/// </summary>
/// <param name="customEntryMetadata">The custom ATOM metadata, or null if there were no custom ATOM metadata.</param>
/// <param name="epmEntryMetadata">The EPM ATOM metadata, or null if there are no EPM mappings to syndication targets.</param>
/// <param name="writerBehavior">The <see cref="ODataWriterBehavior"/> instance configuring the writer.</param>
/// <returns>The merged ATOM metadata to write to the output.</returns>
/// <remarks>The merge means that if one of the sides has null, the other is used, otherwise if both are non-null
/// we verify that the values are the same, otherwise we throw.</remarks>
internal static AtomEntryMetadata MergeCustomAndEpmEntryMetadata(AtomEntryMetadata customEntryMetadata, AtomEntryMetadata epmEntryMetadata, ODataWriterBehavior writerBehavior)
{
DebugUtils.CheckNoExternalCallers();
if (customEntryMetadata != null && writerBehavior.FormatBehaviorKind == ODataBehaviorKind.WcfDataServicesClient)
{
// ODataLib supports specifying ATOM metadata for entries even in the WCF DS client mode;
// WCF DS itself will never do this but ODataLib clients using this mode might. We have
// to convert potential Published and Updated values to the internal string properties
// used in WCF DS client mode.
if (customEntryMetadata.Updated.HasValue)
{
customEntryMetadata.UpdatedString = ODataAtomConvert.ToAtomString(customEntryMetadata.Updated.Value);
}
if (customEntryMetadata.Published.HasValue)
{
customEntryMetadata.PublishedString = ODataAtomConvert.ToAtomString(customEntryMetadata.Published.Value);
}
}
AtomEntryMetadata simpleMergeResult;
if (TryMergeIfNull(customEntryMetadata, epmEntryMetadata, out simpleMergeResult))
{
return simpleMergeResult;
}
// We will be modifying the EPM metadata adding the custom into it
// The reason is that with EPM we can be sure that the enumerations are of type List (since they were created like that) and thus
// we can safely add items into those without reallocating the collections.
// Merge Title
epmEntryMetadata.Title = MergeAtomTextValue(customEntryMetadata.Title, epmEntryMetadata.Title, "Title");
// Merge Summary
epmEntryMetadata.Summary = MergeAtomTextValue(customEntryMetadata.Summary, epmEntryMetadata.Summary, "Summary");
// Merge Rights
epmEntryMetadata.Rights = MergeAtomTextValue(customEntryMetadata.Rights, epmEntryMetadata.Rights, "Rights");
if (writerBehavior.FormatBehaviorKind == ODataBehaviorKind.WcfDataServicesClient)
{
// Merge PublishedString
epmEntryMetadata.PublishedString = MergeTextValue(customEntryMetadata.PublishedString, epmEntryMetadata.PublishedString, "PublishedString");
// Merge UpdatedString
epmEntryMetadata.UpdatedString = MergeTextValue(customEntryMetadata.UpdatedString, epmEntryMetadata.UpdatedString, "UpdatedString");
}
else
{
// Merge Published
epmEntryMetadata.Published = MergeDateTimeValue(customEntryMetadata.Published, epmEntryMetadata.Published, "Published");
// Merge Updated
epmEntryMetadata.Updated = MergeDateTimeValue(customEntryMetadata.Updated, epmEntryMetadata.Updated, "Updated");
}
// Merge authors
epmEntryMetadata.Authors = MergeSyndicationMapping<AtomPersonMetadata>(customEntryMetadata.Authors, epmEntryMetadata.Authors);
// Merge contributors
epmEntryMetadata.Contributors = MergeSyndicationMapping<AtomPersonMetadata>(customEntryMetadata.Contributors, epmEntryMetadata.Contributors);
// Merge Categories
epmEntryMetadata.Categories = MergeSyndicationMapping<AtomCategoryMetadata>(customEntryMetadata.Categories, epmEntryMetadata.Categories);
// Merge Links
epmEntryMetadata.Links = MergeSyndicationMapping<AtomLinkMetadata>(customEntryMetadata.Links, epmEntryMetadata.Links);
// Source
// Copy the source element over from custom metadata since EPM doesn't use it yet.
Debug.Assert(epmEntryMetadata.Source == null, "Once EPM actually writes to source element, implement the merge with custom metadata here.");
epmEntryMetadata.Source = customEntryMetadata.Source;
return epmEntryMetadata;
}
/// <summary>
/// Merges enumerations of person metadata.
/// </summary>
/// <param name="customValues">The enumeration of custom person metadata.</param>
/// <param name="epmValues">The enumeration of EPM person metadata.</param>
/// <typeparam name="T">The type of syndication mapping, one of AtomLinkMetadata, AtomCategoryMetadata, AtomPersonMetadata, </typeparam>
/// <returns>The merged enumeration.</returns>
private static IEnumerable<T> MergeSyndicationMapping<T>(
IEnumerable<T> customValues,
IEnumerable<T> epmValues)
{
IEnumerable<T> simpleMergeResult;
if (TryMergeIfNull(customValues, epmValues, out simpleMergeResult))
{
return simpleMergeResult;
}
// The EPM must always have the syndication mappings as a List<T> so let's use that list to do the merge in.
List<T> epmList = (List<T>)epmValues;
// We must enumerate the custom values exactly once (we guarantee that), so walk those first.
foreach (T mapping in customValues)
{
// There's no reliable way to correlate syndication mapping from one list to a syndication mapping in the other list.
// So instead of trying to be clever and cause confusion we will simply merge the lists by adding one to the other.
// Add that mapping to the list
epmList.Add(mapping);
}
return epmList;
}
/// <summary>
/// Merges ATOM text values.
/// </summary>
/// <param name="customValue">The custom value.</param>
/// <param name="epmValue">The EPM value.</param>
/// <param name="propertyName">The name of the ATOM property which holds the text value, used for error reporting.</param>
/// <returns>The merged ATOM text value.</returns>
private static AtomTextConstruct MergeAtomTextValue(AtomTextConstruct customValue, AtomTextConstruct epmValue, string propertyName)
{
AtomTextConstruct simpleMergeResult;
if (TryMergeIfNull(customValue, epmValue, out simpleMergeResult))
{
return simpleMergeResult;
}
if (customValue.Kind != epmValue.Kind)
{
throw new ODataException(Strings.ODataAtomMetadataEpmMerge_TextKindConflict(propertyName, customValue.Kind.ToString(), epmValue.Kind.ToString()));
}
if (string.CompareOrdinal(customValue.Text, epmValue.Text) != 0)
{
throw new ODataException(Strings.ODataAtomMetadataEpmMerge_TextValueConflict(propertyName, customValue.Text, epmValue.Text));
}
return epmValue;
}
/// <summary>
/// Merges text values.
/// </summary>
/// <param name="customValue">The custom value.</param>
/// <param name="epmValue">The EPM value.</param>
/// <param name="propertyName">The name of the ATOM property which holds the text value, used for error reporting.</param>
/// <returns>The merged text value.</returns>
private static string MergeTextValue(string customValue, string epmValue, string propertyName)
{
string simpleMergeResult;
if (TryMergeIfNull(customValue, epmValue, out simpleMergeResult))
{
return simpleMergeResult;
}
if (string.CompareOrdinal(customValue, epmValue) != 0)
{
throw new ODataException(Strings.ODataAtomMetadataEpmMerge_TextValueConflict(propertyName, customValue, epmValue));
}
return epmValue;
}
/// <summary>
/// Merges date time offset values.
/// </summary>
/// <param name="customValue">The custom value.</param>
/// <param name="epmValue">The EPM value.</param>
/// <param name="propertyName">The name of the ATOM property which holds the value, used for error reporting.</param>
/// <returns>The merged date time offset value.</returns>
private static DateTimeOffset? MergeDateTimeValue(DateTimeOffset? customValue, DateTimeOffset? epmValue, string propertyName)
{
DateTimeOffset? simpleMergeResult;
if (TryMergeIfNull(customValue, epmValue, out simpleMergeResult))
{
return simpleMergeResult;
}
if (customValue != epmValue)
{
throw new ODataException(Strings.ODataAtomMetadataEpmMerge_TextValueConflict(propertyName, customValue.ToString(), epmValue.ToString()));
}
return epmValue;
}
/// <summary>
/// Tries to merge custom and EPM values if one of them is null.
/// </summary>
/// <typeparam name="T">The type of the value to merge.</typeparam>
/// <param name="customValue">The custom value.</param>
/// <param name="epmValue">The EPM value.</param>
/// <param name="result">The merge value if the merge was possible.</param>
/// <returns>true if one of the values was null and thus the other was returned in <paramref name="result"/>;
/// false if both were not null and thus full merge will have to be performed.</returns>
private static bool TryMergeIfNull<T>(T customValue, T epmValue, out T result) where T : class
{
if (customValue == null)
{
result = epmValue;
return true;
}
if (epmValue == null)
{
result = customValue;
return true;
}
result = null;
return false;
}
/// <summary>
/// Tries to merge custom and EPM values if one of them is null.
/// </summary>
/// <typeparam name="T">The type of the value to merge.</typeparam>
/// <param name="customValue">The custom value.</param>
/// <param name="epmValue">The EPM value.</param>
/// <param name="result">The merge value if the merge was possible.</param>
/// <returns>true if one of the values was null and thus the other was returned in <paramref name="result"/>;
/// false if both were not null and thus full merge will have to be performed.</returns>
private static bool TryMergeIfNull<T>(Nullable<T> customValue, Nullable<T> epmValue, out Nullable<T> result) where T : struct
{
if (customValue == null)
{
result = epmValue;
return true;
}
if (epmValue == null)
{
result = customValue;
return true;
}
result = null;
return false;
}
}
}
| |
/* Copyright (c) 2006, 2007 Stefanos Apostolopoulos
* See license.txt for license info
*/
using System;
using System.Collections.Generic;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
namespace Bind
{
internal class Settings
{
public Settings()
{
OverridesFiles = new List<string>();
}
public string DefaultInputPath = "src/Generator.Bind/Specifications";
public string DefaultOutputPath = "src/OpenTK/Graphics/OpenGL";
public string DefaultOutputNamespace = "OpenTK.Graphics.OpenGL";
public string DefaultDocPath = "src/Generator.Bind/Specifications/Docs";
public string DefaultFallbackDocPath = "src/Generator.Bind/Specifications/Docs/GL";
public string DefaultLicenseFile = "License.txt";
public string DefaultLanguageTypeMapFile = "csharp.tm";
public string DefaultKeywordEscapeCharacter = "@";
public string DefaultImportsFile = "Core.cs";
public string DefaultDelegatesFile = "Delegates.cs";
public string DefaultEnumsFile = "Enums.cs";
public string DefaultWrappersFile = "GL.cs";
public Legacy DefaultCompatibility = Legacy.NoDropMultipleTokens;
private string inputPath, outputPath, outputNamespace, docPath, fallbackDocPath, licenseFile,
languageTypeMapFile, keywordEscapeCharacter, importsFile, delegatesFile, enumsFile,
wrappersFile;
private Nullable<Legacy> compatibility;
public string InputPath { get { return inputPath ?? DefaultInputPath; } set { inputPath = value; } }
public string OutputPath { get { return outputPath ?? DefaultOutputPath; } set { outputPath = value; } }
public string OutputNamespace { get { return outputNamespace ?? DefaultOutputNamespace; } set { outputNamespace = value; } }
public string DocPath { get { return docPath ?? DefaultDocPath; } set { docPath = value; } }
public string FallbackDocPath { get { return fallbackDocPath ?? DefaultFallbackDocPath; } set { fallbackDocPath = value; } }
public string LicenseFile { get { return licenseFile ?? DefaultLicenseFile; } set { licenseFile = value; } }
public List<string> OverridesFiles { get; private set; }
public string LanguageTypeMapFile { get { return languageTypeMapFile ?? DefaultLanguageTypeMapFile; } set { languageTypeMapFile = value; } }
public string KeywordEscapeCharacter { get { return keywordEscapeCharacter ?? DefaultKeywordEscapeCharacter; } set { keywordEscapeCharacter = value; } }
public string ImportsFile { get { return importsFile ?? DefaultImportsFile; } set { importsFile = value; } }
public string DelegatesFile { get { return delegatesFile ?? DefaultDelegatesFile; } set { delegatesFile = value; } }
public string EnumsFile { get { return enumsFile ?? DefaultEnumsFile; } set { enumsFile = value; } }
public string WrappersFile { get { return wrappersFile ?? DefaultWrappersFile; } set { wrappersFile = value; } }
public Legacy Compatibility { get { return compatibility ?? DefaultCompatibility; } set { compatibility = value; } }
public string GLClass = "GL"; // Needed by Glu for the AuxEnumsClass. Can be set through -gl:"xxx".
public string OutputClass = "GL"; // The real output class. Can be set through -class:"xxx".
public string FunctionPrefix = "gl";
public string ConstantPrefix = "GL_";
public string EnumPrefix = "";
public string NamespaceSeparator = ".";
// TODO: This code is too fragile.
// Old enums code:
public string normalEnumsClassOverride = null;
public string NestedEnumsClass = "Enums";
public string NormalEnumsClass
{
get
{
return
normalEnumsClassOverride == null ?
String.IsNullOrEmpty(NestedEnumsClass) ? OutputClass : OutputClass + NamespaceSeparator + NestedEnumsClass :
normalEnumsClassOverride;
}
}
public string AuxEnumsClass
{
get { return GLClass + NamespaceSeparator + NestedEnumsClass; }
}
public string EnumsOutput
{
get
{
if ((Compatibility & Legacy.NestedEnums) != Legacy.None)
{
return OutputNamespace + NamespaceSeparator + OutputClass + NamespaceSeparator + NestedEnumsClass;
}
else
{
return String.IsNullOrEmpty(EnumsNamespace) ? OutputNamespace : OutputNamespace + NamespaceSeparator + EnumsNamespace;
}
}
}
public string EnumsAuxOutput
{
get
{
if ((Compatibility & Legacy.NestedEnums) != Legacy.None)
{
return OutputNamespace + NamespaceSeparator + GLClass + NamespaceSeparator + NestedEnumsClass;
}
else
{
return OutputNamespace + NamespaceSeparator + EnumsNamespace;
}
}
}
// New enums namespace (don't use a nested class).
public string EnumsNamespace = null; // = "Enums";
public string DelegatesClass = "Delegates";
public string ImportsClass = "Core";
/// <summary>
/// The name of the C# enum which holds every single OpenGL enum (for compatibility purposes).
/// </summary>
public string CompleteEnumName = "All";
[Flags]
public enum Legacy
{
/// <summary>Default value.</summary>
None = 0x00,
/// <summary>Leave enums as plain const ints.</summary>
ConstIntEnums = 0x01,
/// <summary>Leave enums in the default STRANGE_capitalization.ALL_CAPS form.</summary>
NoAdvancedEnumProcessing = 0x02,
/// <summary>Don't allow unsafe wrappers in the interface.</summary>
NoPublicUnsafeFunctions = 0x04,
/// <summary>Don't trim the [fdisub]v? endings from functions.</summary>
NoTrimFunctionEnding = NoPublicUnsafeFunctions,
/// <summary>Don't trim the [gl|wgl|glx|glu] prefixes from functions.</summary>
NoTrimFunctionPrefix = 0x08,
/// <summary>
/// Don't spearate functions in different namespaces, according to their extension category
/// (e.g. GL.Arb, GL.Ext etc).
/// </summary>
NoSeparateFunctionNamespaces = 0x10,
/// <summary>
/// No public void* parameters (should always be enabled. Disable at your own risk. Disabling
/// means that BitmapData.Scan0 and other .Net properties/functions must be cast to (void*)
/// explicitly, to avoid the 'object' overload from being called.)
/// </summary>
TurnVoidPointersToIntPtr = 0x20,
/// <summary>Generate all possible permutations for ref/array/pointer parameters.</summary>
GenerateAllPermutations = 0x40,
/// <summary>Nest enums inside the GL class.</summary>
NestedEnums = 0x80,
/// <summary>Turn GLboolean to int (Boolean enum), not bool.</summary>
NoBoolParameters = 0x100,
/// <summary>Keep all enum tokens, even if same value (e.g. FooARB, FooEXT and FooSGI).</summary>
NoDropMultipleTokens = 0x200,
/// <summary>Do not emit inline documentation.</summary>
NoDocumentation = 0x400,
/// <summary>Disables ErrorHelper generation.</summary>
NoDebugHelpers = 0x800,
/// <summary>Generate both typed and untyped ("All") signatures for enum parameters.</summary>
KeepUntypedEnums = 0x1000,
/// <summary>Marks deprecated functions as [Obsolete]</summary>
AddDeprecationWarnings = 0x2000,
/// <summary>Use DllImport declaration for core functions (do not generate entry point slots)</summary>
UseDllImports = 0x4000,
/// <summary>
/// Use in conjuction with UseDllImports, to create
/// bindings that are compatible with opengl32.dll on Windows.
/// This uses DllImports up to GL 1.1 and function pointers
/// for higher versions.
/// </summary>
UseWindowsCompatibleGL = 0x8000,
Tao = ConstIntEnums |
NoAdvancedEnumProcessing |
NoPublicUnsafeFunctions |
NoTrimFunctionEnding |
NoTrimFunctionPrefix |
NoSeparateFunctionNamespaces |
TurnVoidPointersToIntPtr |
NestedEnums |
NoBoolParameters |
NoDropMultipleTokens |
NoDocumentation |
NoDebugHelpers,
/*GenerateAllPermutations,*/
}
// Returns true if flag is enabled.
public bool IsEnabled(Legacy flag)
{
return (Compatibility & flag) != (Legacy)0;
}
// Enables the specified flag.
public void Enable(Legacy flag)
{
Compatibility |= flag;
}
// Disables the specified flag.
public void Disable(Legacy flag)
{
Compatibility &= ~flag;
}
/// <summary>True if multiple tokens should be dropped (e.g. FooARB, FooEXT and FooSGI).</summary>
public bool DropMultipleTokens
{
get { return (Compatibility & Legacy.NoDropMultipleTokens) == Legacy.None; }
set { if (value)
{
Compatibility |= Legacy.NoDropMultipleTokens;
}
else
{
Compatibility &= ~Legacy.NoDropMultipleTokens;
}
}
}
public string WindowsGDI = "OpenTK.Platform.Windows.API";
//public Settings Clone()
//{
// IFormatter formatter = new BinaryFormatter();
// using (var stream = new MemoryStream())
// {
// formatter.Serialize(stream, this);
// stream.Seek(0, SeekOrigin.Begin);
// return (Settings)formatter.Deserialize(stream);
// }
//}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.Reflection;
using System.Threading;
using System.Text;
using Microsoft.Xml;
using System.Security;
using System.Linq;
namespace System.Runtime.Serialization
{
#if NET_NATIVE
public sealed class EnumDataContract : DataContract
#else
internal sealed class EnumDataContract : DataContract
#endif
{
[SecurityCritical]
/// <SecurityNote>
/// Critical - holds instance of CriticalHelper which keeps state that is cached statically for serialization.
/// Static fields are marked SecurityCritical or readonly to prevent
/// data from being modified or leaked to other components in appdomain.
/// </SecurityNote>
private EnumDataContractCriticalHelper _helper;
/// <SecurityNote>
/// Critical - initializes SecurityCritical field 'helper'
/// Safe - doesn't leak anything
/// </SecurityNote>
[SecuritySafeCritical]
public EnumDataContract() : base(new EnumDataContractCriticalHelper())
{
_helper = base.Helper as EnumDataContractCriticalHelper;
}
/// <SecurityNote>
/// Critical - Accesses SecurityCritical static cache to look up a base contract name
/// Safe - Read only access
/// </SecurityNote>
[SecuritySafeCritical]
static internal Type GetBaseType(XmlQualifiedName baseContractName)
{
return EnumDataContractCriticalHelper.GetBaseType(baseContractName);
}
internal XmlQualifiedName BaseContractName
{
// TODO: [Fx.Tag.SecurityNote(Critical = "Fetches the critical BaseContractName property.",
// Safe = "BaseContractName only needs to be protected for write.")]
[SecuritySafeCritical]
get { return _helper.BaseContractName; }
// TODO: [Fx.Tag.SecurityNote(Critical = "Sets the critical BaseContractName property.")]
[SecurityCritical]
set { _helper.BaseContractName = value; }
}
/// <SecurityNote>
/// Critical - initializes SecurityCritical field 'helper'
/// Safe - doesn't leak anything
/// </SecurityNote>
[SecuritySafeCritical]
internal EnumDataContract(Type type) : base(new EnumDataContractCriticalHelper(type))
{
_helper = base.Helper as EnumDataContractCriticalHelper;
}
public List<DataMember> Members
{
/// <SecurityNote>
/// Critical - fetches the critical Members property
/// Safe - Members only needs to be protected for write
/// </SecurityNote>
[SecuritySafeCritical]
get
{ return _helper.Members; }
set { _helper.Members = value; }
}
public List<long> Values
{
/// <SecurityNote>
/// Critical - fetches the critical Values property
/// Safe - Values only needs to be protected for write
/// </SecurityNote>
[SecuritySafeCritical]
get
{ return _helper.Values; }
set { _helper.Values = value; }
}
public bool IsFlags
{
/// <SecurityNote>
/// Critical - fetches the critical IsFlags property
/// Safe - IsFlags only needs to be protected for write
/// </SecurityNote>
[SecuritySafeCritical]
get
{ return _helper.IsFlags; }
set { _helper.IsFlags = value; }
}
public bool IsULong
{
/// <SecurityNote>
/// Critical - fetches the critical IsULong property
/// Safe - IsULong only needs to be protected for write
/// </SecurityNote>
[SecuritySafeCritical]
get
{ return _helper.IsULong; }
set { _helper.IsULong = value; }
}
public XmlDictionaryString[] ChildElementNames
{
/// <SecurityNote>
/// Critical - fetches the critical ChildElementNames property
/// Safe - ChildElementNames only needs to be protected for write
/// </SecurityNote>
[SecuritySafeCritical]
get
{ return _helper.ChildElementNames; }
set { _helper.ChildElementNames = value; }
}
internal override bool CanContainReferences
{
get { return false; }
}
[SecurityCritical]
/// <SecurityNote>
/// Critical - holds all state used for (de)serializing enums.
/// since the data is cached statically, we lock down access to it.
/// </SecurityNote>
private class EnumDataContractCriticalHelper : DataContract.DataContractCriticalHelper
{
private static Dictionary<Type, XmlQualifiedName> s_typeToName;
private static Dictionary<XmlQualifiedName, Type> s_nameToType;
private XmlQualifiedName _baseContractName;
private List<DataMember> _members;
private List<long> _values;
private bool _isULong;
private bool _isFlags;
private bool _hasDataContract;
private XmlDictionaryString[] _childElementNames;
static EnumDataContractCriticalHelper()
{
s_typeToName = new Dictionary<Type, XmlQualifiedName>();
s_nameToType = new Dictionary<XmlQualifiedName, Type>();
Add(typeof(sbyte), "byte");
Add(typeof(byte), "unsignedByte");
Add(typeof(short), "short");
Add(typeof(ushort), "unsignedShort");
Add(typeof(int), "int");
Add(typeof(uint), "unsignedInt");
Add(typeof(long), "long");
Add(typeof(ulong), "unsignedLong");
}
static internal void Add(Type type, string localName)
{
XmlQualifiedName stableName = CreateQualifiedName(localName, Globals.SchemaNamespace);
s_typeToName.Add(type, stableName);
s_nameToType.Add(stableName, type);
}
static internal Type GetBaseType(XmlQualifiedName baseContractName)
{
Type retVal = null;
s_nameToType.TryGetValue(baseContractName, out retVal);
return retVal;
}
internal EnumDataContractCriticalHelper()
{
IsValueType = true;
}
internal EnumDataContractCriticalHelper(Type type) : base(type)
{
this.StableName = DataContract.GetStableName(type, out _hasDataContract);
Type baseType = Enum.GetUnderlyingType(type);
ImportBaseType(baseType);
IsFlags = type.GetTypeInfo().IsDefined(Globals.TypeOfFlagsAttribute, false);
ImportDataMembers();
XmlDictionary dictionary = new XmlDictionary(2 + Members.Count);
Name = dictionary.Add(StableName.Name);
Namespace = dictionary.Add(StableName.Namespace);
_childElementNames = new XmlDictionaryString[Members.Count];
for (int i = 0; i < Members.Count; i++)
_childElementNames[i] = dictionary.Add(Members[i].Name);
DataContractAttribute dataContractAttribute;
if (TryGetDCAttribute(type, out dataContractAttribute))
{
if (dataContractAttribute.IsReference)
{
DataContract.ThrowInvalidDataContractException(
string.Format(SRSerialization.EnumTypeCannotHaveIsReference,
DataContract.GetClrTypeFullName(type),
dataContractAttribute.IsReference,
false),
type);
}
}
}
internal XmlQualifiedName BaseContractName
{
get
{
return _baseContractName;
}
set
{
_baseContractName = value;
Type baseType = GetBaseType(_baseContractName);
if (baseType == null)
ThrowInvalidDataContractException(string.Format(SRSerialization.InvalidEnumBaseType, value.Name, value.Namespace, StableName.Name, StableName.Namespace));
ImportBaseType(baseType);
}
}
internal List<DataMember> Members
{
get { return _members; }
set { _members = value; }
}
internal List<long> Values
{
get { return _values; }
set { _values = value; }
}
internal bool IsFlags
{
get { return _isFlags; }
set { _isFlags = value; }
}
internal bool IsULong
{
get { return _isULong; }
set { _isULong = value; }
}
internal XmlDictionaryString[] ChildElementNames
{
get { return _childElementNames; }
set { _childElementNames = value; }
}
private void ImportBaseType(Type baseType)
{
_isULong = (baseType == Globals.TypeOfULong);
}
private void ImportDataMembers()
{
Type type = this.UnderlyingType;
FieldInfo[] fields = type.GetFields(BindingFlags.Static | BindingFlags.Public);
Dictionary<string, DataMember> memberValuesTable = new Dictionary<string, DataMember>();
List<DataMember> tempMembers = new List<DataMember>(fields.Length);
List<long> tempValues = new List<long>(fields.Length);
for (int i = 0; i < fields.Length; i++)
{
FieldInfo field = fields[i];
bool enumMemberValid = false;
if (_hasDataContract)
{
object[] memberAttributes = field.GetCustomAttributes(Globals.TypeOfEnumMemberAttribute, false).ToArray();
if (memberAttributes != null && memberAttributes.Length > 0)
{
if (memberAttributes.Length > 1)
ThrowInvalidDataContractException(string.Format(SRSerialization.TooManyEnumMembers, DataContract.GetClrTypeFullName(field.DeclaringType), field.Name));
EnumMemberAttribute memberAttribute = (EnumMemberAttribute)memberAttributes[0];
DataMember memberContract = new DataMember(field);
if (memberAttribute.IsValueSetExplicitly)
{
if (memberAttribute.Value == null || memberAttribute.Value.Length == 0)
ThrowInvalidDataContractException(string.Format(SRSerialization.InvalidEnumMemberValue, field.Name, DataContract.GetClrTypeFullName(type)));
memberContract.Name = memberAttribute.Value;
}
else
memberContract.Name = field.Name;
ClassDataContract.CheckAndAddMember(tempMembers, memberContract, memberValuesTable);
enumMemberValid = true;
}
object[] dataMemberAttributes = field.GetCustomAttributes(Globals.TypeOfDataMemberAttribute, false).ToArray();
if (dataMemberAttributes != null && dataMemberAttributes.Length > 0)
ThrowInvalidDataContractException(string.Format(SRSerialization.DataMemberOnEnumField, DataContract.GetClrTypeFullName(field.DeclaringType), field.Name));
}
else
{
DataMember memberContract = new DataMember(field);
memberContract.Name = field.Name;
ClassDataContract.CheckAndAddMember(tempMembers, memberContract, memberValuesTable);
enumMemberValid = true;
}
if (enumMemberValid)
{
object enumValue = field.GetValue(null);
if (_isULong)
tempValues.Add((long)Convert.ToUInt64(enumValue, null));
else
tempValues.Add(Convert.ToInt64(enumValue, null));
}
}
Interlocked.MemoryBarrier();
_members = tempMembers;
_values = tempValues;
}
}
internal void WriteEnumValue(XmlWriterDelegator writer, object value)
{
long longValue = IsULong ? (long)Convert.ToUInt64(value, null) : Convert.ToInt64(value, null);
for (int i = 0; i < Values.Count; i++)
{
if (longValue == Values[i])
{
writer.WriteString(ChildElementNames[i].Value);
return;
}
}
if (IsFlags)
{
int zeroIndex = -1;
bool noneWritten = true;
for (int i = 0; i < Values.Count; i++)
{
long current = Values[i];
if (current == 0)
{
zeroIndex = i;
continue;
}
if (longValue == 0)
break;
if ((current & longValue) == current)
{
if (noneWritten)
noneWritten = false;
else
writer.WriteString(DictionaryGlobals.Space.Value);
writer.WriteString(ChildElementNames[i].Value);
longValue &= ~current;
}
}
// enforce that enum value was completely parsed
if (longValue != 0)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(string.Format(SRSerialization.InvalidEnumValueOnWrite, value, DataContract.GetClrTypeFullName(UnderlyingType))));
if (noneWritten && zeroIndex >= 0)
writer.WriteString(ChildElementNames[zeroIndex].Value);
}
else
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(string.Format(SRSerialization.InvalidEnumValueOnWrite, value, DataContract.GetClrTypeFullName(UnderlyingType))));
}
internal object ReadEnumValue(XmlReaderDelegator reader)
{
string stringValue = reader.ReadElementContentAsString();
long longValue = 0;
int i = 0;
if (IsFlags)
{
// Skip initial spaces
for (; i < stringValue.Length; i++)
if (stringValue[i] != ' ')
break;
// Read space-delimited values
int startIndex = i;
int count = 0;
for (; i < stringValue.Length; i++)
{
if (stringValue[i] == ' ')
{
count = i - startIndex;
if (count > 0)
longValue |= ReadEnumValue(stringValue, startIndex, count);
for (++i; i < stringValue.Length; i++)
if (stringValue[i] != ' ')
break;
startIndex = i;
if (i == stringValue.Length)
break;
}
}
count = i - startIndex;
if (count > 0)
longValue |= ReadEnumValue(stringValue, startIndex, count);
}
else
{
if (stringValue.Length == 0)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(string.Format(SRSerialization.InvalidEnumValueOnRead, stringValue, DataContract.GetClrTypeFullName(UnderlyingType))));
longValue = ReadEnumValue(stringValue, 0, stringValue.Length);
}
if (IsULong)
return Enum.ToObject(UnderlyingType, (object)(ulong)longValue);
return Enum.ToObject(UnderlyingType, (object)longValue);
}
private long ReadEnumValue(string value, int index, int count)
{
for (int i = 0; i < Members.Count; i++)
{
string memberName = Members[i].Name;
if (memberName.Length == count && String.CompareOrdinal(value, index, memberName, 0, count) == 0)
{
return Values[i];
}
}
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(string.Format(SRSerialization.InvalidEnumValueOnRead, value.Substring(index, count), DataContract.GetClrTypeFullName(UnderlyingType))));
}
public override void WriteXmlValue(XmlWriterDelegator xmlWriter, object obj, XmlObjectSerializerWriteContext context)
{
WriteEnumValue(xmlWriter, obj);
}
public override object ReadXmlValue(XmlReaderDelegator xmlReader, XmlObjectSerializerReadContext context)
{
object obj = ReadEnumValue(xmlReader);
if (context != null)
context.AddNewObject(obj);
return obj;
}
internal string GetStringFromEnumValue(long value)
{
if (IsULong)
return XmlConvert.ToString((ulong)value);
else
return XmlConvert.ToString(value);
}
internal long GetEnumValueFromString(string value)
{
if (IsULong)
return (long)XmlConverter.ToUInt64(value);
else
return XmlConverter.ToInt64(value);
}
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.IO;
using System.Reflection;
using System.Xml;
using System.Xml.Serialization;
using System.Text;
using System.Collections.Generic;
using log4net;
using OpenSim.Framework;
using OpenMetaverse;
namespace OpenSim.Server.Base
{
public static class ServerUtils
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
public static byte[] SerializeResult(XmlSerializer xs, object data)
{
MemoryStream ms = new MemoryStream();
XmlTextWriter xw = new XmlTextWriter(ms, Util.UTF8);
xw.Formatting = Formatting.Indented;
xs.Serialize(xw, data);
xw.Flush();
ms.Seek(0, SeekOrigin.Begin);
byte[] ret = ms.GetBuffer();
Array.Resize(ref ret, (int)ms.Length);
return ret;
}
/// <summary>
/// Load a plugin from a dll with the given class or interface
/// </summary>
/// <param name="dllName"></param>
/// <param name="args">The arguments which control which constructor is invoked on the plugin</param>
/// <returns></returns>
public static T LoadPlugin<T>(string dllName, Object[] args) where T:class
{
string[] parts = dllName.Split(new char[] {':'});
dllName = parts[0];
string className = String.Empty;
if (parts.Length > 1)
className = parts[1];
return LoadPlugin<T>(dllName, className, args);
}
/// <summary>
/// Load a plugin from a dll with the given class or interface
/// </summary>
/// <param name="dllName"></param>
/// <param name="className"></param>
/// <param name="args">The arguments which control which constructor is invoked on the plugin</param>
/// <returns></returns>
public static T LoadPlugin<T>(string dllName, string className, Object[] args) where T:class
{
string interfaceName = typeof(T).ToString();
try
{
Assembly pluginAssembly = Assembly.LoadFrom(dllName);
foreach (Type pluginType in pluginAssembly.GetTypes())
{
if (pluginType.IsPublic)
{
if (className != String.Empty
&& pluginType.ToString() != pluginType.Namespace + "." + className)
continue;
Type typeInterface = pluginType.GetInterface(interfaceName, true);
if (typeInterface != null)
{
T plug = null;
try
{
plug = (T)Activator.CreateInstance(pluginType,
args);
}
catch (Exception e)
{
if (!(e is System.MissingMethodException))
m_log.ErrorFormat("Error loading plugin from {0}, exception {1}", dllName, e.InnerException);
return null;
}
return plug;
}
}
}
return null;
}
catch (Exception e)
{
m_log.Error(string.Format("Error loading plugin from {0}", dllName), e);
return null;
}
}
public static Dictionary<string, object> ParseQueryString(string query)
{
Dictionary<string, object> result = new Dictionary<string, object>();
string[] terms = query.Split(new char[] {'&'});
if (terms.Length == 0)
return result;
foreach (string t in terms)
{
string[] elems = t.Split(new char[] {'='});
if (elems.Length == 0)
continue;
string name = System.Web.HttpUtility.UrlDecode(elems[0]);
string value = String.Empty;
if (elems.Length > 1)
value = System.Web.HttpUtility.UrlDecode(elems[1]);
if (name.EndsWith("[]"))
{
string cleanName = name.Substring(0, name.Length - 2);
if (result.ContainsKey(cleanName))
{
if (!(result[cleanName] is List<string>))
continue;
List<string> l = (List<string>)result[cleanName];
l.Add(value);
}
else
{
List<string> newList = new List<string>();
newList.Add(value);
result[cleanName] = newList;
}
}
else
{
if (!result.ContainsKey(name))
result[name] = value;
}
}
return result;
}
public static string BuildQueryString(Dictionary<string, object> data)
{
string qstring = String.Empty;
string part;
foreach (KeyValuePair<string, object> kvp in data)
{
if (kvp.Value is List<string>)
{
List<string> l = (List<String>)kvp.Value;
foreach (string s in l)
{
part = System.Web.HttpUtility.UrlEncode(kvp.Key) +
"[]=" + System.Web.HttpUtility.UrlEncode(s);
if (qstring != String.Empty)
qstring += "&";
qstring += part;
}
}
else
{
if (kvp.Value.ToString() != String.Empty)
{
part = System.Web.HttpUtility.UrlEncode(kvp.Key) +
"=" + System.Web.HttpUtility.UrlEncode(kvp.Value.ToString());
}
else
{
part = System.Web.HttpUtility.UrlEncode(kvp.Key);
}
if (qstring != String.Empty)
qstring += "&";
qstring += part;
}
}
return qstring;
}
public static string BuildXmlResponse(Dictionary<string, object> data)
{
XmlDocument doc = new XmlDocument();
XmlNode xmlnode = doc.CreateNode(XmlNodeType.XmlDeclaration,
"", "");
doc.AppendChild(xmlnode);
XmlElement rootElement = doc.CreateElement("", "ServerResponse",
"");
doc.AppendChild(rootElement);
BuildXmlData(rootElement, data);
return doc.InnerXml;
}
private static void BuildXmlData(XmlElement parent, Dictionary<string, object> data)
{
foreach (KeyValuePair<string, object> kvp in data)
{
if (kvp.Value == null)
continue;
XmlElement elem = parent.OwnerDocument.CreateElement("",
kvp.Key, "");
if (kvp.Value is Dictionary<string, object>)
{
XmlAttribute type = parent.OwnerDocument.CreateAttribute("",
"type", "");
type.Value = "List";
elem.Attributes.Append(type);
BuildXmlData(elem, (Dictionary<string, object>)kvp.Value);
}
else
{
elem.AppendChild(parent.OwnerDocument.CreateTextNode(
kvp.Value.ToString()));
}
parent.AppendChild(elem);
}
}
public static Dictionary<string, object> ParseXmlResponse(string data)
{
//m_log.DebugFormat("[XXX]: received xml string: {0}", data);
Dictionary<string, object> ret = new Dictionary<string, object>();
XmlDocument doc = new XmlDocument();
doc.LoadXml(data);
XmlNodeList rootL = doc.GetElementsByTagName("ServerResponse");
if (rootL.Count != 1)
return ret;
XmlNode rootNode = rootL[0];
ret = ParseElement(rootNode);
return ret;
}
private static Dictionary<string, object> ParseElement(XmlNode element)
{
Dictionary<string, object> ret = new Dictionary<string, object>();
XmlNodeList partL = element.ChildNodes;
foreach (XmlNode part in partL)
{
XmlNode type = part.Attributes.GetNamedItem("type");
if (type == null || type.Value != "List")
{
ret[part.Name] = part.InnerText;
}
else
{
ret[part.Name] = ParseElement(part);
}
}
return ret;
}
}
}
| |
// Copyright (c) .NET Foundation and contributors. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.WindowsAzure.Storage;
using Microsoft.WindowsAzure.Storage.Auth;
using Microsoft.WindowsAzure.Storage.Blob;
namespace Microsoft.DotNet.Cli.Build
{
public class AzurePublisher
{
public enum Product
{
SharedFramework,
Host,
HostFxr,
Sdk,
}
private const string s_dotnetBlobContainerName = "dotnet";
private string _connectionString { get; set; }
private string _containerName { get; set; }
private CloudBlobContainer _blobContainer { get; set; }
public AzurePublisher(string containerName = s_dotnetBlobContainerName)
{
_connectionString = EnvVars.EnsureVariable("CONNECTION_STRING").Trim('"');
_containerName = containerName;
_blobContainer = GetDotnetBlobContainer(_connectionString, containerName);
}
public AzurePublisher(string accountName, string accountKey, string containerName = s_dotnetBlobContainerName)
{
_containerName = containerName;
_blobContainer = GetDotnetBlobContainer(accountName, accountKey, containerName);
}
private CloudBlobContainer GetDotnetBlobContainer(string connectionString, string containerName)
{
CloudStorageAccount storageAccount = CloudStorageAccount.Parse(connectionString);
return GetDotnetBlobContainer(storageAccount, containerName);
}
private CloudBlobContainer GetDotnetBlobContainer(string accountName, string accountKey, string containerName)
{
var storageCredentials = new StorageCredentials(accountName, accountKey);
var storageAccount = new CloudStorageAccount(storageCredentials, true);
return GetDotnetBlobContainer(storageAccount, containerName);
}
private CloudBlobContainer GetDotnetBlobContainer(CloudStorageAccount storageAccount, string containerName)
{
CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();
return blobClient.GetContainerReference(containerName);
}
public string UploadFile(string file, Product product, string version)
{
string url = CalculateRelativePathForFile(file, product, version);
CloudBlockBlob blob = _blobContainer.GetBlockBlobReference(url);
blob.UploadFromFileAsync(file).Wait();
SetBlobPropertiesBasedOnFileType(blob);
return url;
}
public void PublishStringToBlob(string blob, string content)
{
CloudBlockBlob blockBlob = _blobContainer.GetBlockBlobReference(blob);
blockBlob.UploadTextAsync(content).Wait();
SetBlobPropertiesBasedOnFileType(blockBlob);
}
public void CopyBlob(string sourceBlob, string targetBlob)
{
CloudBlockBlob source = _blobContainer.GetBlockBlobReference(sourceBlob);
CloudBlockBlob target = _blobContainer.GetBlockBlobReference(targetBlob);
// Create the empty blob
using (MemoryStream ms = new MemoryStream())
{
target.UploadFromStreamAsync(ms).Wait();
}
// Copy actual blob data
target.StartCopyAsync(source).Wait();
}
public void SetBlobPropertiesBasedOnFileType(string path)
{
CloudBlockBlob blob = _blobContainer.GetBlockBlobReference(path);
SetBlobPropertiesBasedOnFileType(blob);
}
private void SetBlobPropertiesBasedOnFileType(CloudBlockBlob blockBlob)
{
if (Path.GetExtension(blockBlob.Uri.AbsolutePath.ToLower()) == ".svg")
{
blockBlob.Properties.ContentType = "image/svg+xml";
blockBlob.Properties.CacheControl = "no-cache";
blockBlob.SetPropertiesAsync().Wait();
}
else if (Path.GetExtension(blockBlob.Uri.AbsolutePath.ToLower()) == ".version")
{
blockBlob.Properties.ContentType = "text/plain";
blockBlob.Properties.CacheControl = "no-cache";
blockBlob.SetPropertiesAsync().Wait();
}
}
public IEnumerable<string> ListBlobs(Product product, string version)
{
string virtualDirectory = $"{product}/{version}";
return ListBlobs(virtualDirectory);
}
public IEnumerable<string> ListBlobs(string virtualDirectory)
{
CloudBlobDirectory blobDir = _blobContainer.GetDirectoryReference(virtualDirectory);
BlobContinuationToken continuationToken = new BlobContinuationToken();
var blobFiles = blobDir.ListBlobsSegmentedAsync(continuationToken).Result;
return blobFiles.Results.Select(bf => bf.Uri.PathAndQuery.Replace($"/{_containerName}/", string.Empty));
}
public string AcquireLeaseOnBlob(
string blob,
TimeSpan? maxWaitDefault = null,
TimeSpan? delayDefault = null)
{
TimeSpan maxWait = maxWaitDefault ?? TimeSpan.FromSeconds(120);
TimeSpan delay = delayDefault ?? TimeSpan.FromMilliseconds(500);
Stopwatch stopWatch = new Stopwatch();
stopWatch.Start();
// This will throw an exception with HTTP code 409 when we cannot acquire the lease
// But we should block until we can get this lease, with a timeout (maxWaitSeconds)
while (stopWatch.ElapsedMilliseconds < maxWait.TotalMilliseconds)
{
try
{
CloudBlockBlob cloudBlob = _blobContainer.GetBlockBlobReference(blob);
Task<string> task = cloudBlob.AcquireLeaseAsync(TimeSpan.FromMinutes(1), null);
task.Wait();
return task.Result;
}
catch (Exception e)
{
Console.WriteLine($"Retrying lease acquisition on {blob}, {e.Message}");
Thread.Sleep(delay);
}
}
throw new Exception($"Unable to acquire lease on {blob}");
}
public void ReleaseLeaseOnBlob(string blob, string leaseId)
{
CloudBlockBlob cloudBlob = _blobContainer.GetBlockBlobReference(blob);
AccessCondition ac = new AccessCondition() { LeaseId = leaseId };
cloudBlob.ReleaseLeaseAsync(ac).Wait();
}
public bool IsLatestSpecifiedVersion(string version)
{
Task<bool> task = _blobContainer.GetBlockBlobReference(version).ExistsAsync();
task.Wait();
return task.Result;
}
public void DropLatestSpecifiedVersion(string version)
{
CloudBlockBlob blob = _blobContainer.GetBlockBlobReference(version);
using (MemoryStream ms = new MemoryStream())
{
blob.UploadFromStreamAsync(ms).Wait();
}
}
public void CreateBlobIfNotExists(string path)
{
Task<bool> task = _blobContainer.GetBlockBlobReference(path).ExistsAsync();
task.Wait();
if (!task.Result)
{
CloudBlockBlob blob = _blobContainer.GetBlockBlobReference(path);
using (MemoryStream ms = new MemoryStream())
{
blob.UploadFromStreamAsync(ms).Wait();
}
}
}
public bool TryDeleteBlob(string path)
{
try
{
DeleteBlob(path);
return true;
}
catch (Exception e)
{
Console.WriteLine($"Deleting blob {path} failed with \r\n{e.Message}");
return false;
}
}
private void DeleteBlob(string path)
{
_blobContainer.GetBlockBlobReference(path).DeleteAsync().Wait();
}
private static string CalculateRelativePathForFile(string file, Product product, string version)
{
return $"{product}/{version}/{Path.GetFileName(file)}";
}
}
}
| |
using Orleans.Serialization.Buffers;
using Orleans.Serialization.Codecs;
using Orleans.Serialization.GeneratedCodeHelpers;
using Orleans.Serialization.Serializers;
using Orleans.Serialization.Session;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Buffers;
using System.IO.Pipelines;
using System.Text;
using Xunit;
using Xunit.Abstractions;
namespace Orleans.Serialization.UnitTests
{
public class ManualVersionToleranceTests
{
private const string TestString = "hello, Orleans.Serialization";
private readonly ITestOutputHelper _log;
private readonly IServiceProvider _serviceProvider;
private readonly CodecProvider _codecProvider;
private readonly IFieldCodec<SubType> _serializer;
private readonly ServiceCollection _serviceCollection;
public ManualVersionToleranceTests(ITestOutputHelper log)
{
_log = log;
var serviceCollection = new ServiceCollection();
_serviceCollection = serviceCollection;
_ = _serviceCollection.AddSerializer(builder =>
{
_ = builder.Configure(configuration =>
{
_ = configuration.Serializers.Add(typeof(SubTypeSerializer));
_ = configuration.Serializers.Add(typeof(BaseTypeSerializer));
_ = configuration.Serializers.Add(typeof(ObjectWithNewFieldTypeSerializer));
_ = configuration.Serializers.Add(typeof(ObjectWithoutNewFieldTypeSerializer));
// Intentionally remove the generated serializer for these type. It will be added back during tests.
configuration.Serializers.RemoveWhere(s => typeof(IFieldCodec<ObjectWithNewField>).IsAssignableFrom(s));
configuration.Serializers.RemoveWhere(s => typeof(IFieldCodec<ObjectWithoutNewField>).IsAssignableFrom(s));
});
});
_serviceProvider = _serviceCollection.BuildServiceProvider();
_codecProvider = _serviceProvider.GetRequiredService<CodecProvider>();
_serializer = _codecProvider.GetCodec<SubType>();
}
[Fact]
public void VersionTolerance_RoundTrip_Tests()
{
RoundTripTest(
new SubType
{
BaseTypeString = "HOHOHO",
AddedLaterString = TestString,
String = null,
Int = 1,
Ref = TestString
});
RoundTripTest(
new SubType
{
BaseTypeString = "base",
String = "sub",
Int = 2,
});
RoundTripTest(
new SubType
{
BaseTypeString = "base",
String = "sub",
Int = int.MinValue,
});
RoundTripTest(
new SubType
{
BaseTypeString = TestString,
String = TestString,
Int = 10
});
RoundTripTest(
new SubType
{
BaseTypeString = TestString,
String = null,
Int = 1
});
RoundTripTest(
new SubType
{
BaseTypeString = TestString,
String = null,
Int = 1
});
TestSkip(
new SubType
{
BaseTypeString = TestString,
String = null,
Int = 1
});
var self = new SubType
{
BaseTypeString = "HOHOHO",
AddedLaterString = TestString,
String = null,
Int = 1
};
self.Ref = self;
RoundTripTest(self, assertRef: false);
self.Ref = Guid.NewGuid();
RoundTripTest(self, assertRef: false);
}
private SerializerSession GetSession() => _serviceProvider.GetRequiredService<SerializerSessionPool>().GetSession();
private void RoundTripTest(SubType expected, bool assertRef = true)
{
using var writerSession = GetSession();
var pipe = new Pipe();
var writer = Writer.Create(pipe.Writer, writerSession);
_serializer.WriteField(ref writer, 0, typeof(SubType), expected);
writer.Commit();
_log.WriteLine($"Size: {writer.Position} bytes.");
_log.WriteLine($"Wrote References:\n{GetWriteReferenceTable(writerSession)}");
_ = pipe.Writer.FlushAsync().AsTask().GetAwaiter().GetResult();
pipe.Writer.Complete();
_ = pipe.Reader.TryRead(out var readResult);
using var readerSesssion = GetSession();
var reader = Reader.Create(readResult.Buffer, readerSesssion);
var initialHeader = reader.ReadFieldHeader();
_log.WriteLine("Header:");
_log.WriteLine(initialHeader.ToString());
var actual = _serializer.ReadValue(ref reader, initialHeader);
pipe.Reader.AdvanceTo(readResult.Buffer.End);
pipe.Reader.Complete();
_log.WriteLine($"Expect: {expected}\nActual: {actual}");
Assert.Equal(expected.BaseTypeString, actual.BaseTypeString);
Assert.Null(actual.AddedLaterString); // The deserializer isn't 'aware' of this field which was added later - version tolerance.
Assert.Equal(expected.String, actual.String);
Assert.Equal(expected.Int, actual.Int);
if (assertRef)
{
Assert.Equal(expected.Ref, actual.Ref);
}
Assert.Equal(writer.Position, reader.Position);
Assert.Equal(writer.Session.ReferencedObjects.CurrentReferenceId, reader.Session.ReferencedObjects.CurrentReferenceId);
var references = GetReadReferenceTable(reader.Session);
_log.WriteLine($"Read references:\n{references}");
}
private void TestSkip(SubType expected)
{
using var writerSession = GetSession();
var pipe = new Pipe();
var writer = Writer.Create(pipe.Writer, writerSession);
_serializer.WriteField(ref writer, 0, typeof(SubType), expected);
writer.Commit();
_ = pipe.Writer.FlushAsync().AsTask().GetAwaiter().GetResult();
var objectWithNewFieldSerializer = _codecProvider.GetCodec<ObjectWithNewField>();
var objectWithoutNewFieldSerializer = _codecProvider.GetCodec<ObjectWithoutNewField>();
pipe.Writer.Complete();
_ = pipe.Reader.TryRead(out var readResult);
using var readerSession = GetSession();
var reader = Reader.Create(readResult.Buffer, readerSession);
var initialHeader = reader.ReadFieldHeader();
var skipCodec = new SkipFieldCodec();
_ = skipCodec.ReadValue(ref reader, initialHeader);
pipe.Reader.AdvanceTo(readResult.Buffer.End);
pipe.Reader.Complete();
Assert.Equal(writer.Session.ReferencedObjects.CurrentReferenceId, reader.Session.ReferencedObjects.CurrentReferenceId);
_log.WriteLine($"Skipped {reader.Position} bytes.");
}
private static StringBuilder GetReadReferenceTable(SerializerSession session)
{
var table = session.ReferencedObjects.CopyReferenceTable();
var references = new StringBuilder();
foreach (var entry in table)
{
_ = references.AppendLine($"\t[{entry.Key}] {entry.Value}");
}
return references;
}
private static StringBuilder GetWriteReferenceTable(SerializerSession session)
{
var table = session.ReferencedObjects.CopyIdTable();
var references = new StringBuilder();
foreach (var entry in table)
{
_ = references.AppendLine($"\t[{entry.Value}] {entry.Key}");
}
return references;
}
[Fact]
public void ObjectWithNewFieldTest()
{
var expected = new ObjectWithNewField("blah", newField: "this field will not be manually serialized -- the binary will not have it!");
using var writerSession = GetSession();
var pipe = new Pipe();
var writer = Writer.Create(pipe.Writer, writerSession);
// Using manual serializer that ignores ObjectWithNewField.NewField
// not serializing NewField to simulate a binary that's created from a previous version of the object
var objectWithNewFieldSerializer = _codecProvider.GetCodec<ObjectWithNewField>();
var objectWithoutNewFieldSerializer = _codecProvider.GetCodec<ObjectWithoutNewField>();
_ = Assert.IsType<ConcreteTypeSerializer<ObjectWithNewField, ObjectWithNewFieldTypeSerializer>>(objectWithNewFieldSerializer);
objectWithNewFieldSerializer.WriteField(ref writer, 0, typeof(ObjectWithNewField), expected);
writer.Commit();
_log.WriteLine($"Size: {writer.Position} bytes.");
_log.WriteLine($"Wrote References:\n{GetWriteReferenceTable(writerSession)}");
_ = pipe.Writer.FlushAsync().AsTask().GetAwaiter().GetResult();
pipe.Writer.Complete();
_ = pipe.Reader.TryRead(out var readResult);
using var readerSesssion = GetSession();
var reader = Reader.Create(readResult.Buffer, readerSesssion);
var initialHeader = reader.ReadFieldHeader();
_log.WriteLine("Header:");
_log.WriteLine(initialHeader.ToString());
GetGeneratedSerializer(out objectWithNewFieldSerializer);
Assert.IsNotType<ConcreteTypeSerializer<ObjectWithNewField, ObjectWithNewFieldTypeSerializer>>(objectWithNewFieldSerializer);
// using Generated Deserializer, which is capable of deserializing NewField
var actual = objectWithNewFieldSerializer.ReadValue(ref reader, initialHeader);
pipe.Reader.AdvanceTo(readResult.Buffer.End);
pipe.Reader.Complete();
_log.WriteLine($"Expect: {expected}\nActual: {actual}");
Assert.Equal(expected.Blah, actual.Blah);
objectWithNewFieldSerializer = _codecProvider.GetCodec<ObjectWithNewField>();
objectWithoutNewFieldSerializer = _codecProvider.GetCodec<ObjectWithoutNewField>();
Assert.Null(actual.NewField); // Null, since it should not be in the binary
Assert.Equal(expected.Version, actual.Version);
Assert.Equal(writer.Position, reader.Position);
Assert.Equal(writer.Session.ReferencedObjects.CurrentReferenceId, reader.Session.ReferencedObjects.CurrentReferenceId);
var references = GetReadReferenceTable(reader.Session);
_log.WriteLine($"Read references:\n{references}");
}
[Fact]
public void ObjectWithoutNewFieldTest()
{
var expected = new ObjectWithoutNewField("blah");
using var writerSession = GetSession();
var pipe = new Pipe();
var writer = Writer.Create(pipe.Writer, writerSession);
var objectWithNewFieldSerializer = _codecProvider.GetCodec<ObjectWithNewField>();
var objectWithoutNewFieldSerializer = _codecProvider.GetCodec<ObjectWithoutNewField>();
// Using a manual serializer that writes a new field
// serializing a new field to simulate a binary that created from a newer version of the object
_ = Assert.IsType<ConcreteTypeSerializer<ObjectWithoutNewField, ObjectWithoutNewFieldTypeSerializer>>(objectWithoutNewFieldSerializer);
objectWithoutNewFieldSerializer.WriteField(ref writer, 0, typeof(ObjectWithoutNewField), expected);
writer.Commit();
_log.WriteLine($"Size: {writer.Position} bytes.");
_log.WriteLine($"Wrote References:\n{GetWriteReferenceTable(writerSession)}");
_ = pipe.Writer.FlushAsync().AsTask().GetAwaiter().GetResult();
pipe.Writer.Complete();
_ = pipe.Reader.TryRead(out var readResult);
using var readerSesssion = GetSession();
var reader = Reader.Create(readResult.Buffer, readerSesssion);
var initialHeader = reader.ReadFieldHeader();
_log.WriteLine("Header:");
_log.WriteLine(initialHeader.ToString());
GetGeneratedSerializer(out objectWithoutNewFieldSerializer);
Assert.IsNotType<ConcreteTypeSerializer<ObjectWithoutNewField, ObjectWithoutNewFieldTypeSerializer>>(objectWithoutNewFieldSerializer);
// using Generated Deserializer, which is not able to deserialize the new field that was serialized
var actual = objectWithoutNewFieldSerializer.ReadValue(ref reader, initialHeader);
pipe.Reader.AdvanceTo(readResult.Buffer.End);
pipe.Reader.Complete();
_log.WriteLine($"Expect: {expected}\nActual: {actual}");
Assert.Equal(expected.Blah, actual.Blah);
Assert.Equal(expected.Version, actual.Version);
Assert.Equal(writer.Position, reader.Position);
Assert.Equal(writer.Session.ReferencedObjects.CurrentReferenceId, reader.Session.ReferencedObjects.CurrentReferenceId);
var references = GetReadReferenceTable(reader.Session);
_log.WriteLine($"Read references:\n{references}");
}
private void GetGeneratedSerializer<T>(out IFieldCodec<T> serializer)
{
var services = new ServiceCollection().AddSerializer();
var serviceProvider = services.BuildServiceProvider();
var codecProvider = serviceProvider.GetRequiredService<CodecProvider>();
serializer = codecProvider.GetCodec<T>();
}
[GenerateSerializer]
public class ObjectWithNewField
{
[Id(0)]
public string Blah { get; set; }
[Id(1)]
public object NewField { get; set; }
[Id(2)]
public int Version { get; set; }
public ObjectWithNewField(string blah, object newField)
{
Blah = blah;
NewField = newField;
Version = 2;
}
public override string ToString() => $"{nameof(Blah)}: {Blah}; {nameof(NewField)}: {NewField}; {nameof(Version)}: {Version}";
}
public class ObjectWithNewFieldTypeSerializer : IBaseCodec<ObjectWithNewField>
{
public void Serialize<TBufferWriter>(ref Writer<TBufferWriter> writer, ObjectWithNewField obj) where TBufferWriter : IBufferWriter<byte>
{
// not serializing newField to simulate a binary that's created from a previous version of the object
StringCodec.WriteField(ref writer, 0, typeof(string), obj.Blah);
Int32Codec.WriteField(ref writer, 2, typeof(int), obj.Version);
}
// using a generated deserializer for deserialization
public void Deserialize<TInput>(ref Reader<TInput> reader, ObjectWithNewField obj)
{
}
}
[GenerateSerializer]
public class ObjectWithoutNewField
{
[Id(0)]
public string Blah { get; set; }
[Id(1)]
public int Version { get; set; }
public ObjectWithoutNewField(string blah)
{
Blah = blah;
Version = 1;
}
public override string ToString() => $"{nameof(Blah)}: {Blah}; {nameof(Version)}: {Version}";
}
public class ObjectWithoutNewFieldTypeSerializer : IBaseCodec<ObjectWithoutNewField>
{
public void Serialize<TBufferWriter>(ref Writer<TBufferWriter> writer, ObjectWithoutNewField obj) where TBufferWriter : IBufferWriter<byte>
{
StringCodec.WriteField(ref writer, 0, typeof(string), obj.Blah);
Int32Codec.WriteField(ref writer, 1, typeof(int), obj.Version);
// serializing a new field to simulate a binary that's created from a newer version of the object
ObjectCodec.WriteField(ref writer, 6, typeof(object), "I will be stuck in binary limbo! (I shouldn't be part of the deserialized object)");
}
// using a generated deserializer for deserialization
public void Deserialize<TInput>(ref Reader<TInput> reader, ObjectWithoutNewField obj)
{
}
}
/// <summary>
/// NOTE: The serializer for this type is HAND-ROLLED. See <see cref="BaseTypeSerializer" />
/// </summary>
public class BaseType : IEquatable<BaseType>
{
public string BaseTypeString { get; set; }
public string AddedLaterString { get; set; }
public bool Equals(BaseType other) => other is object
&& string.Equals(BaseTypeString, other.BaseTypeString, StringComparison.Ordinal)
&& string.Equals(AddedLaterString, other.AddedLaterString, StringComparison.Ordinal);
public override bool Equals(object obj) => obj is BaseType baseType && Equals(baseType);
public override int GetHashCode() => HashCode.Combine(BaseTypeString, AddedLaterString);
public override string ToString() => $"{nameof(BaseTypeString)}: {BaseTypeString}";
}
/// <summary>
/// NOTE: The serializer for this type is HAND-ROLLED. See <see cref="SubTypeSerializer" />
/// </summary>
public class SubType : BaseType, IEquatable<SubType>
{
// 0
public string String { get; set; }
// 1
public int Int { get; set; }
// 3
public object Ref { get; set; }
public bool Equals(SubType other)
{
if (other is null)
{
return false;
}
return
base.Equals(other)
&& string.Equals(String, other.String, StringComparison.Ordinal)
&& Int == other.Int
&& (ReferenceEquals(Ref, other.Ref) || Ref.Equals(other.Ref));
}
public override string ToString()
{
string refString = Ref == this ? "[this]" : $"[{Ref?.ToString() ?? "null"}]";
return $"{base.ToString()}, {nameof(String)}: {String}, {nameof(Int)}: {Int}, Ref: {refString}";
}
public override bool Equals(object obj) => obj is SubType subType && Equals(subType);
public override int GetHashCode()
{
// Avoid stack overflows with this one weird trick.
if (ReferenceEquals(Ref, this))
{
return HashCode.Combine(base.GetHashCode(), String, Int);
}
return HashCode.Combine(base.GetHashCode(), String, Int, Ref);
}
}
public class SubTypeSerializer : IBaseCodec<SubType>
{
private readonly IBaseCodec<BaseType> _baseTypeSerializer;
private readonly IFieldCodec<string> _stringCodec;
private readonly IFieldCodec<int> _intCodec;
private readonly IFieldCodec<object> _objectCodec;
public SubTypeSerializer(IBaseCodec<BaseType> baseTypeSerializer, IFieldCodec<string> stringCodec, IFieldCodec<int> intCodec, IFieldCodec<object> objectCodec)
{
_baseTypeSerializer = OrleansGeneratedCodeHelper.UnwrapService(this, baseTypeSerializer);
_stringCodec = OrleansGeneratedCodeHelper.UnwrapService(this, stringCodec);
_intCodec = OrleansGeneratedCodeHelper.UnwrapService(this, intCodec);
_objectCodec = OrleansGeneratedCodeHelper.UnwrapService(this, objectCodec);
}
public void Serialize<TBufferWriter>(ref Writer<TBufferWriter> writer, SubType obj) where TBufferWriter : IBufferWriter<byte>
{
_baseTypeSerializer.Serialize(ref writer, obj);
writer.WriteEndBase(); // the base object is complete.
_stringCodec.WriteField(ref writer, 0, typeof(string), obj.String);
_intCodec.WriteField(ref writer, 1, typeof(int), obj.Int);
_objectCodec.WriteField(ref writer, 1, typeof(object), obj.Ref);
_intCodec.WriteField(ref writer, 1, typeof(int), obj.Int);
_intCodec.WriteField(ref writer, 409, typeof(int), obj.Int);
/*writer.WriteFieldHeader(session, 1025, typeof(Guid), Guid.Empty.GetType(), WireType.Fixed128);
writer.WriteFieldHeader(session, 1020, typeof(object), typeof(Program), WireType.Reference);*/
}
public void Deserialize<TInput>(ref Reader<TInput> reader, SubType obj)
{
uint fieldId = 0;
_baseTypeSerializer.Deserialize(ref reader, obj);
while (true)
{
var header = reader.ReadFieldHeader();
if (header.IsEndBaseOrEndObject)
{
break;
}
fieldId += header.FieldIdDelta;
switch (fieldId)
{
case 0:
obj.String = _stringCodec.ReadValue(ref reader, header);
break;
case 1:
obj.Int = _intCodec.ReadValue(ref reader, header);
break;
case 2:
obj.Ref = _objectCodec.ReadValue(ref reader, header);
break;
default:
reader.ConsumeUnknownField(header);
break;
}
}
}
}
public class BaseTypeSerializer : IBaseCodec<BaseType>
{
public void Serialize<TBufferWriter>(ref Writer<TBufferWriter> writer, BaseType obj) where TBufferWriter : IBufferWriter<byte>
{
StringCodec.WriteField(ref writer, 0, typeof(string), obj.BaseTypeString);
StringCodec.WriteField(ref writer, 234, typeof(string), obj.AddedLaterString);
}
public void Deserialize<TInput>(ref Reader<TInput> reader, BaseType obj)
{
uint fieldId = 0;
while (true)
{
var header = reader.ReadFieldHeader();
if (header.IsEndBaseOrEndObject)
{
break;
}
fieldId += header.FieldIdDelta;
switch (fieldId)
{
case 0:
obj.BaseTypeString = StringCodec.ReadValue(ref reader, header);
break;
default:
reader.ConsumeUnknownField(header);
break;
}
}
}
}
}
}
| |
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for details.
using System;
using System.Net;
using System.Web;
using System.Xml;
using System.IO;
using System.Drawing;
using System.Text;
using System.Diagnostics;
using System.Globalization;
using System.Windows.Forms;
using OpenLiveWriter.BlogClient;
using OpenLiveWriter.Extensibility.BlogClient;
using OpenLiveWriter.CoreServices ;
using OpenLiveWriter.CoreServices.Settings;
using OpenLiveWriter.CoreServices.HTML;
using OpenLiveWriter.Interop.Windows;
using OpenLiveWriter.Controls ;
using OpenLiveWriter.Localization;
namespace OpenLiveWriter.PostEditor.BlogProviderButtons
{
public class BlogProviderButton : IDisposable
{
public BlogProviderButton(string blogId, string hostBlogId, string homepageUrl, string postApiUrl, string buttonId)
{
_blogId = blogId ;
_hostBlogId = hostBlogId ;
_homepageUrl = UrlHelper.InsureTrailingSlash(homepageUrl) ;
_postApiUrl = postApiUrl ;
_buttonId = buttonId ;
_settingsKey = BlogSettings.GetProviderButtonsSettingsKey(blogId).GetSubSettings(buttonId) ;
_buttonDescription = new BlogProviderButtonDescriptionFromSettings(_settingsKey);
}
public void Dispose()
{
if ( _settingsKey != null )
_settingsKey.Dispose();
}
public string BlogId
{
get
{
return _blogId ;
}
}
// id
public string Id
{
get
{
return _buttonDescription.Id ;
}
}
// tooltip text
public string Description
{
get
{
return _buttonDescription.Description;
}
}
// url to navigate to when clicking the button
public string ClickUrl
{
get
{
return FormatUrl(_buttonDescription.ClickUrl) ;
}
}
public bool SupportsClick
{
get
{
return _buttonDescription.SupportsClick ;
}
}
public string ContentUrl
{
get
{
return FormatUrl(_buttonDescription.ContentUrl);
}
}
public string ContentQueryUrl
{
get
{
return String.Format(CultureInfo.InvariantCulture, "{0}?blog_id={1}&button_id={2}", ContentUrl, HttpUtility.UrlEncode(_hostBlogId), HttpUtility.UrlEncode(_buttonId) ) ;
}
}
// supports display of content from a drop-down
public bool SupportsContent
{
get
{
return _buttonDescription.SupportsContent;
}
}
// the current image
public Bitmap CurrentImage
{
get
{
if ( SupportsNotification && ShowNotificationImage )
{
return SafeGetNotificationImage() ;
}
else
{
return Image ;
}
}
}
public string CurrentText
{
get
{
if ( SupportsNotification && ShowNotificationText )
return NotificationText ;
else
return Description ;
}
}
/// <summary>
/// Initial connection to application frame. Supress notification image and force
/// an immediate polling for notification status
/// </summary>
public void ConnectToFrame()
{
ShowNotificationImage = false ;
_settingsKey.SetDateTime(NOTIFICATION_POLLING_TIME, DateTimeHelper.UtcNow );
}
public Size ContentDisplaySize
{
get
{
Size displaySize = _settingsKey.GetSize(CONTENT_DISPLAY_SIZE, Size.Empty) ;
if ( displaySize != Size.Empty )
return displaySize ;
else
return DefaultContentSize;
}
}
private const string CONTENT_DISPLAY_SIZE = "ContentDisplaySize" ;
private readonly Size DefaultContentSize = new Size(300,350);
public void RecordButtonClicked()
{
if ( ClearNotificationOnClick )
{
ShowNotificationImage = false ;
NotificationText = String.Empty ;
// fire notification events
BlogProviderButtonNotificationSink.FireNotificationEvent(BlogId, Id);
}
}
public void CheckForNotification()
{
try
{
if ( (DateTimeHelper.UtcNow >= NotificationPollingTime) && WinInet.InternetConnectionAvailable )
{
// poll for notification
IBlogProviderButtonNotification buttonNotification = null;
using ( new BlogClientUIContextSilentMode() )
buttonNotification = GetButtonNotification() ;
// update notification text under control of the apply updates lock (the lock along
// with the check for a valid blog-id immediately below ensures that we a background
// notification never creates a "crufty" blog-id by writing to a BlogSettings key
// that has already been deleted).
using ( BlogSettings.ApplyUpdatesLock(BlogId) )
{
if ( BlogSettings.BlogIdIsValid(BlogId) )
{
NotificationText = buttonNotification.NotificationText ;
// update notification image
ShowNotificationImage = SafeUpdateNotificationImage(buttonNotification.NotificationImage) ;
// update clear notification flag
ClearNotificationOnClick = buttonNotification.ClearNotificationOnClick ;
// set next polling time
UpdateNotificationPollingTime(buttonNotification.PollingInterval);
}
else
{
throw new InvalidOperationException("Attempted update notification data for invalid blog-id");
}
}
// fire notification events
BlogProviderButtonNotificationSink.FireNotificationEvent(BlogId, Id);
}
}
catch(Exception ex)
{
Trace.WriteLine("Error occurred polling for button notification: " + ex.ToString());
}
}
private string NotificationUrl
{
get
{
return FormatUrl(_buttonDescription.NotificationUrl);
}
}
private IBlogProviderButtonNotification GetButtonNotification()
{
string notificationUrl = String.Format(
CultureInfo.InvariantCulture,
"{0}?blog_id={1}&button_id={2}&image_url={3}",
NotificationUrl,
HttpUtility.UrlEncode(_hostBlogId),
HttpUtility.UrlEncode(_buttonId),
HttpUtility.UrlEncode(ImageUrl) ) ;
// get the content
HttpWebResponse response = null;
XmlDocument xmlDocument = new XmlDocument();
try
{
using (Blog blog = new Blog(_blogId))
response = blog.SendAuthenticatedHttpRequest(notificationUrl, 10000);
// parse the results
xmlDocument.Load(response.GetResponseStream());
}
catch (Exception)
{
throw;
}
finally
{
if (response != null)
response.Close();
}
// create namespace manager
XmlNamespaceManager nsmgr = new XmlNamespaceManager(xmlDocument.NameTable);
nsmgr.AddNamespace("n", "http://schemas.microsoft.com/wlw/buttons/notification" );
// throw if the root element is not manifest
if ( xmlDocument.DocumentElement.LocalName.ToLower(CultureInfo.InvariantCulture) != "notification")
throw new ArgumentException("Not a valid writer button notification") ;
// polling interval
int checkAgainMinutes = XmlHelper.NodeInt(xmlDocument.SelectSingleNode("//n:checkAgainMinutes", nsmgr), 0) ;
if ( checkAgainMinutes == 0 )
{
throw new ArgumentException("You must specify a value for checkAgainMinutes") ;
}
TimeSpan pollingInterval = TimeSpan.FromMinutes(checkAgainMinutes) ;
// notification text
string notificationText = XmlHelper.NodeText(xmlDocument.SelectSingleNode("//n:text", nsmgr)) ;
// notification image
Bitmap notificationImage = null ;
string notificationImageUrl = XmlHelper.NodeText(xmlDocument.SelectSingleNode("//n:imageUrl", nsmgr)) ;
if ( notificationImageUrl != String.Empty )
{
// compute the absolute url then allow parameter substitution
notificationImageUrl = BlogClientHelper.GetAbsoluteUrl(notificationImageUrl, NotificationUrl) ;
notificationImageUrl = BlogClientHelper.FormatUrl(notificationImageUrl, _homepageUrl, _postApiUrl, _hostBlogId) ;
// try to download it (will use the cache if available)
// note that failing to download it is a recoverable error, we simply won't show a notification image
try
{
// try to get a credentials context for the download
WinInetCredentialsContext credentialsContext = null ;
try
{
credentialsContext = BlogClientHelper.GetCredentialsContext(_blogId, notificationImageUrl) ;
}
catch(BlogClientOperationCancelledException)
{
}
// execute the download
notificationImage = ImageHelper.DownloadBitmap(notificationImageUrl, credentialsContext) ;
}
catch(Exception ex)
{
Trace.WriteLine("Error downloading notification image: " + ex.ToString());
}
}
// clear notification on click
bool clearNotificationOnClick = XmlHelper.NodeBool(xmlDocument.SelectSingleNode("//n:resetOnClick", nsmgr), true) ;
// return the notification
return new BlogProviderButtonNotification(pollingInterval, notificationText, notificationImage, clearNotificationOnClick) ;
}
// icons
private string ImageUrl { get { return _buttonDescription.ImageUrl; } }
private Bitmap Image { get { return _buttonDescription.Image; } }
// supports polling for a notification image
private bool SupportsNotification { get { return _buttonDescription.SupportsNotification; } }
private DateTime NotificationPollingTime
{
get { return _settingsKey.GetDateTime(NOTIFICATION_POLLING_TIME, DateTimeHelper.UtcNow); }
}
private void UpdateNotificationPollingTime(TimeSpan pollingInterval)
{
// enforce minimum polling interval of one minute
pollingInterval = pollingInterval >= TimeSpan.FromMinutes(1) ? pollingInterval : TimeSpan.FromMinutes(1) ;
// set the next polling time
_settingsKey.SetDateTime(NOTIFICATION_POLLING_TIME, DateTimeHelper.UtcNow.Add(pollingInterval) );
}
private const string NOTIFICATION_POLLING_TIME = "NotificationPollingTime" ;
private bool SafeUpdateNotificationImage(Bitmap notificationImage)
{
try
{
if ( notificationImage == null )
return false ;
_settingsKey.SetByteArray(NOTIFICATION_IMAGE, ImageHelper.GetBitmapBytes(notificationImage, new Size(24,24)));
return true ;
}
catch(Exception ex)
{
Trace.Fail(String.Format(CultureInfo.InvariantCulture, "Unexpected exception occurred updating notification image: {0}", ex.ToString()));
return false ;
}
}
private const string NOTIFICATION_IMAGE = "NotificationImage" ;
private Bitmap SafeGetNotificationImage()
{
try
{
byte[] notificationImageBytes = _settingsKey.GetByteArray(NOTIFICATION_IMAGE, null) ;
return new Bitmap(new MemoryStream(notificationImageBytes));
}
catch(Exception ex)
{
Trace.Fail("Unexpected exception loading notification image: " + ex.ToString());
return Image ;
}
}
private string NotificationText
{
get { return _settingsKey.GetString(NOTIFICATION_TEXT, String.Empty); }
set { _settingsKey.SetString(NOTIFICATION_TEXT, value);}
}
private const string NOTIFICATION_TEXT = "NotificationText" ;
private bool ShowNotificationText
{
get { return NotificationText != String.Empty; }
}
private const string SHOW_NOTIFICATION_TEXT = "ShowNotificationText" ;
private bool ShowNotificationImage
{
get { return _settingsKey.GetBoolean(SHOW_NOTIFICATION_IMAGE, false); }
set { _settingsKey.SetBoolean(SHOW_NOTIFICATION_IMAGE, value); }
}
private const string SHOW_NOTIFICATION_IMAGE = "ShowNotificationImage" ;
private bool ClearNotificationOnClick
{
get { return _settingsKey.GetBoolean(CLEAR_NOTIFICATION_ON_CLICK, true); }
set { _settingsKey.SetBoolean(CLEAR_NOTIFICATION_ON_CLICK, value);}
}
private const string CLEAR_NOTIFICATION_ON_CLICK = "ClearNotificationOnClick" ;
internal string FormatUrl(string url)
{
return BlogClientHelper.FormatUrl(url, _homepageUrl, _postApiUrl, _hostBlogId) ;
}
private readonly string _blogId ;
private readonly string _hostBlogId ;
private readonly string _homepageUrl ;
private readonly string _postApiUrl ;
private readonly string _buttonId ;
private readonly SettingsPersisterHelper _settingsKey ;
private readonly BlogProviderButtonDescriptionFromSettings _buttonDescription ;
}
}
| |
// $Id: MessageDispatcher.java,v 1.30 2004/09/02 14:00:40 belaban Exp $
using Alachisoft.NCache.Common.Logger;
using Alachisoft.NCache.Common.Net;
using Alachisoft.NCache.Common.Stats;
using Alachisoft.NCache.Common.Util;
using System;
using System.Collections;
using Alachisoft.NGroups.Util;
namespace Alachisoft.NGroups.Blocks
{
public class MsgDispatcher : RequestHandler, UpHandler
{
private Channel channel;
private RequestCorrelator corr;
private MessageListener msg_listener;
private MembershipListener membership_listener;
private RequestHandler _req_handler;
private ArrayList _members;
private MessageResponder _msgResponder;
private object _statSync = new object();
protected internal bool concurrent_processing;
protected internal bool deadlock_detection;
private Hashtable syncTable = new Hashtable();
private TimeStats _stats = new TimeStats();
private long profileId = 0;
private ILogger _ncacheLog = null;
public ILogger NCacheLog
{
get{return _ncacheLog; }
}
private HPTimeStats _avgReqExecutionTime = new HPTimeStats();
private HPTimeStats _operationOnCacheTimeStats = new HPTimeStats();
private bool useAvgStats = false;
public MsgDispatcher(Channel channel, MessageListener l, MembershipListener l2, RequestHandler req_handler, MessageResponder responder):this(channel, l, l2, req_handler, responder, false)
{
}
public MsgDispatcher(Channel channel, MessageListener l, MembershipListener l2, RequestHandler req_handler, MessageResponder responder, bool deadlock_detection):this(channel, l, l2, req_handler, responder, deadlock_detection, false)
{
}
public MsgDispatcher(Channel channel, MessageListener l, MembershipListener l2, RequestHandler req_handler, MessageResponder responder, bool deadlock_detection, bool concurrent_processing)
{
this.channel = channel;
this._ncacheLog = ((GroupChannel)channel).NCacheLog;
this.deadlock_detection = deadlock_detection;
this.concurrent_processing = concurrent_processing;
msg_listener = l;
membership_listener = l2;
_req_handler = req_handler;
_msgResponder = responder;
channel.UpHandler = this;
start();
}
public virtual void start()
{
if (corr == null)
{
corr = new RequestCorrelator("MsgDisp", channel, this, deadlock_detection, channel.LocalAddress, concurrent_processing, this._ncacheLog);
corr.start();
useAvgStats = ServiceConfiguration.UseAvgStats;
}
}
public virtual void stop()
{
if (corr != null)
{
corr.stop();
}
}
public void StopReplying()
{
if (corr != null) corr.StopReplying();
}
/// <summary> Called by channel (we registered before) when event is received. This is the UpHandler interface.</summary>
public void up(Event evt)
{
try
{
if (corr != null)
{
if (corr.receive(evt))
{
return;
}
}
passUp(evt);
}
catch (NullReferenceException) { }
catch (Exception e)
{
NCacheLog.Error("MsgDispatcher.up()", "exception=" + e);
}
}
/// <summary> Called by request correlator when message was not generated by it. We handle it and call the message
/// listener's corresponding methods
/// </summary>
protected void passUp(Event evt)
{
switch (evt.Type)
{
case Event.MSG:
if (msg_listener != null)
{
HPTimeStats reqHandleStats = null;
msg_listener.receive((Message) evt.Arg);
}
break;
case Event.HASHMAP_REQ:
if (_msgResponder != null)
{
NCacheLog.Debug("MessageDispatcher.PassUp()", "here comes the request for hashmap");
object map = null;
try
{
map = _msgResponder.GetDistributionAndMirrorMaps(evt.Arg);
}
catch (Exception e)
{
NCacheLog.CriticalInfo("MsgDispatcher.passUP", "An error occurred while getting new hashmap. Error: " + e.ToString());
}
Event evnt = new Event();
evnt.Type = Event.HASHMAP_RESP;
evnt.Arg = map;
channel.down(evnt);
NCacheLog.Debug("MessageDispatcher.PassUp()", "sending the response for hashmap back...");
}
break;
case Event.VIEW_CHANGE:
View v = (View) evt.Arg;
ArrayList new_mbrs = v.Members;
if (membership_listener != null)
{
NCacheLog.Debug("MessageDispatcher.passUp", "Event.VIEW_CHANGE-> Entering: " + v.ToString());
membership_listener.viewAccepted(v);
NCacheLog.Debug("MessageDispatcher.passUp", "Event.VIEW_CHANGE->Done" + v.ToString());
}
break;
case Event.ASK_JOIN:
if (membership_listener != null)
{
Event et = new Event();
et.Type = Event.ASK_JOIN_RESPONSE;
et.Arg = membership_listener.AllowJoin();
channel.down(et);
}
break;
case Event.SET_LOCAL_ADDRESS:
break;
case Event.SUSPECT:
if (membership_listener != null)
{
membership_listener.suspect((Address) evt.Arg);
}
break;
case Event.BLOCK:
if (membership_listener != null)
{
membership_listener.block();
}
break;
}
}
public virtual void send(Message msg)
{
if (channel != null)
{
channel.send(msg);
}
else
{
NCacheLog.Error("channel == null");
}
}
/// <summary> Cast a message to all members, and wait for <code>mode</code> responses. The responses are returned in a response
/// list, where each response is associated with its sender.<p> Uses <code>GroupRequest</code>.
///
/// </summary>
/// <param name="dests"> The members to which the message is to be sent. If it is null, then the message is sent to all
/// members
/// </param>
/// <param name="msg"> The message to be sent to n members
/// </param>
/// <param name="mode"> Defined in <code>GroupRequest</code>. The number of responses to wait for: <ol> <li>GET_FIRST:
/// return the first response received. <li>GET_ALL: wait for all responses (minus the ones from
/// suspected members) <li>GET_MAJORITY: wait for a majority of all responses (relative to the grp
/// size) <li>GET_ABS_MAJORITY: wait for majority (absolute, computed once) <li>GET_N: wait for n
/// responses (may block if n > group size) <li>GET_NONE: wait for no responses, return immediately
/// (non-blocking) </ol>
/// </param>
/// <param name="timeout">If 0: wait forever. Otherwise, wait for <code>mode</code> responses <em>or</em> timeout time.
/// </param>
/// <returns> RspList A list of responses. Each response is an <code>Object</code> and associated to its sender.
/// </returns>
public virtual RspList castMessage(ArrayList dests, Message msg, byte mode, long timeout)
{
GroupRequest _req = null;
ArrayList real_dests;
ArrayList clusterMembership = channel.View.Members != null ? (ArrayList)channel.View.Members.Clone() : null;
// we need to clone because we don't want to modify the original
// (we remove ourselves if LOCAL is false, see below) !
real_dests = dests != null ? (ArrayList)dests.Clone() : clusterMembership;
// if local delivery is off, then we should not wait for the message from the local member.
// therefore remove it from the membership
if (channel != null && channel.getOpt(Channel.LOCAL).Equals(false))
{
real_dests.Remove(channel.LocalAddress);
}
// don't even send the message if the destination list is empty
if (NCacheLog.IsInfoEnabled) NCacheLog.Info("MsgDispatcher.castMessage()", "real_dests=" + Global.CollectionToString(real_dests));
if (real_dests == null || real_dests.Count == 0)
{
if (NCacheLog.IsInfoEnabled) NCacheLog.Info("MsgDispatcher.castMessage()", "destination list is empty, won't send message");
return new RspList(); // return empty response list
}
_req = new GroupRequest(msg, corr, real_dests, clusterMembership, mode, timeout, 0, this._ncacheLog);
_req.execute();
if(mode != GroupRequest.GET_NONE)
((GroupChannel)channel).Stack.perfStatsColl.IncrementClusteredOperationsPerSecStats();
RspList rspList = _req.Results;
if(rspList != null)
{
for(int i = 0; i< rspList.size(); i++)
{
Rsp rsp = rspList.elementAt(i) as Rsp;
if (rsp != null)
{
if (!rsp.wasReceived() && !rsp.wasSuspected())
{
if (corr.CheckForMembership((Address)rsp.sender))
rsp.suspected = true;
}
}
}
}
return rspList;
}
public void SendResponse(long resp_id, Message response)
{
corr.SendResponse(resp_id, response);
}
/// <summary> Multicast a message request to all members in <code>dests</code> and receive responses via the RspCollector
/// interface. When done receiving the required number of responses, the caller has to call done(req_id) on the
/// underlyinh RequestCorrelator, so that the resources allocated to that request can be freed.
///
/// </summary>
/// <param name="dests"> The list of members from which to receive responses. Null means all members
/// </param>
/// <param name="req_id">The ID of the request. Used by the underlying RequestCorrelator to correlate responses with
/// requests
/// </param>
/// <param name="msg"> The request to be sent
/// </param>
/// <param name="coll"> The sender needs to provide this interface to collect responses. Call will return immediately if
/// this is null
/// </param>
public virtual void castMessage(ArrayList dests, long req_id, Message msg, RspCollector coll)
{
ArrayList real_dests;
if (msg == null)
{
NCacheLog.Error("MsgDispatcher.castMessage()", "request is null");
return ;
}
if (coll == null)
{
NCacheLog.Error("MessageDispatcher.castMessage()", "response collector is null (must be non-null)");
return ;
}
// we need to clone because we don't want to modify the original
// (we remove ourselves if LOCAL is false, see below) !
real_dests = dests != null?(ArrayList) dests.Clone():(ArrayList) channel.View.Members.Clone();
// if local delivery is off, then we should not wait for the message from the local member.
// therefore remove it from the membership
if (channel != null && channel.getOpt(Channel.LOCAL).Equals(false))
{
real_dests.Remove(channel.LocalAddress);
}
// don't even send the message if the destination list is empty
if (real_dests.Count == 0)
{
NCacheLog.Debug("MsgDispatcher.castMessage()", "destination list is empty, won't send message");
return ;
}
corr.sendRequest(req_id, real_dests, msg, coll);
}
public virtual void done(long req_id)
{
corr.done(req_id);
}
/// <summary> Sends a message to a single member (destination = msg.dest) and returns the response. The message's destination
/// must be non-zero !
/// </summary>
public virtual object sendMessage(Message msg, byte mode, long timeout)
{
RspList rsp_list = null;
object dest = msg.Dest;
Rsp rsp;
GroupRequest _req = null;
if (dest == null)
return null;
ArrayList mbrs = ArrayList.Synchronized(new ArrayList(1));
mbrs.Add(dest);
ArrayList clusterMembership = channel.View.Members != null ? (ArrayList)channel.View.Members.Clone() : null;
_req = new GroupRequest(msg, corr, mbrs, clusterMembership, mode, timeout, 0, this._ncacheLog);
_req.execute();
if (mode == GroupRequest.GET_NONE)
{
return null;
}
((GroupChannel)channel).Stack.perfStatsColl.IncrementClusteredOperationsPerSecStats();
rsp_list = _req.Results;
if (rsp_list.size() == 0)
{
NCacheLog.Warn("MsgDispatcher.sendMessage()", " response list is empty");
return null;
}
if (rsp_list.size() > 1)
{
NCacheLog.Warn("MsgDispatcher.sendMessage()", "response list contains more that 1 response; returning first response !");
}
rsp = (Rsp) rsp_list.elementAt(0);
if (rsp.wasSuspected())
{
throw new SuspectedException(dest);
}
if (!rsp.wasReceived())
{
//we verify for the destination whether it is still part of the cluster or not.
if (corr.CheckForMembership((Address)rsp.Sender))
throw new NCache.Runtime.Exceptions.TimeoutException("operation timeout");
else
{
rsp.suspected = true;
throw new SuspectedException(dest);
}
}
return rsp.Value;
}
/* ------------------------ RequestHandler Interface ---------------------- */
public virtual object handle(Message msg)
{
if (_req_handler != null)
{
object result = _req_handler.handle(msg);
return result;
}
return null;
}
public virtual object handleNHopRequest(Message msg, out Address destination, out Message replicationMsg)
{
destination = null;
replicationMsg = null;
if (_req_handler != null)
{
object result = _req_handler.handleNHopRequest(msg, out destination, out replicationMsg);
return result;
}
return null;
}
}
}
| |
//
// Copyright 2011-2013, Xamarin Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
using System;
using System.Device.Location;
using System.Threading;
using System.Threading.Tasks;
using Plugin.Geolocator.Abstractions;
namespace Plugin.Geolocator
{
/// <summary>
/// Implementation for Geolocator
/// </summary>
public class GeolocatorImplementation : IGeolocator
{
public GeolocatorImplementation()
{
DesiredAccuracy = 100;
}
public event EventHandler<PositionErrorEventArgs> PositionError;
public event EventHandler<PositionEventArgs> PositionChanged;
/// <inheritdoc/>
public bool IsGeolocationAvailable
{
get { return true; }
}
/// <inheritdoc/>
public bool IsGeolocationEnabled
{
get
{
if (this.watcher != null)
this.isEnabled = (this.watcher.Permission == GeoPositionPermission.Granted && this.watcher.Status != GeoPositionStatus.Disabled);
else
this.isEnabled = GetEnabled();
return this.isEnabled;
}
}
/// <inheritdoc/>
public double DesiredAccuracy
{
get;
set;
}
/// <inheritdoc/>
public bool SupportsHeading
{
get { return true; }
}
/// <inheritdoc/>
public bool IsListening
{
get { return (this.watcher != null); }
}
/// <inheritdoc/>
public Task<Position> GetPositionAsync(int timeoutMilliseconds = Timeout.Infinite, CancellationToken? cancelToken = null, bool includeHeading = false)
{
if (!cancelToken.HasValue)
cancelToken = CancellationToken.None;
if (timeoutMilliseconds <= 0 && timeoutMilliseconds != Timeout.Infinite)
throw new ArgumentOutOfRangeException("timeoutMilliseconds", "timeout must be greater than or equal to 0");
return new SinglePositionListener(DesiredAccuracy, timeoutMilliseconds, cancelToken.Value).Task;
}
/// <inheritdoc/>
public Task<bool> StartListeningAsync(int minTime, double minDistance, bool includeHeading = false, ListenerSettings settings = null)
{
if (minTime < 0)
throw new ArgumentOutOfRangeException("minTime");
if (minDistance < 0)
throw new ArgumentOutOfRangeException("minDistance");
if (IsListening)
throw new InvalidOperationException("This Geolocator is already listening");
this.watcher = new GeoCoordinateWatcher(GetAccuracy(DesiredAccuracy));
this.watcher.MovementThreshold = minDistance;
this.watcher.PositionChanged += WatcherOnPositionChanged;
this.watcher.StatusChanged += WatcherOnStatusChanged;
this.watcher.Start();
return Task.FromResult(true);
}
/// <inheritdoc/>
public Task<bool> StopListeningAsync()
{
if (this.watcher == null)
return Task.FromResult(true);
this.watcher.PositionChanged -= WatcherOnPositionChanged;
this.watcher.StatusChanged -= WatcherOnStatusChanged;
this.watcher.Stop();
this.watcher.Dispose();
this.watcher = null;
return Task.FromResult(true);
}
private GeoCoordinateWatcher watcher;
private bool isEnabled;
private static bool GetEnabled()
{
GeoCoordinateWatcher w = new GeoCoordinateWatcher();
try
{
w.Start(true);
bool enabled = (w.Permission == GeoPositionPermission.Granted && w.Status != GeoPositionStatus.Disabled);
w.Stop();
return enabled;
}
catch (Exception)
{
return false;
}
finally
{
w.Dispose();
}
}
private async void WatcherOnStatusChanged(object sender, GeoPositionStatusChangedEventArgs e)
{
this.isEnabled = (this.watcher.Permission == GeoPositionPermission.Granted && this.watcher.Status != GeoPositionStatus.Disabled);
GeolocationError error;
switch (e.Status)
{
case GeoPositionStatus.Disabled:
error = GeolocationError.Unauthorized;
break;
case GeoPositionStatus.NoData:
error = GeolocationError.PositionUnavailable;
break;
default:
return;
}
await StopListeningAsync();
var perror = PositionError;
if (perror != null)
perror(this, new PositionErrorEventArgs(error));
}
private void WatcherOnPositionChanged(object sender, GeoPositionChangedEventArgs<GeoCoordinate> e)
{
Position p = GetPosition(e.Position);
if (p != null)
{
var pupdate = PositionChanged;
if (pupdate != null)
pupdate(this, new PositionEventArgs(p));
}
}
internal static GeoPositionAccuracy GetAccuracy(double desiredAccuracy)
{
if (desiredAccuracy < 100)
return GeoPositionAccuracy.High;
return GeoPositionAccuracy.Default;
}
internal static Position GetPosition(GeoPosition<GeoCoordinate> position)
{
if (position.Location.IsUnknown)
return null;
var p = new Position();
p.Accuracy = position.Location.HorizontalAccuracy;
p.Longitude = position.Location.Longitude;
p.Latitude = position.Location.Latitude;
if (!Double.IsNaN(position.Location.VerticalAccuracy) && !Double.IsNaN(position.Location.Altitude))
{
p.AltitudeAccuracy = position.Location.VerticalAccuracy;
p.Altitude = position.Location.Altitude;
}
if (!Double.IsNaN(position.Location.Course))
p.Heading = position.Location.Course;
if (!Double.IsNaN(position.Location.Speed))
p.Speed = position.Location.Speed;
p.Timestamp = position.Timestamp.ToUniversalTime();
return p;
}
}
}
| |
//
// XamStoreStyleKit.cs
// XamStoreAdditions
//
// Created by Ryan Davis on 18/05/2014.
// Copyright (c) 2014 :). All rights reserved.
//
// Generated by PaintCode (www.paintcodeapp.com)
//
using System;
using System.Drawing;
using MonoTouch.Foundation;
using MonoTouch.UIKit;
using MonoTouch.CoreGraphics;
namespace XamarinStore.iOS
{
[Register ("XamStoreStyleKit")]
public class XamStoreStyleKit : NSObject
{
//// Initialization
static XamStoreStyleKit()
{
}
//// Drawing Methods
public static void DrawCellProto(float cellHeight, float cellWidth)
{
//// General Declarations
var colorSpace = CGColorSpace.CreateDeviceRGB();
var context = UIGraphics.GetCurrentContext();
//// Color Declarations
var cellBgGradientTop = UIColor.FromRGBA(0.753f, 0.725f, 0.702f, 1.000f);
var cellBgGradientBottom = UIColor.FromRGBA(0.773f, 0.800f, 0.835f, 1.000f);
var cellBgGradientBottomHSBA = new float[4];
cellBgGradientBottom.GetHSBA(out cellBgGradientBottomHSBA[0], out cellBgGradientBottomHSBA[1], out cellBgGradientBottomHSBA[2], out cellBgGradientBottomHSBA[3]);
var color = UIColor.FromHSBA(cellBgGradientBottomHSBA[0], cellBgGradientBottomHSBA[1], 0.95f, cellBgGradientBottomHSBA[3]);
//// Gradient Declarations
var cellBgGradientColors = new CGColor [] {cellBgGradientBottom.CGColor, color.CGColor, cellBgGradientTop.CGColor};
var cellBgGradientLocations = new float [] {0.0f, 0.53f, 1.0f};
var cellBgGradient = new CGGradient(colorSpace, cellBgGradientColors, cellBgGradientLocations);
//// Rectangle Drawing
context.SaveState();
context.TranslateCTM(-71.17f, 0.0f);
var rectanglePath = UIBezierPath.FromRect(new RectangleF(71.17f, 0.0f, cellWidth, cellHeight));
context.SaveState();
rectanglePath.AddClip();
context.DrawLinearGradient(cellBgGradient, new PointF(391.17f, 190.0f), new PointF(391.17f, -0.0f), 0);
context.RestoreState();
context.RestoreState();
}
public static void DrawBlueShirt(RectangleF frame, float shirtAngle, float shirtScaleFactor)
{
//// General Declarations
var context = UIGraphics.GetCurrentContext();
//// Color Declarations
var blueShirtBase = UIColor.FromRGBA(0.173f, 0.435f, 0.702f, 1.000f);
var blueShirtBaseRGBA = new float[4];
blueShirtBase.GetRGBA(out blueShirtBaseRGBA[0], out blueShirtBaseRGBA[1], out blueShirtBaseRGBA[2], out blueShirtBaseRGBA[3]);
var blueShirtStroke = UIColor.FromRGBA((blueShirtBaseRGBA[0] * 0.7f + 0.3f), (blueShirtBaseRGBA[1] * 0.7f + 0.3f), (blueShirtBaseRGBA[2] * 0.7f + 0.3f), (blueShirtBaseRGBA[3] * 0.7f + 0.3f));
//// Shadow Declarations
var blueShirtShadow = blueShirtBase.CGColor;
var blueShirtShadowOffset = new SizeF(2.1f, 2.1f);
var blueShirtShadowBlurRadius = 3.0f;
//// shirtBezier Drawing
context.SaveState();
context.TranslateCTM(frame.GetMinX() + 61.94f, frame.GetMinY() + 59.36f);
context.RotateCTM(-shirtAngle * (float)Math.PI / 180.0f);
context.ScaleCTM(shirtScaleFactor, shirtScaleFactor);
UIBezierPath shirtBezierPath = new UIBezierPath();
shirtBezierPath.MoveTo(new PointF(-27.46f, -43.29f));
shirtBezierPath.AddCurveToPoint(new PointF(-11.8f, -30.19f), new PointF(-27.46f, -43.29f), new PointF(-15.62f, -33.38f));
shirtBezierPath.AddLineTo(new PointF(-10.9f, -30.19f));
shirtBezierPath.AddCurveToPoint(new PointF(-10.59f, -29.78f), new PointF(-10.8f, -30.05f), new PointF(-10.7f, -29.92f));
shirtBezierPath.AddCurveToPoint(new PointF(10.42f, -29.78f), new PointF(-4.79f, -22.48f), new PointF(4.62f, -22.48f));
shirtBezierPath.AddCurveToPoint(new PointF(10.74f, -30.19f), new PointF(10.53f, -29.92f), new PointF(10.63f, -30.05f));
shirtBezierPath.AddCurveToPoint(new PointF(11.8f, -30.19f), new PointF(10.74f, -30.19f), new PointF(11.13f, -30.19f));
shirtBezierPath.AddCurveToPoint(new PointF(27.46f, -43.29f), new PointF(15.62f, -33.38f), new PointF(27.46f, -43.29f));
shirtBezierPath.AddLineTo(new PointF(48.92f, -10.09f));
shirtBezierPath.AddLineTo(new PointF(32.09f, 3.99f));
shirtBezierPath.AddCurveToPoint(new PointF(27.12f, -3.69f), new PointF(32.09f, 3.99f), new PointF(30.0f, 0.76f));
shirtBezierPath.AddCurveToPoint(new PointF(27.12f, 43.29f), new PointF(27.12f, 17.36f), new PointF(27.12f, 43.29f));
shirtBezierPath.AddLineTo(new PointF(-27.46f, 43.29f));
shirtBezierPath.AddCurveToPoint(new PointF(-27.46f, -3.18f), new PointF(-27.46f, 43.29f), new PointF(-27.46f, 17.78f));
shirtBezierPath.AddCurveToPoint(new PointF(-32.09f, 3.99f), new PointF(-30.16f, 1.0f), new PointF(-32.09f, 3.99f));
shirtBezierPath.AddLineTo(new PointF(-48.92f, -10.09f));
shirtBezierPath.AddLineTo(new PointF(-27.46f, -43.29f));
shirtBezierPath.ClosePath();
context.SaveState();
context.SetShadowWithColor(blueShirtShadowOffset, blueShirtShadowBlurRadius, blueShirtShadow);
blueShirtBase.SetFill();
shirtBezierPath.Fill();
context.RestoreState();
blueShirtStroke.SetStroke();
shirtBezierPath.LineWidth = 8.0f;
shirtBezierPath.Stroke();
context.RestoreState();
//// Text Drawing
context.SaveState();
context.TranslateCTM(frame.GetMinX() + 62.0f, frame.GetMinY() + 61.95f);
context.RotateCTM(-shirtAngle * (float)Math.PI / 180.0f);
context.ScaleCTM(shirtScaleFactor, shirtScaleFactor);
RectangleF textRect = new RectangleF(-24.7f, -25.61f, 50.0f, 50.0f);
var textPath = UIBezierPath.FromRect(textRect);
UIColor.Red.SetStroke();
textPath.LineWidth = 1.0f;
textPath.Stroke();
{
var textContent = "?";
UIColor.White.SetFill();
var textFont = UIFont.FromName("HelveticaNeue-Bold", 36.0f);
textRect.Offset(0.0f, (textRect.Height - new NSString(textContent).StringSize(textFont, textRect.Size).Height) / 2.0f);
new NSString(textContent).DrawString(textRect, textFont, UILineBreakMode.WordWrap, UITextAlignment.Center);
}
context.RestoreState();
}
public static void DrawGreenShirt(RectangleF frame, float shirtAngle, float shirtScaleFactor)
{
//// General Declarations
var context = UIGraphics.GetCurrentContext();
//// Color Declarations
var blueShirtBase = UIColor.FromRGBA(0.173f, 0.435f, 0.702f, 1.000f);
var greenShirtBase = UIColor.FromRGBA(0.178f, 0.481f, 0.120f, 1.000f);
var greenShirtBaseRGBA = new float[4];
greenShirtBase.GetRGBA(out greenShirtBaseRGBA[0], out greenShirtBaseRGBA[1], out greenShirtBaseRGBA[2], out greenShirtBaseRGBA[3]);
var greenShirtStroke = UIColor.FromRGBA((greenShirtBaseRGBA[0] * 0.7f + 0.3f), (greenShirtBaseRGBA[1] * 0.7f + 0.3f), (greenShirtBaseRGBA[2] * 0.7f + 0.3f), (greenShirtBaseRGBA[3] * 0.7f + 0.3f));
//// Shadow Declarations
var blueShirtShadow = blueShirtBase.CGColor;
var blueShirtShadowOffset = new SizeF(2.1f, 2.1f);
var blueShirtShadowBlurRadius = 3.0f;
//// shirtBezier Drawing
context.SaveState();
context.TranslateCTM(frame.GetMinX() + 61.94f, frame.GetMinY() + 59.36f);
context.RotateCTM(-shirtAngle * (float)Math.PI / 180.0f);
context.ScaleCTM(shirtScaleFactor, shirtScaleFactor);
UIBezierPath shirtBezierPath = new UIBezierPath();
shirtBezierPath.MoveTo(new PointF(-27.46f, -43.29f));
shirtBezierPath.AddCurveToPoint(new PointF(-11.8f, -30.19f), new PointF(-27.46f, -43.29f), new PointF(-15.62f, -33.38f));
shirtBezierPath.AddLineTo(new PointF(-10.9f, -30.19f));
shirtBezierPath.AddCurveToPoint(new PointF(-10.59f, -29.78f), new PointF(-10.8f, -30.05f), new PointF(-10.7f, -29.92f));
shirtBezierPath.AddCurveToPoint(new PointF(10.42f, -29.78f), new PointF(-4.79f, -22.48f), new PointF(4.62f, -22.48f));
shirtBezierPath.AddCurveToPoint(new PointF(10.74f, -30.19f), new PointF(10.53f, -29.92f), new PointF(10.63f, -30.05f));
shirtBezierPath.AddCurveToPoint(new PointF(11.8f, -30.19f), new PointF(10.74f, -30.19f), new PointF(11.13f, -30.19f));
shirtBezierPath.AddCurveToPoint(new PointF(27.46f, -43.29f), new PointF(15.62f, -33.38f), new PointF(27.46f, -43.29f));
shirtBezierPath.AddLineTo(new PointF(48.92f, -10.09f));
shirtBezierPath.AddLineTo(new PointF(32.09f, 3.99f));
shirtBezierPath.AddCurveToPoint(new PointF(27.12f, -3.69f), new PointF(32.09f, 3.99f), new PointF(30.0f, 0.76f));
shirtBezierPath.AddCurveToPoint(new PointF(27.12f, 43.29f), new PointF(27.12f, 17.36f), new PointF(27.12f, 43.29f));
shirtBezierPath.AddLineTo(new PointF(-27.46f, 43.29f));
shirtBezierPath.AddCurveToPoint(new PointF(-27.46f, -3.18f), new PointF(-27.46f, 43.29f), new PointF(-27.46f, 17.78f));
shirtBezierPath.AddCurveToPoint(new PointF(-32.09f, 3.99f), new PointF(-30.16f, 1.0f), new PointF(-32.09f, 3.99f));
shirtBezierPath.AddLineTo(new PointF(-48.92f, -10.09f));
shirtBezierPath.AddLineTo(new PointF(-27.46f, -43.29f));
shirtBezierPath.ClosePath();
context.SaveState();
context.SetShadowWithColor(blueShirtShadowOffset, blueShirtShadowBlurRadius, blueShirtShadow);
greenShirtBase.SetFill();
shirtBezierPath.Fill();
context.RestoreState();
greenShirtStroke.SetStroke();
shirtBezierPath.LineWidth = 8.0f;
shirtBezierPath.Stroke();
context.RestoreState();
//// Text Drawing
context.SaveState();
context.TranslateCTM(frame.GetMinX() + 62.91f, frame.GetMinY() + 59.44f);
context.RotateCTM(-shirtAngle * (float)Math.PI / 180.0f);
context.ScaleCTM(shirtScaleFactor, shirtScaleFactor);
RectangleF textRect = new RectangleF(-25.61f, -23.1f, 50.0f, 50.0f);
var textPath = UIBezierPath.FromRect(textRect);
UIColor.Red.SetStroke();
textPath.LineWidth = 1.0f;
textPath.Stroke();
{
var textContent = "?";
UIColor.White.SetFill();
var textFont = UIFont.FromName("HelveticaNeue-Bold", 36.0f);
textRect.Offset(0.0f, (textRect.Height - new NSString(textContent).StringSize(textFont, textRect.Size).Height) / 2.0f);
new NSString(textContent).DrawString(textRect, textFont, UILineBreakMode.WordWrap, UITextAlignment.Center);
}
context.RestoreState();
}
public static void DrawNavyShirt(RectangleF frame, float shirtAngle, float shirtScaleFactor)
{
//// General Declarations
var context = UIGraphics.GetCurrentContext();
//// Color Declarations
var navyShirtBase = UIColor.FromRGBA(0.102f, 0.114f, 0.180f, 1.000f);
var navyShirtBaseRGBA = new float[4];
navyShirtBase.GetRGBA(out navyShirtBaseRGBA[0], out navyShirtBaseRGBA[1], out navyShirtBaseRGBA[2], out navyShirtBaseRGBA[3]);
var navyShirtStroke = UIColor.FromRGBA((navyShirtBaseRGBA[0] * 0.7f + 0.3f), (navyShirtBaseRGBA[1] * 0.7f + 0.3f), (navyShirtBaseRGBA[2] * 0.7f + 0.3f), (navyShirtBaseRGBA[3] * 0.7f + 0.3f));
//// Shadow Declarations
var navyShirtShadow = UIColor.Black.CGColor;
var navyShirtShadowOffset = new SizeF(2.1f, 2.1f);
var navyShirtShadowBlurRadius = 3.0f;
//// shirtBezier Drawing
context.SaveState();
context.TranslateCTM(frame.GetMinX() + 61.94f, frame.GetMinY() + 59.36f);
context.RotateCTM(-shirtAngle * (float)Math.PI / 180.0f);
context.ScaleCTM(shirtScaleFactor, shirtScaleFactor);
UIBezierPath shirtBezierPath = new UIBezierPath();
shirtBezierPath.MoveTo(new PointF(-27.46f, -43.29f));
shirtBezierPath.AddCurveToPoint(new PointF(-11.8f, -30.19f), new PointF(-27.46f, -43.29f), new PointF(-15.62f, -33.38f));
shirtBezierPath.AddLineTo(new PointF(-10.9f, -30.19f));
shirtBezierPath.AddCurveToPoint(new PointF(-10.59f, -29.78f), new PointF(-10.8f, -30.05f), new PointF(-10.7f, -29.92f));
shirtBezierPath.AddCurveToPoint(new PointF(10.42f, -29.78f), new PointF(-4.79f, -22.48f), new PointF(4.62f, -22.48f));
shirtBezierPath.AddCurveToPoint(new PointF(10.74f, -30.19f), new PointF(10.53f, -29.92f), new PointF(10.63f, -30.05f));
shirtBezierPath.AddCurveToPoint(new PointF(11.8f, -30.19f), new PointF(10.74f, -30.19f), new PointF(11.13f, -30.19f));
shirtBezierPath.AddCurveToPoint(new PointF(27.46f, -43.29f), new PointF(15.62f, -33.38f), new PointF(27.46f, -43.29f));
shirtBezierPath.AddLineTo(new PointF(48.92f, -10.09f));
shirtBezierPath.AddLineTo(new PointF(32.09f, 3.99f));
shirtBezierPath.AddCurveToPoint(new PointF(27.12f, -3.69f), new PointF(32.09f, 3.99f), new PointF(30.0f, 0.76f));
shirtBezierPath.AddCurveToPoint(new PointF(27.12f, 43.29f), new PointF(27.12f, 17.36f), new PointF(27.12f, 43.29f));
shirtBezierPath.AddLineTo(new PointF(-27.46f, 43.29f));
shirtBezierPath.AddCurveToPoint(new PointF(-27.46f, -3.18f), new PointF(-27.46f, 43.29f), new PointF(-27.46f, 17.78f));
shirtBezierPath.AddCurveToPoint(new PointF(-32.09f, 3.99f), new PointF(-30.16f, 1.0f), new PointF(-32.09f, 3.99f));
shirtBezierPath.AddLineTo(new PointF(-48.92f, -10.09f));
shirtBezierPath.AddLineTo(new PointF(-27.46f, -43.29f));
shirtBezierPath.ClosePath();
context.SaveState();
context.SetShadowWithColor(navyShirtShadowOffset, navyShirtShadowBlurRadius, navyShirtShadow);
navyShirtBase.SetFill();
shirtBezierPath.Fill();
context.RestoreState();
navyShirtStroke.SetStroke();
shirtBezierPath.LineWidth = 8.0f;
shirtBezierPath.Stroke();
context.RestoreState();
//// Text Drawing
context.SaveState();
context.TranslateCTM(frame.GetMinX() + 62.91f, frame.GetMinY() + 59.44f);
context.RotateCTM(-shirtAngle * (float)Math.PI / 180.0f);
context.ScaleCTM(shirtScaleFactor, shirtScaleFactor);
RectangleF textRect = new RectangleF(-25.61f, -23.1f, 50.0f, 50.0f);
var textPath = UIBezierPath.FromRect(textRect);
UIColor.Red.SetStroke();
textPath.LineWidth = 1.0f;
textPath.Stroke();
{
var textContent = "?";
UIColor.White.SetFill();
var textFont = UIFont.FromName("HelveticaNeue-Bold", 36.0f);
textRect.Offset(0.0f, (textRect.Height - new NSString(textContent).StringSize(textFont, textRect.Size).Height) / 2.0f);
new NSString(textContent).DrawString(textRect, textFont, UILineBreakMode.WordWrap, UITextAlignment.Center);
}
context.RestoreState();
}
}
}
| |
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Xml.Linq;
using Palmmedia.ReportGenerator.Core.Common;
using Palmmedia.ReportGenerator.Core.Logging;
using Palmmedia.ReportGenerator.Core.Parser.Analysis;
using Palmmedia.ReportGenerator.Core.Parser.FileReading;
using Palmmedia.ReportGenerator.Core.Parser.Filtering;
using Palmmedia.ReportGenerator.Core.Properties;
namespace Palmmedia.ReportGenerator.Core.Parser
{
/// <summary>
/// Parser for XML reports generated by OpenCover.
/// </summary>
internal class OpenCoverParser : ParserBase
{
/// <summary>
/// The Logger.
/// </summary>
private static readonly ILogger Logger = LoggerFactory.GetLogger(typeof(OpenCoverParser));
/// <summary>
/// Regex to analyze if a method name belongs to a lamda expression.
/// </summary>
private static readonly Regex LambdaMethodNameRegex = new Regex("::<.+>.+__", RegexOptions.Compiled);
/// <summary>
/// Regex to analyze if a method name is generated by compiler.
/// </summary>
private static readonly Regex CompilerGeneratedMethodNameRegex = new Regex(@"<(?<CompilerGeneratedName>.+)>.+__.+::MoveNext\(\)$", RegexOptions.Compiled);
/// <summary>
/// Regex to extract short method name.
/// </summary>
private static readonly Regex MethodRegex = new Regex(@"^.*::(?<MethodName>.+)\((?<Arguments>.*)\)$", RegexOptions.Compiled);
/// <summary>
/// Cache for method names.
/// </summary>
private static readonly ConcurrentDictionary<string, string> MethodNameMap = new ConcurrentDictionary<string, string>();
/// <summary>
/// Initializes a new instance of the <see cref="OpenCoverParser" /> class.
/// </summary>
/// <param name="assemblyFilter">The assembly filter.</param>
/// <param name="classFilter">The class filter.</param>
/// <param name="fileFilter">The file filter.</param>
internal OpenCoverParser(IFilter assemblyFilter, IFilter classFilter, IFilter fileFilter)
: base(assemblyFilter, classFilter, fileFilter)
{
}
/// <summary>
/// Parses the given XML report.
/// </summary>
/// <param name="report">The XML report.</param>
/// <returns>The parser result.</returns>
public ParserResult Parse(XContainer report)
{
if (report == null)
{
throw new ArgumentNullException(nameof(report));
}
var assemblies = new List<Assembly>();
var modules = report.Descendants("Module")
.Where(m => m.Attribute("skippedDueTo") == null)
.ToArray();
var files = report.Descendants("File").ToArray();
var trackedMethods = new Dictionary<string, string>();
foreach (var trackedMethodElement in report.Descendants("TrackedMethod"))
{
if (trackedMethods.ContainsKey(trackedMethodElement.Attribute("uid").Value))
{
Logger.WarnFormat(
Resources.ErrorNotUniqueTrackedMethodUid,
trackedMethodElement.Attribute("name").Value);
trackedMethods.Clear();
break;
}
else
{
trackedMethods.Add(trackedMethodElement.Attribute("uid").Value, trackedMethodElement.Attribute("name").Value);
}
}
var assemblyNames = modules
.Select(m => m.Element("ModuleName").Value)
.Distinct()
.Where(a => this.AssemblyFilter.IsElementIncludedInReport(a))
.OrderBy(a => a)
.ToArray();
var assemblyModules = assemblyNames.
ToDictionary(
k => k,
v => modules.Where(t => t.Element("ModuleName").Value.Equals(v)).ToArray());
foreach (var assemblyName in assemblyNames)
{
assemblies.Add(this.ProcessAssembly(assemblyModules, files, trackedMethods, assemblyName));
}
var result = new ParserResult(assemblies.OrderBy(a => a.Name).ToList(), true, this.ToString());
return result;
}
/// <summary>
/// Processes the given assembly.
/// </summary>
/// <param name="assemblyModules">The modules belonging to a assembly name.</param>
/// <param name="files">The files.</param>
/// <param name="trackedMethods">The tracked methods.</param>
/// <param name="assemblyName">Name of the assembly.</param>
/// <returns>The <see cref="Assembly"/>.</returns>
private Assembly ProcessAssembly(IDictionary<string, XElement[]> assemblyModules, XElement[] files, IDictionary<string, string> trackedMethods, string assemblyName)
{
Logger.DebugFormat(Resources.CurrentAssembly, assemblyName);
var fileIdsByFilename = assemblyModules[assemblyName]
.Elements("Files")
.Elements("File")
.GroupBy(f => f.Attribute("fullPath").Value)
.ToDictionary(g => g.Key, g => new FileElement(g));
var classNames = assemblyModules[assemblyName]
.Elements("Classes")
.Elements("Class")
.Where(c => c.Attribute("skippedDueTo") == null)
.Where(c => c.Element("Methods").Elements("Method").Any())
.Select(c =>
{
string fullname = c.Element("FullName").Value;
int nestedClassSeparatorIndex = fullname.IndexOf('/');
return nestedClassSeparatorIndex > -1 ? fullname.Substring(0, nestedClassSeparatorIndex) : fullname;
})
.Where(name => name.IndexOf("<") < 1)
.Distinct()
.Where(c => this.ClassFilter.IsElementIncludedInReport(c))
.OrderBy(name => name)
.ToArray();
var assembly = new Assembly(assemblyName);
Parallel.ForEach(classNames, className => this.ProcessClass(assemblyModules, files, trackedMethods, fileIdsByFilename, assembly, className));
return assembly;
}
/// <summary>
/// Processes the given class.
/// </summary>
/// <param name="assemblyModules">The modules belonging to a assembly name.</param>
/// <param name="files">The files.</param>
/// <param name="trackedMethods">The tracked methods.</param>
/// <param name="fileIdsByFilename">Dictionary containing the file ids by filename.</param>
/// <param name="assembly">The assembly.</param>
/// <param name="className">Name of the class.</param>
private void ProcessClass(IDictionary<string, XElement[]> assemblyModules, XElement[] files, IDictionary<string, string> trackedMethods, Dictionary<string, FileElement> fileIdsByFilename, Assembly assembly, string className)
{
var methods = assemblyModules[assembly.Name]
.Elements("Classes")
.Elements("Class")
.Where(c => c.Element("FullName").Value.Equals(className)
|| c.Element("FullName").Value.StartsWith(className + "/", StringComparison.Ordinal))
.Elements("Methods")
.Elements("Method")
.Where(m => m.Attribute("skippedDueTo") == null)
.ToArray();
var fileIdsOfClassInSequencePoints = methods
.Elements("SequencePoints")
.Elements("SequencePoint")
.Select(seqpnt => seqpnt.Attribute("fileid")?.Value)
.Where(seqpnt => seqpnt != null && seqpnt != "0")
.ToArray();
// Only required for backwards compatibility, older versions of OpenCover did not apply fileid for partial classes
var fileIdsOfClassInFileRef = methods
.Select(m => m.Element("FileRef")?.Attribute("uid").Value)
.Where(m => m != null)
.ToArray();
var fileIdsOfClass = fileIdsOfClassInSequencePoints
.Concat(fileIdsOfClassInFileRef)
.Distinct()
.ToHashSet();
var filesOfClass = files
.Where(file => fileIdsOfClass.Contains(file.Attribute("uid").Value))
.Select(file => file.Attribute("fullPath").Value)
.Distinct()
.ToArray();
var filteredFilesOfClass = filesOfClass
.Where(f => this.FileFilter.IsElementIncludedInReport(f))
.ToArray();
// If all files are removed by filters, then the whole class is omitted
if ((filesOfClass.Length == 0 && !this.FileFilter.HasCustomFilters) || filteredFilesOfClass.Length > 0)
{
var @class = new Class(className, assembly);
foreach (var file in filteredFilesOfClass)
{
@class.AddFile(ProcessFile(trackedMethods, fileIdsByFilename[file], file, methods));
}
@class.CoverageQuota = GetCoverageQuotaOfClass(methods);
assembly.AddClass(@class);
}
}
/// <summary>
/// Processes the file.
/// </summary>
/// <param name="trackedMethods">The tracked methods.</param>
/// <param name="fileIds">The file ids of the class.</param>
/// <param name="filePath">The file path.</param>
/// <param name="methods">The methods.</param>
/// <returns>The <see cref="CodeFile"/>.</returns>
private static CodeFile ProcessFile(IDictionary<string, string> trackedMethods, FileElement fileIds, string filePath, XElement[] methods)
{
var seqpntsOfFile = methods
.Elements("SequencePoints")
.Elements("SequencePoint")
.Where(seqpnt => (seqpnt.Attribute("fileid") != null
&& fileIds.Uids.Contains(seqpnt.Attribute("fileid").Value))
|| (seqpnt.Attribute("fileid") == null && seqpnt.Parent.Parent.Element("FileRef") != null
&& fileIds.Uids.Contains(seqpnt.Parent.Parent.Element("FileRef").Attribute("uid").Value)))
.Select(seqpnt => new
{
LineNumberStart = int.Parse(seqpnt.Attribute("sl").Value, CultureInfo.InvariantCulture),
LineNumberEnd = seqpnt.Attribute("el") != null ? int.Parse(seqpnt.Attribute("el").Value, CultureInfo.InvariantCulture) : int.Parse(seqpnt.Attribute("sl").Value, CultureInfo.InvariantCulture),
Visits = seqpnt.Attribute("vc").Value.ParseLargeInteger(),
TrackedMethodRefs = seqpnt.Elements("TrackedMethodRefs")
.Elements("TrackedMethodRef")
.Select(t => new
{
Visits = t.Attribute("vc").Value.ParseLargeInteger(),
TrackedMethodId = t.Attribute("uid").Value
})
})
.OrderBy(seqpnt => seqpnt.LineNumberEnd)
.ToArray();
var branches = GetBranches(methods, fileIds);
var coverageByTrackedMethod = seqpntsOfFile
.SelectMany(s => s.TrackedMethodRefs)
.Select(t => t.TrackedMethodId)
.Distinct()
.ToDictionary(id => id, id => new CoverageByTrackedMethod { Coverage = new int[] { }, LineVisitStatus = new LineVisitStatus[] { } });
int[] coverage = new int[] { };
LineVisitStatus[] lineVisitStatus = new LineVisitStatus[] { };
if (seqpntsOfFile.Length > 0)
{
coverage = new int[seqpntsOfFile[seqpntsOfFile.LongLength - 1].LineNumberEnd + 1];
lineVisitStatus = new LineVisitStatus[seqpntsOfFile[seqpntsOfFile.LongLength - 1].LineNumberEnd + 1];
for (int i = 0; i < coverage.Length; i++)
{
coverage[i] = -1;
}
foreach (var trackedMethodCoverage in coverageByTrackedMethod)
{
trackedMethodCoverage.Value.Coverage = (int[])coverage.Clone();
trackedMethodCoverage.Value.LineVisitStatus = new LineVisitStatus[seqpntsOfFile[seqpntsOfFile.LongLength - 1].LineNumberEnd + 1];
}
foreach (var seqpnt in seqpntsOfFile)
{
for (int lineNumber = seqpnt.LineNumberStart; lineNumber <= seqpnt.LineNumberEnd; lineNumber++)
{
int visits = coverage[lineNumber] == -1 ? seqpnt.Visits : coverage[lineNumber] + seqpnt.Visits;
coverage[lineNumber] = visits;
if (lineVisitStatus[lineNumber] != LineVisitStatus.Covered)
{
bool partiallyCovered = false;
// Use 'LineNumberStart' instead of 'lineNumber' here. Branches have line number of first line of seqpnt
if (branches.TryGetValue(seqpnt.LineNumberStart, out ICollection<Branch> branchesOfLine))
{
partiallyCovered = branchesOfLine.Any(b => b.BranchVisits == 0);
}
LineVisitStatus statusOfLine = visits > 0 ? (partiallyCovered ? LineVisitStatus.PartiallyCovered : LineVisitStatus.Covered) : LineVisitStatus.NotCovered;
lineVisitStatus[lineNumber] = (LineVisitStatus)Math.Max((int)lineVisitStatus[lineNumber], (int)statusOfLine);
}
if (visits > -1)
{
foreach (var trackedMethodCoverage in coverageByTrackedMethod)
{
if (trackedMethodCoverage.Value.Coverage[lineNumber] == -1)
{
trackedMethodCoverage.Value.Coverage[lineNumber] = 0;
trackedMethodCoverage.Value.LineVisitStatus[lineNumber] = LineVisitStatus.NotCovered;
}
}
}
foreach (var trackedMethod in seqpnt.TrackedMethodRefs)
{
var trackedMethodCoverage = coverageByTrackedMethod[trackedMethod.TrackedMethodId];
int trackeMethodVisits = trackedMethodCoverage.Coverage[lineNumber] == -1 ? trackedMethod.Visits : trackedMethodCoverage.Coverage[lineNumber] + trackedMethod.Visits;
LineVisitStatus statusOfLine = trackeMethodVisits > 0 ? (LineVisitStatus)Math.Min((int)LineVisitStatus.Covered, (int)lineVisitStatus[lineNumber]) : LineVisitStatus.NotCovered;
trackedMethodCoverage.Coverage[lineNumber] = trackeMethodVisits;
trackedMethodCoverage.LineVisitStatus[lineNumber] = statusOfLine;
}
}
}
}
CodeFile codeFile = null;
if (!string.IsNullOrWhiteSpace(fileIds.EmbeddedSource))
{
var additionalFileReader = new AltCoverEmbeddedFileReader(fileIds.EmbeddedSource);
codeFile = new CodeFile(filePath, coverage, lineVisitStatus, branches, additionalFileReader);
}
else
{
codeFile = new CodeFile(filePath, coverage, lineVisitStatus, branches);
}
foreach (var trackedMethodCoverage in coverageByTrackedMethod)
{
// Sometimes no corresponding MethodRef element exists
if (trackedMethods.TryGetValue(trackedMethodCoverage.Key, out string name))
{
string shortName = name.Substring(name.Substring(0, name.IndexOf(':') + 1).LastIndexOf('.') + 1);
TestMethod testMethod = new TestMethod(name, shortName);
codeFile.AddCoverageByTestMethod(testMethod, trackedMethodCoverage.Value);
}
}
var methodsOfFile = methods
.Where(m => m.Element("FileRef") != null && fileIds.Uids.Contains(m.Element("FileRef").Attribute("uid").Value))
.ToArray();
SetMethodMetrics(codeFile, methodsOfFile);
SetCodeElements(codeFile, methodsOfFile);
return codeFile;
}
/// <summary>
/// Extracts the metrics from the given <see cref="XElement">XElements</see>.
/// </summary>
/// <param name="codeFile">The code file.</param>
/// <param name="methodsOfFile">The methods of the file.</param>
private static void SetMethodMetrics(CodeFile codeFile, IEnumerable<XElement> methodsOfFile)
{
foreach (var methodGroup in methodsOfFile.GroupBy(m => m.Element("Name").Value))
{
var method = methodGroup.First();
// Exclude properties and lambda expressions
if (method.Attribute("skippedDueTo") != null
|| method.HasAttributeWithValue("isGetter", "true")
|| method.HasAttributeWithValue("isSetter", "true")
|| LambdaMethodNameRegex.IsMatch(methodGroup.Key))
{
continue;
}
var metrics = new List<Metric>()
{
new Metric(
ReportResources.CyclomaticComplexity,
ParserBase.CyclomaticComplexityUri,
MetricType.CodeQuality,
methodGroup.Max(m => int.Parse(m.Attribute("cyclomaticComplexity").Value, CultureInfo.InvariantCulture)),
MetricMergeOrder.LowerIsBetter),
new Metric(
ReportResources.SequenceCoverage,
ParserBase.CodeCoverageUri,
MetricType.CoveragePercentual,
methodGroup.Max(m => decimal.Parse(m.Attribute("sequenceCoverage").Value, CultureInfo.InvariantCulture))),
new Metric(
ReportResources.BranchCoverage,
ParserBase.CodeCoverageUri,
MetricType.CoveragePercentual,
methodGroup.Max(m => decimal.Parse(m.Attribute("branchCoverage").Value, CultureInfo.InvariantCulture)))
};
var npathComplexityAttributes = methodGroup.Select(m => m.Attribute("nPathComplexity")).Where(a => a != null).ToArray();
if (npathComplexityAttributes.Length > 0)
{
metrics.Insert(
1,
new Metric(
ReportResources.NPathComplexity,
ParserBase.NPathComplexityUri,
MetricType.CodeQuality,
npathComplexityAttributes
.Select(a => int.Parse(a.Value, CultureInfo.InvariantCulture))
.Max(a => a < 0 ? int.MaxValue : a),
MetricMergeOrder.LowerIsBetter));
}
var crapScoreAttributes = methodGroup.Select(m => m.Attribute("crapScore")).Where(a => a != null).ToArray();
if (crapScoreAttributes.Length > 0)
{
metrics.Add(new Metric(
ReportResources.CrapScore,
ParserBase.CrapScoreUri,
MetricType.CodeQuality,
crapScoreAttributes.Max(a => decimal.Parse(a.Value, CultureInfo.InvariantCulture)),
MetricMergeOrder.LowerIsBetter));
}
string fullName = ExtractMethodName(methodGroup.Key);
string shortName = MethodRegex.Replace(fullName, m => string.Format(CultureInfo.InvariantCulture, "{0}({1})", m.Groups["MethodName"].Value, m.Groups["Arguments"].Value.Length > 0 ? "..." : string.Empty));
var methodMetric = new MethodMetric(fullName, shortName, metrics);
var seqpnt = method
.Elements("SequencePoints")
.Elements("SequencePoint")
.FirstOrDefault();
if (seqpnt != null)
{
methodMetric.Line = int.Parse(seqpnt.Attribute("sl").Value, CultureInfo.InvariantCulture);
}
codeFile.AddMethodMetric(methodMetric);
}
}
/// <summary>
/// Gets the branches by line number.
/// </summary>
/// <param name="methods">The methods.</param>
/// <param name="fileIds">The file ids of the class.</param>
/// <returns>The branches by line number.</returns>
private static Dictionary<int, ICollection<Branch>> GetBranches(XElement[] methods, FileElement fileIds)
{
var branchPoints = methods
.Elements("BranchPoints")
.Elements("BranchPoint")
.ToArray();
// OpenCover supports this since version 4.5.3207
if (branchPoints.Length == 0 || branchPoints[0].Attribute("sl") == null)
{
return new Dictionary<int, ICollection<Branch>>();
}
var result = new Dictionary<int, Dictionary<string, Branch>>();
foreach (var branchPoint in branchPoints)
{
if (branchPoint.Attribute("fileid") != null
&& !fileIds.Uids.Contains(branchPoint.Attribute("fileid").Value))
{
// If fileid is available, verify that branch belongs to same file (available since version OpenCover.4.5.3418)
continue;
}
int lineNumber = int.Parse(branchPoint.Attribute("sl").Value, CultureInfo.InvariantCulture);
string identifier = string.Format(
CultureInfo.InvariantCulture,
"{0}_{1}_{2}_{3}",
lineNumber,
branchPoint.Attribute("path").Value,
branchPoint.Attribute("offset").Value,
branchPoint.Attribute("offsetend").Value);
int vc = int.Parse(branchPoint.Attribute("vc").Value, CultureInfo.InvariantCulture);
if (result.TryGetValue(lineNumber, out var branches))
{
if (branches.TryGetValue(identifier, out var found))
{
found.BranchVisits += vc;
}
else
{
branches.Add(identifier, new Branch(vc, identifier));
}
}
else
{
branches = new Dictionary<string, Branch>
{
{ identifier, new Branch(vc, identifier) }
};
result.Add(lineNumber, branches);
}
}
return result.ToDictionary(k => k.Key, v => (ICollection<Branch>)v.Value.Values.ToHashSet());
}
/// <summary>
/// Extracts the methods/properties of the given <see cref="XElement">XElements</see>.
/// </summary>
/// <param name="codeFile">The code file.</param>
/// <param name="methodsOfFile">The methods of the file.</param>
private static void SetCodeElements(CodeFile codeFile, IEnumerable<XElement> methodsOfFile)
{
foreach (var method in methodsOfFile)
{
if (method.Attribute("skippedDueTo") != null
|| LambdaMethodNameRegex.IsMatch(method.Element("Name").Value))
{
continue;
}
string methodName = ExtractMethodName(method.Element("Name").Value);
methodName = methodName.Substring(methodName.LastIndexOf(':') + 1);
CodeElementType type = CodeElementType.Method;
if (method.HasAttributeWithValue("isGetter", "true")
|| method.HasAttributeWithValue("isSetter", "true"))
{
type = CodeElementType.Property;
methodName = methodName.Substring(4);
}
var seqpnts = method
.Elements("SequencePoints")
.Elements("SequencePoint")
.Select(seqpnt => new
{
LineNumberStart = int.Parse(seqpnt.Attribute("sl").Value, CultureInfo.InvariantCulture),
LineNumberEnd = seqpnt.Attribute("el") != null ? int.Parse(seqpnt.Attribute("el").Value, CultureInfo.InvariantCulture) : int.Parse(seqpnt.Attribute("sl").Value, CultureInfo.InvariantCulture)
})
.ToArray();
if (seqpnts.Length > 0)
{
int firstLine = seqpnts.Min(s => s.LineNumberStart);
int lastLine = seqpnts.Max(s => s.LineNumberEnd);
codeFile.AddCodeElement(new CodeElement(
methodName,
type,
firstLine,
lastLine,
codeFile.CoverageQuota(firstLine, lastLine)));
}
}
}
/// <summary>
/// Extracts the method name. For async methods the original name is returned.
/// </summary>
/// <param name="methodName">The full method name.</param>
/// <returns>The method name.</returns>
private static string ExtractMethodName(string methodName)
{
if (!MethodNameMap.TryGetValue(methodName, out var fullName))
{
// Quick check before expensive regex is called
if (methodName.EndsWith("::MoveNext()"))
{
Match match = CompilerGeneratedMethodNameRegex.Match(methodName);
if (match.Success)
{
methodName = match.Groups["CompilerGeneratedName"].Value + "()";
}
}
fullName = methodName;
MethodNameMap.TryAdd(methodName, fullName);
}
return fullName;
}
/// <summary>
/// Gets the coverage quota of a class.
/// This method is used to get coverage quota if line coverage is not available.
/// </summary>
/// <param name="methods">The methods.</param>
/// <returns>The coverage quota.</returns>
private static decimal? GetCoverageQuotaOfClass(XElement[] methods)
{
var methodGroups = methods
.Where(m => m.Attribute("skippedDueTo") == null && m.Element("FileRef") == null && !m.Element("Name").Value.EndsWith(".ctor()", StringComparison.OrdinalIgnoreCase))
.GroupBy(m => m.Element("Name").Value)
.ToArray();
int visitedMethods = methodGroups.Count(g => g.Any(m => m.Attribute("visited").Value == "true"));
return (methodGroups.Length == 0) ? (decimal?)null : (decimal)Math.Truncate(1000 * (double)visitedMethods / (double)methodGroups.Length) / 10;
}
private class FileElement
{
/// <summary>
/// Initializes a new instance of the <see cref="FileElement" /> class.
/// </summary>
/// <param name="elements">The File elements.</param>
public FileElement(IEnumerable<XElement> elements)
{
this.Uids = elements.Select(f => f.Attribute("uid").Value).ToHashSet();
this.EmbeddedSource = elements
.Select(e => e.Attribute("altcover.embed"))
.Where(e => e != null)
.FirstOrDefault()
?.Value;
}
/// <summary>
/// Gets the uids.
/// </summary>
public HashSet<string> Uids { get; }
/// <summary>
/// Gets or sets the embedded source code.
/// </summary>
public string EmbeddedSource { get; set; }
}
}
}
| |
// Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
using gax = Google.Api.Gax;
using gcdv = Google.Cloud.DataLabeling.V1Beta1;
using sys = System;
namespace Google.Cloud.DataLabeling.V1Beta1
{
/// <summary>Resource name for the <c>AnnotationSpecSet</c> resource.</summary>
public sealed partial class AnnotationSpecSetName : gax::IResourceName, sys::IEquatable<AnnotationSpecSetName>
{
/// <summary>The possible contents of <see cref="AnnotationSpecSetName"/>.</summary>
public enum ResourceNameType
{
/// <summary>An unparsed resource name.</summary>
Unparsed = 0,
/// <summary>
/// A resource name with pattern <c>projects/{project}/annotationSpecSets/{annotation_spec_set}</c>.
/// </summary>
ProjectAnnotationSpecSet = 1,
}
private static gax::PathTemplate s_projectAnnotationSpecSet = new gax::PathTemplate("projects/{project}/annotationSpecSets/{annotation_spec_set}");
/// <summary>Creates a <see cref="AnnotationSpecSetName"/> containing an unparsed resource name.</summary>
/// <param name="unparsedResourceName">The unparsed resource name. Must not be <c>null</c>.</param>
/// <returns>
/// A new instance of <see cref="AnnotationSpecSetName"/> containing the provided
/// <paramref name="unparsedResourceName"/>.
/// </returns>
public static AnnotationSpecSetName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) =>
new AnnotationSpecSetName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName)));
/// <summary>
/// Creates a <see cref="AnnotationSpecSetName"/> with the pattern
/// <c>projects/{project}/annotationSpecSets/{annotation_spec_set}</c>.
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="annotationSpecSetId">The <c>AnnotationSpecSet</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>A new instance of <see cref="AnnotationSpecSetName"/> constructed from the provided ids.</returns>
public static AnnotationSpecSetName FromProjectAnnotationSpecSet(string projectId, string annotationSpecSetId) =>
new AnnotationSpecSetName(ResourceNameType.ProjectAnnotationSpecSet, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), annotationSpecSetId: gax::GaxPreconditions.CheckNotNullOrEmpty(annotationSpecSetId, nameof(annotationSpecSetId)));
/// <summary>
/// Formats the IDs into the string representation of this <see cref="AnnotationSpecSetName"/> with pattern
/// <c>projects/{project}/annotationSpecSets/{annotation_spec_set}</c>.
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="annotationSpecSetId">The <c>AnnotationSpecSet</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="AnnotationSpecSetName"/> with pattern
/// <c>projects/{project}/annotationSpecSets/{annotation_spec_set}</c>.
/// </returns>
public static string Format(string projectId, string annotationSpecSetId) =>
FormatProjectAnnotationSpecSet(projectId, annotationSpecSetId);
/// <summary>
/// Formats the IDs into the string representation of this <see cref="AnnotationSpecSetName"/> with pattern
/// <c>projects/{project}/annotationSpecSets/{annotation_spec_set}</c>.
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="annotationSpecSetId">The <c>AnnotationSpecSet</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="AnnotationSpecSetName"/> with pattern
/// <c>projects/{project}/annotationSpecSets/{annotation_spec_set}</c>.
/// </returns>
public static string FormatProjectAnnotationSpecSet(string projectId, string annotationSpecSetId) =>
s_projectAnnotationSpecSet.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), gax::GaxPreconditions.CheckNotNullOrEmpty(annotationSpecSetId, nameof(annotationSpecSetId)));
/// <summary>
/// Parses the given resource name string into a new <see cref="AnnotationSpecSetName"/> instance.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item><description><c>projects/{project}/annotationSpecSets/{annotation_spec_set}</c></description></item>
/// </list>
/// </remarks>
/// <param name="annotationSpecSetName">The resource name in string form. Must not be <c>null</c>.</param>
/// <returns>The parsed <see cref="AnnotationSpecSetName"/> if successful.</returns>
public static AnnotationSpecSetName Parse(string annotationSpecSetName) => Parse(annotationSpecSetName, false);
/// <summary>
/// Parses the given resource name string into a new <see cref="AnnotationSpecSetName"/> instance; optionally
/// allowing an unparseable resource name.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item><description><c>projects/{project}/annotationSpecSets/{annotation_spec_set}</c></description></item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="annotationSpecSetName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="allowUnparsed">
/// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/>
/// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is
/// specified.
/// </param>
/// <returns>The parsed <see cref="AnnotationSpecSetName"/> if successful.</returns>
public static AnnotationSpecSetName Parse(string annotationSpecSetName, bool allowUnparsed) =>
TryParse(annotationSpecSetName, allowUnparsed, out AnnotationSpecSetName result) ? result : throw new sys::ArgumentException("The given resource-name matches no pattern.");
/// <summary>
/// Tries to parse the given resource name string into a new <see cref="AnnotationSpecSetName"/> instance.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item><description><c>projects/{project}/annotationSpecSets/{annotation_spec_set}</c></description></item>
/// </list>
/// </remarks>
/// <param name="annotationSpecSetName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="result">
/// When this method returns, the parsed <see cref="AnnotationSpecSetName"/>, or <c>null</c> if parsing failed.
/// </param>
/// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns>
public static bool TryParse(string annotationSpecSetName, out AnnotationSpecSetName result) =>
TryParse(annotationSpecSetName, false, out result);
/// <summary>
/// Tries to parse the given resource name string into a new <see cref="AnnotationSpecSetName"/> instance;
/// optionally allowing an unparseable resource name.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item><description><c>projects/{project}/annotationSpecSets/{annotation_spec_set}</c></description></item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="annotationSpecSetName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="allowUnparsed">
/// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/>
/// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is
/// specified.
/// </param>
/// <param name="result">
/// When this method returns, the parsed <see cref="AnnotationSpecSetName"/>, or <c>null</c> if parsing failed.
/// </param>
/// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns>
public static bool TryParse(string annotationSpecSetName, bool allowUnparsed, out AnnotationSpecSetName result)
{
gax::GaxPreconditions.CheckNotNull(annotationSpecSetName, nameof(annotationSpecSetName));
gax::TemplatedResourceName resourceName;
if (s_projectAnnotationSpecSet.TryParseName(annotationSpecSetName, out resourceName))
{
result = FromProjectAnnotationSpecSet(resourceName[0], resourceName[1]);
return true;
}
if (allowUnparsed)
{
if (gax::UnparsedResourceName.TryParse(annotationSpecSetName, out gax::UnparsedResourceName unparsedResourceName))
{
result = FromUnparsed(unparsedResourceName);
return true;
}
}
result = null;
return false;
}
private AnnotationSpecSetName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string annotationSpecSetId = null, string projectId = null)
{
Type = type;
UnparsedResource = unparsedResourceName;
AnnotationSpecSetId = annotationSpecSetId;
ProjectId = projectId;
}
/// <summary>
/// Constructs a new instance of a <see cref="AnnotationSpecSetName"/> class from the component parts of pattern
/// <c>projects/{project}/annotationSpecSets/{annotation_spec_set}</c>
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="annotationSpecSetId">The <c>AnnotationSpecSet</c> ID. Must not be <c>null</c> or empty.</param>
public AnnotationSpecSetName(string projectId, string annotationSpecSetId) : this(ResourceNameType.ProjectAnnotationSpecSet, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), annotationSpecSetId: gax::GaxPreconditions.CheckNotNullOrEmpty(annotationSpecSetId, nameof(annotationSpecSetId)))
{
}
/// <summary>The <see cref="ResourceNameType"/> of the contained resource name.</summary>
public ResourceNameType Type { get; }
/// <summary>
/// The contained <see cref="gax::UnparsedResourceName"/>. Only non-<c>null</c> if this instance contains an
/// unparsed resource name.
/// </summary>
public gax::UnparsedResourceName UnparsedResource { get; }
/// <summary>
/// The <c>AnnotationSpecSet</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource
/// name.
/// </summary>
public string AnnotationSpecSetId { get; }
/// <summary>
/// The <c>Project</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string ProjectId { get; }
/// <summary>Whether this instance contains a resource name with a known pattern.</summary>
public bool IsKnownPattern => Type != ResourceNameType.Unparsed;
/// <summary>The string representation of the resource name.</summary>
/// <returns>The string representation of the resource name.</returns>
public override string ToString()
{
switch (Type)
{
case ResourceNameType.Unparsed: return UnparsedResource.ToString();
case ResourceNameType.ProjectAnnotationSpecSet: return s_projectAnnotationSpecSet.Expand(ProjectId, AnnotationSpecSetId);
default: throw new sys::InvalidOperationException("Unrecognized resource-type.");
}
}
/// <summary>Returns a hash code for this resource name.</summary>
public override int GetHashCode() => ToString().GetHashCode();
/// <inheritdoc/>
public override bool Equals(object obj) => Equals(obj as AnnotationSpecSetName);
/// <inheritdoc/>
public bool Equals(AnnotationSpecSetName other) => ToString() == other?.ToString();
/// <inheritdoc/>
public static bool operator ==(AnnotationSpecSetName a, AnnotationSpecSetName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false);
/// <inheritdoc/>
public static bool operator !=(AnnotationSpecSetName a, AnnotationSpecSetName b) => !(a == b);
}
public partial class AnnotationSpecSet
{
/// <summary>
/// <see cref="gcdv::AnnotationSpecSetName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
public gcdv::AnnotationSpecSetName AnnotationSpecSetName
{
get => string.IsNullOrEmpty(Name) ? null : gcdv::AnnotationSpecSetName.Parse(Name, allowUnparsed: true);
set => Name = value?.ToString() ?? "";
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Formatting;
using System.Net.Http.Headers;
using System.Web.Http.Description;
using System.Xml.Linq;
using Newtonsoft.Json;
namespace StudentSystem.Api.Areas.HelpPage
{
/// <summary>
/// This class will generate the samples for the help page.
/// </summary>
public class HelpPageSampleGenerator
{
/// <summary>
/// Initializes a new instance of the <see cref="HelpPageSampleGenerator"/> class.
/// </summary>
public HelpPageSampleGenerator()
{
ActualHttpMessageTypes = new Dictionary<HelpPageSampleKey, Type>();
ActionSamples = new Dictionary<HelpPageSampleKey, object>();
SampleObjects = new Dictionary<Type, object>();
SampleObjectFactories = new List<Func<HelpPageSampleGenerator, Type, object>>
{
DefaultSampleObjectFactory,
};
}
/// <summary>
/// Gets CLR types that are used as the content of <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/>.
/// </summary>
public IDictionary<HelpPageSampleKey, Type> ActualHttpMessageTypes { get; internal set; }
/// <summary>
/// Gets the objects that are used directly as samples for certain actions.
/// </summary>
public IDictionary<HelpPageSampleKey, object> ActionSamples { get; internal set; }
/// <summary>
/// Gets the objects that are serialized as samples by the supported formatters.
/// </summary>
public IDictionary<Type, object> SampleObjects { get; internal set; }
/// <summary>
/// Gets factories for the objects that the supported formatters will serialize as samples. Processed in order,
/// stopping when the factory successfully returns a non-<see langref="null"/> object.
/// </summary>
/// <remarks>
/// Collection includes just <see cref="ObjectGenerator.GenerateObject(Type)"/> initially. Use
/// <code>SampleObjectFactories.Insert(0, func)</code> to provide an override and
/// <code>SampleObjectFactories.Add(func)</code> to provide a fallback.</remarks>
[SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures",
Justification = "This is an appropriate nesting of generic types")]
public IList<Func<HelpPageSampleGenerator, Type, object>> SampleObjectFactories { get; private set; }
/// <summary>
/// Gets the request body samples for a given <see cref="ApiDescription"/>.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The samples keyed by media type.</returns>
public IDictionary<MediaTypeHeaderValue, object> GetSampleRequests(ApiDescription api)
{
return GetSample(api, SampleDirection.Request);
}
/// <summary>
/// Gets the response body samples for a given <see cref="ApiDescription"/>.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The samples keyed by media type.</returns>
public IDictionary<MediaTypeHeaderValue, object> GetSampleResponses(ApiDescription api)
{
return GetSample(api, SampleDirection.Response);
}
/// <summary>
/// Gets the request or response body samples.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param>
/// <returns>The samples keyed by media type.</returns>
public virtual IDictionary<MediaTypeHeaderValue, object> GetSample(ApiDescription api, SampleDirection sampleDirection)
{
if (api == null)
{
throw new ArgumentNullException("api");
}
string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName;
string actionName = api.ActionDescriptor.ActionName;
IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name);
Collection<MediaTypeFormatter> formatters;
Type type = ResolveType(api, controllerName, actionName, parameterNames, sampleDirection, out formatters);
var samples = new Dictionary<MediaTypeHeaderValue, object>();
// Use the samples provided directly for actions
var actionSamples = GetAllActionSamples(controllerName, actionName, parameterNames, sampleDirection);
foreach (var actionSample in actionSamples)
{
samples.Add(actionSample.Key.MediaType, WrapSampleIfString(actionSample.Value));
}
// Do the sample generation based on formatters only if an action doesn't return an HttpResponseMessage.
// Here we cannot rely on formatters because we don't know what's in the HttpResponseMessage, it might not even use formatters.
if (type != null && !typeof(HttpResponseMessage).IsAssignableFrom(type))
{
object sampleObject = GetSampleObject(type);
foreach (var formatter in formatters)
{
foreach (MediaTypeHeaderValue mediaType in formatter.SupportedMediaTypes)
{
if (!samples.ContainsKey(mediaType))
{
object sample = GetActionSample(controllerName, actionName, parameterNames, type, formatter, mediaType, sampleDirection);
// If no sample found, try generate sample using formatter and sample object
if (sample == null && sampleObject != null)
{
sample = WriteSampleObjectUsingFormatter(formatter, sampleObject, type, mediaType);
}
samples.Add(mediaType, WrapSampleIfString(sample));
}
}
}
}
return samples;
}
/// <summary>
/// Search for samples that are provided directly through <see cref="ActionSamples"/>.
/// </summary>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
/// <param name="type">The CLR type.</param>
/// <param name="formatter">The formatter.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param>
/// <returns>The sample that matches the parameters.</returns>
public virtual object GetActionSample(string controllerName, string actionName, IEnumerable<string> parameterNames, Type type, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, SampleDirection sampleDirection)
{
object sample;
// First, try to get the sample provided for the specified mediaType, sampleDirection, controllerName, actionName and parameterNames.
// If not found, try to get the sample provided for the specified mediaType, sampleDirection, controllerName and actionName regardless of the parameterNames.
// If still not found, try to get the sample provided for the specified mediaType and type.
// Finally, try to get the sample provided for the specified mediaType.
if (ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, parameterNames), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, new[] { "*" }), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, type), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType), out sample))
{
return sample;
}
return null;
}
/// <summary>
/// Gets the sample object that will be serialized by the formatters.
/// First, it will look at the <see cref="SampleObjects"/>. If no sample object is found, it will try to create
/// one using <see cref="DefaultSampleObjectFactory"/> (which wraps an <see cref="ObjectGenerator"/>) and other
/// factories in <see cref="SampleObjectFactories"/>.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>The sample object.</returns>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes",
Justification = "Even if all items in SampleObjectFactories throw, problem will be visible as missing sample.")]
public virtual object GetSampleObject(Type type)
{
object sampleObject;
if (!SampleObjects.TryGetValue(type, out sampleObject))
{
// No specific object available, try our factories.
foreach (Func<HelpPageSampleGenerator, Type, object> factory in SampleObjectFactories)
{
if (factory == null)
{
continue;
}
try
{
sampleObject = factory(this, type);
if (sampleObject != null)
{
break;
}
}
catch
{
// Ignore any problems encountered in the factory; go on to the next one (if any).
}
}
}
return sampleObject;
}
/// <summary>
/// Resolves the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The type.</returns>
public virtual Type ResolveHttpRequestMessageType(ApiDescription api)
{
string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName;
string actionName = api.ActionDescriptor.ActionName;
IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name);
Collection<MediaTypeFormatter> formatters;
return ResolveType(api, controllerName, actionName, parameterNames, SampleDirection.Request, out formatters);
}
/// <summary>
/// Resolves the type of the action parameter or return value when <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/> is used.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or a response.</param>
/// <param name="formatters">The formatters.</param>
[SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", Justification = "This is only used in advanced scenarios.")]
public virtual Type ResolveType(ApiDescription api, string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection, out Collection<MediaTypeFormatter> formatters)
{
if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection))
{
throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection));
}
if (api == null)
{
throw new ArgumentNullException("api");
}
Type type;
if (ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, parameterNames), out type) ||
ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, new[] { "*" }), out type))
{
// Re-compute the supported formatters based on type
Collection<MediaTypeFormatter> newFormatters = new Collection<MediaTypeFormatter>();
foreach (var formatter in api.ActionDescriptor.Configuration.Formatters)
{
if (IsFormatSupported(sampleDirection, formatter, type))
{
newFormatters.Add(formatter);
}
}
formatters = newFormatters;
}
else
{
switch (sampleDirection)
{
case SampleDirection.Request:
ApiParameterDescription requestBodyParameter = api.ParameterDescriptions.FirstOrDefault(p => p.Source == ApiParameterSource.FromBody);
type = requestBodyParameter == null ? null : requestBodyParameter.ParameterDescriptor.ParameterType;
formatters = api.SupportedRequestBodyFormatters;
break;
case SampleDirection.Response:
default:
type = api.ResponseDescription.ResponseType ?? api.ResponseDescription.DeclaredType;
formatters = api.SupportedResponseFormatters;
break;
}
}
return type;
}
/// <summary>
/// Writes the sample object using formatter.
/// </summary>
/// <param name="formatter">The formatter.</param>
/// <param name="value">The value.</param>
/// <param name="type">The type.</param>
/// <param name="mediaType">Type of the media.</param>
/// <returns></returns>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as InvalidSample.")]
public virtual object WriteSampleObjectUsingFormatter(MediaTypeFormatter formatter, object value, Type type, MediaTypeHeaderValue mediaType)
{
if (formatter == null)
{
throw new ArgumentNullException("formatter");
}
if (mediaType == null)
{
throw new ArgumentNullException("mediaType");
}
object sample = String.Empty;
MemoryStream ms = null;
HttpContent content = null;
try
{
if (formatter.CanWriteType(type))
{
ms = new MemoryStream();
content = new ObjectContent(type, value, formatter, mediaType);
formatter.WriteToStreamAsync(type, value, ms, content, null).Wait();
ms.Position = 0;
StreamReader reader = new StreamReader(ms);
string serializedSampleString = reader.ReadToEnd();
if (mediaType.MediaType.ToUpperInvariant().Contains("XML"))
{
serializedSampleString = TryFormatXml(serializedSampleString);
}
else if (mediaType.MediaType.ToUpperInvariant().Contains("JSON"))
{
serializedSampleString = TryFormatJson(serializedSampleString);
}
sample = new TextSample(serializedSampleString);
}
else
{
sample = new InvalidSample(String.Format(
CultureInfo.CurrentCulture,
"Failed to generate the sample for media type '{0}'. Cannot use formatter '{1}' to write type '{2}'.",
mediaType,
formatter.GetType().Name,
type.Name));
}
}
catch (Exception e)
{
sample = new InvalidSample(String.Format(
CultureInfo.CurrentCulture,
"An exception has occurred while using the formatter '{0}' to generate sample for media type '{1}'. Exception message: {2}",
formatter.GetType().Name,
mediaType.MediaType,
UnwrapException(e).Message));
}
finally
{
if (ms != null)
{
ms.Dispose();
}
if (content != null)
{
content.Dispose();
}
}
return sample;
}
internal static Exception UnwrapException(Exception exception)
{
AggregateException aggregateException = exception as AggregateException;
if (aggregateException != null)
{
return aggregateException.Flatten().InnerException;
}
return exception;
}
// Default factory for sample objects
private static object DefaultSampleObjectFactory(HelpPageSampleGenerator sampleGenerator, Type type)
{
// Try to create a default sample object
ObjectGenerator objectGenerator = new ObjectGenerator();
return objectGenerator.GenerateObject(type);
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")]
private static string TryFormatJson(string str)
{
try
{
object parsedJson = JsonConvert.DeserializeObject(str);
return JsonConvert.SerializeObject(parsedJson, Formatting.Indented);
}
catch
{
// can't parse JSON, return the original string
return str;
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")]
private static string TryFormatXml(string str)
{
try
{
XDocument xml = XDocument.Parse(str);
return xml.ToString();
}
catch
{
// can't parse XML, return the original string
return str;
}
}
private static bool IsFormatSupported(SampleDirection sampleDirection, MediaTypeFormatter formatter, Type type)
{
switch (sampleDirection)
{
case SampleDirection.Request:
return formatter.CanReadType(type);
case SampleDirection.Response:
return formatter.CanWriteType(type);
}
return false;
}
private IEnumerable<KeyValuePair<HelpPageSampleKey, object>> GetAllActionSamples(string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection)
{
HashSet<string> parameterNamesSet = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase);
foreach (var sample in ActionSamples)
{
HelpPageSampleKey sampleKey = sample.Key;
if (String.Equals(controllerName, sampleKey.ControllerName, StringComparison.OrdinalIgnoreCase) &&
String.Equals(actionName, sampleKey.ActionName, StringComparison.OrdinalIgnoreCase) &&
(sampleKey.ParameterNames.SetEquals(new[] { "*" }) || parameterNamesSet.SetEquals(sampleKey.ParameterNames)) &&
sampleDirection == sampleKey.SampleDirection)
{
yield return sample;
}
}
}
private static object WrapSampleIfString(object sample)
{
string stringSample = sample as string;
if (stringSample != null)
{
return new TextSample(stringSample);
}
return sample;
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Collections.Generic;
using System.Collections;
using System.ComponentModel;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Net;
using System.Runtime.InteropServices;
using System.Threading.Tasks;
using System.Threading;
namespace System.Net.Sockets
{
internal static class SocketPal
{
public const bool SupportsMultipleConnectAttempts = true;
private readonly static int s_protocolInformationSize = Marshal.SizeOf<Interop.Winsock.WSAPROTOCOL_INFO>();
public static int ProtocolInformationSize { get { return s_protocolInformationSize; } }
private static void MicrosecondsToTimeValue(long microseconds, ref Interop.Winsock.TimeValue socketTime)
{
const int microcnv = 1000000;
socketTime.Seconds = (int)(microseconds / microcnv);
socketTime.Microseconds = (int)(microseconds % microcnv);
}
public static SocketError GetLastSocketError()
{
return (SocketError)Marshal.GetLastWin32Error();
}
public static SocketError CreateSocket(AddressFamily addressFamily, SocketType socketType, ProtocolType protocolType, out SafeCloseSocket socket)
{
socket = SafeCloseSocket.CreateWSASocket(addressFamily, socketType, protocolType);
return socket.IsInvalid ? GetLastSocketError() : SocketError.Success;
}
public static SocketError SetBlocking(SafeCloseSocket handle, bool shouldBlock, out bool willBlock)
{
int intBlocking = shouldBlock ? 0 : -1;
SocketError errorCode;
errorCode = Interop.Winsock.ioctlsocket(
handle,
Interop.Winsock.IoctlSocketConstants.FIONBIO,
ref intBlocking);
if (errorCode == SocketError.SocketError)
{
errorCode = (SocketError)Marshal.GetLastWin32Error();
}
willBlock = intBlocking == 0;
return errorCode;
}
public static SocketError GetSockName(SafeCloseSocket handle, byte[] buffer, ref int nameLen)
{
SocketError errorCode = Interop.Winsock.getsockname(handle, buffer, ref nameLen);
return errorCode == SocketError.SocketError ? GetLastSocketError() : SocketError.Success;
}
public static SocketError GetAvailable(SafeCloseSocket handle, out int available)
{
int value = 0;
SocketError errorCode = Interop.Winsock.ioctlsocket(
handle,
Interop.Winsock.IoctlSocketConstants.FIONREAD,
ref value);
available = value;
return errorCode == SocketError.SocketError ? GetLastSocketError() : SocketError.Success;
}
public static SocketError GetPeerName(SafeCloseSocket handle, byte[] buffer, ref int nameLen)
{
SocketError errorCode = Interop.Winsock.getpeername(handle, buffer, ref nameLen);
return errorCode == SocketError.SocketError ? GetLastSocketError() : SocketError.Success;
}
public static SocketError Bind(SafeCloseSocket handle, byte[] buffer, int nameLen)
{
SocketError errorCode = Interop.Winsock.bind(handle, buffer, nameLen);
return errorCode == SocketError.SocketError ? GetLastSocketError() : SocketError.Success;
}
public static SocketError Listen(SafeCloseSocket handle, int backlog)
{
SocketError errorCode = Interop.Winsock.listen(handle, backlog);
return errorCode == SocketError.SocketError ? GetLastSocketError() : SocketError.Success;
}
public static SocketError Accept(SafeCloseSocket handle, byte[] buffer, ref int nameLen, out SafeCloseSocket socket)
{
socket = SafeCloseSocket.Accept(handle, buffer, ref nameLen);
return socket.IsInvalid ? GetLastSocketError() : SocketError.Success;
}
public static SocketError Connect(SafeCloseSocket handle, byte[] peerAddress, int peerAddressLen)
{
SocketError errorCode = Interop.Winsock.WSAConnect(
handle.DangerousGetHandle(),
peerAddress,
peerAddressLen,
IntPtr.Zero,
IntPtr.Zero,
IntPtr.Zero,
IntPtr.Zero);
return errorCode == SocketError.SocketError ? GetLastSocketError() : SocketError.Success;
}
public static SocketError Send(SafeCloseSocket handle, IList<ArraySegment<byte>> buffers, SocketFlags socketFlags, out int bytesTransferred)
{
int count = buffers.Count;
WSABuffer[] WSABuffers = new WSABuffer[count];
GCHandle[] objectsToPin = null;
try
{
objectsToPin = new GCHandle[count];
for (int i = 0; i < count; ++i)
{
ArraySegment<byte> buffer = buffers[i];
RangeValidationHelpers.ValidateSegment(buffer);
objectsToPin[i] = GCHandle.Alloc(buffer.Array, GCHandleType.Pinned);
WSABuffers[i].Length = buffer.Count;
WSABuffers[i].Pointer = Marshal.UnsafeAddrOfPinnedArrayElement(buffer.Array, buffer.Offset);
}
// This may throw ObjectDisposedException.
SocketError errorCode = Interop.Winsock.WSASend_Blocking(
handle.DangerousGetHandle(),
WSABuffers,
count,
out bytesTransferred,
socketFlags,
SafeNativeOverlapped.Zero,
IntPtr.Zero);
if ((SocketError)errorCode == SocketError.SocketError)
{
errorCode = (SocketError)Marshal.GetLastWin32Error();
}
return errorCode;
}
finally
{
if (objectsToPin != null)
{
for (int i = 0; i < objectsToPin.Length; ++i)
{
if (objectsToPin[i].IsAllocated)
{
objectsToPin[i].Free();
}
}
}
}
}
public static unsafe SocketError Send(SafeCloseSocket handle, byte[] buffer, int offset, int size, SocketFlags socketFlags, out int bytesTransferred)
{
int bytesSent;
if (buffer.Length == 0)
{
bytesSent = Interop.Winsock.send(handle.DangerousGetHandle(), null, 0, socketFlags);
}
else
{
fixed (byte* pinnedBuffer = buffer)
{
bytesSent = Interop.Winsock.send(
handle.DangerousGetHandle(),
pinnedBuffer + offset,
size,
socketFlags);
}
}
if (bytesSent == (int)SocketError.SocketError)
{
bytesTransferred = 0;
return GetLastSocketError();
}
bytesTransferred = bytesSent;
return SocketError.Success;
}
public static unsafe SocketError SendTo(SafeCloseSocket handle, byte[] buffer, int offset, int size, SocketFlags socketFlags, byte[] peerAddress, int peerAddressSize, out int bytesTransferred)
{
int bytesSent;
if (buffer.Length == 0)
{
bytesSent = Interop.Winsock.sendto(
handle.DangerousGetHandle(),
null,
0,
socketFlags,
peerAddress,
peerAddressSize);
}
else
{
fixed (byte* pinnedBuffer = buffer)
{
bytesSent = Interop.Winsock.sendto(
handle.DangerousGetHandle(),
pinnedBuffer + offset,
size,
socketFlags,
peerAddress,
peerAddressSize);
}
}
if (bytesSent == (int)SocketError.SocketError)
{
bytesTransferred = 0;
return GetLastSocketError();
}
bytesTransferred = bytesSent;
return SocketError.Success;
}
public static SocketError Receive(SafeCloseSocket handle, IList<ArraySegment<byte>> buffers, ref SocketFlags socketFlags, out int bytesTransferred)
{
int count = buffers.Count;
WSABuffer[] WSABuffers = new WSABuffer[count];
GCHandle[] objectsToPin = null;
try
{
objectsToPin = new GCHandle[count];
for (int i = 0; i < count; ++i)
{
ArraySegment<byte> buffer = buffers[i];
RangeValidationHelpers.ValidateSegment(buffer);
objectsToPin[i] = GCHandle.Alloc(buffer.Array, GCHandleType.Pinned);
WSABuffers[i].Length = buffer.Count;
WSABuffers[i].Pointer = Marshal.UnsafeAddrOfPinnedArrayElement(buffer.Array, buffer.Offset);
}
// This can throw ObjectDisposedException.
SocketError errorCode = Interop.Winsock.WSARecv_Blocking(
handle.DangerousGetHandle(),
WSABuffers,
count,
out bytesTransferred,
ref socketFlags,
SafeNativeOverlapped.Zero,
IntPtr.Zero);
if ((SocketError)errorCode == SocketError.SocketError)
{
errorCode = (SocketError)Marshal.GetLastWin32Error();
}
return errorCode;
}
finally
{
if (objectsToPin != null)
{
for (int i = 0; i < objectsToPin.Length; ++i)
{
if (objectsToPin[i].IsAllocated)
{
objectsToPin[i].Free();
}
}
}
}
}
public static unsafe SocketError Receive(SafeCloseSocket handle, byte[] buffer, int offset, int size, SocketFlags socketFlags, out int bytesTransferred)
{
int bytesReceived;
if (buffer.Length == 0)
{
bytesReceived = Interop.Winsock.recv(handle.DangerousGetHandle(), null, 0, socketFlags);
}
else
{
fixed (byte* pinnedBuffer = buffer)
{
bytesReceived = Interop.Winsock.recv(handle.DangerousGetHandle(), pinnedBuffer + offset, size, socketFlags);
}
}
if (bytesReceived == (int)SocketError.SocketError)
{
bytesTransferred = 0;
return GetLastSocketError();
}
bytesTransferred = bytesReceived;
return SocketError.Success;
}
public static SocketError ReceiveMessageFrom(Socket socket, SafeCloseSocket handle, byte[] buffer, int offset, int size, ref SocketFlags socketFlags, Internals.SocketAddress socketAddress, out Internals.SocketAddress receiveAddress, out IPPacketInformation ipPacketInformation, out int bytesTransferred)
{
ReceiveMessageOverlappedAsyncResult asyncResult = new ReceiveMessageOverlappedAsyncResult(socket, null, null);
asyncResult.SetUnmanagedStructures(buffer, offset, size, socketAddress, socketFlags);
SocketError errorCode = SocketError.Success;
bytesTransferred = 0;
try
{
// This can throw ObjectDisposedException (retrieving the delegate AND resolving the handle).
if (socket.WSARecvMsgBlocking(
handle.DangerousGetHandle(),
Marshal.UnsafeAddrOfPinnedArrayElement(asyncResult._messageBuffer, 0),
out bytesTransferred,
IntPtr.Zero,
IntPtr.Zero) == SocketError.SocketError)
{
errorCode = (SocketError)Marshal.GetLastWin32Error();
}
}
finally
{
asyncResult.SyncReleaseUnmanagedStructures();
}
socketFlags = asyncResult.SocketFlags;
receiveAddress = asyncResult.SocketAddress;
ipPacketInformation = asyncResult.IPPacketInformation;
return errorCode;
}
public static unsafe SocketError ReceiveFrom(SafeCloseSocket handle, byte[] buffer, int offset, int size, SocketFlags socketFlags, byte[] socketAddress, ref int addressLength, out int bytesTransferred)
{
int bytesReceived;
if (buffer.Length == 0)
{
bytesReceived = Interop.Winsock.recvfrom(handle.DangerousGetHandle(), null, 0, socketFlags, socketAddress, ref addressLength);
}
else
{
fixed (byte* pinnedBuffer = buffer)
{
bytesReceived = Interop.Winsock.recvfrom(handle.DangerousGetHandle(), pinnedBuffer + offset, size, socketFlags, socketAddress, ref addressLength);
}
}
if (bytesReceived == (int)SocketError.SocketError)
{
bytesTransferred = 0;
return GetLastSocketError();
}
bytesTransferred = bytesReceived;
return SocketError.Success;
}
public static SocketError Ioctl(SafeCloseSocket handle, int ioControlCode, byte[] optionInValue, byte[] optionOutValue, out int optionLength)
{
if (ioControlCode == Interop.Winsock.IoctlSocketConstants.FIONBIO)
{
throw new InvalidOperationException(SR.net_sockets_useblocking);
}
SocketError errorCode = Interop.Winsock.WSAIoctl_Blocking(
handle.DangerousGetHandle(),
ioControlCode,
optionInValue,
optionInValue != null ? optionInValue.Length : 0,
optionOutValue,
optionOutValue != null ? optionOutValue.Length : 0,
out optionLength,
SafeNativeOverlapped.Zero,
IntPtr.Zero);
return errorCode == SocketError.SocketError ? GetLastSocketError() : SocketError.Success;
}
public static SocketError IoctlInternal(SafeCloseSocket handle, IOControlCode ioControlCode, IntPtr optionInValue, int inValueLength, IntPtr optionOutValue, int outValueLength, out int optionLength)
{
if ((unchecked((int)ioControlCode)) == Interop.Winsock.IoctlSocketConstants.FIONBIO)
{
throw new InvalidOperationException(SR.net_sockets_useblocking);
}
SocketError errorCode = Interop.Winsock.WSAIoctl_Blocking_Internal(
handle.DangerousGetHandle(),
(uint)ioControlCode,
optionInValue,
inValueLength,
optionOutValue,
outValueLength,
out optionLength,
SafeNativeOverlapped.Zero,
IntPtr.Zero);
return errorCode == SocketError.SocketError ? GetLastSocketError() : SocketError.Success;
}
public static unsafe SocketError SetSockOpt(SafeCloseSocket handle, SocketOptionLevel optionLevel, SocketOptionName optionName, int optionValue)
{
SocketError errorCode = Interop.Winsock.setsockopt(
handle,
optionLevel,
optionName,
ref optionValue,
sizeof(int));
return errorCode == SocketError.SocketError ? GetLastSocketError() : SocketError.Success;
}
public static SocketError SetSockOpt(SafeCloseSocket handle, SocketOptionLevel optionLevel, SocketOptionName optionName, byte[] optionValue)
{
SocketError errorCode = Interop.Winsock.setsockopt(
handle,
optionLevel,
optionName,
optionValue,
optionValue != null ? optionValue.Length : 0);
return errorCode == SocketError.SocketError ? GetLastSocketError() : SocketError.Success;
}
public static void SetReceivingDualModeIPv4PacketInformation(Socket socket)
{
socket.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.PacketInformation, true);
}
public static SocketError SetMulticastOption(SafeCloseSocket handle, SocketOptionName optionName, MulticastOption optionValue)
{
Interop.Winsock.IPMulticastRequest ipmr = new Interop.Winsock.IPMulticastRequest();
ipmr.MulticastAddress = unchecked((int)optionValue.Group.GetAddress());
if (optionValue.LocalAddress != null)
{
ipmr.InterfaceAddress = unchecked((int)optionValue.LocalAddress.GetAddress());
}
else
{ //this structure works w/ interfaces as well
int ifIndex = IPAddress.HostToNetworkOrder(optionValue.InterfaceIndex);
ipmr.InterfaceAddress = unchecked((int)ifIndex);
}
#if BIGENDIAN
ipmr.MulticastAddress = (int) (((uint) ipmr.MulticastAddress << 24) |
(((uint) ipmr.MulticastAddress & 0x0000FF00) << 8) |
(((uint) ipmr.MulticastAddress >> 8) & 0x0000FF00) |
((uint) ipmr.MulticastAddress >> 24));
if (optionValue.LocalAddress != null)
{
ipmr.InterfaceAddress = (int) (((uint) ipmr.InterfaceAddress << 24) |
(((uint) ipmr.InterfaceAddress & 0x0000FF00) << 8) |
(((uint) ipmr.InterfaceAddress >> 8) & 0x0000FF00) |
((uint) ipmr.InterfaceAddress >> 24));
}
#endif
// This can throw ObjectDisposedException.
SocketError errorCode = Interop.Winsock.setsockopt(
handle,
SocketOptionLevel.IP,
optionName,
ref ipmr,
Interop.Winsock.IPMulticastRequest.Size);
return errorCode == SocketError.SocketError ? GetLastSocketError() : SocketError.Success;
}
public static SocketError SetIPv6MulticastOption(SafeCloseSocket handle, SocketOptionName optionName, IPv6MulticastOption optionValue)
{
Interop.Winsock.IPv6MulticastRequest ipmr = new Interop.Winsock.IPv6MulticastRequest();
ipmr.MulticastAddress = optionValue.Group.GetAddressBytes();
ipmr.InterfaceIndex = unchecked((int)optionValue.InterfaceIndex);
// This can throw ObjectDisposedException.
SocketError errorCode = Interop.Winsock.setsockopt(
handle,
SocketOptionLevel.IPv6,
optionName,
ref ipmr,
Interop.Winsock.IPv6MulticastRequest.Size);
return errorCode == SocketError.SocketError ? GetLastSocketError() : SocketError.Success;
}
public static SocketError SetLingerOption(SafeCloseSocket handle, LingerOption optionValue)
{
Interop.Winsock.Linger lngopt = new Interop.Winsock.Linger();
lngopt.OnOff = optionValue.Enabled ? (ushort)1 : (ushort)0;
lngopt.Time = (ushort)optionValue.LingerTime;
// This can throw ObjectDisposedException.
SocketError errorCode = Interop.Winsock.setsockopt(
handle,
SocketOptionLevel.Socket,
SocketOptionName.Linger,
ref lngopt,
4);
return errorCode == SocketError.SocketError ? GetLastSocketError() : SocketError.Success;
}
public static SocketError GetSockOpt(SafeCloseSocket handle, SocketOptionLevel optionLevel, SocketOptionName optionName, out int optionValue)
{
int optionLength = 4; // sizeof(int)
SocketError errorCode = Interop.Winsock.getsockopt(
handle,
optionLevel,
optionName,
out optionValue,
ref optionLength);
return errorCode == SocketError.SocketError ? GetLastSocketError() : SocketError.Success;
}
public static SocketError GetSockOpt(SafeCloseSocket handle, SocketOptionLevel optionLevel, SocketOptionName optionName, byte[] optionValue, ref int optionLength)
{
SocketError errorCode = Interop.Winsock.getsockopt(
handle,
optionLevel,
optionName,
optionValue,
ref optionLength);
return errorCode == SocketError.SocketError ? GetLastSocketError() : SocketError.Success;
}
public static SocketError GetMulticastOption(SafeCloseSocket handle, SocketOptionName optionName, out MulticastOption optionValue)
{
Interop.Winsock.IPMulticastRequest ipmr = new Interop.Winsock.IPMulticastRequest();
int optlen = Interop.Winsock.IPMulticastRequest.Size;
// This can throw ObjectDisposedException.
SocketError errorCode = Interop.Winsock.getsockopt(
handle,
SocketOptionLevel.IP,
optionName,
out ipmr,
ref optlen);
if (errorCode == SocketError.SocketError)
{
optionValue = default(MulticastOption);
return GetLastSocketError();
}
#if BIGENDIAN
ipmr.MulticastAddress = (int) (((uint) ipmr.MulticastAddress << 24) |
(((uint) ipmr.MulticastAddress & 0x0000FF00) << 8) |
(((uint) ipmr.MulticastAddress >> 8) & 0x0000FF00) |
((uint) ipmr.MulticastAddress >> 24));
ipmr.InterfaceAddress = (int) (((uint) ipmr.InterfaceAddress << 24) |
(((uint) ipmr.InterfaceAddress & 0x0000FF00) << 8) |
(((uint) ipmr.InterfaceAddress >> 8) & 0x0000FF00) |
((uint) ipmr.InterfaceAddress >> 24));
#endif // BIGENDIAN
IPAddress multicastAddr = new IPAddress(ipmr.MulticastAddress);
IPAddress multicastIntr = new IPAddress(ipmr.InterfaceAddress);
optionValue = new MulticastOption(multicastAddr, multicastIntr);
return SocketError.Success;
}
public static SocketError GetIPv6MulticastOption(SafeCloseSocket handle, SocketOptionName optionName, out IPv6MulticastOption optionValue)
{
Interop.Winsock.IPv6MulticastRequest ipmr = new Interop.Winsock.IPv6MulticastRequest();
int optlen = Interop.Winsock.IPv6MulticastRequest.Size;
// This can throw ObjectDisposedException.
SocketError errorCode = Interop.Winsock.getsockopt(
handle,
SocketOptionLevel.IP,
optionName,
out ipmr,
ref optlen);
if (errorCode == SocketError.SocketError)
{
optionValue = default(IPv6MulticastOption);
return GetLastSocketError();
}
optionValue = new IPv6MulticastOption(new IPAddress(ipmr.MulticastAddress), ipmr.InterfaceIndex);
return SocketError.Success;
}
public static SocketError GetLingerOption(SafeCloseSocket handle, out LingerOption optionValue)
{
Interop.Winsock.Linger lngopt = new Interop.Winsock.Linger();
int optlen = 4;
// This can throw ObjectDisposedException.
SocketError errorCode = Interop.Winsock.getsockopt(
handle,
SocketOptionLevel.Socket,
SocketOptionName.Linger,
out lngopt,
ref optlen);
if (errorCode == SocketError.SocketError)
{
optionValue = default(LingerOption);
return GetLastSocketError();
}
optionValue = new LingerOption(lngopt.OnOff != 0, (int)lngopt.Time);
return SocketError.Success;
}
public static SocketError Poll(SafeCloseSocket handle, int microseconds, SelectMode mode, out bool status)
{
IntPtr rawHandle = handle.DangerousGetHandle();
IntPtr[] fileDescriptorSet = new IntPtr[2] { (IntPtr)1, rawHandle };
Interop.Winsock.TimeValue IOwait = new Interop.Winsock.TimeValue();
// A negative timeout value implies an indefinite wait.
int socketCount;
if (microseconds != -1)
{
MicrosecondsToTimeValue((long)(uint)microseconds, ref IOwait);
socketCount =
Interop.Winsock.select(
0,
mode == SelectMode.SelectRead ? fileDescriptorSet : null,
mode == SelectMode.SelectWrite ? fileDescriptorSet : null,
mode == SelectMode.SelectError ? fileDescriptorSet : null,
ref IOwait);
}
else
{
socketCount =
Interop.Winsock.select(
0,
mode == SelectMode.SelectRead ? fileDescriptorSet : null,
mode == SelectMode.SelectWrite ? fileDescriptorSet : null,
mode == SelectMode.SelectError ? fileDescriptorSet : null,
IntPtr.Zero);
}
if ((SocketError)socketCount == SocketError.SocketError)
{
status = false;
return GetLastSocketError();
}
status = (int)fileDescriptorSet[0] != 0 && fileDescriptorSet[1] == rawHandle;
return SocketError.Success;
}
public static SocketError Select(IList checkRead, IList checkWrite, IList checkError, int microseconds)
{
IntPtr[] readfileDescriptorSet = Socket.SocketListToFileDescriptorSet(checkRead);
IntPtr[] writefileDescriptorSet = Socket.SocketListToFileDescriptorSet(checkWrite);
IntPtr[] errfileDescriptorSet = Socket.SocketListToFileDescriptorSet(checkError);
// This code used to erroneously pass a non-null timeval structure containing zeroes
// to select() when the caller specified (-1) for the microseconds parameter. That
// caused select to actually have a *zero* timeout instead of an infinite timeout
// turning the operation into a non-blocking poll.
//
// Now we pass a null timeval struct when microseconds is (-1).
//
// Negative microsecond values that weren't exactly (-1) were originally successfully
// converted to a timeval struct containing unsigned non-zero integers. This code
// retains that behavior so that any app working around the original bug with,
// for example, (-2) specified for microseconds, will continue to get the same behavior.
int socketCount;
if (microseconds != -1)
{
Interop.Winsock.TimeValue IOwait = new Interop.Winsock.TimeValue();
MicrosecondsToTimeValue((long)(uint)microseconds, ref IOwait);
socketCount =
Interop.Winsock.select(
0, // ignored value
readfileDescriptorSet,
writefileDescriptorSet,
errfileDescriptorSet,
ref IOwait);
}
else
{
socketCount =
Interop.Winsock.select(
0, // ignored value
readfileDescriptorSet,
writefileDescriptorSet,
errfileDescriptorSet,
IntPtr.Zero);
}
GlobalLog.Print("Socket::Select() Interop.Winsock.select returns socketCount:" + socketCount);
if ((SocketError)socketCount == SocketError.SocketError)
{
return GetLastSocketError();
}
Socket.SelectFileDescriptor(checkRead, readfileDescriptorSet);
Socket.SelectFileDescriptor(checkWrite, writefileDescriptorSet);
Socket.SelectFileDescriptor(checkError, errfileDescriptorSet);
return SocketError.Success;
}
public static SocketError Shutdown(SafeCloseSocket handle, bool isConnected, bool isDisconnected, SocketShutdown how)
{
SocketError err = Interop.Winsock.shutdown(handle, (int)how);
if (err != SocketError.SocketError)
{
return SocketError.Success;
}
err = GetLastSocketError();
Debug.Assert(err != SocketError.NotConnected || (!isConnected && !isDisconnected));
return err;
}
public static unsafe SocketError ConnectAsync(Socket socket, SafeCloseSocket handle, byte[] socketAddress, int socketAddressLen, ConnectOverlappedAsyncResult asyncResult)
{
// This will pin the socketAddress buffer.
asyncResult.SetUnmanagedStructures(socketAddress);
int ignoreBytesSent;
if (!socket.ConnectEx(
handle,
Marshal.UnsafeAddrOfPinnedArrayElement(socketAddress, 0),
socketAddressLen,
IntPtr.Zero,
0,
out ignoreBytesSent,
asyncResult.OverlappedHandle))
{
return GetLastSocketError();
}
return SocketError.Success;
}
public static unsafe SocketError SendAsync(SafeCloseSocket handle, byte[] buffer, int offset, int count, SocketFlags socketFlags, OverlappedAsyncResult asyncResult)
{
// Set up asyncResult for overlapped WSASend.
// This call will use completion ports.
asyncResult.SetUnmanagedStructures(buffer, offset, count, null, false /*don't pin null remoteEP*/);
// This can throw ObjectDisposedException.
int bytesTransferred;
SocketError errorCode = Interop.Winsock.WSASend(
handle,
ref asyncResult._singleBuffer,
1, // There is only ever 1 buffer being sent.
out bytesTransferred,
socketFlags,
asyncResult.OverlappedHandle,
IntPtr.Zero);
if (errorCode != SocketError.Success)
{
errorCode = GetLastSocketError();
}
return errorCode;
}
public static unsafe SocketError SendAsync(SafeCloseSocket handle, IList<ArraySegment<byte>> buffers, SocketFlags socketFlags, OverlappedAsyncResult asyncResult)
{
// Set up asyncResult for overlapped WSASend.
// This call will use completion ports.
asyncResult.SetUnmanagedStructures(buffers);
// This can throw ObjectDisposedException.
int bytesTransferred;
SocketError errorCode = Interop.Winsock.WSASend(
handle,
asyncResult._wsaBuffers,
asyncResult._wsaBuffers.Length,
out bytesTransferred,
socketFlags,
asyncResult.OverlappedHandle,
IntPtr.Zero);
if (errorCode != SocketError.Success)
{
errorCode = GetLastSocketError();
}
return errorCode;
}
public static unsafe SocketError SendToAsync(SafeCloseSocket handle, byte[] buffer, int offset, int count, SocketFlags socketFlags, Internals.SocketAddress socketAddress, OverlappedAsyncResult asyncResult)
{
// Set up asyncResult for overlapped WSASendTo.
// This call will use completion ports.
asyncResult.SetUnmanagedStructures(buffer, offset, count, socketAddress, false /* don't pin RemoteEP*/);
int bytesTransferred;
SocketError errorCode = Interop.Winsock.WSASendTo(
handle,
ref asyncResult._singleBuffer,
1, // There is only ever 1 buffer being sent.
out bytesTransferred,
socketFlags,
asyncResult.GetSocketAddressPtr(),
asyncResult.SocketAddress.Size,
asyncResult.OverlappedHandle,
IntPtr.Zero);
if (errorCode != SocketError.Success)
{
errorCode = GetLastSocketError();
}
return errorCode;
}
public static unsafe SocketError ReceiveAsync(SafeCloseSocket handle, byte[] buffer, int offset, int count, SocketFlags socketFlags, OverlappedAsyncResult asyncResult)
{
// Set up asyncResult for overlapped WSARecv.
// This call will use completion ports.
asyncResult.SetUnmanagedStructures(buffer, offset, count, null, false /* don't pin null RemoteEP*/);
// This can throw ObjectDisposedException.
int bytesTransferred;
SocketError errorCode = Interop.Winsock.WSARecv(
handle,
ref asyncResult._singleBuffer,
1,
out bytesTransferred,
ref socketFlags,
asyncResult.OverlappedHandle,
IntPtr.Zero);
if (errorCode != SocketError.Success)
{
errorCode = GetLastSocketError();
}
return errorCode;
}
public static unsafe SocketError ReceiveAsync(SafeCloseSocket handle, IList<ArraySegment<byte>> buffers, SocketFlags socketFlags, OverlappedAsyncResult asyncResult)
{
// Set up asyncResult for overlapped WSASend.
// This call will use completion ports.
asyncResult.SetUnmanagedStructures(buffers);
// This can throw ObjectDisposedException.
int bytesTransferred;
SocketError errorCode = Interop.Winsock.WSARecv(
handle,
asyncResult._wsaBuffers,
asyncResult._wsaBuffers.Length,
out bytesTransferred,
ref socketFlags,
asyncResult.OverlappedHandle,
IntPtr.Zero);
if (errorCode != SocketError.Success)
{
errorCode = GetLastSocketError();
}
return errorCode;
}
public static unsafe SocketError ReceiveFromAsync(SafeCloseSocket handle, byte[] buffer, int offset, int count, SocketFlags socketFlags, Internals.SocketAddress socketAddress, OverlappedAsyncResult asyncResult)
{
// Set up asyncResult for overlapped WSARecvFrom.
// This call will use completion ports on WinNT and Overlapped IO on Win9x.
asyncResult.SetUnmanagedStructures(buffer, offset, count, socketAddress, true);
int bytesTransferred;
SocketError errorCode = Interop.Winsock.WSARecvFrom(
handle,
ref asyncResult._singleBuffer,
1,
out bytesTransferred,
ref socketFlags,
asyncResult.GetSocketAddressPtr(),
asyncResult.GetSocketAddressSizePtr(),
asyncResult.OverlappedHandle,
IntPtr.Zero);
if (errorCode != SocketError.Success)
{
errorCode = GetLastSocketError();
}
return errorCode;
}
public static unsafe SocketError ReceiveMessageFromAsync(Socket socket, SafeCloseSocket handle, byte[] buffer, int offset, int count, SocketFlags socketFlags, Internals.SocketAddress socketAddress, ReceiveMessageOverlappedAsyncResult asyncResult)
{
asyncResult.SetUnmanagedStructures(buffer, offset, count, socketAddress, socketFlags);
int bytesTransfered;
SocketError errorCode = (SocketError)socket.WSARecvMsg(
handle,
Marshal.UnsafeAddrOfPinnedArrayElement(asyncResult._messageBuffer, 0),
out bytesTransfered,
asyncResult.OverlappedHandle,
IntPtr.Zero);
if (errorCode != SocketError.Success)
{
errorCode = GetLastSocketError();
}
return errorCode;
}
public static unsafe SocketError AcceptAsync(Socket socket, SafeCloseSocket handle, SafeCloseSocket acceptHandle, int receiveSize, int socketAddressSize, AcceptOverlappedAsyncResult asyncResult)
{
// The buffer needs to contain the requested data plus room for two sockaddrs and 16 bytes
// of associated data for each.
int addressBufferSize = socketAddressSize + 16;
byte[] buffer = new byte[receiveSize + ((addressBufferSize) * 2)];
// Set up asyncResult for overlapped AcceptEx.
// This call will use completion ports on WinNT.
asyncResult.SetUnmanagedStructures(buffer, addressBufferSize);
// This can throw ObjectDisposedException.
int bytesTransferred;
SocketError errorCode = SocketError.Success;
if (!socket.AcceptEx(
handle,
acceptHandle,
Marshal.UnsafeAddrOfPinnedArrayElement(asyncResult.Buffer, 0),
receiveSize,
addressBufferSize,
addressBufferSize,
out bytesTransferred,
asyncResult.OverlappedHandle))
{
errorCode = GetLastSocketError();
}
return errorCode;
}
}
}
| |
/*
* Copyright (c) 2014 Behrooz Amoozad
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the bd2 nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARm E IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL Behrooz Amoozad BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
* */
using System;
using System.Collections.Generic;
using System.Security.Cryptography;
using Mono.Security.Cryptography;
using BD2.Core;
using System.Diagnostics.SymbolStore;
using System.IO;
using System.Runtime.InteropServices.ComTypes;
using System.Reflection.Emit;
using System.Globalization;
using CSharpTest.Net.Collections;
namespace BD2.Core
{
public sealed class Database
{
public string Name {
get {
return System.Text.Encoding.Unicode.GetString (userStorage.GetMetaData (System.Text.Encoding.Unicode.GetBytes ("Name")));
}
}
public event ChunkRepositoryAddedEventHandler ChunkRepositoryAdded;
readonly UserStorageBase userStorage;
readonly SortedDictionary<byte[], ChunkRepository> dataStorage = new SortedDictionary<byte[], ChunkRepository> (ByteSequenceComparer.Shared);
readonly SortedDictionary<string, FrontendBase> frontends = new SortedDictionary<string, FrontendBase> ();
//readonly SortedSet<DataContext> frontendInstances = new SortedSet<DataContext> ();
readonly EncryptedStorageManager encryptedStorageManager;
public UserStorageBase UserStorage {
get {
return userStorage;
}
}
public SortedDictionary<byte[], ChunkRepository> DataStorage {
get {
return dataStorage;
}
}
//byte[] DefaultStorage { get; set; }
//
// public IEnumerable<DataContext> FrontendInstances {
// get {
// return new SortedSet<DataContext> (frontendInstances);
// }
// }
public IEnumerable<KeyValuePair<byte[], string>> GetUsers ()
{
return userStorage.GetUsers ();
}
public bool VerifyPassword (UserCredentials user, string pepper)
{
return userStorage.VerifyPassword (user, pepper);
}
DatabasePath GetRepositoryPath (byte[] id)
{
return new DatabasePath (basePath + Path.DirectorySeparatorChar + id.ToHexadecimal ());
}
void LoadUserStorageBase (byte[] userID, byte[] ur)
{
Log.WriteLine ("Database.LoadUserStorageBase()");
{
byte[] repoInfo = userStorage.GetRawRepositoryInfo (ur);
Log.WriteLine ("Raw Repository info:{0}", repoInfo.ToHexadecimal ());
System.Xml.Serialization.XmlSerializer xmls = new System.Xml.Serialization.XmlSerializer (typeof(ChunkRepositoryConfiguration));
ChunkRepositoryConfiguration cri = (ChunkRepositoryConfiguration)xmls.Deserialize (new MemoryStream (repoInfo, false));
Log.WriteLine ("Repository info id:{0}", cri.ID);
DatabasePath dbp = GetRepositoryPath (cri.ID);
if (dataStorage.ContainsKey (ur)) {
Log.WriteLine ("repo {0} is already loaded. loading encrypted parts with new keys.", ur);
foreach (var sk in userStorage.GetUserStorage (userID).SymmetricKeys) {
if (!dataStorage [ur].LencryptedData.ContainsKey (sk.Key)) {
Log.WriteLine ("loading key {0}", sk.Key.ToHexadecimal ());
KeyValueStorageConfiguration ESC = new KeyValueStorageConfiguration ();
ESC.Type = cri.Data.Type;
ESC.Path = sk.Key.ToHexadecimal ();
dataStorage [ur].LencryptedData.Add (sk.Key, new AESEncryptingKeyValueStorage (ESC.OpenStorage<byte[]> (dbp.CreatePath ("Encrypted")), sk.Value));
}
}
} else {
SortedDictionary<byte[], KeyValueStorage<byte[]>> EncryptedData = new SortedDictionary<byte[], KeyValueStorage<byte[]>> ();
foreach (var sk in userStorage.GetUserStorage (userID).SymmetricKeys) {
KeyValueStorageConfiguration ESC = new KeyValueStorageConfiguration ();
ESC.Type = cri.Data.Type;
ESC.Path = sk.Key.ToHexadecimal ();
EncryptedData.Add (sk.Key, new AESEncryptingKeyValueStorage (ESC.OpenStorage<byte[]> (dbp.CreatePath ("Encrypted")), sk.Value));
}
ChunkRepository cr = new ChunkRepository (cri.ID, cri.Data.OpenStorage<byte[]> (dbp), cri.TopLevels.OpenStorage<byte[][]> (dbp), cri.Dependencies.OpenStorage<byte[][]> (dbp), cri.Meta.OpenStorage<byte[]> (dbp), cri.MetaTopLevels.OpenStorage<byte[][]> (dbp), cri.MetaDependencies.OpenStorage<byte[][]> (dbp), cri.Signatures.OpenStorage<byte[][]> (dbp), cri.ChunkSymmetricKeys.OpenStorage<byte[][]> (dbp), cri.Index.OpenStorage<byte[]> (dbp), cri.InternalMeta.OpenStorage<byte[]> (dbp), EncryptedData);
dataStorage.Add (cr.ID, cr);
ChunkRepositoryAdded (this, new ChunkRepositoryAddedEventArgs (cr));
}
//encryptedStorageManager.Add (ur, new EncryptedStorageManager (cr, userStorage));
}
{
byte[] cus = userStorage.GetCommonStorage ();
Log.WriteLine ("Common storage id is {0}", cus.ToHexadecimal ());
if (!dataStorage.ContainsKey (cus)) {
Log.WriteLine ("and we don't have it.");
Log.WriteLine ("we only have:");
foreach (var t in dataStorage)
Log.WriteLine (" ID: {0}", t.Key.ToHexadecimal ());
throw new NotImplementedException ();
byte[] repoInfo = userStorage.GetRawRepositoryInfo (ur);
SortedDictionary<byte[], KeyValueStorage<byte[]>> EncryptedData = new SortedDictionary<byte[], KeyValueStorage<byte[]>> ();
System.Xml.Serialization.XmlSerializer xmls = new System.Xml.Serialization.XmlSerializer (typeof(ChunkRepositoryConfiguration));
ChunkRepositoryConfiguration cri = (ChunkRepositoryConfiguration)xmls.Deserialize (new MemoryStream (repoInfo, false));
DatabasePath dbp = GetRepositoryPath (cri.ID);
KeyValueStorageConfiguration ESC = new KeyValueStorageConfiguration ();
ESC.Type = cri.Data.Type;
ESC.Path = cus.ToHexadecimal ();
byte[] ak = null;
EncryptedData.Add (cus, new AESEncryptingKeyValueStorage (ESC.OpenStorage<byte[]> (dbp.CreatePath ("Encrypted")), ak));
ChunkRepository cr = new ChunkRepository (cri.ID, cri.Data.OpenStorage<byte[]> (dbp), cri.TopLevels.OpenStorage<byte[][]> (dbp), cri.Dependencies.OpenStorage<byte[][]> (dbp), cri.Meta.OpenStorage<byte[]> (dbp), cri.MetaTopLevels.OpenStorage<byte[][]> (dbp), cri.MetaDependencies.OpenStorage<byte[][]> (dbp), cri.Signatures.OpenStorage<byte[][]> (dbp), cri.ChunkSymmetricKeys.OpenStorage<byte[][]> (dbp), cri.Index.OpenStorage<byte[]> (dbp), cri.InternalMeta.OpenStorage<byte[]> (dbp), EncryptedData);
dataStorage.Add (cr.ID, cr);
ChunkRepositoryAdded (this, new ChunkRepositoryAddedEventArgs (cr));
}
}
}
void PostLogin (byte[] userID)
{
if (!userStorage.EnumerateRepositories ().MoveNext ())
userStorage.AddRepositoryForAll ();
foreach (var ur in userStorage.GetUserRepositories (userID))
LoadUserStorageBase (userID, ur);
}
public bool Login (UserCredentials user, string pepper)
{
if (userStorage.LoggedInUsers.Contains (user.UserID))
throw new InvalidOperationException (string.Format ("User [0x{0}] is already logged in.", user.UserID.ToHexadecimal ()));
bool v = userStorage.Login (new [] { user }, pepper);
if (v) {
PostLogin (user.UserID);
}
return v;
}
public FrontendBase GetFrontend (string frontendName)
{
if (frontendName == null)
throw new ArgumentNullException ("frontendName");
return frontends [frontendName];
}
string basePath;
public Database (string basePath, UserStorageBase userStorage)
{
if (basePath == null)
throw new ArgumentNullException ("basePath");
if (userStorage == null)
throw new ArgumentNullException ("userStorage");
this.basePath = basePath;
this.userStorage = userStorage;
this.frontends = new SortedDictionary<string, FrontendBase> ();
encryptedStorageManager = new EncryptedStorageManager (userStorage);
}
public void AddFrontend (FrontendBase f)
{
Log.WriteLine ("Database.AddFrontend()");
if (f == null)
throw new ArgumentNullException ("f");
this.frontends.Add (f.Name, f);
}
public void Load ()
{
Log.WriteLine ("Database.Load()");
foreach (var f in frontends)
f.Value.Load ();
//sanity check
foreach (var crt in dataStorage) {
byte[][] deps = crt.Value.GetRepositoryDependencies ();
foreach (byte[] dep in deps) {
if (!dataStorage.ContainsKey (dep)) {
throw new Exception ("DONTPANIC Unresolved repository.");
}
}
}
SortedDictionary<byte[], ChunkRepository> repos = new SortedDictionary<byte[], ChunkRepository> ();
while (repos.Count < dataStorage.Count)
foreach (var crt in dataStorage) {
byte[][] deps = crt.Value.GetRepositoryDependencies ();
foreach (byte[] dep in deps) {
if (!repos.ContainsKey (dep))
continue;
}
LoadRepository (crt.Value);
repos.Add (crt.Key, crt.Value);
}
}
void LoadRepository (ChunkRepository cr)
{
Log.WriteLine ("Database.LoadRepository()");
SortedSet<byte[]> pendingData = new SortedSet<byte[]> (ByteSequenceComparer.Shared);
var e = cr.Ldata.EnumerateKeys ();
while (e.MoveNext ())
pendingData.Add (e.Current);
while (pendingData.Count != 0)
foreach (var nchunk in new SortedSet<byte[]>(pendingData, ByteSequenceComparer.Shared)) {
//Log.WriteLine ("Testing object");
byte[][] deps = cr.LdataDependencies.Get (nchunk);
if (deps == null)
throw new InvalidDataException ();
Log.WriteLine ("dependency count = {0}", deps.Length);
if (pendingData.Overlaps (deps)) {
Log.WriteLine ("Found an unloaded dependency, skipping...");
continue;
}
Log.WriteLine ("All the dependencies are loaded, proceeding...");
LoadChunk (nchunk, cr);
pendingData.Remove (nchunk);
}
}
ChunkHeaderv1 LoadChunk (byte[] chunkID, ChunkRepository cr)
{
Log.WriteLine ("Database.LoadChunk()");
foreach (var f in frontends)
f.Value.AddDataObjects (chunkID, cr);
return null;
}
public void Close ()
{
Log.WriteLine ("Database.Close()");
//foreach (var fib in frontendInstances) {
//fib.Close ();
//}
foreach (var f in frontends) {
//f.Value.Close ();
}
//backends.Close ();
}
#region IDataSource implementation
public byte[] CommitTransaction (SortedSet<BaseDataObjectVersion> objects)
{
Log.WriteLine ("Database.CommitTransaction()");
int oc = objects.Count;
objects.RemoveWhere (obj => obj.ChunkID != null);
Log.WriteLine ("Ommitting {0} objects in commit", oc - objects.Count);
System.IO.MemoryStream MS = new System.IO.MemoryStream ();
System.IO.MemoryStream MSRP = new System.IO.MemoryStream ();
System.IO.BinaryWriter MSBW = new System.IO.BinaryWriter (MS);
SortedSet<byte[]> dependencies = new SortedSet<byte[]> (BD2.Core.ByteSequenceComparer.Shared);
ChunkHeaderv1 ch = new ChunkHeaderv1 (DateTime.UtcNow, "");
MSBW.Write (ch.Version);
byte[] chbytes = ch.Serialize ();
MSBW.Write (chbytes.Length);
MSBW.Write (chbytes);
MSBW.Write (1);//section count
Log.WriteLine ("{0} sections", 1);
int n = 0;
//foreach (var tup in data) {
MSBW.Write (1);
Log.WriteLine ("Section version is {0}", 1);
System.Collections.Generic.SortedDictionary <BaseDataObjectVersion, LinkedListNode<BaseDataObjectVersion>> ss = new System.Collections.Generic.SortedDictionary <BaseDataObjectVersion, LinkedListNode<BaseDataObjectVersion>> ();
System.Collections.Generic.LinkedList <BaseDataObjectVersion> ll = new LinkedList<BaseDataObjectVersion> ();
foreach (BaseDataObjectVersion bdo in objects) {
if (!ss.ContainsKey (bdo))
ss.Add (bdo, ll.AddLast (bdo));
foreach (BaseDataObjectVersion dependency in bdo.GetDependenies ()) {
byte[] dep = dependency.ChunkID;
if (dep == null) {
if (ss.ContainsKey (bdo)) {
} else {
ss.Add (dependency, ll.AddBefore (ss [bdo], dependency));
}
} else {
if (!dependencies.Contains (dependency.ChunkID))
dependencies.Add (dependency.ChunkID);
}
}
}
foreach (BaseDataObjectVersion bdo in ll) {
n++;
System.IO.MemoryStream MST = new System.IO.MemoryStream ();
MST.Write (bdo.ObjectType.ToByteArray (), 0, 16);
bdo.Serialize (MST, encryptedStorageManager);
byte[] bytes = MST.ToArray ();
Log.WriteLine ("object type+bytes: {0}", bytes.ToHexadecimal ());
//Log.WriteLine ("Object of type {0} serialized to {1} bytes.", bdo.GetType ().FullName, bytes.Length);
{
System.IO.MemoryStream MSC = new System.IO.MemoryStream ();
System.IO.BinaryWriter BWC = new System.IO.BinaryWriter (MSC);
BWC.Write (bytes.Length);
MSRP.Write (MSC.ToArray (), 0, 4);
}
MSRP.Write (bytes, 0, bytes.Length);
}
byte[] encoded = MSRP.ToArray ();
Log.WriteLine ("{0} objects encoded in {1} bytes", objects.Count, encoded.Length);
MSBW.Write (n);
MSBW.Write (encoded.Length);
MSBW.Write (encoded);
Log.WriteLine ("encoded:{0}", encoded.ToHexadecimal ());
//}
if (n == 0) {
Log.WriteLine ("No objects to save, nothing to do");
return null;
}
System.Security.Cryptography.SHA256 sha = System.Security.Cryptography.SHA256.Create ();
Log.WriteLine ("{0} dependencies", dependencies.Count);
byte[][] deps = new byte [dependencies.Count][];
int depid = 0;
foreach (byte[] dep in dependencies)
deps [depid++] = dep;
Log.WriteLine ("Writing {0} bytes representing {1} objects to backend", MS.Length, n);
byte[] buf = MS.ToArray ();
byte[] chunkID = sha.ComputeHash (buf);
foreach (var ds in dataStorage)
Log.WriteLine ("We have: {0}", ds.Key.ToHexadecimal ());
byte[] cus = userStorage.GetCommonStorage ();
Log.WriteLine ("Common storage id is {0}", cus.ToHexadecimal ());
if (!dataStorage.ContainsKey (cus)) {
Log.WriteLine ("and we don't have it.");
Log.WriteLine ("we only have:");
foreach (var t in dataStorage)
Log.WriteLine (" ID: {0}", t.Key.ToHexadecimal ());
}
dataStorage [cus].Push (chunkID, buf, deps, userStorage.Sign (chunkID));
foreach (var bdo in objects) {
bdo.SetChunkID (chunkID);
}
Log.WriteLine ("Chunk saved with ID:{0}", chunkID.ToHexadecimal ());
return chunkID;
}
#endregion
}
}
| |
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
using System;
using System.IO;
using System.Globalization;
#if !(NET20 || NET35 || SILVERLIGHT || PORTABLE)
using System.Threading.Tasks;
#endif
using Newtonsoft.Json.Utilities;
using System.Xml;
using Newtonsoft.Json.Converters;
using System.Text;
#if !NET20 && (!SILVERLIGHT || WINDOWS_PHONE) && !PORTABLE
using System.Xml.Linq;
#endif
#if NETFX_CORE
using IConvertible = Newtonsoft.Json.Utilities.Convertible;
#endif
namespace Newtonsoft.Json
{
/// <summary>
/// Provides methods for converting between common language runtime types and JSON types.
/// </summary>
public static class JsonConvert
{
/// <summary>
/// Represents JavaScript's boolean value true as a string. This field is read-only.
/// </summary>
public static readonly string True = "true";
/// <summary>
/// Represents JavaScript's boolean value false as a string. This field is read-only.
/// </summary>
public static readonly string False = "false";
/// <summary>
/// Represents JavaScript's null as a string. This field is read-only.
/// </summary>
public static readonly string Null = "null";
/// <summary>
/// Represents JavaScript's undefined as a string. This field is read-only.
/// </summary>
public static readonly string Undefined = "undefined";
/// <summary>
/// Represents JavaScript's positive infinity as a string. This field is read-only.
/// </summary>
public static readonly string PositiveInfinity = "Infinity";
/// <summary>
/// Represents JavaScript's negative infinity as a string. This field is read-only.
/// </summary>
public static readonly string NegativeInfinity = "-Infinity";
/// <summary>
/// Represents JavaScript's NaN as a string. This field is read-only.
/// </summary>
public static readonly string NaN = "NaN";
internal static readonly long InitialJavaScriptDateTicks = 621355968000000000;
/// <summary>
/// Converts the <see cref="DateTime"/> to its JSON string representation.
/// </summary>
/// <param name="value">The value to convert.</param>
/// <returns>A JSON string representation of the <see cref="DateTime"/>.</returns>
public static string ToString(DateTime value)
{
return ToString(value, DateFormatHandling.IsoDateFormat, DateTimeZoneHandling.RoundtripKind);
}
/// <summary>
/// Converts the <see cref="DateTime"/> to its JSON string representation using the <see cref="DateFormatHandling"/> specified.
/// </summary>
/// <param name="value">The value to convert.</param>
/// <param name="format">The format the date will be converted to.</param>
/// <param name="timeZoneHandling">The time zone handling when the date is converted to a string.</param>
/// <returns>A JSON string representation of the <see cref="DateTime"/>.</returns>
public static string ToString(DateTime value, DateFormatHandling format, DateTimeZoneHandling timeZoneHandling)
{
DateTime updatedDateTime = EnsureDateTime(value, timeZoneHandling);
using (StringWriter writer = StringUtils.CreateStringWriter(64))
{
WriteDateTimeString(writer, updatedDateTime, updatedDateTime.GetUtcOffset(), updatedDateTime.Kind, format);
return writer.ToString();
}
}
internal static DateTime EnsureDateTime(DateTime value, DateTimeZoneHandling timeZone)
{
switch (timeZone)
{
case DateTimeZoneHandling.Local:
value = SwitchToLocalTime(value);
break;
case DateTimeZoneHandling.Utc:
value = SwitchToUtcTime(value);
break;
case DateTimeZoneHandling.Unspecified:
value = new DateTime(value.Ticks, DateTimeKind.Unspecified);
break;
case DateTimeZoneHandling.RoundtripKind:
break;
default:
throw new ArgumentException("Invalid date time handling value.");
}
return value;
}
#if !PocketPC && !NET20
/// <summary>
/// Converts the <see cref="DateTimeOffset"/> to its JSON string representation.
/// </summary>
/// <param name="value">The value to convert.</param>
/// <returns>A JSON string representation of the <see cref="DateTimeOffset"/>.</returns>
public static string ToString(DateTimeOffset value)
{
return ToString(value, DateFormatHandling.IsoDateFormat);
}
/// <summary>
/// Converts the <see cref="DateTimeOffset"/> to its JSON string representation using the <see cref="DateFormatHandling"/> specified.
/// </summary>
/// <param name="value">The value to convert.</param>
/// <param name="format">The format the date will be converted to.</param>
/// <returns>A JSON string representation of the <see cref="DateTimeOffset"/>.</returns>
public static string ToString(DateTimeOffset value, DateFormatHandling format)
{
using (StringWriter writer = StringUtils.CreateStringWriter(64))
{
WriteDateTimeString(writer, (format == DateFormatHandling.IsoDateFormat) ? value.DateTime : value.UtcDateTime, value.Offset, DateTimeKind.Local, format);
return writer.ToString();
}
}
#endif
internal static void WriteDateTimeString(TextWriter writer, DateTime value, DateFormatHandling format)
{
WriteDateTimeString(writer, value, value.GetUtcOffset(), value.Kind, format);
}
internal static void WriteDateTimeString(TextWriter writer, DateTime value, TimeSpan offset, DateTimeKind kind, DateFormatHandling format)
{
if (format == DateFormatHandling.MicrosoftDateFormat)
{
long javaScriptTicks = ConvertDateTimeToJavaScriptTicks(value, offset);
writer.Write(@"""\/Date(");
writer.Write(javaScriptTicks);
switch (kind)
{
case DateTimeKind.Unspecified:
if (value != DateTime.MaxValue && value != DateTime.MinValue)
WriteDateTimeOffset(writer, offset, format);
break;
case DateTimeKind.Local:
WriteDateTimeOffset(writer, offset, format);
break;
}
writer.Write(@")\/""");
}
else
{
writer.Write(@"""");
writer.Write(value.ToString("yyyy'-'MM'-'dd'T'HH':'mm':'ss.FFFFFFF", CultureInfo.InvariantCulture));
switch (kind)
{
case DateTimeKind.Local:
WriteDateTimeOffset(writer, offset, format);
break;
case DateTimeKind.Utc:
writer.Write("Z");
break;
}
writer.Write(@"""");
}
}
internal static void WriteDateTimeOffset(TextWriter writer, TimeSpan offset, DateFormatHandling format)
{
writer.Write((offset.Ticks >= 0L) ? "+" : "-");
int absHours = Math.Abs(offset.Hours);
if (absHours < 10)
writer.Write(0);
writer.Write(absHours);
if (format == DateFormatHandling.IsoDateFormat)
writer.Write(':');
int absMinutes = Math.Abs(offset.Minutes);
if (absMinutes < 10)
writer.Write(0);
writer.Write(absMinutes);
}
private static long ToUniversalTicks(DateTime dateTime)
{
if (dateTime.Kind == DateTimeKind.Utc)
return dateTime.Ticks;
return ToUniversalTicks(dateTime, dateTime.GetUtcOffset());
}
private static long ToUniversalTicks(DateTime dateTime, TimeSpan offset)
{
// special case min and max value
// they never have a timezone appended to avoid issues
if (dateTime.Kind == DateTimeKind.Utc || dateTime == DateTime.MaxValue || dateTime == DateTime.MinValue)
return dateTime.Ticks;
long ticks = dateTime.Ticks - offset.Ticks;
if (ticks > 3155378975999999999L)
return 3155378975999999999L;
if (ticks < 0L)
return 0L;
return ticks;
}
internal static long ConvertDateTimeToJavaScriptTicks(DateTime dateTime, TimeSpan offset)
{
long universialTicks = ToUniversalTicks(dateTime, offset);
return UniversialTicksToJavaScriptTicks(universialTicks);
}
internal static long ConvertDateTimeToJavaScriptTicks(DateTime dateTime)
{
return ConvertDateTimeToJavaScriptTicks(dateTime, true);
}
internal static long ConvertDateTimeToJavaScriptTicks(DateTime dateTime, bool convertToUtc)
{
long ticks = (convertToUtc) ? ToUniversalTicks(dateTime) : dateTime.Ticks;
return UniversialTicksToJavaScriptTicks(ticks);
}
private static long UniversialTicksToJavaScriptTicks(long universialTicks)
{
long javaScriptTicks = (universialTicks - InitialJavaScriptDateTicks)/10000;
return javaScriptTicks;
}
internal static DateTime ConvertJavaScriptTicksToDateTime(long javaScriptTicks)
{
DateTime dateTime = new DateTime((javaScriptTicks*10000) + InitialJavaScriptDateTicks, DateTimeKind.Utc);
return dateTime;
}
private static DateTime SwitchToLocalTime(DateTime value)
{
switch (value.Kind)
{
case DateTimeKind.Unspecified:
return new DateTime(value.Ticks, DateTimeKind.Local);
case DateTimeKind.Utc:
return value.ToLocalTime();
case DateTimeKind.Local:
return value;
}
return value;
}
private static DateTime SwitchToUtcTime(DateTime value)
{
switch (value.Kind)
{
case DateTimeKind.Unspecified:
return new DateTime(value.Ticks, DateTimeKind.Utc);
case DateTimeKind.Utc:
return value;
case DateTimeKind.Local:
return value.ToUniversalTime();
}
return value;
}
/// <summary>
/// Converts the <see cref="Boolean"/> to its JSON string representation.
/// </summary>
/// <param name="value">The value to convert.</param>
/// <returns>A JSON string representation of the <see cref="Boolean"/>.</returns>
public static string ToString(bool value)
{
return (value) ? True : False;
}
/// <summary>
/// Converts the <see cref="Char"/> to its JSON string representation.
/// </summary>
/// <param name="value">The value to convert.</param>
/// <returns>A JSON string representation of the <see cref="Char"/>.</returns>
public static string ToString(char value)
{
return ToString(char.ToString(value));
}
/// <summary>
/// Converts the <see cref="Enum"/> to its JSON string representation.
/// </summary>
/// <param name="value">The value to convert.</param>
/// <returns>A JSON string representation of the <see cref="Enum"/>.</returns>
public static string ToString(Enum value)
{
return value.ToString("D");
}
/// <summary>
/// Converts the <see cref="Int32"/> to its JSON string representation.
/// </summary>
/// <param name="value">The value to convert.</param>
/// <returns>A JSON string representation of the <see cref="Int32"/>.</returns>
public static string ToString(int value)
{
return value.ToString(null, CultureInfo.InvariantCulture);
}
/// <summary>
/// Converts the <see cref="Int16"/> to its JSON string representation.
/// </summary>
/// <param name="value">The value to convert.</param>
/// <returns>A JSON string representation of the <see cref="Int16"/>.</returns>
public static string ToString(short value)
{
return value.ToString(null, CultureInfo.InvariantCulture);
}
/// <summary>
/// Converts the <see cref="UInt16"/> to its JSON string representation.
/// </summary>
/// <param name="value">The value to convert.</param>
/// <returns>A JSON string representation of the <see cref="UInt16"/>.</returns>
[CLSCompliant(false)]
public static string ToString(ushort value)
{
return value.ToString(null, CultureInfo.InvariantCulture);
}
/// <summary>
/// Converts the <see cref="UInt32"/> to its JSON string representation.
/// </summary>
/// <param name="value">The value to convert.</param>
/// <returns>A JSON string representation of the <see cref="UInt32"/>.</returns>
[CLSCompliant(false)]
public static string ToString(uint value)
{
return value.ToString(null, CultureInfo.InvariantCulture);
}
/// <summary>
/// Converts the <see cref="Int64"/> to its JSON string representation.
/// </summary>
/// <param name="value">The value to convert.</param>
/// <returns>A JSON string representation of the <see cref="Int64"/>.</returns>
public static string ToString(long value)
{
return value.ToString(null, CultureInfo.InvariantCulture);
}
/// <summary>
/// Converts the <see cref="UInt64"/> to its JSON string representation.
/// </summary>
/// <param name="value">The value to convert.</param>
/// <returns>A JSON string representation of the <see cref="UInt64"/>.</returns>
[CLSCompliant(false)]
public static string ToString(ulong value)
{
return value.ToString(null, CultureInfo.InvariantCulture);
}
/// <summary>
/// Converts the <see cref="Single"/> to its JSON string representation.
/// </summary>
/// <param name="value">The value to convert.</param>
/// <returns>A JSON string representation of the <see cref="Single"/>.</returns>
public static string ToString(float value)
{
return EnsureDecimalPlace(value, value.ToString("R", CultureInfo.InvariantCulture));
}
/// <summary>
/// Converts the <see cref="Double"/> to its JSON string representation.
/// </summary>
/// <param name="value">The value to convert.</param>
/// <returns>A JSON string representation of the <see cref="Double"/>.</returns>
public static string ToString(double value)
{
return EnsureDecimalPlace(value, value.ToString("R", CultureInfo.InvariantCulture));
}
private static string EnsureDecimalPlace(double value, string text)
{
if (double.IsNaN(value) || double.IsInfinity(value) || text.IndexOf('.') != -1 || text.IndexOf('E') != -1 || text.IndexOf('e') != -1)
return text;
return text + ".0";
}
private static string EnsureDecimalPlace(string text)
{
if (text.IndexOf('.') != -1)
return text;
return text + ".0";
}
/// <summary>
/// Converts the <see cref="Byte"/> to its JSON string representation.
/// </summary>
/// <param name="value">The value to convert.</param>
/// <returns>A JSON string representation of the <see cref="Byte"/>.</returns>
public static string ToString(byte value)
{
return value.ToString(null, CultureInfo.InvariantCulture);
}
/// <summary>
/// Converts the <see cref="SByte"/> to its JSON string representation.
/// </summary>
/// <param name="value">The value to convert.</param>
/// <returns>A JSON string representation of the <see cref="SByte"/>.</returns>
[CLSCompliant(false)]
public static string ToString(sbyte value)
{
return value.ToString(null, CultureInfo.InvariantCulture);
}
/// <summary>
/// Converts the <see cref="Decimal"/> to its JSON string representation.
/// </summary>
/// <param name="value">The value to convert.</param>
/// <returns>A JSON string representation of the <see cref="SByte"/>.</returns>
public static string ToString(decimal value)
{
return EnsureDecimalPlace(value.ToString(null, CultureInfo.InvariantCulture));
}
/// <summary>
/// Converts the <see cref="Guid"/> to its JSON string representation.
/// </summary>
/// <param name="value">The value to convert.</param>
/// <returns>A JSON string representation of the <see cref="Guid"/>.</returns>
public static string ToString(Guid value)
{
string text = null;
#if !(NETFX_CORE || PORTABLE)
text = value.ToString("D", CultureInfo.InvariantCulture);
#else
text = value.ToString("D");
#endif
return '"' + text + '"';
}
/// <summary>
/// Converts the <see cref="TimeSpan"/> to its JSON string representation.
/// </summary>
/// <param name="value">The value to convert.</param>
/// <returns>A JSON string representation of the <see cref="TimeSpan"/>.</returns>
public static string ToString(TimeSpan value)
{
return '"' + value.ToString() + '"';
}
/// <summary>
/// Converts the <see cref="Uri"/> to its JSON string representation.
/// </summary>
/// <param name="value">The value to convert.</param>
/// <returns>A JSON string representation of the <see cref="Uri"/>.</returns>
public static string ToString(Uri value)
{
if (value == null)
return Null;
return ToString(value.ToString());
}
/// <summary>
/// Converts the <see cref="String"/> to its JSON string representation.
/// </summary>
/// <param name="value">The value to convert.</param>
/// <returns>A JSON string representation of the <see cref="String"/>.</returns>
public static string ToString(string value)
{
return ToString(value, '"');
}
/// <summary>
/// Converts the <see cref="String"/> to its JSON string representation.
/// </summary>
/// <param name="value">The value to convert.</param>
/// <param name="delimter">The string delimiter character.</param>
/// <returns>A JSON string representation of the <see cref="String"/>.</returns>
public static string ToString(string value, char delimter)
{
return JavaScriptUtils.ToEscapedJavaScriptString(value, delimter, true);
}
/// <summary>
/// Converts the <see cref="Object"/> to its JSON string representation.
/// </summary>
/// <param name="value">The value to convert.</param>
/// <returns>A JSON string representation of the <see cref="Object"/>.</returns>
public static string ToString(object value)
{
if (value == null)
return Null;
IConvertible convertible = ConvertUtils.ToConvertible(value);
if (convertible != null)
{
switch (convertible.GetTypeCode())
{
case TypeCode.String:
return ToString(convertible.ToString(CultureInfo.InvariantCulture));
case TypeCode.Char:
return ToString(convertible.ToChar(CultureInfo.InvariantCulture));
case TypeCode.Boolean:
return ToString(convertible.ToBoolean(CultureInfo.InvariantCulture));
case TypeCode.SByte:
return ToString(convertible.ToSByte(CultureInfo.InvariantCulture));
case TypeCode.Int16:
return ToString(convertible.ToInt16(CultureInfo.InvariantCulture));
case TypeCode.UInt16:
return ToString(convertible.ToUInt16(CultureInfo.InvariantCulture));
case TypeCode.Int32:
return ToString(convertible.ToInt32(CultureInfo.InvariantCulture));
case TypeCode.Byte:
return ToString(convertible.ToByte(CultureInfo.InvariantCulture));
case TypeCode.UInt32:
return ToString(convertible.ToUInt32(CultureInfo.InvariantCulture));
case TypeCode.Int64:
return ToString(convertible.ToInt64(CultureInfo.InvariantCulture));
case TypeCode.UInt64:
return ToString(convertible.ToUInt64(CultureInfo.InvariantCulture));
case TypeCode.Single:
return ToString(convertible.ToSingle(CultureInfo.InvariantCulture));
case TypeCode.Double:
return ToString(convertible.ToDouble(CultureInfo.InvariantCulture));
case TypeCode.DateTime:
return ToString(convertible.ToDateTime(CultureInfo.InvariantCulture));
case TypeCode.Decimal:
return ToString(convertible.ToDecimal(CultureInfo.InvariantCulture));
#if !(NETFX_CORE || PORTABLE)
case TypeCode.DBNull:
return Null;
#endif
}
}
#if !PocketPC && !NET20
else if (value is DateTimeOffset)
{
return ToString((DateTimeOffset) value);
}
#endif
else if (value is Guid)
{
return ToString((Guid) value);
}
else if (value is Uri)
{
return ToString((Uri) value);
}
else if (value is TimeSpan)
{
return ToString((TimeSpan) value);
}
throw new ArgumentException("Unsupported type: {0}. Use the JsonSerializer class to get the object's JSON representation.".FormatWith(CultureInfo.InvariantCulture, value.GetType()));
}
private static bool IsJsonPrimitiveTypeCode(TypeCode typeCode)
{
switch (typeCode)
{
case TypeCode.String:
case TypeCode.Char:
case TypeCode.Boolean:
case TypeCode.SByte:
case TypeCode.Int16:
case TypeCode.UInt16:
case TypeCode.Int32:
case TypeCode.Byte:
case TypeCode.UInt32:
case TypeCode.Int64:
case TypeCode.UInt64:
case TypeCode.Single:
case TypeCode.Double:
case TypeCode.DateTime:
case TypeCode.Decimal:
#if !(NETFX_CORE || PORTABLE)
case TypeCode.DBNull:
#endif
return true;
default:
return false;
}
}
internal static bool IsJsonPrimitiveType(Type type)
{
if (ReflectionUtils.IsNullableType(type))
type = Nullable.GetUnderlyingType(type);
#if !PocketPC && !NET20
if (type == typeof (DateTimeOffset))
return true;
#endif
if (type == typeof (byte[]))
return true;
if (type == typeof (Uri))
return true;
if (type == typeof (TimeSpan))
return true;
if (type == typeof (Guid))
return true;
return IsJsonPrimitiveTypeCode(ConvertUtils.GetTypeCode(type));
}
#region Serialize
/// <summary>
/// Serializes the specified object to a JSON string.
/// </summary>
/// <param name="value">The object to serialize.</param>
/// <returns>A JSON string representation of the object.</returns>
public static string SerializeObject(object value)
{
return SerializeObject(value, Formatting.None, (JsonSerializerSettings) null);
}
/// <summary>
/// Serializes the specified object to a JSON string.
/// </summary>
/// <param name="value">The object to serialize.</param>
/// <param name="formatting">Indicates how the output is formatted.</param>
/// <returns>
/// A JSON string representation of the object.
/// </returns>
public static string SerializeObject(object value, Formatting formatting)
{
return SerializeObject(value, formatting, (JsonSerializerSettings) null);
}
/// <summary>
/// Serializes the specified object to a JSON string using a collection of <see cref="JsonConverter"/>.
/// </summary>
/// <param name="value">The object to serialize.</param>
/// <param name="converters">A collection converters used while serializing.</param>
/// <returns>A JSON string representation of the object.</returns>
public static string SerializeObject(object value, params JsonConverter[] converters)
{
return SerializeObject(value, Formatting.None, converters);
}
/// <summary>
/// Serializes the specified object to a JSON string using a collection of <see cref="JsonConverter"/>.
/// </summary>
/// <param name="value">The object to serialize.</param>
/// <param name="formatting">Indicates how the output is formatted.</param>
/// <param name="converters">A collection converters used while serializing.</param>
/// <returns>A JSON string representation of the object.</returns>
public static string SerializeObject(object value, Formatting formatting, params JsonConverter[] converters)
{
JsonSerializerSettings settings = (converters != null && converters.Length > 0)
? new JsonSerializerSettings {Converters = converters}
: null;
return SerializeObject(value, formatting, settings);
}
/// <summary>
/// Serializes the specified object to a JSON string using a collection of <see cref="JsonConverter"/>.
/// </summary>
/// <param name="value">The object to serialize.</param>
/// <param name="settings">The <see cref="JsonSerializerSettings"/> used to serialize the object.
/// If this is null, default serialization settings will be is used.</param>
/// <returns>
/// A JSON string representation of the object.
/// </returns>
public static string SerializeObject(object value, JsonSerializerSettings settings)
{
return SerializeObject(value, Formatting.None, settings);
}
/// <summary>
/// Serializes the specified object to a JSON string using a collection of <see cref="JsonConverter"/>.
/// </summary>
/// <param name="value">The object to serialize.</param>
/// <param name="formatting">Indicates how the output is formatted.</param>
/// <param name="settings">The <see cref="JsonSerializerSettings"/> used to serialize the object.
/// If this is null, default serialization settings will be is used.</param>
/// <returns>
/// A JSON string representation of the object.
/// </returns>
public static string SerializeObject(object value, Formatting formatting, JsonSerializerSettings settings)
{
JsonSerializer jsonSerializer = JsonSerializer.Create(settings);
StringBuilder sb = new StringBuilder(256);
StringWriter sw = new StringWriter(sb, CultureInfo.InvariantCulture);
using (JsonTextWriter jsonWriter = new JsonTextWriter(sw))
{
jsonWriter.Formatting = formatting;
jsonSerializer.Serialize(jsonWriter, value);
}
return sw.ToString();
}
#if !(NET20 || NET35 || SILVERLIGHT || PORTABLE)
/// <summary>
/// Asynchronously serializes the specified object to a JSON string using a collection of <see cref="JsonConverter"/>.
/// </summary>
/// <param name="value">The object to serialize.</param>
/// <returns>
/// A task that represents the asynchronous serialize operation. The value of the <c>TResult</c> parameter contains a JSON string representation of the object.
/// </returns>
public static Task<string> SerializeObjectAsync(object value)
{
return SerializeObjectAsync(value, Formatting.None, null);
}
/// <summary>
/// Asynchronously serializes the specified object to a JSON string using a collection of <see cref="JsonConverter"/>.
/// </summary>
/// <param name="value">The object to serialize.</param>
/// <param name="formatting">Indicates how the output is formatted.</param>
/// <returns>
/// A task that represents the asynchronous serialize operation. The value of the <c>TResult</c> parameter contains a JSON string representation of the object.
/// </returns>
public static Task<string> SerializeObjectAsync(object value, Formatting formatting)
{
return SerializeObjectAsync(value, formatting, null);
}
/// <summary>
/// Asynchronously serializes the specified object to a JSON string using a collection of <see cref="JsonConverter"/>.
/// </summary>
/// <param name="value">The object to serialize.</param>
/// <param name="formatting">Indicates how the output is formatted.</param>
/// <param name="settings">The <see cref="JsonSerializerSettings"/> used to serialize the object.
/// If this is null, default serialization settings will be is used.</param>
/// <returns>
/// A task that represents the asynchronous serialize operation. The value of the <c>TResult</c> parameter contains a JSON string representation of the object.
/// </returns>
public static Task<string> SerializeObjectAsync(object value, Formatting formatting, JsonSerializerSettings settings)
{
return Task.Factory.StartNew(() => SerializeObject(value, formatting, settings));
}
#endif
#endregion
#region Deserialize
/// <summary>
/// Deserializes the JSON to a .NET object.
/// </summary>
/// <param name="value">The JSON to deserialize.</param>
/// <returns>The deserialized object from the Json string.</returns>
public static object DeserializeObject(string value)
{
return DeserializeObject(value, null, (JsonSerializerSettings) null);
}
/// <summary>
/// Deserializes the JSON to a .NET object.
/// </summary>
/// <param name="value">The JSON to deserialize.</param>
/// <param name="settings">
/// The <see cref="JsonSerializerSettings"/> used to deserialize the object.
/// If this is null, default serialization settings will be is used.
/// </param>
/// <returns>The deserialized object from the JSON string.</returns>
public static object DeserializeObject(string value, JsonSerializerSettings settings)
{
return DeserializeObject(value, null, settings);
}
/// <summary>
/// Deserializes the JSON to the specified .NET type.
/// </summary>
/// <param name="value">The JSON to deserialize.</param>
/// <param name="type">The <see cref="Type"/> of object being deserialized.</param>
/// <returns>The deserialized object from the Json string.</returns>
public static object DeserializeObject(string value, Type type)
{
return DeserializeObject(value, type, (JsonSerializerSettings) null);
}
/// <summary>
/// Deserializes the JSON to the specified .NET type.
/// </summary>
/// <typeparam name="T">The type of the object to deserialize to.</typeparam>
/// <param name="value">The JSON to deserialize.</param>
/// <returns>The deserialized object from the Json string.</returns>
public static T DeserializeObject<T>(string value)
{
return DeserializeObject<T>(value, (JsonSerializerSettings) null);
}
/// <summary>
/// Deserializes the JSON to the given anonymous type.
/// </summary>
/// <typeparam name="T">
/// The anonymous type to deserialize to. This can't be specified
/// traditionally and must be infered from the anonymous type passed
/// as a parameter.
/// </typeparam>
/// <param name="value">The JSON to deserialize.</param>
/// <param name="anonymousTypeObject">The anonymous type object.</param>
/// <returns>The deserialized anonymous type from the JSON string.</returns>
public static T DeserializeAnonymousType<T>(string value, T anonymousTypeObject)
{
return DeserializeObject<T>(value);
}
/// <summary>
/// Deserializes the JSON to the specified .NET type.
/// </summary>
/// <typeparam name="T">The type of the object to deserialize to.</typeparam>
/// <param name="value">The JSON to deserialize.</param>
/// <param name="converters">Converters to use while deserializing.</param>
/// <returns>The deserialized object from the JSON string.</returns>
public static T DeserializeObject<T>(string value, params JsonConverter[] converters)
{
return (T) DeserializeObject(value, typeof (T), converters);
}
/// <summary>
/// Deserializes the JSON to the specified .NET type.
/// </summary>
/// <typeparam name="T">The type of the object to deserialize to.</typeparam>
/// <param name="value">The object to deserialize.</param>
/// <param name="settings">
/// The <see cref="JsonSerializerSettings"/> used to deserialize the object.
/// If this is null, default serialization settings will be is used.
/// </param>
/// <returns>The deserialized object from the JSON string.</returns>
public static T DeserializeObject<T>(string value, JsonSerializerSettings settings)
{
return (T) DeserializeObject(value, typeof (T), settings);
}
/// <summary>
/// Deserializes the JSON to the specified .NET type.
/// </summary>
/// <param name="value">The JSON to deserialize.</param>
/// <param name="type">The type of the object to deserialize.</param>
/// <param name="converters">Converters to use while deserializing.</param>
/// <returns>The deserialized object from the JSON string.</returns>
public static object DeserializeObject(string value, Type type, params JsonConverter[] converters)
{
JsonSerializerSettings settings = (converters != null && converters.Length > 0)
? new JsonSerializerSettings {Converters = converters}
: null;
return DeserializeObject(value, type, settings);
}
/// <summary>
/// Deserializes the JSON to the specified .NET type.
/// </summary>
/// <param name="value">The JSON to deserialize.</param>
/// <param name="type">The type of the object to deserialize to.</param>
/// <param name="settings">
/// The <see cref="JsonSerializerSettings"/> used to deserialize the object.
/// If this is null, default serialization settings will be is used.
/// </param>
/// <returns>The deserialized object from the JSON string.</returns>
public static object DeserializeObject(string value, Type type, JsonSerializerSettings settings)
{
ValidationUtils.ArgumentNotNull(value, "value");
StringReader sr = new StringReader(value);
JsonSerializer jsonSerializer = JsonSerializer.Create(settings);
object deserializedValue;
using (JsonReader jsonReader = new JsonTextReader(sr))
{
deserializedValue = jsonSerializer.Deserialize(jsonReader, type);
if (jsonReader.Read() && jsonReader.TokenType != JsonToken.Comment)
throw new JsonSerializationException("Additional text found in JSON string after finishing deserializing object.");
}
return deserializedValue;
}
#if !(NET20 || NET35 || SILVERLIGHT || PORTABLE)
/// <summary>
/// Asynchronously deserializes the JSON to the specified .NET type.
/// </summary>
/// <typeparam name="T">The type of the object to deserialize to.</typeparam>
/// <param name="value">The JSON to deserialize.</param>
/// <returns>
/// A task that represents the asynchronous deserialize operation. The value of the <c>TResult</c> parameter contains the deserialized object from the JSON string.
/// </returns>
public static Task<T> DeserializeObjectAsync<T>(string value)
{
return DeserializeObjectAsync<T>(value, null);
}
/// <summary>
/// Asynchronously deserializes the JSON to the specified .NET type.
/// </summary>
/// <typeparam name="T">The type of the object to deserialize to.</typeparam>
/// <param name="value">The JSON to deserialize.</param>
/// <param name="settings">
/// The <see cref="JsonSerializerSettings"/> used to deserialize the object.
/// If this is null, default serialization settings will be is used.
/// </param>
/// <returns>
/// A task that represents the asynchronous deserialize operation. The value of the <c>TResult</c> parameter contains the deserialized object from the JSON string.
/// </returns>
public static Task<T> DeserializeObjectAsync<T>(string value, JsonSerializerSettings settings)
{
return Task.Factory.StartNew(() => DeserializeObject<T>(value, settings));
}
/// <summary>
/// Asynchronously deserializes the JSON to the specified .NET type.
/// </summary>
/// <param name="value">The JSON to deserialize.</param>
/// <returns>
/// A task that represents the asynchronous deserialize operation. The value of the <c>TResult</c> parameter contains the deserialized object from the JSON string.
/// </returns>
public static Task<object> DeserializeObjectAsync(string value)
{
return DeserializeObjectAsync(value, null, null);
}
/// <summary>
/// Asynchronously deserializes the JSON to the specified .NET type.
/// </summary>
/// <param name="value">The JSON to deserialize.</param>
/// <param name="type">The type of the object to deserialize to.</param>
/// <param name="settings">
/// The <see cref="JsonSerializerSettings"/> used to deserialize the object.
/// If this is null, default serialization settings will be is used.
/// </param>
/// <returns>
/// A task that represents the asynchronous deserialize operation. The value of the <c>TResult</c> parameter contains the deserialized object from the JSON string.
/// </returns>
public static Task<object> DeserializeObjectAsync(string value, Type type, JsonSerializerSettings settings)
{
return Task.Factory.StartNew(() => DeserializeObject(value, type, settings));
}
#endif
#endregion
/// <summary>
/// Populates the object with values from the JSON string.
/// </summary>
/// <param name="value">The JSON to populate values from.</param>
/// <param name="target">The target object to populate values onto.</param>
public static void PopulateObject(string value, object target)
{
PopulateObject(value, target, null);
}
/// <summary>
/// Populates the object with values from the JSON string.
/// </summary>
/// <param name="value">The JSON to populate values from.</param>
/// <param name="target">The target object to populate values onto.</param>
/// <param name="settings">
/// The <see cref="JsonSerializerSettings"/> used to deserialize the object.
/// If this is null, default serialization settings will be is used.
/// </param>
public static void PopulateObject(string value, object target, JsonSerializerSettings settings)
{
StringReader sr = new StringReader(value);
JsonSerializer jsonSerializer = JsonSerializer.Create(settings);
using (JsonReader jsonReader = new JsonTextReader(sr))
{
jsonSerializer.Populate(jsonReader, target);
if (jsonReader.Read() && jsonReader.TokenType != JsonToken.Comment)
throw new JsonSerializationException("Additional text found in JSON string after finishing deserializing object.");
}
}
#if !(NET20 || NET35 || SILVERLIGHT || PORTABLE)
/// <summary>
/// Asynchronously populates the object with values from the JSON string.
/// </summary>
/// <param name="value">The JSON to populate values from.</param>
/// <param name="target">The target object to populate values onto.</param>
/// <param name="settings">
/// The <see cref="JsonSerializerSettings"/> used to deserialize the object.
/// If this is null, default serialization settings will be is used.
/// </param>
/// <returns>
/// A task that represents the asynchronous populate operation.
/// </returns>
public static Task PopulateObjectAsync(string value, object target, JsonSerializerSettings settings)
{
return Task.Factory.StartNew(() => PopulateObject(value, target, settings));
}
#endif
#if !(SILVERLIGHT || PORTABLE || NETFX_CORE)
/// <summary>
/// Serializes the XML node to a JSON string.
/// </summary>
/// <param name="node">The node to serialize.</param>
/// <returns>A JSON string of the XmlNode.</returns>
public static string SerializeXmlNode(XmlNode node)
{
return SerializeXmlNode(node, Formatting.None);
}
/// <summary>
/// Serializes the XML node to a JSON string.
/// </summary>
/// <param name="node">The node to serialize.</param>
/// <param name="formatting">Indicates how the output is formatted.</param>
/// <returns>A JSON string of the XmlNode.</returns>
public static string SerializeXmlNode(XmlNode node, Formatting formatting)
{
XmlNodeConverter converter = new XmlNodeConverter();
return SerializeObject(node, formatting, converter);
}
/// <summary>
/// Serializes the XML node to a JSON string.
/// </summary>
/// <param name="node">The node to serialize.</param>
/// <param name="formatting">Indicates how the output is formatted.</param>
/// <param name="omitRootObject">Omits writing the root object.</param>
/// <returns>A JSON string of the XmlNode.</returns>
public static string SerializeXmlNode(XmlNode node, Formatting formatting, bool omitRootObject)
{
XmlNodeConverter converter = new XmlNodeConverter {OmitRootObject = omitRootObject};
return SerializeObject(node, formatting, converter);
}
/// <summary>
/// Deserializes the XmlNode from a JSON string.
/// </summary>
/// <param name="value">The JSON string.</param>
/// <returns>The deserialized XmlNode</returns>
public static XmlDocument DeserializeXmlNode(string value)
{
return DeserializeXmlNode(value, null);
}
/// <summary>
/// Deserializes the XmlNode from a JSON string nested in a root elment.
/// </summary>
/// <param name="value">The JSON string.</param>
/// <param name="deserializeRootElementName">The name of the root element to append when deserializing.</param>
/// <returns>The deserialized XmlNode</returns>
public static XmlDocument DeserializeXmlNode(string value, string deserializeRootElementName)
{
return DeserializeXmlNode(value, deserializeRootElementName, false);
}
/// <summary>
/// Deserializes the XmlNode from a JSON string nested in a root elment.
/// </summary>
/// <param name="value">The JSON string.</param>
/// <param name="deserializeRootElementName">The name of the root element to append when deserializing.</param>
/// <param name="writeArrayAttribute">
/// A flag to indicate whether to write the Json.NET array attribute.
/// This attribute helps preserve arrays when converting the written XML back to JSON.
/// </param>
/// <returns>The deserialized XmlNode</returns>
public static XmlDocument DeserializeXmlNode(string value, string deserializeRootElementName, bool writeArrayAttribute)
{
XmlNodeConverter converter = new XmlNodeConverter();
converter.DeserializeRootElementName = deserializeRootElementName;
converter.WriteArrayAttribute = writeArrayAttribute;
return (XmlDocument) DeserializeObject(value, typeof (XmlDocument), converter);
}
#endif
#if !NET20 && (!(SILVERLIGHT || PORTABLE) || WINDOWS_PHONE)
/// <summary>
/// Serializes the <see cref="XNode"/> to a JSON string.
/// </summary>
/// <param name="node">The node to convert to JSON.</param>
/// <returns>A JSON string of the XNode.</returns>
public static string SerializeXNode(XObject node)
{
return SerializeXNode(node, Formatting.None);
}
/// <summary>
/// Serializes the <see cref="XNode"/> to a JSON string.
/// </summary>
/// <param name="node">The node to convert to JSON.</param>
/// <param name="formatting">Indicates how the output is formatted.</param>
/// <returns>A JSON string of the XNode.</returns>
public static string SerializeXNode(XObject node, Formatting formatting)
{
return SerializeXNode(node, formatting, false);
}
/// <summary>
/// Serializes the <see cref="XNode"/> to a JSON string.
/// </summary>
/// <param name="node">The node to serialize.</param>
/// <param name="formatting">Indicates how the output is formatted.</param>
/// <param name="omitRootObject">Omits writing the root object.</param>
/// <returns>A JSON string of the XNode.</returns>
public static string SerializeXNode(XObject node, Formatting formatting, bool omitRootObject)
{
XmlNodeConverter converter = new XmlNodeConverter {OmitRootObject = omitRootObject};
return SerializeObject(node, formatting, converter);
}
/// <summary>
/// Deserializes the <see cref="XNode"/> from a JSON string.
/// </summary>
/// <param name="value">The JSON string.</param>
/// <returns>The deserialized XNode</returns>
public static XDocument DeserializeXNode(string value)
{
return DeserializeXNode(value, null);
}
/// <summary>
/// Deserializes the <see cref="XNode"/> from a JSON string nested in a root elment.
/// </summary>
/// <param name="value">The JSON string.</param>
/// <param name="deserializeRootElementName">The name of the root element to append when deserializing.</param>
/// <returns>The deserialized XNode</returns>
public static XDocument DeserializeXNode(string value, string deserializeRootElementName)
{
return DeserializeXNode(value, deserializeRootElementName, false);
}
/// <summary>
/// Deserializes the <see cref="XNode"/> from a JSON string nested in a root elment.
/// </summary>
/// <param name="value">The JSON string.</param>
/// <param name="deserializeRootElementName">The name of the root element to append when deserializing.</param>
/// <param name="writeArrayAttribute">
/// A flag to indicate whether to write the Json.NET array attribute.
/// This attribute helps preserve arrays when converting the written XML back to JSON.
/// </param>
/// <returns>The deserialized XNode</returns>
public static XDocument DeserializeXNode(string value, string deserializeRootElementName, bool writeArrayAttribute)
{
XmlNodeConverter converter = new XmlNodeConverter();
converter.DeserializeRootElementName = deserializeRootElementName;
converter.WriteArrayAttribute = writeArrayAttribute;
return (XDocument) DeserializeObject(value, typeof (XDocument), converter);
}
#endif
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Text.RegularExpressions;
using System.Xml;
using log4net;
namespace CVNBot
{
class Project
{
static ILog logger = LogManager.GetLogger("CVNBot.Project");
public string projectName;
public string interwikiLink;
public string rooturl; // Format: https://en.wikipedia.org/
public Regex rrestoreRegex;
public Regex rdeleteRegex;
public Regex rprotectRegex;
public Regex runprotectRegex;
public Regex rmodifyprotectRegex;
public Regex ruploadRegex;
public Regex rmoveRegex;
public Regex rmoveredirRegex;
public Regex rblockRegex;
public Regex runblockRegex;
public Regex rreblockRegex;
public Regex rautosummBlank;
public Regex rautosummReplace;
public Regex rSpecialLogRegex;
public Regex rCreate2Regex;
public Hashtable namespaces;
Dictionary<string, string> regexDict = new Dictionary<string, string>();
static char[] rechars = {'\\', '.' ,'(', ')', '[' , ']' ,'^' ,'*' ,'+' ,'?' ,'{' ,'}' ,'|' };
string snamespaces;
/// <summary>
/// Generates Regex objects from regex strings in class. Always generate the namespace list before calling this!
/// </summary>
void GenerateRegexen()
{
rrestoreRegex = new Regex(regexDict["restoreRegex"]);
rdeleteRegex = new Regex(regexDict["deleteRegex"]);
rprotectRegex = new Regex(regexDict["protectRegex"]);
runprotectRegex = new Regex(regexDict["unprotectRegex"]);
if (!regexDict.ContainsKey("modifyprotectRegex"))
{
// Added in CVNBot 1.20, fallback if missing in older XML files.
regexDict["modifyprotectRegex"] = regexDict["protectRegex"];
logger.Warn("generateRegexen: modifyprotectRegex is missing. Please reload this wiki.");
}
rmodifyprotectRegex = new Regex(regexDict["modifyprotectRegex"]);
ruploadRegex = new Regex(regexDict["uploadRegex"]);
rmoveRegex = new Regex(regexDict["moveRegex"]);
rmoveredirRegex = new Regex(regexDict["moveredirRegex"]);
rblockRegex = new Regex(regexDict["blockRegex"]);
runblockRegex = new Regex(regexDict["unblockRegex"]);
if (!regexDict.ContainsKey("reblockRegex")) {
// Added in CVNBot 1.22, fallback if missing in older XML files.
regexDict["reblockRegex"] = "^$";
logger.Warn("generateRegexen: reblockRegex is missing. Please reload this wiki.");
}
rreblockRegex = new Regex(regexDict["reblockRegex"]);
rautosummBlank = new Regex(regexDict["autosummBlank"]);
rautosummReplace = new Regex(regexDict["autosummReplace"]);
rSpecialLogRegex = new Regex(regexDict["specialLogRegex"]);
rCreate2Regex = new Regex( namespaces["2"]+@":([^:]+)" );
}
public string DumpProjectDetails()
{
StringWriter output = new StringWriter();
using (XmlTextWriter dump = new XmlTextWriter(output))
{
dump.WriteStartElement("project");
dump.WriteElementString("projectName", projectName);
dump.WriteElementString("interwikiLink", interwikiLink);
dump.WriteElementString("rooturl", rooturl);
dump.WriteElementString("speciallog", regexDict["specialLogRegex"]);
dump.WriteElementString("namespaces", snamespaces.Replace("<?xml version=\"1.0\" encoding=\"utf-8\"?>", ""));
dump.WriteElementString("restoreRegex", regexDict["restoreRegex"]);
dump.WriteElementString("deleteRegex", regexDict["deleteRegex"]);
dump.WriteElementString("protectRegex", regexDict["protectRegex"]);
dump.WriteElementString("unprotectRegex", regexDict["unprotectRegex"]);
dump.WriteElementString("modifyprotectRegex", regexDict["modifyprotectRegex"]);
dump.WriteElementString("uploadRegex", regexDict["uploadRegex"]);
dump.WriteElementString("moveRegex", regexDict["moveRegex"]);
dump.WriteElementString("moveredirRegex", regexDict["moveredirRegex"]);
dump.WriteElementString("blockRegex", regexDict["blockRegex"]);
dump.WriteElementString("unblockRegex", regexDict["unblockRegex"]);
dump.WriteElementString("reblockRegex", regexDict["reblockRegex"]);
dump.WriteElementString("autosummBlank", regexDict["autosummBlank"]);
dump.WriteElementString("autosummReplace", regexDict["autosummReplace"]);
dump.WriteEndElement();
dump.Flush();
}
return output.ToString();
}
public void ReadProjectDetails(string xml)
{
XmlDocument doc = new XmlDocument();
doc.LoadXml(xml);
XmlNode parentnode = doc.FirstChild;
for (int i = 0; i < parentnode.ChildNodes.Count; i++)
{
string key = parentnode.ChildNodes[i].Name;
string value = parentnode.ChildNodes[i].InnerText;
switch (key)
{
case "projectName": projectName = value; break;
case "interwikiLink": interwikiLink = value; break;
case "rooturl": rooturl = value; break;
case "speciallog": regexDict["specialLogRegex"] = value; break;
case "namespaces": snamespaces = value; break;
case "restoreRegex": regexDict["restoreRegex"] = value; break;
case "deleteRegex": regexDict["deleteRegex"] = value; break;
case "protectRegex": regexDict["protectRegex"] = value; break;
case "unprotectRegex": regexDict["unprotectRegex"] = value; break;
case "modifyprotectRegex": regexDict["modifyprotectRegex"] = value; break;
case "uploadRegex": regexDict["uploadRegex"] = value; break;
case "moveRegex": regexDict["moveRegex"] = value; break;
case "moveredirRegex": regexDict["moveredirRegex"] = value; break;
case "blockRegex": regexDict["blockRegex"] = value; break;
case "unblockRegex": regexDict["unblockRegex"] = value; break;
case "reblockRegex": regexDict["reblockRegex"] = value; break;
case "autosummBlank": regexDict["autosummBlank"] = value; break;
case "autosummReplace": regexDict["autosummReplace"] = value; break;
}
}
// Always get namespaces before generating regexen
GetNamespaces(true);
// Regenerate regexen
GenerateRegexen();
}
void GetNamespaces(bool snamespacesAlreadySet)
{
if (!snamespacesAlreadySet)
{
logger.InfoFormat("Fetching namespaces from {0}", rooturl);
snamespaces = CVNBotUtils.GetRawDocument(rooturl + "w/api.php?format=xml&action=query&meta=siteinfo&siprop=namespaces");
if (snamespaces == "")
throw new Exception("Can't load list of namespaces from " + rooturl);
}
namespaces = new Hashtable();
XmlDocument doc = new XmlDocument();
doc.LoadXml(snamespaces);
string namespacesLogline = "";
XmlNode namespacesNode = doc.GetElementsByTagName("namespaces")[0];
for (int i = 0; i < namespacesNode.ChildNodes.Count; i++)
{
namespaces.Add(namespacesNode.ChildNodes[i].Attributes["id"].Value, namespacesNode.ChildNodes[i].InnerText);
namespacesLogline += "id["+namespacesNode.ChildNodes[i].Attributes["id"].Value + "]="+namespacesNode.ChildNodes[i].InnerText + "; ";
}
}
public struct MessagesOption
{
public int NumberOfArgs;
public string RegexName;
public bool NonStrictFlag;
public MessagesOption (int ArgNumberOfArgs, string ArgRegexName, bool ArgNonStrictFlag)
{
NumberOfArgs = ArgNumberOfArgs;
RegexName = ArgRegexName;
NonStrictFlag = ArgNonStrictFlag;
}
}
public void RetrieveWikiDetails()
{
//Find out what the localized Special: (ID -1) namespace is, and create a regex
GetNamespaces(false);
regexDict["specialLogRegex"] = namespaces["-1"] + @":.+?/(.+)";
logger.InfoFormat("Fetching interface messages from {0}", rooturl);
Dictionary<string, MessagesOption> Messages = new Dictionary<string, MessagesOption>();
// Location of message, number of required parameters, reference to regex, allow lazy
// Retrieve messages for all the required events and generate regexen for them
Messages.Add("Undeletedarticle", new MessagesOption(1, "restoreRegex", false));
Messages.Add("Deletedarticle", new MessagesOption(1, "deleteRegex", false));
Messages.Add("Protectedarticle", new MessagesOption(1, "protectRegex", false));
Messages.Add("Unprotectedarticle", new MessagesOption(1, "unprotectRegex", false));
Messages.Add("Modifiedarticleprotection", new MessagesOption(1, "modifyprotectRegex", true));
Messages.Add("Uploadedimage", new MessagesOption(0, "uploadRegex", false));
Messages.Add("1movedto2",new MessagesOption(2, "moveRegex", false));
Messages.Add("1movedto2_redir", new MessagesOption(2, "moveredirRegex", false));
// blockRegex is nonStrict because some wikis override the message without including $2 (block length).
// RCReader will fall back to "24 hours" if this is the case.
// Some newer messages (e.g. https://lmo.wikipedia.org/wiki/MediaWiki:Blocklogentry) have a third item,
// $3 ("anononly,nocreate,autoblock"). This may conflict with $2 detection.
// Trying (changed 2 -> 3) to see if length of time will be correctly detected using just this method:
Messages.Add("Blocklogentry", new MessagesOption(3, "blockRegex", true));
Messages.Add("Unblocklogentry", new MessagesOption(0, "unblockRegex", false));
Messages.Add("Reblock-logentry", new MessagesOption(3, "reblockRegex", false));
Messages.Add("Autosumm-blank", new MessagesOption(0, "autosummBlank", false));
// autosummReplace is nonStrict because some wikis use translations overrides without
// a "$1" parameter for the content.
Messages.Add("Autosumm-replace", new MessagesOption(1, "autosummReplace", true));
GetInterfaceMessages(Messages);
GenerateRegexen();
}
void GetInterfaceMessages(Dictionary<string, MessagesOption> Messages)
{
string CombinedMessages = string.Join("|", Messages.Keys);
string sMwMessages = CVNBotUtils.GetRawDocument(
rooturl +
"w/api.php?action=query&meta=allmessages&format=xml" +
"&ammessages=" + CombinedMessages
);
if (sMwMessages == "")
throw new Exception("Can't load list of InterfaceMessages from " + rooturl);
XmlDocument doc = new XmlDocument();
doc.LoadXml(sMwMessages);
string mwMessagesLogline = "";
XmlNode allmessagesNode = doc.GetElementsByTagName("allmessages")[0];
for (int i = 0; i < allmessagesNode.ChildNodes.Count; i++)
{
string elmName = allmessagesNode.ChildNodes[i].Attributes["name"].Value;
GenerateRegex(
elmName,
allmessagesNode.ChildNodes[i].InnerText,
Messages[elmName].NumberOfArgs,
Messages[elmName].RegexName,
Messages[elmName].NonStrictFlag
);
mwMessagesLogline += "name[" + elmName + "]="+allmessagesNode.ChildNodes[i].InnerText + "; ";
}
}
void GenerateRegex(string mwMessageTitle, string mwMessage, int reqCount, string destRegex, bool nonStrict)
{
// Now gently coax that into a regex
foreach (char c in rechars)
mwMessage = mwMessage.Replace(c.ToString(), @"\" + c.ToString());
mwMessage = mwMessage.Replace("$1", "(?<item1>.+?)");
mwMessage = mwMessage.Replace("$2", "(?<item2>.+?)");
mwMessage = mwMessage.Replace("$3", "(?<item3>.+?)");
mwMessage = mwMessage.Replace("$1", "(?:.+?)");
mwMessage = mwMessage.Replace("$2", "(?:.+?)");
mwMessage = mwMessage.Replace("$3", "(?:.+?)");
mwMessage = mwMessage.Replace("$", @"\$");
mwMessage = "^" + mwMessage + @"(?:: (?<comment>.*?))?$"; // Special:Log comments are preceded by a colon
// Dirty code: Block log exceptions!
if (mwMessageTitle == "Blocklogentry")
{
mwMessage = mwMessage.Replace("(?<item3>.+?)", "\\((?<item3>.+?)\\)");
mwMessage = mwMessage.Replace(@"(?<item2>.+?)(?:: (?<comment>.*?))?$", "(?<item2>.+?)$");
}
try
{
Regex.Match("", mwMessage);
}
catch (Exception e)
{
throw new Exception("Failed to test-generate regex " + mwMessage + " for " + mwMessageTitle + "; " + e.Message);
}
if (reqCount >= 1)
{
if (!mwMessage.Contains(@"(?<item1>.+?)") && !nonStrict)
throw new Exception("Regex " + mwMessageTitle + " requires one or more items but item1 not found in "+mwMessage);
if (reqCount >= 2)
{
if (!mwMessage.Contains(@"(?<item2>.+?)") && !nonStrict)
throw new Exception("Regex " + mwMessageTitle + " requires two or more items but item2 not found in "+mwMessage);
}
}
regexDict[destRegex] = mwMessage;
}
/// <summary>
/// Gets the namespace code
/// </summary>
/// <param name="pageTitle">A page title, such as "Special:Helloworld" and "Helloworld"</param>
/// <returns></returns>
public int DetectNamespace(string pageTitle)
{
if (pageTitle.Contains(":"))
{
string nsLocal = pageTitle.Substring(0, pageTitle.IndexOf(':'));
// Try to locate value (As fast as ContainsValue())
foreach (DictionaryEntry de in this.namespaces)
{
if ((string)de.Value == nsLocal)
return Convert.ToInt32(de.Key);
}
}
// If no match for the prefix found, or if no colon,
// assume main namespace
return 0;
}
/// <summary>
/// Returns a copy of the article title with the namespace translated into English
/// </summary>
/// <param name="originalTitle">Title in original (localized) language</param>
/// <returns></returns>
public static string TranslateNamespace(string project, string originalTitle)
{
if (originalTitle.Contains(":"))
{
string nsEnglish;
// *Don't change these* unless it's a stopping bug. These names are made part of the title
// in the watchlist and items database. (ie. don't change Image to File unless Image is broken)
// When they do need to be changed, make sure to make note in the RELEASE-NOTES that databases
// should be updated manually to keep all regexes and watchlists functional!
switch (((Project)Program.prjlist[project]).DetectNamespace(originalTitle))
{
case -2:
nsEnglish = "Media";
break;
case -1:
nsEnglish = "Special";
break;
case 1:
nsEnglish = "Talk";
break;
case 2:
nsEnglish = "User";
break;
case 3:
nsEnglish = "User talk";
break;
case 4:
nsEnglish = "Project";
break;
case 5:
nsEnglish = "Project talk";
break;
case 6:
nsEnglish = "Image";
break;
case 7:
nsEnglish = "Image talk";
break;
case 8:
nsEnglish = "MediaWiki";
break;
case 9:
nsEnglish = "MediaWiki talk";
break;
case 10:
nsEnglish = "Template";
break;
case 11:
nsEnglish = "Template talk";
break;
case 12:
nsEnglish = "Help";
break;
case 13:
nsEnglish = "Help talk";
break;
case 14:
nsEnglish = "Category";
break;
case 15:
nsEnglish = "Category talk";
break;
default:
return originalTitle;
}
// If we're still here, then nsEnglish has been set
return nsEnglish + originalTitle.Substring(originalTitle.IndexOf(':'));
}
// Mainspace articles do not need translation
return originalTitle;
}
}
}
| |
//---------------------------------------------------------------------------
//
// <copyright file="TransformedBitmap.cs" company="Microsoft">
// Copyright (C) Microsoft Corporation. All rights reserved.
// </copyright>
//
// This file was generated, please do not edit it directly.
//
// Please see http://wiki/default.aspx/Microsoft.Projects.Avalon/MilCodeGen.html for more information.
//
//---------------------------------------------------------------------------
using MS.Internal;
using MS.Internal.PresentationCore;
using System;
using System.IO;
using System.Collections;
using System.ComponentModel;
using System.Net.Cache;
using System.Runtime.InteropServices;
using System.Windows.Threading;
using System.Windows;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Media.Composition;
using System.Windows.Media.Imaging;
using System.Windows.Media.Media3D;
using System.Diagnostics;
// These types are aliased to match the unamanaged names used in interop
using BOOL = System.UInt32;
using WORD = System.UInt16;
using Float = System.Single;
namespace System.Windows.Media.Imaging
{
sealed partial class TransformedBitmap : BitmapSource
{
//------------------------------------------------------
//
// Public Methods
//
//------------------------------------------------------
#region Public Methods
/// <summary>
/// Shadows inherited Clone() with a strongly typed
/// version for convenience.
/// </summary>
public new TransformedBitmap Clone()
{
return (TransformedBitmap)base.Clone();
}
/// <summary>
/// Shadows inherited CloneCurrentValue() with a strongly typed
/// version for convenience.
/// </summary>
public new TransformedBitmap CloneCurrentValue()
{
return (TransformedBitmap)base.CloneCurrentValue();
}
#endregion Public Methods
//------------------------------------------------------
//
// Public Properties
//
//------------------------------------------------------
private static void SourcePropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
TransformedBitmap target = ((TransformedBitmap) d);
target.SourcePropertyChangedHook(e);
// The first change to the default value of a mutable collection property (e.g. GeometryGroup.Children)
// will promote the property value from a default value to a local value. This is technically a sub-property
// change because the collection was changed and not a new collection set (GeometryGroup.Children.
// Add versus GeometryGroup.Children = myNewChildrenCollection). However, we never marshalled
// the default value to the compositor. If the property changes from a default value, the new local value
// needs to be marshalled to the compositor. We detect this scenario with the second condition
// e.OldValueSource != e.NewValueSource. Specifically in this scenario the OldValueSource will be
// Default and the NewValueSource will be Local.
if (e.IsASubPropertyChange &&
(e.OldValueSource == e.NewValueSource))
{
return;
}
target.PropertyChanged(SourceProperty);
}
private static void TransformPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
TransformedBitmap target = ((TransformedBitmap) d);
target.TransformPropertyChangedHook(e);
// The first change to the default value of a mutable collection property (e.g. GeometryGroup.Children)
// will promote the property value from a default value to a local value. This is technically a sub-property
// change because the collection was changed and not a new collection set (GeometryGroup.Children.
// Add versus GeometryGroup.Children = myNewChildrenCollection). However, we never marshalled
// the default value to the compositor. If the property changes from a default value, the new local value
// needs to be marshalled to the compositor. We detect this scenario with the second condition
// e.OldValueSource != e.NewValueSource. Specifically in this scenario the OldValueSource will be
// Default and the NewValueSource will be Local.
if (e.IsASubPropertyChange &&
(e.OldValueSource == e.NewValueSource))
{
return;
}
target.PropertyChanged(TransformProperty);
}
#region Public Properties
/// <summary>
/// Source - BitmapSource. Default value is null.
/// </summary>
public BitmapSource Source
{
get
{
return (BitmapSource) GetValue(SourceProperty);
}
set
{
SetValueInternal(SourceProperty, value);
}
}
/// <summary>
/// Transform - Transform. Default value is Transform.Identity.
/// </summary>
public Transform Transform
{
get
{
return (Transform) GetValue(TransformProperty);
}
set
{
SetValueInternal(TransformProperty, value);
}
}
#endregion Public Properties
//------------------------------------------------------
//
// Protected Methods
//
//------------------------------------------------------
#region Protected Methods
/// <summary>
/// Implementation of <see cref="System.Windows.Freezable.CreateInstanceCore">Freezable.CreateInstanceCore</see>.
/// </summary>
/// <returns>The new Freezable.</returns>
protected override Freezable CreateInstanceCore()
{
return new TransformedBitmap();
}
/// <summary>
/// Implementation of Freezable.CloneCore()
/// </summary>
protected override void CloneCore(Freezable source)
{
TransformedBitmap sourceTransformedBitmap = (TransformedBitmap) source;
// Set any state required before actual clone happens
ClonePrequel(sourceTransformedBitmap);
base.CloneCore(source);
// Set state once clone has finished
ClonePostscript(sourceTransformedBitmap);
}
/// <summary>
/// Implementation of Freezable.CloneCurrentValueCore()
/// </summary>
protected override void CloneCurrentValueCore(Freezable source)
{
TransformedBitmap sourceTransformedBitmap = (TransformedBitmap) source;
// Set any state required before actual clone happens
ClonePrequel(sourceTransformedBitmap);
base.CloneCurrentValueCore(source);
// Set state once clone has finished
ClonePostscript(sourceTransformedBitmap);
}
/// <summary>
/// Implementation of Freezable.GetAsFrozenCore()
/// </summary>
protected override void GetAsFrozenCore(Freezable source)
{
TransformedBitmap sourceTransformedBitmap = (TransformedBitmap) source;
// Set any state required before actual clone happens
ClonePrequel(sourceTransformedBitmap);
base.GetAsFrozenCore(source);
// Set state once clone has finished
ClonePostscript(sourceTransformedBitmap);
}
/// <summary>
/// Implementation of Freezable.GetCurrentValueAsFrozenCore()
/// </summary>
protected override void GetCurrentValueAsFrozenCore(Freezable source)
{
TransformedBitmap sourceTransformedBitmap = (TransformedBitmap) source;
// Set any state required before actual clone happens
ClonePrequel(sourceTransformedBitmap);
base.GetCurrentValueAsFrozenCore(source);
// Set state once clone has finished
ClonePostscript(sourceTransformedBitmap);
}
#endregion ProtectedMethods
//------------------------------------------------------
//
// Internal Methods
//
//------------------------------------------------------
#region Internal Methods
#endregion Internal Methods
//------------------------------------------------------
//
// Internal Properties
//
//------------------------------------------------------
#region Internal Properties
#endregion Internal Properties
//------------------------------------------------------
//
// Dependency Properties
//
//------------------------------------------------------
#region Dependency Properties
/// <summary>
/// The DependencyProperty for the TransformedBitmap.Source property.
/// </summary>
public static readonly DependencyProperty SourceProperty;
/// <summary>
/// The DependencyProperty for the TransformedBitmap.Transform property.
/// </summary>
public static readonly DependencyProperty TransformProperty;
#endregion Dependency Properties
//------------------------------------------------------
//
// Internal Fields
//
//------------------------------------------------------
#region Internal Fields
internal static BitmapSource s_Source = null;
internal static Transform s_Transform = Transform.Identity;
#endregion Internal Fields
#region Constructors
//------------------------------------------------------
//
// Constructors
//
//------------------------------------------------------
static TransformedBitmap()
{
// We check our static default fields which are of type Freezable
// to make sure that they are not mutable, otherwise we will throw
// if these get touched by more than one thread in the lifetime
// of your app. (Windows OS Bug #947272)
//
Debug.Assert(s_Source == null || s_Source.IsFrozen,
"Detected context bound default value TransformedBitmap.s_Source (See OS Bug #947272).");
Debug.Assert(s_Transform == null || s_Transform.IsFrozen,
"Detected context bound default value TransformedBitmap.s_Transform (See OS Bug #947272).");
// Initializations
Type typeofThis = typeof(TransformedBitmap);
SourceProperty =
RegisterProperty("Source",
typeof(BitmapSource),
typeofThis,
null,
new PropertyChangedCallback(SourcePropertyChanged),
null,
/* isIndependentlyAnimated = */ false,
/* coerceValueCallback */ new CoerceValueCallback(CoerceSource));
TransformProperty =
RegisterProperty("Transform",
typeof(Transform),
typeofThis,
Transform.Identity,
new PropertyChangedCallback(TransformPropertyChanged),
null,
/* isIndependentlyAnimated = */ false,
/* coerceValueCallback */ new CoerceValueCallback(CoerceTransform));
}
#endregion Constructors
}
}
| |
//------------------------------------------------------------------------------
// <copyright file="TextWriterTraceListener.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//------------------------------------------------------------------------------
/*
*/
namespace System.Diagnostics {
using System;
using System.IO;
using System.Text;
using System.Security.Permissions;
using System.Runtime.InteropServices;
using Microsoft.Win32;
using System.Runtime.Versioning;
/// <devdoc>
/// <para>Directs tracing or debugging output to
/// a <see cref='T:System.IO.TextWriter'/> or to a <see cref='T:System.IO.Stream'/>,
/// such as <see cref='F:System.Console.Out'/> or <see cref='T:System.IO.FileStream'/>.</para>
/// </devdoc>
[HostProtection(Synchronization=true)]
public class TextWriterTraceListener : TraceListener {
internal TextWriter writer;
String fileName = null;
/// <devdoc>
/// <para>Initializes a new instance of the <see cref='System.Diagnostics.TextWriterTraceListener'/> class with
/// <see cref='System.IO.TextWriter'/>
/// as the output recipient.</para>
/// </devdoc>
public TextWriterTraceListener() {
}
/// <devdoc>
/// <para>Initializes a new instance of the <see cref='System.Diagnostics.TextWriterTraceListener'/> class, using the
/// stream as the recipient of the debugging and tracing output.</para>
/// </devdoc>
public TextWriterTraceListener(Stream stream)
: this(stream, string.Empty) {
}
/// <devdoc>
/// <para>Initializes a new instance of the <see cref='System.Diagnostics.TextWriterTraceListener'/> class with the
/// specified name and using the stream as the recipient of the debugging and tracing output.</para>
/// </devdoc>
public TextWriterTraceListener(Stream stream, string name)
: base(name) {
if (stream == null) throw new ArgumentNullException("stream");
this.writer = new StreamWriter(stream);
}
/// <devdoc>
/// <para>Initializes a new instance of the <see cref='System.Diagnostics.TextWriterTraceListener'/> class using the
/// specified writer as recipient of the tracing or debugging output.</para>
/// </devdoc>
public TextWriterTraceListener(TextWriter writer)
: this(writer, string.Empty) {
}
/// <devdoc>
/// <para>Initializes a new instance of the <see cref='System.Diagnostics.TextWriterTraceListener'/> class with the
/// specified name and using the specified writer as recipient of the tracing or
/// debugging
/// output.</para>
/// </devdoc>
public TextWriterTraceListener(TextWriter writer, string name)
: base(name) {
if (writer == null) throw new ArgumentNullException("writer");
this.writer = writer;
}
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
[ResourceExposure(ResourceScope.Machine)]
public TextWriterTraceListener(string fileName) {
this.fileName = fileName;
}
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
[ResourceExposure(ResourceScope.Machine)]
public TextWriterTraceListener(string fileName, string name) : base(name) {
this.fileName = fileName;
}
/// <devdoc>
/// <para> Indicates the text writer that receives the tracing
/// or debugging output.</para>
/// </devdoc>
public TextWriter Writer {
get {
EnsureWriter();
return writer;
}
set {
writer = value;
}
}
/// <devdoc>
/// <para>Closes the <see cref='System.Diagnostics.TextWriterTraceListener.Writer'/> so that it no longer
/// receives tracing or debugging output.</para>
/// </devdoc>
public override void Close() {
if (writer != null) {
try {
writer.Close();
} catch (ObjectDisposedException) { }
}
writer = null;
}
/// <internalonly/>
/// <devdoc>
/// </devdoc>
protected override void Dispose(bool disposing) {
try {
if (disposing) {
this.Close();
}
else {
// clean up resources
if (writer != null)
try {
writer.Close();
} catch (ObjectDisposedException) { }
writer = null;
}
}
finally {
base.Dispose(disposing);
}
}
/// <devdoc>
/// <para>Flushes the output buffer for the <see cref='System.Diagnostics.TextWriterTraceListener.Writer'/>.</para>
/// </devdoc>
public override void Flush() {
if (!EnsureWriter()) return;
try {
writer.Flush();
} catch (ObjectDisposedException) { }
}
/// <devdoc>
/// <para>Writes a message
/// to this instance's <see cref='System.Diagnostics.TextWriterTraceListener.Writer'/>.</para>
/// </devdoc>
public override void Write(string message) {
if (!EnsureWriter()) return;
if (NeedIndent) WriteIndent();
try {
writer.Write(message);
} catch (ObjectDisposedException) { }
}
/// <devdoc>
/// <para>Writes a message
/// to this instance's <see cref='System.Diagnostics.TextWriterTraceListener.Writer'/> followed by a line terminator. The
/// default line terminator is a carriage return followed by a line feed (\r\n).</para>
/// </devdoc>
public override void WriteLine(string message) {
if (!EnsureWriter()) return;
if (NeedIndent) WriteIndent();
try {
writer.WriteLine(message);
NeedIndent = true;
} catch (ObjectDisposedException) { }
}
private static Encoding GetEncodingWithFallback(Encoding encoding)
{
// Clone it and set the "?" replacement fallback
Encoding fallbackEncoding = (Encoding)encoding.Clone();
fallbackEncoding.EncoderFallback = EncoderFallback.ReplacementFallback;
fallbackEncoding.DecoderFallback = DecoderFallback.ReplacementFallback;
return fallbackEncoding;
}
// This uses a machine resource, scoped by the fileName variable.
[ResourceExposure(ResourceScope.None)]
[ResourceConsumption(ResourceScope.Machine, ResourceScope.Machine)]
internal bool EnsureWriter() {
bool ret = true;
if (writer == null) {
ret = false;
if (fileName == null)
return ret;
// StreamWriter by default uses UTF8Encoding which will throw on invalid encoding errors.
// This can cause the internal StreamWriter's state to be irrecoverable. It is bad for tracing
// APIs to throw on encoding errors. Instead, we should provide a "?" replacement fallback
// encoding to substitute illegal chars. For ex, In case of high surrogate character
// D800-DBFF without a following low surrogate character DC00-DFFF
// NOTE: We also need to use an encoding that does't emit BOM whic is StreamWriter's default
Encoding noBOMwithFallback = GetEncodingWithFallback(new UTF8Encoding(false));
// To support multiple appdomains/instances tracing to the same file,
// we will try to open the given file for append but if we encounter
// IO errors, we will prefix the file name with a unique GUID value
// and try one more time
string fullPath = Path.GetFullPath(fileName);
string dirPath = Path.GetDirectoryName(fullPath);
string fileNameOnly = Path.GetFileName(fullPath);
for (int i=0; i<2; i++) {
try {
writer = new StreamWriter(fullPath, true, noBOMwithFallback, 4096);
ret = true;
break;
}
catch (IOException ) {
// Should we do this only for ERROR_SHARING_VIOLATION?
//if (InternalResources.MakeErrorCodeFromHR(Marshal.GetHRForException(ioexc)) == InternalResources.ERROR_SHARING_VIOLATION) {
fileNameOnly = Guid.NewGuid().ToString() + fileNameOnly;
fullPath = Path.Combine(dirPath, fileNameOnly);
continue;
}
catch (UnauthorizedAccessException ) {
//ERROR_ACCESS_DENIED, mostly ACL issues
break;
}
catch (Exception ) {
break;
}
}
if (!ret) {
// Disable tracing to this listener. Every Write will be nop.
// We need to think of a central way to deal with the listener
// init errors in the future. The default should be that we eat
// up any errors from listener and optionally notify the user
fileName = null;
}
}
return ret;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Reflection.Internal;
using System.Runtime.CompilerServices;
using System.Text;
namespace System.Reflection.Metadata.Ecma335
{
public sealed partial class MetadataBuilder
{
private sealed class HeapBlobBuilder : BlobBuilder
{
private int _capacityExpansion;
public HeapBlobBuilder(int capacity)
: base(capacity)
{
}
protected override BlobBuilder AllocateChunk(int minimalSize)
{
return new HeapBlobBuilder(Math.Max(Math.Max(minimalSize, ChunkCapacity), _capacityExpansion));
}
internal void SetCapacity(int capacity)
{
_capacityExpansion = Math.Max(0, capacity - Count - FreeBytes);
}
}
// #US heap
private const int UserStringHeapSizeLimit = 0x01000000;
private readonly Dictionary<string, UserStringHandle> _userStrings = new Dictionary<string, UserStringHandle>(256);
private readonly HeapBlobBuilder _userStringBuilder = new HeapBlobBuilder(4 * 1024);
private readonly int _userStringHeapStartOffset;
// #String heap
private Dictionary<string, StringHandle> _strings = new Dictionary<string, StringHandle>(256);
private readonly int _stringHeapStartOffset;
private int _stringHeapCapacity = 4 * 1024;
// #Blob heap
private readonly Dictionary<ImmutableArray<byte>, BlobHandle> _blobs = new Dictionary<ImmutableArray<byte>, BlobHandle>(1024, ByteSequenceComparer.Instance);
private readonly int _blobHeapStartOffset;
private int _blobHeapSize;
// #GUID heap
private readonly Dictionary<Guid, GuidHandle> _guids = new Dictionary<Guid, GuidHandle>();
private readonly HeapBlobBuilder _guidBuilder = new HeapBlobBuilder(16); // full metadata has just a single guid
/// <summary>
/// Creates a builder for metadata tables and heaps.
/// </summary>
/// <param name="userStringHeapStartOffset">
/// Start offset of the User String heap.
/// The cumulative size of User String heaps of all previous EnC generations. Should be 0 unless the metadata is EnC delta metadata.
/// </param>
/// <param name="stringHeapStartOffset">
/// Start offset of the String heap.
/// The cumulative size of String heaps of all previous EnC generations. Should be 0 unless the metadata is EnC delta metadata.
/// </param>
/// <param name="blobHeapStartOffset">
/// Start offset of the Blob heap.
/// The cumulative size of Blob heaps of all previous EnC generations. Should be 0 unless the metadata is EnC delta metadata.
/// </param>
/// <param name="guidHeapStartOffset">
/// Start offset of the Guid heap.
/// The cumulative size of Guid heaps of all previous EnC generations. Should be 0 unless the metadata is EnC delta metadata.
/// </param>
/// <exception cref="ImageFormatLimitationException">Offset is too big.</exception>
/// <exception cref="ArgumentOutOfRangeException">Offset is negative.</exception>
/// <exception cref="ArgumentException"><paramref name="guidHeapStartOffset"/> is not a multiple of size of GUID.</exception>
public MetadataBuilder(
int userStringHeapStartOffset = 0,
int stringHeapStartOffset = 0,
int blobHeapStartOffset = 0,
int guidHeapStartOffset = 0)
{
// -1 for the 0 we always write at the beginning of the heap:
if (userStringHeapStartOffset >= UserStringHeapSizeLimit - 1)
{
Throw.HeapSizeLimitExceeded(HeapIndex.UserString);
}
if (userStringHeapStartOffset < 0)
{
Throw.ArgumentOutOfRange(nameof(userStringHeapStartOffset));
}
if (stringHeapStartOffset < 0)
{
Throw.ArgumentOutOfRange(nameof(stringHeapStartOffset));
}
if (blobHeapStartOffset < 0)
{
Throw.ArgumentOutOfRange(nameof(blobHeapStartOffset));
}
if (guidHeapStartOffset < 0)
{
Throw.ArgumentOutOfRange(nameof(guidHeapStartOffset));
}
if (guidHeapStartOffset % BlobUtilities.SizeOfGuid != 0)
{
throw new ArgumentException(SR.Format(SR.ValueMustBeMultiple, BlobUtilities.SizeOfGuid), nameof(guidHeapStartOffset));
}
// Add zero-th entry to all heaps, even in EnC delta.
// We don't want generation-relative handles to ever be IsNil.
// In both full and delta metadata all nil heap handles should have zero value.
// There should be no blob handle that references the 0 byte added at the
// beginning of the delta blob.
_userStringBuilder.WriteByte(0);
_blobs.Add(ImmutableArray<byte>.Empty, default(BlobHandle));
_blobHeapSize = 1;
// When EnC delta is applied #US, #String and #Blob heaps are appended.
// Thus indices of strings and blobs added to this generation are offset
// by the sum of respective heap sizes of all previous generations.
_userStringHeapStartOffset = userStringHeapStartOffset;
_stringHeapStartOffset = stringHeapStartOffset;
_blobHeapStartOffset = blobHeapStartOffset;
// Unlike other heaps, #Guid heap in EnC delta is zero-padded.
_guidBuilder.WriteBytes(0, guidHeapStartOffset);
}
/// <summary>
/// Sets the capacity of the specified table.
/// </summary>
/// <param name="heap">Heap index.</param>
/// <param name="byteCount">Number of bytes.</param>
/// <exception cref="ArgumentOutOfRangeException"><paramref name="heap"/> is not a valid heap index.</exception>
/// <exception cref="ArgumentOutOfRangeException"><paramref name="byteCount"/> is negative.</exception>
/// <remarks>
/// Use to reduce allocations if the approximate number of bytes is known ahead of time.
/// </remarks>
public void SetCapacity(HeapIndex heap, int byteCount)
{
if (byteCount < 0)
{
Throw.ArgumentOutOfRange(nameof(byteCount));
}
switch (heap)
{
case HeapIndex.Blob:
// Not useful to set capacity.
// By the time the blob heap is serialized we know the exact size we need.
break;
case HeapIndex.Guid:
_guidBuilder.SetCapacity(byteCount);
break;
case HeapIndex.String:
_stringHeapCapacity = byteCount;
break;
case HeapIndex.UserString:
_userStringBuilder.SetCapacity(byteCount);
break;
default:
Throw.ArgumentOutOfRange(nameof(heap));
break;
}
}
// internal for testing
internal int SerializeHandle(ImmutableArray<int> map, StringHandle handle) => map[handle.GetWriterVirtualIndex()];
internal int SerializeHandle(BlobHandle handle) => handle.GetHeapOffset();
internal int SerializeHandle(GuidHandle handle) => handle.Index;
internal int SerializeHandle(UserStringHandle handle) => handle.GetHeapOffset();
/// <summary>
/// Adds specified blob to Blob heap, if it's not there already.
/// </summary>
/// <param name="value"><see cref="BlobBuilder"/> containing the blob.</param>
/// <returns>Handle to the added or existing blob.</returns>
/// <exception cref="ArgumentNullException"><paramref name="value"/> is null.</exception>
public BlobHandle GetOrAddBlob(BlobBuilder value)
{
if (value == null)
{
Throw.ArgumentNull(nameof(value));
}
// TODO: avoid making a copy if the blob exists in the index
return GetOrAddBlob(value.ToImmutableArray());
}
/// <summary>
/// Adds specified blob to Blob heap, if it's not there already.
/// </summary>
/// <param name="value">Array containing the blob.</param>
/// <returns>Handle to the added or existing blob.</returns>
/// <exception cref="ArgumentNullException"><paramref name="value"/> is null.</exception>
public BlobHandle GetOrAddBlob(byte[] value)
{
if (value == null)
{
Throw.ArgumentNull(nameof(value));
}
// TODO: avoid making a copy if the blob exists in the index
return GetOrAddBlob(ImmutableArray.Create(value));
}
/// <summary>
/// Adds specified blob to Blob heap, if it's not there already.
/// </summary>
/// <param name="value">Array containing the blob.</param>
/// <returns>Handle to the added or existing blob.</returns>
/// <exception cref="ArgumentNullException"><paramref name="value"/> is null.</exception>
public BlobHandle GetOrAddBlob(ImmutableArray<byte> value)
{
if (value.IsDefault)
{
Throw.ArgumentNull(nameof(value));
}
BlobHandle handle;
if (!_blobs.TryGetValue(value, out handle))
{
handle = BlobHandle.FromOffset(_blobHeapStartOffset + _blobHeapSize);
_blobs.Add(value, handle);
_blobHeapSize += BlobWriterImpl.GetCompressedIntegerSize(value.Length) + value.Length;
}
return handle;
}
/// <summary>
/// Encodes a constant value to a blob and adds it to the Blob heap, if it's not there already.
/// Uses UTF16 to encode string constants.
/// </summary>
/// <param name="value">Constant value.</param>
/// <returns>Handle to the added or existing blob.</returns>
public unsafe BlobHandle GetOrAddConstantBlob(object value)
{
string str = value as string;
if (str != null)
{
return GetOrAddBlobUTF16(str);
}
var builder = PooledBlobBuilder.GetInstance();
builder.WriteConstant(value);
var result = GetOrAddBlob(builder);
builder.Free();
return result;
}
/// <summary>
/// Encodes a string using UTF16 encoding to a blob and adds it to the Blob heap, if it's not there already.
/// </summary>
/// <param name="value">String.</param>
/// <returns>Handle to the added or existing blob.</returns>
/// <exception cref="ArgumentNullException"><paramref name="value"/> is null.</exception>
public BlobHandle GetOrAddBlobUTF16(string value)
{
var builder = PooledBlobBuilder.GetInstance();
builder.WriteUTF16(value);
var handle = GetOrAddBlob(builder);
builder.Free();
return handle;
}
/// <summary>
/// Encodes a string using UTF8 encoding to a blob and adds it to the Blob heap, if it's not there already.
/// </summary>
/// <param name="value">Constant value.</param>
/// <param name="allowUnpairedSurrogates">
/// True to encode unpaired surrogates as specified, otherwise replace them with U+FFFD character.
/// </param>
/// <returns>Handle to the added or existing blob.</returns>
/// <exception cref="ArgumentNullException"><paramref name="value"/> is null.</exception>
public BlobHandle GetOrAddBlobUTF8(string value, bool allowUnpairedSurrogates = true)
{
var builder = PooledBlobBuilder.GetInstance();
builder.WriteUTF8(value, allowUnpairedSurrogates);
var handle = GetOrAddBlob(builder);
builder.Free();
return handle;
}
/// <summary>
/// Encodes a debug document name and adds it to the Blob heap, if it's not there already.
/// </summary>
/// <param name="value">Document name.</param>
/// <returns>
/// Handle to the added or existing document name blob
/// (see https://github.com/dotnet/corefx/blob/master/src/System.Reflection.Metadata/specs/PortablePdb-Metadata.md#DocumentNameBlob).
/// </returns>
/// <exception cref="ArgumentNullException"><paramref name="value"/> is null.</exception>
public BlobHandle GetOrAddDocumentName(string value)
{
if (value == null)
{
Throw.ArgumentNull(nameof(value));
}
char separator = ChooseSeparator(value);
var resultBuilder = PooledBlobBuilder.GetInstance();
resultBuilder.WriteByte((byte)separator);
var partBuilder = PooledBlobBuilder.GetInstance();
int i = 0;
while (true)
{
int next = value.IndexOf(separator, i);
partBuilder.WriteUTF8(value, i, (next >= 0 ? next : value.Length) - i, allowUnpairedSurrogates: true, prependSize: false);
resultBuilder.WriteCompressedInteger(GetOrAddBlob(partBuilder).GetHeapOffset());
if (next == -1)
{
break;
}
if (next == value.Length - 1)
{
// trailing separator:
resultBuilder.WriteByte(0);
break;
}
partBuilder.Clear();
i = next + 1;
}
partBuilder.Free();
var resultHandle = GetOrAddBlob(resultBuilder);
resultBuilder.Free();
return resultHandle;
}
private static char ChooseSeparator(string str)
{
const char s1 = '/';
const char s2 = '\\';
int count1 = 0, count2 = 0;
foreach (var c in str)
{
if (c == s1)
{
count1++;
}
else if (c == s2)
{
count2++;
}
}
return (count1 >= count2) ? s1 : s2;
}
/// <summary>
/// Adds specified Guid to Guid heap, if it's not there already.
/// </summary>
/// <param name="guid">Guid to add.</param>
/// <returns>Handle to the added or existing Guid.</returns>
public GuidHandle GetOrAddGuid(Guid guid)
{
if (guid == Guid.Empty)
{
return default(GuidHandle);
}
GuidHandle result;
if (_guids.TryGetValue(guid, out result))
{
return result;
}
result = GetNewGuidHandle();
_guids.Add(guid, result);
_guidBuilder.WriteGuid(guid);
return result;
}
/// <summary>
/// Reserves space on the Guid heap for a GUID.
/// </summary>
/// <param name="content">
/// <see cref="Blob"/> representing the GUID blob as stored on the heap.
/// </param>
/// <returns>Handle to the reserved Guid.</returns>
/// <exception cref="ImageFormatLimitationException">The remaining space on the heap is too small to fit the string.</exception>
public GuidHandle ReserveGuid(out Blob content)
{
var handle = GetNewGuidHandle();
content = _guidBuilder.ReserveBytes(BlobUtilities.SizeOfGuid);
return handle;
}
private GuidHandle GetNewGuidHandle()
{
// Unlike #Blob, #String and #US streams delta #GUID stream is padded to the
// size of the previous generation #GUID stream before new GUIDs are added.
// The first GUID added in a delta will thus have an index that equals the number
// of GUIDs in all previous generations + 1.
// Metadata Spec:
// The Guid heap is an array of GUIDs, each 16 bytes wide.
// Its first element is numbered 1, its second 2, and so on.
return GuidHandle.FromIndex((_guidBuilder.Count >> 4) + 1);
}
/// <summary>
/// Adds specified string to String heap, if it's not there already.
/// </summary>
/// <param name="value">Array containing the blob.</param>
/// <returns>Handle to the added or existing blob.</returns>
/// <exception cref="ArgumentNullException"><paramref name="value"/> is null.</exception>
public StringHandle GetOrAddString(string value)
{
if (value == null)
{
Throw.ArgumentNull(nameof(value));
}
StringHandle handle;
if (value.Length == 0)
{
handle = default(StringHandle);
}
else if (!_strings.TryGetValue(value, out handle))
{
handle = StringHandle.FromWriterVirtualIndex(_strings.Count + 1); // idx 0 is reserved for empty string
_strings.Add(value, handle);
}
return handle;
}
/// <summary>
/// Reserves space on the User String heap for a string of specified length.
/// </summary>
/// <param name="length">The number of characters to reserve.</param>
/// <param name="reservedUserString">
/// <see cref="Blob"/> representing the entire User String blob (including its length and terminal character).
/// Use <see cref="BlobWriter.WriteUserString(string)"/> to fill in the content.
/// </param>
/// <returns>
/// Handle to the reserved User String.
/// May be used in <see cref="InstructionEncoder.LoadString(UserStringHandle)"/>.
/// </returns>
/// <exception cref="ImageFormatLimitationException">The remaining space on the heap is too small to fit the string.</exception>
/// <exception cref="ArgumentOutOfRangeException"><paramref name="length"/> is negative.</exception>
public UserStringHandle ReserveUserString(int length, out Blob reservedUserString)
{
if (length < 0)
{
Throw.ArgumentOutOfRange(nameof(length));
}
var handle = GetNewUserStringHandle();
int encodedLength = BlobUtilities.GetUserStringByteLength(length);
reservedUserString = _userStringBuilder.ReserveBytes(BlobWriterImpl.GetCompressedIntegerSize(encodedLength) + encodedLength);
return handle;
}
/// <summary>
/// Adds specified string to User String heap, if it's not there already.
/// </summary>
/// <param name="value">String to add.</param>
/// <returns>
/// Handle to the added or existing string.
/// May be used in <see cref="InstructionEncoder.LoadString(UserStringHandle)"/>.
/// </returns>
/// <exception cref="ImageFormatLimitationException">The remaining space on the heap is too small to fit the string.</exception>
/// <exception cref="ArgumentNullException"><paramref name="value"/> is null.</exception>
public UserStringHandle GetOrAddUserString(string value)
{
if (value == null)
{
Throw.ArgumentNull(nameof(value));
}
UserStringHandle handle;
if (!_userStrings.TryGetValue(value, out handle))
{
handle = GetNewUserStringHandle();
_userStrings.Add(value, handle);
_userStringBuilder.WriteUserString(value);
}
return handle;
}
private UserStringHandle GetNewUserStringHandle()
{
int offset = _userStringHeapStartOffset + _userStringBuilder.Count;
// Native metadata emitter allows strings to exceed the heap size limit as long
// as the index is within the limits (see https://github.com/dotnet/roslyn/issues/9852)
if (offset >= UserStringHeapSizeLimit)
{
Throw.HeapSizeLimitExceeded(HeapIndex.UserString);
}
return UserStringHandle.FromOffset(offset);
}
/// <summary>
/// Fills in stringIndexMap with data from stringIndex and write to stringWriter.
/// Releases stringIndex as the stringTable is sealed after this point.
/// </summary>
private static ImmutableArray<int> SerializeStringHeap(
BlobBuilder heapBuilder,
Dictionary<string, StringHandle> strings,
int stringHeapStartOffset)
{
// Sort by suffix and remove stringIndex
var sorted = new List<KeyValuePair<string, StringHandle>>(strings);
sorted.Sort(SuffixSort.Instance);
// Create VirtIdx to Idx map and add entry for empty string
int totalCount = sorted.Count + 1;
var stringVirtualIndexToHeapOffsetMap = ImmutableArray.CreateBuilder<int>(totalCount);
stringVirtualIndexToHeapOffsetMap.Count = totalCount;
stringVirtualIndexToHeapOffsetMap[0] = 0;
heapBuilder.WriteByte(0);
// Find strings that can be folded
string prev = string.Empty;
foreach (KeyValuePair<string, StringHandle> entry in sorted)
{
int position = stringHeapStartOffset + heapBuilder.Count;
// It is important to use ordinal comparison otherwise we'll use the current culture!
if (prev.EndsWith(entry.Key, StringComparison.Ordinal) && !BlobUtilities.IsLowSurrogateChar(entry.Key[0]))
{
// Map over the tail of prev string. Watch for null-terminator of prev string.
stringVirtualIndexToHeapOffsetMap[entry.Value.GetWriterVirtualIndex()] = position - (BlobUtilities.GetUTF8ByteCount(entry.Key) + 1);
}
else
{
stringVirtualIndexToHeapOffsetMap[entry.Value.GetWriterVirtualIndex()] = position;
heapBuilder.WriteUTF8(entry.Key, allowUnpairedSurrogates: false);
heapBuilder.WriteByte(0);
}
prev = entry.Key;
}
return stringVirtualIndexToHeapOffsetMap.MoveToImmutable();
}
/// <summary>
/// Sorts strings such that a string is followed immediately by all strings
/// that are a suffix of it.
/// </summary>
private sealed class SuffixSort : IComparer<KeyValuePair<string, StringHandle>>
{
internal static SuffixSort Instance = new SuffixSort();
public int Compare(KeyValuePair<string, StringHandle> xPair, KeyValuePair<string, StringHandle> yPair)
{
string x = xPair.Key;
string y = yPair.Key;
for (int i = x.Length - 1, j = y.Length - 1; i >= 0 & j >= 0; i--, j--)
{
if (x[i] < y[j])
{
return -1;
}
if (x[i] > y[j])
{
return +1;
}
}
return y.Length.CompareTo(x.Length);
}
}
internal void WriteHeapsTo(BlobBuilder builder, BlobBuilder stringHeap)
{
WriteAligned(stringHeap, builder);
WriteAligned(_userStringBuilder, builder);
WriteAligned(_guidBuilder, builder);
WriteAlignedBlobHeap(builder);
}
private void WriteAlignedBlobHeap(BlobBuilder builder)
{
int alignment = BitArithmetic.Align(_blobHeapSize, 4) - _blobHeapSize;
var writer = new BlobWriter(builder.ReserveBytes(_blobHeapSize + alignment));
// Perf consideration: With large heap the following loop may cause a lot of cache misses
// since the order of entries in _blobs dictionary depends on the hash of the array values,
// which is not correlated to the heap index. If we observe such issue we should order
// the entries by heap position before running this loop.
int startOffset = _blobHeapStartOffset;
foreach (var entry in _blobs)
{
int heapOffset = entry.Value.GetHeapOffset();
var blob = entry.Key;
writer.Offset = (heapOffset == 0) ? 0 : heapOffset - startOffset;
writer.WriteCompressedInteger(blob.Length);
writer.WriteBytes(blob);
}
writer.Offset = _blobHeapSize;
writer.WriteBytes(0, alignment);
}
private static void WriteAligned(BlobBuilder source, BlobBuilder target)
{
int length = source.Count;
target.LinkSuffix(source);
target.WriteBytes(0, BitArithmetic.Align(length, 4) - length);
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using Xunit;
namespace System.Threading.Tasks.Dataflow.Tests
{
public class TransformManyBlockTests
{
[Fact]
public async Task TestCtor()
{
var blocks = new[] {
new TransformManyBlock<int, int>(DataflowTestHelpers.ToEnumerable),
new TransformManyBlock<int, int>(DataflowTestHelpers.ToEnumerable, new ExecutionDataflowBlockOptions { MaxMessagesPerTask = 1 }),
new TransformManyBlock<int, int>(i => Task.Run(() => DataflowTestHelpers.ToEnumerable(i)), new ExecutionDataflowBlockOptions { MaxMessagesPerTask = 1 })
};
foreach (var block in blocks)
{
Assert.Equal(expected: 0, actual: block.InputCount);
Assert.Equal(expected: 0, actual: block.OutputCount);
Assert.False(block.Completion.IsCompleted);
}
blocks = new[] {
new TransformManyBlock<int, int>(DataflowTestHelpers.ToEnumerable,
new ExecutionDataflowBlockOptions { CancellationToken = new CancellationToken(true) }),
new TransformManyBlock<int, int>(i => Task.Run(() => DataflowTestHelpers.ToEnumerable(i)),
new ExecutionDataflowBlockOptions { CancellationToken = new CancellationToken(true) })
};
foreach (var block in blocks)
{
Assert.Equal(expected: 0, actual: block.InputCount);
Assert.Equal(expected: 0, actual: block.OutputCount);
await Assert.ThrowsAnyAsync<OperationCanceledException>(() => block.Completion);
}
}
[Fact]
public void TestArgumentExceptions()
{
Assert.Throws<ArgumentNullException>(() => new TransformManyBlock<int, int>((Func<int, IEnumerable<int>>)null));
Assert.Throws<ArgumentNullException>(() => new TransformManyBlock<int, int>((Func<int, Task<IEnumerable<int>>>)null));
Assert.Throws<ArgumentNullException>(() => new TransformManyBlock<int, int>(DataflowTestHelpers.ToEnumerable, null));
Assert.Throws<ArgumentNullException>(() => new TransformManyBlock<int, int>(i => Task.Run(() => DataflowTestHelpers.ToEnumerable(i)), null));
DataflowTestHelpers.TestArgumentsExceptions(new TransformManyBlock<int, int>(DataflowTestHelpers.ToEnumerable));
}
[Fact]
public void TestToString()
{
DataflowTestHelpers.TestToString(nameFormat =>
nameFormat != null ?
new TransformManyBlock<int, int>(DataflowTestHelpers.ToEnumerable, new ExecutionDataflowBlockOptions() { NameFormat = nameFormat }) :
new TransformManyBlock<int, int>(DataflowTestHelpers.ToEnumerable));
}
[Fact]
public async Task TestOfferMessage()
{
var generators = new Func<TransformManyBlock<int, int>>[]
{
() => new TransformManyBlock<int, int>(DataflowTestHelpers.ToEnumerable),
() => new TransformManyBlock<int, int>(DataflowTestHelpers.ToEnumerable, new ExecutionDataflowBlockOptions { BoundedCapacity = 10 }),
() => new TransformManyBlock<int, int>(i => Task.Run(() => DataflowTestHelpers.ToEnumerable(i)), new ExecutionDataflowBlockOptions { BoundedCapacity = 10, MaxMessagesPerTask = 1 })
};
foreach (var generator in generators)
{
DataflowTestHelpers.TestOfferMessage_ArgumentValidation(generator());
var target = generator();
DataflowTestHelpers.TestOfferMessage_AcceptsDataDirectly(target);
DataflowTestHelpers.TestOfferMessage_CompleteAndOffer(target);
target = generator();
await DataflowTestHelpers.TestOfferMessage_AcceptsViaLinking(target);
DataflowTestHelpers.TestOfferMessage_CompleteAndOffer(target);
}
}
[Fact]
public void TestPost()
{
foreach (bool bounded in DataflowTestHelpers.BooleanValues)
foreach (var tb in new[] {
new TransformManyBlock<int, int>(DataflowTestHelpers.ToEnumerable, new ExecutionDataflowBlockOptions { BoundedCapacity = bounded ? 1 : -1 }),
new TransformManyBlock<int, int>(i => Task.Run(() => DataflowTestHelpers.ToEnumerable(i)), new ExecutionDataflowBlockOptions { BoundedCapacity = bounded ? 1 : -1 })})
{
Assert.True(tb.Post(0));
tb.Complete();
Assert.False(tb.Post(0));
}
}
[Fact]
public Task TestCompletionTask()
{
return DataflowTestHelpers.TestCompletionTask(() => new TransformManyBlock<int, int>(DataflowTestHelpers.ToEnumerable));
}
[Fact]
public async Task TestLinkToOptions()
{
const int Messages = 1;
foreach (bool append in DataflowTestHelpers.BooleanValues)
foreach (var tb in new[] {
new TransformManyBlock<int, int>(DataflowTestHelpers.ToEnumerable),
new TransformManyBlock<int, int>(i => Task.Run(() => DataflowTestHelpers.ToEnumerable(i))) })
{
var values = new int[Messages];
var targets = new ActionBlock<int>[Messages];
for (int i = 0; i < Messages; i++)
{
int slot = i;
targets[i] = new ActionBlock<int>(item => values[slot] = item);
tb.LinkTo(targets[i], new DataflowLinkOptions { MaxMessages = 1, Append = append });
}
tb.PostRange(0, Messages);
tb.Complete();
await tb.Completion;
for (int i = 0; i < Messages; i++)
{
Assert.Equal(
expected: append ? i : Messages - i - 1,
actual: values[i]);
}
}
}
[Fact]
public async Task TestReceives()
{
for (int test = 0; test < 2; test++)
{
foreach (var tb in new[] {
new TransformManyBlock<int, int>(i => Enumerable.Repeat(i * 2, 1)),
new TransformManyBlock<int, int>(i => Task.Run(() => Enumerable.Repeat(i * 2, 1))) })
{
tb.PostRange(0, 5);
for (int i = 0; i < 5; i++)
{
Assert.Equal(expected: i * 2, actual: await tb.ReceiveAsync());
}
int item;
IList<int> items;
Assert.False(tb.TryReceive(out item));
Assert.False(tb.TryReceiveAll(out items));
}
}
}
[Fact]
public async Task TestCircularLinking()
{
const int Iters = 200;
foreach (bool sync in DataflowTestHelpers.BooleanValues)
{
var tcs = new TaskCompletionSource<bool>();
Func<int, IEnumerable<int>> body = i => {
if (i >= Iters) tcs.SetResult(true);
return Enumerable.Repeat(i + 1, 1);
};
TransformManyBlock<int, int> tb = sync ?
new TransformManyBlock<int, int>(body) :
new TransformManyBlock<int, int>(i => Task.Run(() => body(i)));
using (tb.LinkTo(tb))
{
tb.Post(0);
await tcs.Task;
tb.Complete();
}
}
}
[Fact]
public async Task TestProducerConsumer()
{
foreach (TaskScheduler scheduler in new[] { TaskScheduler.Default, new ConcurrentExclusiveSchedulerPair().ConcurrentScheduler })
foreach (int maxMessagesPerTask in new[] { DataflowBlockOptions.Unbounded, 1, 2 })
foreach (int boundedCapacity in new[] { DataflowBlockOptions.Unbounded, 1, 2 })
foreach (int dop in new[] { 1, 2 })
foreach (int elementsPerItem in new[] { 1, 3, 5 })
foreach (bool sync in DataflowTestHelpers.BooleanValues)
{
const int Messages = 50;
var options = new ExecutionDataflowBlockOptions
{
BoundedCapacity = boundedCapacity,
MaxDegreeOfParallelism = dop,
MaxMessagesPerTask = maxMessagesPerTask,
TaskScheduler = scheduler
};
TransformManyBlock<int, int> tb = sync ?
new TransformManyBlock<int, int>(i => Enumerable.Repeat(i, elementsPerItem), options) :
new TransformManyBlock<int, int>(i => Task.Run(() => Enumerable.Repeat(i, elementsPerItem)), options);
await Task.WhenAll(
Task.Run(async delegate { // consumer
int i = 0;
int processed = 0;
while (await tb.OutputAvailableAsync())
{
Assert.Equal(expected: i, actual: await tb.ReceiveAsync());
processed++;
if (processed % elementsPerItem == 0)
{
i++;
}
}
}),
Task.Run(async delegate { // producer
for (int i = 0; i < Messages; i++)
{
await tb.SendAsync(i);
}
tb.Complete();
}));
}
}
[Fact]
public async Task TestMessagePostponement()
{
const int Excess = 10;
foreach (int boundedCapacity in new[] { 1, 3 })
{
var options = new ExecutionDataflowBlockOptions { BoundedCapacity = boundedCapacity };
foreach (var tb in new[] {
new TransformManyBlock<int, int>(DataflowTestHelpers.ToEnumerable, options),
new TransformManyBlock<int, int>(i => Task.Run(() => DataflowTestHelpers.ToEnumerable(i)), options) })
{
var sendAsync = new Task<bool>[boundedCapacity + Excess];
for (int i = 0; i < boundedCapacity + Excess; i++)
{
sendAsync[i] = tb.SendAsync(i);
}
tb.Complete();
for (int i = 0; i < boundedCapacity; i++)
{
Assert.True(sendAsync[i].IsCompleted);
Assert.True(sendAsync[i].Result);
}
for (int i = 0; i < Excess; i++)
{
Assert.False(await sendAsync[boundedCapacity + i]);
}
}
}
}
[Fact]
public async Task TestMultipleYields()
{
const int Messages = 10;
var t = new TransformManyBlock<int, int>(i => Enumerable.Range(0, Messages));
t.Post(42);
t.Complete();
for (int i = 0; i < Messages; i++)
{
Assert.False(t.Completion.IsCompleted);
Assert.Equal(expected: i, actual: await t.ReceiveAsync());
}
await t.Completion;
}
[Fact]
public async Task TestReserveReleaseConsume()
{
var tb = new TransformManyBlock<int, int>(DataflowTestHelpers.ToEnumerable);
tb.Post(1);
await DataflowTestHelpers.TestReserveAndRelease(tb);
tb = new TransformManyBlock<int, int>(DataflowTestHelpers.ToEnumerable);
tb.Post(2);
await DataflowTestHelpers.TestReserveAndConsume(tb);
}
[Fact]
public async Task TestCountZeroAtCompletion()
{
var cts = new CancellationTokenSource();
var tb = new TransformManyBlock<int, int>(DataflowTestHelpers.ToEnumerable, new ExecutionDataflowBlockOptions() { CancellationToken = cts.Token });
tb.Post(1);
cts.Cancel();
await Assert.ThrowsAnyAsync<OperationCanceledException>(() => tb.Completion);
Assert.Equal(expected: 0, actual: tb.InputCount);
Assert.Equal(expected: 0, actual: tb.OutputCount);
cts = new CancellationTokenSource();
tb = new TransformManyBlock<int, int>(DataflowTestHelpers.ToEnumerable);
tb.Post(1);
((IDataflowBlock)tb).Fault(new InvalidOperationException());
await Assert.ThrowsAnyAsync<InvalidOperationException>(() => tb.Completion);
Assert.Equal(expected: 0, actual: tb.InputCount);
Assert.Equal(expected: 0, actual: tb.OutputCount);
}
[Fact]
public void TestInputCount()
{
foreach (bool sync in DataflowTestHelpers.BooleanValues)
{
Barrier barrier1 = new Barrier(2), barrier2 = new Barrier(2);
Func<int, IEnumerable<int>> body = item => {
barrier1.SignalAndWait();
// will test InputCount here
barrier2.SignalAndWait();
return new[] { item };
};
TransformManyBlock<int, int> tb = sync ?
new TransformManyBlock<int, int>(body) :
new TransformManyBlock<int, int>(i => Task.Run(() => body(i)));
for (int iter = 0; iter < 2; iter++)
{
tb.PostItems(1, 2);
for (int i = 1; i >= 0; i--)
{
barrier1.SignalAndWait();
Assert.Equal(expected: i, actual: tb.InputCount);
barrier2.SignalAndWait();
}
}
}
}
[Fact]
[OuterLoop] // spins waiting for a condition to be true, though it should happen very quickly
public async Task TestCount()
{
var tb = new TransformManyBlock<int, int>(DataflowTestHelpers.ToEnumerable);
Assert.Equal(expected: 0, actual: tb.InputCount);
Assert.Equal(expected: 0, actual: tb.OutputCount);
tb.PostRange(1, 11);
await Task.Run(() => SpinWait.SpinUntil(() => tb.OutputCount == 10));
for (int i = 10; i > 0; i--)
{
int item;
Assert.True(tb.TryReceive(out item));
Assert.Equal(expected: 11 - i, actual: item);
Assert.Equal(expected: i - 1, actual: tb.OutputCount);
}
}
[Fact]
public async Task TestChainedSendReceive()
{
foreach (bool post in DataflowTestHelpers.BooleanValues)
foreach (bool sync in DataflowTestHelpers.BooleanValues)
{
Func<TransformManyBlock<int, int>> func = sync ?
(Func<TransformManyBlock<int, int>>)(() => new TransformManyBlock<int, int>(i => new[] { i * 2 })) :
(Func<TransformManyBlock<int, int>>)(() => new TransformManyBlock<int, int>(i => Task.Run(() => Enumerable.Repeat(i * 2, 1))));
var network = DataflowTestHelpers.Chain<TransformManyBlock<int, int>, int>(4, func);
const int Iters = 10;
for (int i = 0; i < Iters; i++)
{
if (post)
{
network.Post(i);
}
else
{
await network.SendAsync(i);
}
Assert.Equal(expected: i * 16, actual: await network.ReceiveAsync());
}
}
}
[Fact]
public async Task TestSendAllThenReceive()
{
foreach (bool post in DataflowTestHelpers.BooleanValues)
foreach (bool sync in DataflowTestHelpers.BooleanValues)
{
Func<TransformManyBlock<int, int>> func = sync ?
(Func<TransformManyBlock<int, int>>)(() => new TransformManyBlock<int, int>(i => new[] { i * 2 })) :
(Func<TransformManyBlock<int, int>>)(() => new TransformManyBlock<int, int>(i => Task.Run(() => Enumerable.Repeat(i * 2, 1))));
var network = DataflowTestHelpers.Chain<TransformManyBlock<int, int>, int>(4, func);
const int Iters = 10;
if (post)
{
network.PostRange(0, Iters);
}
else
{
await Task.WhenAll(from i in Enumerable.Range(0, Iters) select network.SendAsync(i));
}
for (int i = 0; i < Iters; i++)
{
Assert.Equal(expected: i * 16, actual: await network.ReceiveAsync());
}
}
}
[Fact]
public async Task TestPrecanceled()
{
var bb = new TransformManyBlock<int, int>(DataflowTestHelpers.ToEnumerable,
new ExecutionDataflowBlockOptions { CancellationToken = new CancellationToken(canceled: true) });
int ignoredValue;
IList<int> ignoredValues;
IDisposable link = bb.LinkTo(DataflowBlock.NullTarget<int>());
Assert.NotNull(link);
link.Dispose();
Assert.False(bb.Post(42));
var t = bb.SendAsync(42);
Assert.True(t.IsCompleted);
Assert.False(t.Result);
Assert.False(bb.TryReceiveAll(out ignoredValues));
Assert.False(bb.TryReceive(out ignoredValue));
Assert.NotNull(bb.Completion);
await Assert.ThrowsAnyAsync<OperationCanceledException>(() => bb.Completion);
bb.Complete(); // just make sure it doesn't throw
}
[Fact]
public async Task TestExceptions()
{
var tb1 = new TransformManyBlock<int, int>((Func<int, IEnumerable<int>>)(i => { throw new InvalidCastException(); }));
var tb2 = new TransformManyBlock<int, int>((Func<int, Task<IEnumerable<int>>>)(i => { throw new InvalidProgramException(); }));
var tb3 = new TransformManyBlock<int, int>((Func<int, Task<IEnumerable<int>>>)(i => Task.Run((Func<IEnumerable<int>>)(() => { throw new InvalidTimeZoneException(); }))));
var tb4 = new TransformManyBlock<int, int>(i => ExceptionAfter(3));
var tb5 = new TransformManyBlock<int, int>(i => Task.Run(() => ExceptionAfter(3)));
for (int i = 0; i < 3; i++)
{
tb1.Post(i);
tb2.Post(i);
tb3.Post(i);
tb4.Post(i);
tb5.Post(i);
}
await Assert.ThrowsAsync<InvalidCastException>(() => tb1.Completion);
await Assert.ThrowsAsync<InvalidProgramException>(() => tb2.Completion);
await Assert.ThrowsAsync<InvalidTimeZoneException>(() => tb3.Completion);
await Assert.ThrowsAsync<FormatException>(() => tb4.Completion);
await Assert.ThrowsAsync<FormatException>(() => tb5.Completion);
Assert.All(new[] { tb1, tb2, tb3 }, tb => Assert.True(tb.InputCount == 0 && tb.OutputCount == 0));
}
private IEnumerable<int> ExceptionAfter(int iterations)
{
for (int i = 0; i < iterations; i++)
{
yield return i;
}
throw new FormatException();
}
[Fact]
public async Task TestFaultingAndCancellation()
{
foreach (bool fault in DataflowTestHelpers.BooleanValues)
{
var cts = new CancellationTokenSource();
var tb = new TransformManyBlock<int, int>(DataflowTestHelpers.ToEnumerable, new ExecutionDataflowBlockOptions { CancellationToken = cts.Token });
tb.PostRange(0, 4);
Assert.Equal(expected: 0, actual: await tb.ReceiveAsync());
Assert.Equal(expected: 1, actual: await tb.ReceiveAsync());
if (fault)
{
Assert.Throws<ArgumentNullException>(() => ((IDataflowBlock)tb).Fault(null));
((IDataflowBlock)tb).Fault(new InvalidCastException());
await Assert.ThrowsAsync<InvalidCastException>(() => tb.Completion);
}
else
{
cts.Cancel();
await Assert.ThrowsAnyAsync<OperationCanceledException>(() => tb.Completion);
}
Assert.Equal(expected: 0, actual: tb.InputCount);
Assert.Equal(expected: 0, actual: tb.OutputCount);
}
}
[Fact]
public async Task TestCancellationExceptionsIgnored()
{
foreach (bool sync in DataflowTestHelpers.BooleanValues)
{
Func<int, IEnumerable<int>> body = i => {
if ((i % 2) == 0) throw new OperationCanceledException();
return new[] { i };
};
TransformManyBlock<int, int> t = sync ?
new TransformManyBlock<int, int>(body) :
new TransformManyBlock<int, int>(async i => await Task.Run(() => body(i)));
t.PostRange(0, 2);
t.Complete();
for (int i = 0; i < 2; i++)
{
if ((i % 2) != 0)
{
Assert.Equal(expected: i, actual: await t.ReceiveAsync());
}
}
await t.Completion;
}
}
[Fact]
public async Task TestNullTasksIgnored()
{
foreach (int dop in new[] { DataflowBlockOptions.Unbounded, 1, 2 })
{
var tb = new TransformManyBlock<int, int>(i => {
if ((i % 2) == 0) return null;
return Task.Run(() => (IEnumerable<int>)new[] { i });
}, new ExecutionDataflowBlockOptions { MaxDegreeOfParallelism = dop });
const int Iters = 100;
tb.PostRange(0, Iters);
tb.Complete();
for (int i = 0; i < Iters; i++)
{
if ((i % 2) != 0)
{
Assert.Equal(expected: i, actual: await tb.ReceiveAsync());
}
}
await tb.Completion;
}
}
[Fact]
public async Task TestYieldingNoResults()
{
foreach (int dop in new[] { 1, Environment.ProcessorCount })
foreach (int boundedCapacity in new[] { DataflowBlockOptions.Unbounded, 1, 2 })
{
const int Modes = 3, Iters = 100;
var tb = new TransformManyBlock<int, int>(i => {
switch (i % Modes)
{
default:
case 0:
return new List<int> { i };
case 1:
return new int[0];
case 2:
return new Collection<int> { i, i + 1 };
}
}, new ExecutionDataflowBlockOptions { MaxDegreeOfParallelism = dop, BoundedCapacity = boundedCapacity });
var source = new BufferBlock<int>();
source.PostRange(0, Modes * Iters);
source.Complete();
source.LinkTo(tb, new DataflowLinkOptions { PropagateCompletion = true });
int received = 0;
while (await tb.OutputAvailableAsync())
{
await tb.ReceiveAsync();
received++;
}
Assert.Equal(expected: Modes * Iters, actual: received);
}
}
[Fact]
public async Task TestArrayListReusePossibleForDop1()
{
foreach (int boundedCapacity in new[] { DataflowBlockOptions.Unbounded, 2 })
foreach (bool sync in DataflowTestHelpers.BooleanValues)
{
foreach (int dop in new[] { 1, Environment.ProcessorCount })
{
var dbo = new ExecutionDataflowBlockOptions { BoundedCapacity = boundedCapacity, MaxDegreeOfParallelism = dop };
foreach (IList<int> list in new IList<int>[] { new int[1], new List<int> { 0 }, new Collection<int> { 0 } })
{
int nextExpectedValue = 1;
TransformManyBlock<int, int> transform = null;
Func<int, IEnumerable<int>> body = i => {
if (i == 100) // we're done iterating
{
transform.Complete();
return (IEnumerable<int>)null;
}
else if (dop == 1)
{
list[0] = i + 1; // reuse the list over and over, but only at dop == 1
return (IEnumerable<int>)list;
}
else if (list is int[])
{
return new int[1] { i + 1 };
}
else if (list is List<int>)
{
return new List<int>() { i + 1 };
}
else
{
return new Collection<int>() { i + 1 };
}
};
transform = sync ?
new TransformManyBlock<int, int>(body, dbo) :
new TransformManyBlock<int, int>(i => Task.Run(() => body(i)), dbo);
TransformBlock<int, int> verifier = new TransformBlock<int, int>(i => {
Assert.Equal(expected: nextExpectedValue, actual: i);
nextExpectedValue++;
return i;
});
transform.LinkTo(verifier);
verifier.LinkTo(transform);
await transform.SendAsync(0);
await transform.Completion;
}
}
}
}
[Theory]
[InlineData(DataflowBlockOptions.Unbounded, 1, null)]
[InlineData(DataflowBlockOptions.Unbounded, 2, null)]
[InlineData(DataflowBlockOptions.Unbounded, DataflowBlockOptions.Unbounded, null)]
[InlineData(1, 1, null)]
[InlineData(1, 2, null)]
[InlineData(1, DataflowBlockOptions.Unbounded, null)]
[InlineData(2, 2, true)]
[InlineData(2, 1, false)] // no force ordered, but dop == 1, so it doesn't matter
public async Task TestOrdering_Sync_OrderedEnabled(int mmpt, int dop, bool? EnsureOrdered)
{
const int iters = 1000;
var options = new ExecutionDataflowBlockOptions { MaxDegreeOfParallelism = dop, MaxMessagesPerTask = mmpt };
if (EnsureOrdered == null)
{
Assert.True(options.EnsureOrdered);
}
else
{
options.EnsureOrdered = EnsureOrdered.Value;
}
var tb = new TransformManyBlock<int, int>(i => new[] { i }, options);
tb.PostRange(0, iters);
for (int i = 0; i < iters; i++)
{
Assert.Equal(expected: i, actual: await tb.ReceiveAsync());
}
tb.Complete();
await tb.Completion;
}
[Theory]
[InlineData(DataflowBlockOptions.Unbounded, 1, null)]
[InlineData(DataflowBlockOptions.Unbounded, 2, null)]
[InlineData(DataflowBlockOptions.Unbounded, DataflowBlockOptions.Unbounded, null)]
[InlineData(1, 1, null)]
[InlineData(1, 2, null)]
[InlineData(1, DataflowBlockOptions.Unbounded, null)]
[InlineData(2, 2, true)]
[InlineData(2, 1, false)] // no force ordered, but dop == 1, so it doesn't matter
public async Task TestOrdering_Async_OrderedEnabled(int mmpt, int dop, bool? EnsureOrdered)
{
const int iters = 1000;
var options = new ExecutionDataflowBlockOptions { MaxDegreeOfParallelism = dop, MaxMessagesPerTask = mmpt };
if (EnsureOrdered == null)
{
Assert.True(options.EnsureOrdered);
}
else
{
options.EnsureOrdered = EnsureOrdered.Value;
}
var tb = new TransformManyBlock<int, int>(i => Task.FromResult(Enumerable.Repeat(i, 1)), options);
tb.PostRange(0, iters);
for (int i = 0; i < iters; i++)
{
Assert.Equal(expected: i, actual: await tb.ReceiveAsync());
}
tb.Complete();
await tb.Completion;
}
[Theory]
[InlineData(true)]
[InlineData(false)]
public async Task TestOrdering_Async_OrderedDisabled(bool trustedEnumeration)
{
// If ordering were enabled, this test would hang.
var options = new ExecutionDataflowBlockOptions { MaxDegreeOfParallelism = DataflowBlockOptions.Unbounded, EnsureOrdered = false };
var tasks = new TaskCompletionSource<IEnumerable<int>>[10];
for (int i = 0; i < tasks.Length; i++)
{
tasks[i] = new TaskCompletionSource<IEnumerable<int>>();
}
var tb = new TransformManyBlock<int, int>(i => tasks[i].Task, options);
tb.PostRange(0, tasks.Length);
for (int i = tasks.Length - 1; i >= 0; i--)
{
tasks[i].SetResult(trustedEnumeration ?
new[] { i } :
Enumerable.Repeat(i, 1));
Assert.Equal(expected: i, actual: await tb.ReceiveAsync());
}
tb.Complete();
await tb.Completion;
}
[Theory]
[InlineData(true)]
[InlineData(false)]
public async Task TestOrdering_Sync_OrderedDisabled(bool trustedEnumeration)
{
// If ordering were enabled, this test would hang.
var options = new ExecutionDataflowBlockOptions { MaxDegreeOfParallelism = 2, EnsureOrdered = false };
var mres = new ManualResetEventSlim();
var tb = new TransformManyBlock<int, int>(i =>
{
if (i == 0) mres.Wait();
return trustedEnumeration ?
new[] { i } :
Enumerable.Repeat(i, 1);
}, options);
tb.Post(0);
tb.Post(1);
Assert.Equal(1, await tb.ReceiveAsync());
mres.Set();
Assert.Equal(0, await tb.ReceiveAsync());
tb.Complete();
await tb.Completion;
}
}
}
| |
namespace DockSample
{
partial class DummySolutionExplorer
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
System.Windows.Forms.TreeNode treeNode1 = new System.Windows.Forms.TreeNode("Solution \'WinFormsUI\' (2 projects)");
System.Windows.Forms.TreeNode treeNode2 = new System.Windows.Forms.TreeNode("System", 6, 6);
System.Windows.Forms.TreeNode treeNode3 = new System.Windows.Forms.TreeNode("System.Data", 6, 6);
System.Windows.Forms.TreeNode treeNode4 = new System.Windows.Forms.TreeNode("System.Drawing", 6, 6);
System.Windows.Forms.TreeNode treeNode5 = new System.Windows.Forms.TreeNode("System.Windows.Forms", 6, 6);
System.Windows.Forms.TreeNode treeNode6 = new System.Windows.Forms.TreeNode("System.XML", 6, 6);
System.Windows.Forms.TreeNode treeNode7 = new System.Windows.Forms.TreeNode("WeifenLuo.WinFormsUI.Docking", 6, 6);
System.Windows.Forms.TreeNode treeNode8 = new System.Windows.Forms.TreeNode("References", 4, 4, new System.Windows.Forms.TreeNode[] {
treeNode2,
treeNode3,
treeNode4,
treeNode5,
treeNode6,
treeNode7});
System.Windows.Forms.TreeNode treeNode9 = new System.Windows.Forms.TreeNode("BlankIcon.ico", 5, 5);
System.Windows.Forms.TreeNode treeNode10 = new System.Windows.Forms.TreeNode("CSProject.ico", 5, 5);
System.Windows.Forms.TreeNode treeNode11 = new System.Windows.Forms.TreeNode("OutputWindow.ico", 5, 5);
System.Windows.Forms.TreeNode treeNode12 = new System.Windows.Forms.TreeNode("References.ico", 5, 5);
System.Windows.Forms.TreeNode treeNode13 = new System.Windows.Forms.TreeNode("SolutionExplorer.ico", 5, 5);
System.Windows.Forms.TreeNode treeNode14 = new System.Windows.Forms.TreeNode("TaskListWindow.ico", 5, 5);
System.Windows.Forms.TreeNode treeNode15 = new System.Windows.Forms.TreeNode("ToolboxWindow.ico", 5, 5);
System.Windows.Forms.TreeNode treeNode16 = new System.Windows.Forms.TreeNode("Images", 2, 1, new System.Windows.Forms.TreeNode[] {
treeNode9,
treeNode10,
treeNode11,
treeNode12,
treeNode13,
treeNode14,
treeNode15});
System.Windows.Forms.TreeNode treeNode17 = new System.Windows.Forms.TreeNode("AboutDialog.cs", 8, 8);
System.Windows.Forms.TreeNode treeNode18 = new System.Windows.Forms.TreeNode("App.ico", 5, 5);
System.Windows.Forms.TreeNode treeNode19 = new System.Windows.Forms.TreeNode("AssemblyInfo.cs", 7, 7);
System.Windows.Forms.TreeNode treeNode20 = new System.Windows.Forms.TreeNode("DummyOutputWindow.cs", 8, 8);
System.Windows.Forms.TreeNode treeNode21 = new System.Windows.Forms.TreeNode("DummyPropertyWindow.cs", 8, 8);
System.Windows.Forms.TreeNode treeNode22 = new System.Windows.Forms.TreeNode("DummySolutionExplorer.cs", 8, 8);
System.Windows.Forms.TreeNode treeNode23 = new System.Windows.Forms.TreeNode("DummyTaskList.cs", 8, 8);
System.Windows.Forms.TreeNode treeNode24 = new System.Windows.Forms.TreeNode("DummyToolbox.cs", 8, 8);
System.Windows.Forms.TreeNode treeNode25 = new System.Windows.Forms.TreeNode("MianForm.cs", 8, 8);
System.Windows.Forms.TreeNode treeNode26 = new System.Windows.Forms.TreeNode("Options.cs", 7, 7);
System.Windows.Forms.TreeNode treeNode27 = new System.Windows.Forms.TreeNode("OptionsDialog.cs", 8, 8);
System.Windows.Forms.TreeNode treeNode28 = new System.Windows.Forms.TreeNode("DockSample", 3, 3, new System.Windows.Forms.TreeNode[] {
treeNode8,
treeNode16,
treeNode17,
treeNode18,
treeNode19,
treeNode20,
treeNode21,
treeNode22,
treeNode23,
treeNode24,
treeNode25,
treeNode26,
treeNode27});
System.Windows.Forms.TreeNode treeNode29 = new System.Windows.Forms.TreeNode("System", 6, 6);
System.Windows.Forms.TreeNode treeNode30 = new System.Windows.Forms.TreeNode("System.Data", 6, 6);
System.Windows.Forms.TreeNode treeNode31 = new System.Windows.Forms.TreeNode("System.Design", 6, 6);
System.Windows.Forms.TreeNode treeNode32 = new System.Windows.Forms.TreeNode("System.Drawing", 6, 6);
System.Windows.Forms.TreeNode treeNode33 = new System.Windows.Forms.TreeNode("System.Windows.Forms", 6, 6);
System.Windows.Forms.TreeNode treeNode34 = new System.Windows.Forms.TreeNode("System.XML", 6, 6);
System.Windows.Forms.TreeNode treeNode35 = new System.Windows.Forms.TreeNode("References", 4, 4, new System.Windows.Forms.TreeNode[] {
treeNode29,
treeNode30,
treeNode31,
treeNode32,
treeNode33,
treeNode34});
System.Windows.Forms.TreeNode treeNode36 = new System.Windows.Forms.TreeNode("DockWindow.AutoHideNo.bmp", 9, 9);
System.Windows.Forms.TreeNode treeNode37 = new System.Windows.Forms.TreeNode("DockWindow.AutoHideYes.bmp", 9, 9);
System.Windows.Forms.TreeNode treeNode38 = new System.Windows.Forms.TreeNode("DockWindow.Close.bmp", 9, 9);
System.Windows.Forms.TreeNode treeNode39 = new System.Windows.Forms.TreeNode("DocumentWindow.Close.bmp", 9, 9);
System.Windows.Forms.TreeNode treeNode40 = new System.Windows.Forms.TreeNode("DocumentWindow.ScrollLeftDisabled.bmp", 9, 9);
System.Windows.Forms.TreeNode treeNode41 = new System.Windows.Forms.TreeNode("DocumentWindow.ScrollLeftEnabled.bmp", 9, 9);
System.Windows.Forms.TreeNode treeNode42 = new System.Windows.Forms.TreeNode("DocumentWindow.ScrollRightDisabled.bmp", 9, 9);
System.Windows.Forms.TreeNode treeNode43 = new System.Windows.Forms.TreeNode("DocumentWindow.ScrollRightEnabled.bmp", 9, 9);
System.Windows.Forms.TreeNode treeNode44 = new System.Windows.Forms.TreeNode("Resources", 2, 1, new System.Windows.Forms.TreeNode[] {
treeNode36,
treeNode37,
treeNode38,
treeNode39,
treeNode40,
treeNode41,
treeNode42,
treeNode43});
System.Windows.Forms.TreeNode treeNode45 = new System.Windows.Forms.TreeNode("Enums.cs", 7, 7);
System.Windows.Forms.TreeNode treeNode46 = new System.Windows.Forms.TreeNode("Gdi32.cs", 7, 3);
System.Windows.Forms.TreeNode treeNode47 = new System.Windows.Forms.TreeNode("Structs.cs", 7, 7);
System.Windows.Forms.TreeNode treeNode48 = new System.Windows.Forms.TreeNode("User32.cs", 7, 7);
System.Windows.Forms.TreeNode treeNode49 = new System.Windows.Forms.TreeNode("Win32", 2, 1, new System.Windows.Forms.TreeNode[] {
treeNode45,
treeNode46,
treeNode47,
treeNode48});
System.Windows.Forms.TreeNode treeNode50 = new System.Windows.Forms.TreeNode("AssemblyInfo.cs", 7, 7);
System.Windows.Forms.TreeNode treeNode51 = new System.Windows.Forms.TreeNode("Content.cs", 8, 8);
System.Windows.Forms.TreeNode treeNode52 = new System.Windows.Forms.TreeNode("CotentCollection.cs", 7, 7);
System.Windows.Forms.TreeNode treeNode53 = new System.Windows.Forms.TreeNode("CotentWindowCollection.cs", 7, 7);
System.Windows.Forms.TreeNode treeNode54 = new System.Windows.Forms.TreeNode("DockHelper.cs", 7, 7);
System.Windows.Forms.TreeNode treeNode55 = new System.Windows.Forms.TreeNode("DragHandler.cs", 7, 7);
System.Windows.Forms.TreeNode treeNode56 = new System.Windows.Forms.TreeNode("DragHandlerBase.cs", 7, 7);
System.Windows.Forms.TreeNode treeNode57 = new System.Windows.Forms.TreeNode("FloatWindow.cs", 8, 8);
System.Windows.Forms.TreeNode treeNode58 = new System.Windows.Forms.TreeNode("HiddenMdiChild.cs", 8, 8);
System.Windows.Forms.TreeNode treeNode59 = new System.Windows.Forms.TreeNode("InertButton.cs", 7, 7);
System.Windows.Forms.TreeNode treeNode60 = new System.Windows.Forms.TreeNode("Measures.cs", 7, 7);
System.Windows.Forms.TreeNode treeNode61 = new System.Windows.Forms.TreeNode("NormalTabStripWindow.cs", 8, 8);
System.Windows.Forms.TreeNode treeNode62 = new System.Windows.Forms.TreeNode("ResourceHelper.cs", 7, 7);
System.Windows.Forms.TreeNode treeNode63 = new System.Windows.Forms.TreeNode("WeifenLuo.WinFormsUI.Docking", 3, 3, new System.Windows.Forms.TreeNode[] {
treeNode35,
treeNode44,
treeNode49,
treeNode50,
treeNode51,
treeNode52,
treeNode53,
treeNode54,
treeNode55,
treeNode56,
treeNode57,
treeNode58,
treeNode59,
treeNode60,
treeNode61,
treeNode62});
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(DummySolutionExplorer));
this.treeView1 = new System.Windows.Forms.TreeView();
this.imageList1 = new System.Windows.Forms.ImageList(this.components);
this.SuspendLayout();
//
// treeView1
//
this.treeView1.BorderStyle = System.Windows.Forms.BorderStyle.None;
this.treeView1.Dock = System.Windows.Forms.DockStyle.Fill;
this.treeView1.ImageIndex = 0;
this.treeView1.ImageList = this.imageList1;
this.treeView1.Indent = 19;
this.treeView1.Location = new System.Drawing.Point(0, 24);
this.treeView1.Margin = new System.Windows.Forms.Padding(10, 3, 3, 3);
this.treeView1.Name = "treeView1";
treeNode1.Name = "";
treeNode1.Text = "Solution \'WinFormsUI\' (2 projects)";
treeNode2.ImageIndex = 6;
treeNode2.Name = "";
treeNode2.SelectedImageIndex = 6;
treeNode2.Text = "System";
treeNode3.ImageIndex = 6;
treeNode3.Name = "";
treeNode3.SelectedImageIndex = 6;
treeNode3.Text = "System.Data";
treeNode4.ImageIndex = 6;
treeNode4.Name = "";
treeNode4.SelectedImageIndex = 6;
treeNode4.Text = "System.Drawing";
treeNode5.ImageIndex = 6;
treeNode5.Name = "";
treeNode5.SelectedImageIndex = 6;
treeNode5.Text = "System.Windows.Forms";
treeNode6.ImageIndex = 6;
treeNode6.Name = "";
treeNode6.SelectedImageIndex = 6;
treeNode6.Text = "System.XML";
treeNode7.ImageIndex = 6;
treeNode7.Name = "";
treeNode7.SelectedImageIndex = 6;
treeNode7.Text = "WeifenLuo.WinFormsUI.Docking";
treeNode8.ImageIndex = 4;
treeNode8.Name = "";
treeNode8.SelectedImageIndex = 4;
treeNode8.Text = "References";
treeNode9.ImageIndex = 5;
treeNode9.Name = "";
treeNode9.SelectedImageIndex = 5;
treeNode9.Text = "BlankIcon.ico";
treeNode10.ImageIndex = 5;
treeNode10.Name = "";
treeNode10.SelectedImageIndex = 5;
treeNode10.Text = "CSProject.ico";
treeNode11.ImageIndex = 5;
treeNode11.Name = "";
treeNode11.SelectedImageIndex = 5;
treeNode11.Text = "OutputWindow.ico";
treeNode12.ImageIndex = 5;
treeNode12.Name = "";
treeNode12.SelectedImageIndex = 5;
treeNode12.Text = "References.ico";
treeNode13.ImageIndex = 5;
treeNode13.Name = "";
treeNode13.SelectedImageIndex = 5;
treeNode13.Text = "SolutionExplorer.ico";
treeNode14.ImageIndex = 5;
treeNode14.Name = "";
treeNode14.SelectedImageIndex = 5;
treeNode14.Text = "TaskListWindow.ico";
treeNode15.ImageIndex = 5;
treeNode15.Name = "";
treeNode15.SelectedImageIndex = 5;
treeNode15.Text = "ToolboxWindow.ico";
treeNode16.ImageIndex = 2;
treeNode16.Name = "";
treeNode16.SelectedImageIndex = 1;
treeNode16.Text = "Images";
treeNode17.ImageIndex = 8;
treeNode17.Name = "";
treeNode17.SelectedImageIndex = 8;
treeNode17.Text = "AboutDialog.cs";
treeNode18.ImageIndex = 5;
treeNode18.Name = "";
treeNode18.SelectedImageIndex = 5;
treeNode18.Text = "App.ico";
treeNode19.ImageIndex = 7;
treeNode19.Name = "";
treeNode19.SelectedImageIndex = 7;
treeNode19.Text = "AssemblyInfo.cs";
treeNode20.ImageIndex = 8;
treeNode20.Name = "";
treeNode20.SelectedImageIndex = 8;
treeNode20.Text = "DummyOutputWindow.cs";
treeNode21.ImageIndex = 8;
treeNode21.Name = "";
treeNode21.SelectedImageIndex = 8;
treeNode21.Text = "DummyPropertyWindow.cs";
treeNode22.ImageIndex = 8;
treeNode22.Name = "";
treeNode22.SelectedImageIndex = 8;
treeNode22.Text = "DummySolutionExplorer.cs";
treeNode23.ImageIndex = 8;
treeNode23.Name = "";
treeNode23.SelectedImageIndex = 8;
treeNode23.Text = "DummyTaskList.cs";
treeNode24.ImageIndex = 8;
treeNode24.Name = "";
treeNode24.SelectedImageIndex = 8;
treeNode24.Text = "DummyToolbox.cs";
treeNode25.ImageIndex = 8;
treeNode25.Name = "";
treeNode25.SelectedImageIndex = 8;
treeNode25.Text = "MianForm.cs";
treeNode26.ImageIndex = 7;
treeNode26.Name = "";
treeNode26.SelectedImageIndex = 7;
treeNode26.Text = "Options.cs";
treeNode27.ImageIndex = 8;
treeNode27.Name = "";
treeNode27.SelectedImageIndex = 8;
treeNode27.Text = "OptionsDialog.cs";
treeNode28.ImageIndex = 3;
treeNode28.Name = "";
treeNode28.SelectedImageIndex = 3;
treeNode28.Text = "DockSample";
treeNode29.ImageIndex = 6;
treeNode29.Name = "";
treeNode29.SelectedImageIndex = 6;
treeNode29.Text = "System";
treeNode30.ImageIndex = 6;
treeNode30.Name = "";
treeNode30.SelectedImageIndex = 6;
treeNode30.Text = "System.Data";
treeNode31.ImageIndex = 6;
treeNode31.Name = "";
treeNode31.SelectedImageIndex = 6;
treeNode31.Text = "System.Design";
treeNode32.ImageIndex = 6;
treeNode32.Name = "";
treeNode32.SelectedImageIndex = 6;
treeNode32.Text = "System.Drawing";
treeNode33.ImageIndex = 6;
treeNode33.Name = "";
treeNode33.SelectedImageIndex = 6;
treeNode33.Text = "System.Windows.Forms";
treeNode34.ImageIndex = 6;
treeNode34.Name = "";
treeNode34.SelectedImageIndex = 6;
treeNode34.Text = "System.XML";
treeNode35.ImageIndex = 4;
treeNode35.Name = "";
treeNode35.SelectedImageIndex = 4;
treeNode35.Text = "References";
treeNode36.ImageIndex = 9;
treeNode36.Name = "";
treeNode36.SelectedImageIndex = 9;
treeNode36.Text = "DockWindow.AutoHideNo.bmp";
treeNode37.ImageIndex = 9;
treeNode37.Name = "";
treeNode37.SelectedImageIndex = 9;
treeNode37.Text = "DockWindow.AutoHideYes.bmp";
treeNode38.ImageIndex = 9;
treeNode38.Name = "";
treeNode38.SelectedImageIndex = 9;
treeNode38.Text = "DockWindow.Close.bmp";
treeNode39.ImageIndex = 9;
treeNode39.Name = "";
treeNode39.SelectedImageIndex = 9;
treeNode39.Text = "DocumentWindow.Close.bmp";
treeNode40.ImageIndex = 9;
treeNode40.Name = "";
treeNode40.SelectedImageIndex = 9;
treeNode40.Text = "DocumentWindow.ScrollLeftDisabled.bmp";
treeNode41.ImageIndex = 9;
treeNode41.Name = "";
treeNode41.SelectedImageIndex = 9;
treeNode41.Text = "DocumentWindow.ScrollLeftEnabled.bmp";
treeNode42.ImageIndex = 9;
treeNode42.Name = "";
treeNode42.SelectedImageIndex = 9;
treeNode42.Text = "DocumentWindow.ScrollRightDisabled.bmp";
treeNode43.ImageIndex = 9;
treeNode43.Name = "";
treeNode43.SelectedImageIndex = 9;
treeNode43.Text = "DocumentWindow.ScrollRightEnabled.bmp";
treeNode44.ImageIndex = 2;
treeNode44.Name = "";
treeNode44.SelectedImageIndex = 1;
treeNode44.Text = "Resources";
treeNode45.ImageIndex = 7;
treeNode45.Name = "";
treeNode45.SelectedImageIndex = 7;
treeNode45.Text = "Enums.cs";
treeNode46.ImageIndex = 7;
treeNode46.Name = "";
treeNode46.SelectedImageIndex = 3;
treeNode46.Text = "Gdi32.cs";
treeNode47.ImageIndex = 7;
treeNode47.Name = "";
treeNode47.SelectedImageIndex = 7;
treeNode47.Text = "Structs.cs";
treeNode48.ImageIndex = 7;
treeNode48.Name = "";
treeNode48.SelectedImageIndex = 7;
treeNode48.Text = "User32.cs";
treeNode49.ImageIndex = 2;
treeNode49.Name = "";
treeNode49.SelectedImageIndex = 1;
treeNode49.Text = "Win32";
treeNode50.ImageIndex = 7;
treeNode50.Name = "";
treeNode50.SelectedImageIndex = 7;
treeNode50.Text = "AssemblyInfo.cs";
treeNode51.ImageIndex = 8;
treeNode51.Name = "";
treeNode51.SelectedImageIndex = 8;
treeNode51.Text = "Content.cs";
treeNode52.ImageIndex = 7;
treeNode52.Name = "";
treeNode52.SelectedImageIndex = 7;
treeNode52.Text = "CotentCollection.cs";
treeNode53.ImageIndex = 7;
treeNode53.Name = "";
treeNode53.SelectedImageIndex = 7;
treeNode53.Text = "CotentWindowCollection.cs";
treeNode54.ImageIndex = 7;
treeNode54.Name = "";
treeNode54.SelectedImageIndex = 7;
treeNode54.Text = "DockHelper.cs";
treeNode55.ImageIndex = 7;
treeNode55.Name = "";
treeNode55.SelectedImageIndex = 7;
treeNode55.Text = "DragHandler.cs";
treeNode56.ImageIndex = 7;
treeNode56.Name = "";
treeNode56.SelectedImageIndex = 7;
treeNode56.Text = "DragHandlerBase.cs";
treeNode57.ImageIndex = 8;
treeNode57.Name = "";
treeNode57.SelectedImageIndex = 8;
treeNode57.Text = "FloatWindow.cs";
treeNode58.ImageIndex = 8;
treeNode58.Name = "";
treeNode58.SelectedImageIndex = 8;
treeNode58.Text = "HiddenMdiChild.cs";
treeNode59.ImageIndex = 7;
treeNode59.Name = "";
treeNode59.SelectedImageIndex = 7;
treeNode59.Text = "InertButton.cs";
treeNode60.ImageIndex = 7;
treeNode60.Name = "";
treeNode60.SelectedImageIndex = 7;
treeNode60.Text = "Measures.cs";
treeNode61.ImageIndex = 8;
treeNode61.Name = "";
treeNode61.SelectedImageIndex = 8;
treeNode61.Text = "NormalTabStripWindow.cs";
treeNode62.ImageIndex = 7;
treeNode62.Name = "";
treeNode62.SelectedImageIndex = 7;
treeNode62.Text = "ResourceHelper.cs";
treeNode63.ImageIndex = 3;
treeNode63.Name = "";
treeNode63.SelectedImageIndex = 3;
treeNode63.Text = "WeifenLuo.WinFormsUI.Docking";
this.treeView1.Nodes.AddRange(new System.Windows.Forms.TreeNode[] {
treeNode1,
treeNode28,
treeNode63});
this.treeView1.SelectedImageIndex = 0;
this.treeView1.Size = new System.Drawing.Size(327, 346);
this.treeView1.TabIndex = 0;
//
// imageList1
//
this.imageList1.ImageStream = ((System.Windows.Forms.ImageListStreamer)(resources.GetObject("imageList1.ImageStream")));
this.imageList1.TransparentColor = System.Drawing.Color.Transparent;
this.imageList1.Images.SetKeyName(0, "");
this.imageList1.Images.SetKeyName(1, "");
this.imageList1.Images.SetKeyName(2, "");
this.imageList1.Images.SetKeyName(3, "");
this.imageList1.Images.SetKeyName(4, "");
this.imageList1.Images.SetKeyName(5, "");
this.imageList1.Images.SetKeyName(6, "");
this.imageList1.Images.SetKeyName(7, "");
this.imageList1.Images.SetKeyName(8, "");
this.imageList1.Images.SetKeyName(9, "");
//
// DummySolutionExplorer
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.ClientSize = new System.Drawing.Size(327, 371);
this.Controls.Add(this.treeView1);
this.DockAreas = ((WeifenLuo.WinFormsUI.Docking.DockAreas)((((WeifenLuo.WinFormsUI.Docking.DockAreas.DockLeft | WeifenLuo.WinFormsUI.Docking.DockAreas.DockRight)
| WeifenLuo.WinFormsUI.Docking.DockAreas.DockTop)
| WeifenLuo.WinFormsUI.Docking.DockAreas.DockBottom)));
this.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.HideOnClose = true;
this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
this.Name = "DummySolutionExplorer";
this.Padding = new System.Windows.Forms.Padding(0, 24, 0, 1);
this.ShowHint = WeifenLuo.WinFormsUI.Docking.DockState.DockRight;
this.TabText = "Solution Explorer";
this.Text = "Solution Explorer - WinFormsUI";
this.ResumeLayout(false);
}
#endregion
private System.Windows.Forms.TreeView treeView1;
private System.Windows.Forms.ImageList imageList1;
}
}
| |
/*
Copyright (c) Microsoft Corporation. All rights reserved.
Licensed under the MIT License. See License.txt in the project root for license information.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.Caching;
using Adxstudio.Xrm.Configuration;
using Adxstudio.Xrm.ContentAccess;
using Adxstudio.Xrm.Core.Flighting;
using Adxstudio.Xrm.Diagnostics.Trace;
using Adxstudio.Xrm.Security;
using Adxstudio.Xrm.Services.Query;
using Adxstudio.Xrm.SharePoint;
using Adxstudio.Xrm.SharePoint.Handlers;
using Microsoft.SharePoint.Client;
using Microsoft.Xrm.Client;
using Microsoft.Xrm.Client.Security;
using Microsoft.Xrm.Portal.Configuration;
using Microsoft.Xrm.Portal.Web.Handlers;
using Microsoft.Xrm.Portal.Web.Modules;
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Client;
using Microsoft.Xrm.Sdk.Messages;
using Microsoft.Xrm.Sdk.Metadata;
using Microsoft.Xrm.Sdk.Query;
namespace Adxstudio.Xrm.Web.Routing
{
/// <summary>
/// Handles requests to <see cref="Entity"/> objects.
/// </summary>
/// <seealso cref="PortalRoutingModule"/>
/// <seealso cref="AnnotationHandler"/>
public class EntityRouteHandler : Microsoft.Xrm.Portal.Web.Routing.EntityRouteHandler
{
/// <summary>
/// Class Initialization
/// </summary>
/// <param name="portalName">Portal Name</param>
public EntityRouteHandler(string portalName)
: base(portalName)
{
}
protected override bool TryCreateHandler(OrganizationServiceContext context, string logicalName, Guid id, out IHttpHandler handler)
{
if (string.Equals(logicalName, "annotation", StringComparison.InvariantCulture))
{
var annotation = context.CreateQuery(logicalName).FirstOrDefault(e => e.GetAttributeValue<Guid>("annotationid") == id);
if (annotation != null)
{
var regarding = annotation.GetAttributeValue<EntityReference>("objectid");
if (regarding != null && string.Equals(regarding.LogicalName, "knowledgearticle", StringComparison.InvariantCulture))
{
// Access to a note associated to a knowledge article requires the CMS Security to grant read of the annotation and the related knowledge article.
// Additionally, if CAL or Product filtering is enabled and the CAL and/or Product providers reject access to the knowledge article
// then access to the note is denied. If CAL and Product filtering are NOT enabled or CAL and/or Product Provider assertion passed,
// we must continue to check the Entity Permissions. If the Entity Permission Provider grants read to the knowledge article then the
// note can be accessed, otherwise access will be denied.
// Assert CMS Security on the annotation and knowledge article.
if (TryAssertByCrmEntitySecurityProvider(context, annotation.ToEntityReference()) && TryAssertByCrmEntitySecurityProvider(context, regarding))
{
// Assert CAL and/or Product Filtering if enabled.
var contentAccessLevelProvider = new ContentAccessLevelProvider();
var productAccessProvider = new ProductAccessProvider();
if (contentAccessLevelProvider.IsEnabled() || productAccessProvider.IsEnabled())
{
if (!AssertKnowledgeArticleCalAndProductFiltering(annotation, context, contentAccessLevelProvider, productAccessProvider))
{
ADXTrace.Instance.TraceInfo(TraceCategory.Application, $"Access to {EntityNamePrivacy.GetEntityName(annotation.LogicalName)} was denied. Id:{id} RegardingId={regarding.Id} RegardingLogicalName={EntityNamePrivacy.GetEntityName(regarding.LogicalName)}");
handler = null;
return false;
}
}
// Assert Entity Permissions on the knowledge article.
if (TryAssertByCrmEntityPermissionProvider(context, regarding))
{
ADXTrace.Instance.TraceInfo(TraceCategory.Application, $"Access to {EntityNamePrivacy.GetEntityName(annotation.LogicalName)} was granted. Id:{id} RegardingId={regarding.Id} RegardingLogicalName={EntityNamePrivacy.GetEntityName(regarding.LogicalName)}");
handler = CreateAnnotationHandler(annotation);
return true;
}
}
ADXTrace.Instance.TraceInfo(TraceCategory.Application, $"Access to {EntityNamePrivacy.GetEntityName(annotation.LogicalName)} was denied. Id:{id} RegardingId={regarding.Id} RegardingLogicalName={EntityNamePrivacy.GetEntityName(regarding.LogicalName)}");
handler = null;
return false;
}
// Assert CMS security on the regarding entity or assert entity permission on the annotation and the regarding entity.
if (TryAssertByCrmEntitySecurityProvider(context, regarding) || TryAssertByCrmEntityPermissionProvider(context, annotation, regarding))
{
ADXTrace.Instance.TraceInfo(TraceCategory.Application, $"Access to {EntityNamePrivacy.GetEntityName(annotation.LogicalName)} was granted. Id={id} RegardingId={regarding?.Id} RegardingLogicalName={EntityNamePrivacy.GetEntityName(regarding?.LogicalName)}");
handler = CreateAnnotationHandler(annotation);
return true;
}
}
}
if (string.Equals(logicalName, "salesliteratureitem", StringComparison.InvariantCulture))
{
var salesliteratureitem = context.CreateQuery(logicalName).FirstOrDefault(e => e.GetAttributeValue<Guid>("salesliteratureitemid") == id);
if (salesliteratureitem != null)
{
//Currently salesliteratureitem.iscustomerviewable is not exposed to CRM UI, therefore get the parent and check visibility.
//var isCustomerViewable = salesliteratureitem.GetAttributeValue<bool?>("iscustomerviewable").GetValueOrDefault();
var salesliterature =
context.CreateQuery("salesliterature")
.FirstOrDefault(
e =>
e.GetAttributeValue<Guid>("salesliteratureid") ==
salesliteratureitem.GetAttributeValue<EntityReference>("salesliteratureid").Id);
if (salesliterature != null)
{
var isCustomerViewable = salesliterature.GetAttributeValue<bool?>("iscustomerviewable").GetValueOrDefault();
if (isCustomerViewable)
{
handler = CreateSalesAttachmentHandler(salesliteratureitem);
return true;
}
}
}
}
if (string.Equals(logicalName, "sharepointdocumentlocation", StringComparison.InvariantCulture))
{
var location = context.CreateQuery(logicalName).FirstOrDefault(e => e.GetAttributeValue<Guid>("sharepointdocumentlocationid") == id);
if (location != null)
{
var httpContext = HttpContext.Current;
var regardingId = location.GetAttributeValue<EntityReference>("regardingobjectid");
// assert CMS access to the regarding entity or assert entity permission on the entity
if (TryAssertByCrmEntitySecurityProvider(context, regardingId) || TryAssertByCrmEntityPermissionProvider(context, location, location.GetAttributeValue<EntityReference>("regardingobjectid")))
{
var locationUrl = context.GetDocumentLocationUrl(location);
var fileName = httpContext.Request["file"];
// Ensure safe file URL - it cannot begin or end with dot, contain consecutive dots, or any of ~ " # % & * : < > ? \ { | }
fileName = Regex.Replace(fileName, @"(\.{2,})|([\~\""\#\%\&\*\:\<\>\?\/\\\{\|\}])|(^\.)|(\.$)", string.Empty); // also removes solidus
var folderPath = httpContext.Request["folderPath"];
Uri sharePointFileUrl;
if (!string.IsNullOrWhiteSpace(folderPath))
{
// Ensure safe folder URL - it cannot begin or end with dot, contain consecutive dots, or any of ~ " # % & * : < > ? \ { | }
folderPath = Regex.Replace(folderPath, @"(\.{2,})|([\~\""\#\%\&\*\:\<\>\?\\\{\|\}])|(^\.)|(\.$)", string.Empty).Trim('/');
sharePointFileUrl = new Uri("{0}/{1}/{2}".FormatWith(locationUrl.OriginalString, folderPath, fileName));
}
else
{
sharePointFileUrl = new Uri("{0}/{1}".FormatWith(locationUrl.OriginalString, fileName));
}
handler = CreateSharePointFileHandler(sharePointFileUrl, fileName);
return true;
}
if (!httpContext.Request.IsAuthenticated)
{
httpContext.Response.ForbiddenAndEndResponse();
}
else
{
// Sending Forbidden gets caught by the Application_EndRequest and throws an error trying to redirect to the Access Denied page.
// Send a 404 instead with plain text indicating Access Denied.
httpContext.Response.StatusCode = (int)HttpStatusCode.NotFound;
httpContext.Response.ContentType = "text/plain";
httpContext.Response.Write("Access Denied");
httpContext.Response.End();
}
}
}
if (string.Equals(logicalName, "activitymimeattachment", StringComparison.InvariantCulture))
{
var attachment = context.CreateQuery(logicalName).FirstOrDefault(e => e.GetAttributeValue<Guid>("attachmentid") == id);
if (attachment != null)
{
// retrieve the parent object for the annoation
var objectId = attachment.GetAttributeValue<EntityReference>("objectid");
// assert CMS access to the regarding entity or assert entity permission on the entity
if (TryAssertByCrmEntitySecurityProvider(context, objectId) || TryAssertByCrmEntityPermissionProvider(context, attachment, attachment.GetAttributeValue<EntityReference>("objectid")))
{
handler = CreateActivityMimeAttachmentHandler(attachment);
return true;
}
}
}
handler = null;
return false;
}
protected virtual bool TryAssertByCrmEntitySecurityProvider(OrganizationServiceContext context, EntityReference regardingId)
{
if (regardingId == null) return false;
// determine the primary ID attribute
var request = new RetrieveEntityRequest { LogicalName = regardingId.LogicalName, EntityFilters = EntityFilters.Entity };
var response = context.Execute(request) as RetrieveEntityResponse;
var primaryIdAttribute = response.EntityMetadata.PrimaryIdAttribute;
var regarding = context.CreateQuery(regardingId.LogicalName).FirstOrDefault(e => e.GetAttributeValue<Guid>(primaryIdAttribute) == regardingId.Id);
if (regarding == null) return false;
// assert read access on the regarding entity
var securityProvider = PortalCrmConfigurationManager.CreateCrmEntitySecurityProvider(PortalName);
return securityProvider.TryAssert(context, regarding, CrmEntityRight.Read);
}
protected virtual bool TryAssertByCrmEntityPermissionProvider(OrganizationServiceContext context, EntityReference entityReference)
{
if (!AdxstudioCrmConfigurationManager.GetCrmSection().ContentMap.Enabled) return false;
var crmEntityPermissionProvider = new CrmEntityPermissionProvider(PortalName);
return crmEntityPermissionProvider.TryAssert(context, CrmEntityPermissionRight.Read, entityReference);
}
protected virtual bool TryAssertByCrmEntityPermissionProvider(OrganizationServiceContext context, Entity entity)
{
if (!AdxstudioCrmConfigurationManager.GetCrmSection().ContentMap.Enabled) return false;
var crmEntityPermissionProvider = new CrmEntityPermissionProvider(PortalName);
return crmEntityPermissionProvider.TryAssert(context, CrmEntityPermissionRight.Read, entity);
}
protected virtual bool TryAssertByCrmEntityPermissionProvider(OrganizationServiceContext context, Entity entity, EntityReference regarding)
{
if (!AdxstudioCrmConfigurationManager.GetCrmSection().ContentMap.Enabled) return false;
var crmEntityPermissionProvider = new CrmEntityPermissionProvider(PortalName);
if (string.Equals(entity.LogicalName, "annotation", StringComparison.InvariantCulture)
&& regarding != null
&& string.Equals(regarding.LogicalName, "adx_portalcomment", StringComparison.InvariantCulture))
{
// If can read portal comment, bypass assertion check on notes and assume read permission.
return TryAssertPortalCommentPermission(context, crmEntityPermissionProvider, CrmEntityPermissionRight.Read, regarding);
}
return crmEntityPermissionProvider.TryAssert(context, CrmEntityPermissionRight.Read, entity, regarding: regarding);
}
protected override IHttpHandler CreateAnnotationHandler(Entity entity)
{
return new Handlers.AnnotationHandler(entity);
}
protected virtual IHttpHandler CreateSalesAttachmentHandler(Entity entity)
{
return new Handlers.SalesAttachmentHandler(entity);
}
protected virtual IHttpHandler CreateSharePointFileHandler(Uri sharePointFileUrl, string fileName)
{
return new SharePointFileHandler(sharePointFileUrl, fileName);
}
protected IHttpHandler CreateActivityMimeAttachmentHandler(Entity entity)
{
return new Handlers.ActivityMimeAttachmentHandler(entity);
}
private static bool TryAssertPortalCommentPermission(OrganizationServiceContext context, CrmEntityPermissionProvider entityPermissionProvider, CrmEntityPermissionRight right, EntityReference target)
{
var response = context.Execute<RetrieveResponse>(new RetrieveRequest
{
Target = target,
ColumnSet = new ColumnSet("regardingobjectid"),
});
var regarding = response.Entity.GetAttributeValue<EntityReference>("regardingobjectid");
return regarding != null
&& entityPermissionProvider.TryAssert(context, right, target, regarding: regarding);
}
/// <summary>
/// Adds Content Access Level and Product Filtering to fetch
/// </summary>
/// <param name="annotation">Annotation</param>
/// <param name="context">Context</param>
/// <param name="contentAccessLevelProvider">content Access Level Provider</param>
/// <param name="productAccessProvider">product Access Provider</param>
private bool AssertKnowledgeArticleCalAndProductFiltering(Entity annotation, OrganizationServiceContext context, ContentAccessLevelProvider contentAccessLevelProvider, ProductAccessProvider productAccessProvider)
{
if (!contentAccessLevelProvider.IsEnabled() & !productAccessProvider.IsEnabled())
{
// If CAL and Product Filtering is not enabled then we must not restrict access to the article. This will also eliminate an unnecessary knowledge article query.
return true;
}
var entityReference = annotation.GetAttributeValue<EntityReference>("objectid");
var fetch = new Fetch();
var knowledgeArticleFetch = new FetchEntity("knowledgearticle")
{
Filters = new List<Filter>
{
new Filter
{
Type = LogicalOperator.And,
Conditions = new List<Condition>
{
new Condition("knowledgearticleid", ConditionOperator.Equal, entityReference.Id)
}
}
},
Links = new List<Link>()
};
fetch.Entity = knowledgeArticleFetch;
// Apply Content Access Level filtering. If it is not enabled the fetch will not be modified
contentAccessLevelProvider.TryApplyRecordLevelFiltersToFetch(CrmEntityPermissionRight.Read, fetch);
// Apply Product filtering. If it is not enabled the fetch will not be modified.
productAccessProvider.TryApplyRecordLevelFiltersToFetch(CrmEntityPermissionRight.Read, fetch);
var kaResponse = (RetrieveMultipleResponse)context.Execute(fetch.ToRetrieveMultipleRequest());
var isValid = kaResponse.EntityCollection.Entities.Any();
if (isValid)
{
if (FeatureCheckHelper.IsFeatureEnabled(FeatureNames.TelemetryFeatureUsage))
{
PortalFeatureTrace.TraceInstance.LogFeatureUsage(FeatureTraceCategory.Note, HttpContext.Current, "TryCreateHandler CAL/PF passed", 1, annotation.ToEntityReference(), "read");
}
return true;
}
if (FeatureCheckHelper.IsFeatureEnabled(FeatureNames.TelemetryFeatureUsage))
{
PortalFeatureTrace.TraceInstance.LogFeatureUsage(FeatureTraceCategory.Note, HttpContext.Current, "TryCreateHandler CAL/PF failed", 1, annotation.ToEntityReference(), "read");
}
return false;
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
//-----------------------------------------------------------------------
// </copyright>
// <summary>Tests for ProjectItemInstance public members</summary>
//-----------------------------------------------------------------------
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Xml;
using Microsoft.Build.Construction;
using Microsoft.Build.Evaluation;
using Microsoft.Build.Execution;
using Microsoft.Build.Framework;
using InvalidProjectFileException = Microsoft.Build.Exceptions.InvalidProjectFileException;
using Xunit;
namespace Microsoft.Build.UnitTests.OM.Instance
{
/// <summary>
/// Tests for ProjectItemInstance public members
/// </summary>
public class ProjectItemInstance_Tests
{
/// <summary>
/// The number of built-in metadata for items.
/// </summary>
public const int BuiltInMetadataCount = 15;
/// <summary>
/// Basic ProjectItemInstance without metadata
/// </summary>
[Fact]
public void AccessorsWithoutMetadata()
{
ProjectItemInstance item = GetItemInstance();
Assert.Equal("i", item.ItemType);
Assert.Equal("i1", item.EvaluatedInclude);
Assert.Equal(false, item.Metadata.GetEnumerator().MoveNext());
}
/// <summary>
/// Basic ProjectItemInstance with metadata
/// </summary>
[Fact]
public void AccessorsWithMetadata()
{
ProjectItemInstance item = GetItemInstance();
item.SetMetadata("m1", "v0");
item.SetMetadata("m1", "v1");
item.SetMetadata("m2", "v2");
Assert.Equal("m1", item.GetMetadata("m1").Name);
Assert.Equal("m2", item.GetMetadata("m2").Name);
Assert.Equal("v1", item.GetMetadataValue("m1"));
Assert.Equal("v2", item.GetMetadataValue("m2"));
}
/// <summary>
/// Get metadata not present
/// </summary>
[Fact]
public void GetMissingMetadata()
{
ProjectItemInstance item = GetItemInstance();
Assert.Equal(null, item.GetMetadata("X"));
Assert.Equal(String.Empty, item.GetMetadataValue("X"));
}
/// <summary>
/// Set include
/// </summary>
[Fact]
public void SetInclude()
{
ProjectItemInstance item = GetItemInstance();
item.EvaluatedInclude = "i1b";
Assert.Equal("i1b", item.EvaluatedInclude);
}
/// <summary>
/// Set include to empty string
/// </summary>
[Fact]
public void SetInvalidEmptyInclude()
{
Assert.Throws<ArgumentException>(() =>
{
ProjectItemInstance item = GetItemInstance();
item.EvaluatedInclude = String.Empty;
}
);
}
/// <summary>
/// Set include to invalid null value
/// </summary>
[Fact]
public void SetInvalidNullInclude()
{
Assert.Throws<ArgumentNullException>(() =>
{
ProjectItemInstance item = GetItemInstance();
item.EvaluatedInclude = null;
}
);
}
/// <summary>
/// Create an item with a metadatum that has a null value
/// </summary>
[Fact]
public void CreateItemWithNullMetadataValue()
{
Project project = new Project();
ProjectInstance projectInstance = project.CreateProjectInstance();
IDictionary<string, string> metadata = new Dictionary<string, string>();
metadata.Add("m", null);
ProjectItemInstance item = projectInstance.AddItem("i", "i1", metadata);
Assert.Equal(String.Empty, item.GetMetadataValue("m"));
}
/// <summary>
/// Set metadata value
/// </summary>
[Fact]
public void SetMetadata()
{
ProjectItemInstance item = GetItemInstance();
item.SetMetadata("m", "m1");
Assert.Equal("m1", item.GetMetadataValue("m"));
}
/// <summary>
/// Set metadata value to empty string
/// </summary>
[Fact]
public void SetMetadataEmptyString()
{
ProjectItemInstance item = GetItemInstance();
item.SetMetadata("m", String.Empty);
Assert.Equal(String.Empty, item.GetMetadataValue("m"));
}
/// <summary>
/// Set metadata value to null value -- this is allowed, but
/// internally converted to the empty string.
/// </summary>
[Fact]
public void SetNullMetadataValue()
{
ProjectItemInstance item = GetItemInstance();
item.SetMetadata("m", null);
Assert.Equal(String.Empty, item.GetMetadataValue("m"));
}
/// <summary>
/// Set metadata with invalid empty name
/// </summary>
[Fact]
public void SetInvalidNullMetadataName()
{
Assert.Throws<ArgumentNullException>(() =>
{
ProjectItemInstance item = GetItemInstance();
item.SetMetadata(null, "m1");
}
);
}
/// <summary>
/// Set metadata with invalid empty name
/// </summary>
[Fact]
public void SetInvalidEmptyMetadataName()
{
Assert.Throws<ArgumentException>(() =>
{
ProjectItemInstance item = GetItemInstance();
item.SetMetadata(String.Empty, "m1");
}
);
}
/// <summary>
/// Cast to ITaskItem
/// </summary>
[Fact]
public void CastToITaskItem()
{
ProjectItemInstance item = GetItemInstance();
item.SetMetadata("m", "m1");
ITaskItem taskItem = (ITaskItem)item;
Assert.Equal(item.EvaluatedInclude, taskItem.ItemSpec);
Assert.Equal(1 + BuiltInMetadataCount, taskItem.MetadataCount);
Assert.Equal(1 + BuiltInMetadataCount, taskItem.MetadataNames.Count);
Assert.Equal("m1", taskItem.GetMetadata("m"));
taskItem.SetMetadata("m", "m2");
Assert.Equal("m2", item.GetMetadataValue("m"));
}
/// <summary>
/// Creates a ProjectItemInstance and casts it to ITaskItem2; makes sure that all escaped information is
/// maintained correctly. Also creates a new Microsoft.Build.Utilities.TaskItem from the ProjectItemInstance
/// and verifies that none of the information is lost.
/// </summary>
[Fact]
public void ITaskItem2Operations()
{
Project project = new Project();
ProjectInstance projectInstance = project.CreateProjectInstance();
ProjectItemInstance item = projectInstance.AddItem("EscapedItem", "esca%20ped%3bitem");
item.SetMetadata("m", "m1");
item.SetMetadata("m;", "m%3b1");
ITaskItem2 taskItem = (ITaskItem2)item;
Assert.Equal(taskItem.EvaluatedIncludeEscaped, "esca%20ped%3bitem");
Assert.Equal(taskItem.ItemSpec, "esca ped;item");
Assert.Equal(taskItem.GetMetadata("m;"), "m;1");
Assert.Equal(taskItem.GetMetadataValueEscaped("m;"), "m%3b1");
Assert.Equal(taskItem.GetMetadataValueEscaped("m"), "m1");
Assert.Equal(taskItem.EvaluatedIncludeEscaped, "esca%20ped%3bitem");
Assert.Equal(taskItem.ItemSpec, "esca ped;item");
ITaskItem2 taskItem2 = new Microsoft.Build.Utilities.TaskItem(taskItem);
taskItem2.SetMetadataValueLiteral("m;", "m;2");
Assert.Equal(taskItem2.GetMetadataValueEscaped("m;"), "m%3b2");
Assert.Equal(taskItem2.GetMetadata("m;"), "m;2");
IDictionary<string, string> taskItem2Metadata = (IDictionary<string, string>)taskItem2.CloneCustomMetadata();
Assert.Equal(3, taskItem2Metadata.Count);
foreach (KeyValuePair<string, string> pair in taskItem2Metadata)
{
if (pair.Key.Equals("m"))
{
Assert.Equal("m1", pair.Value);
}
if (pair.Key.Equals("m;"))
{
Assert.Equal("m;2", pair.Value);
}
if (pair.Key.Equals("OriginalItemSpec"))
{
Assert.Equal("esca ped;item", pair.Value);
}
}
IDictionary<string, string> taskItem2MetadataEscaped = (IDictionary<string, string>)taskItem2.CloneCustomMetadataEscaped();
Assert.Equal(3, taskItem2MetadataEscaped.Count);
foreach (KeyValuePair<string, string> pair in taskItem2MetadataEscaped)
{
if (pair.Key.Equals("m"))
{
Assert.Equal("m1", pair.Value);
}
if (pair.Key.Equals("m;"))
{
Assert.Equal("m%3b2", pair.Value);
}
if (pair.Key.Equals("OriginalItemSpec"))
{
Assert.Equal("esca%20ped%3bitem", pair.Value);
}
}
}
/// <summary>
/// Cast to ITaskItem
/// </summary>
[Fact]
public void CastToITaskItemNoMetadata()
{
ProjectItemInstance item = GetItemInstance();
ITaskItem taskItem = (ITaskItem)item;
Assert.Equal(0 + BuiltInMetadataCount, taskItem.MetadataCount);
Assert.Equal(0 + BuiltInMetadataCount, taskItem.MetadataNames.Count);
Assert.Equal(String.Empty, taskItem.GetMetadata("m"));
}
/*
* We must repeat all the evaluation-related tests here,
* to exercise the path that evaluates directly to instance objects.
* Although the Evaluator class is shared, its interactions with the two
* different item classes could be different, and shouldn't be.
*/
/// <summary>
/// No metadata, simple case
/// </summary>
[Fact]
public void NoMetadata()
{
string content = @"
<Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' >
<ItemGroup>
<i Include='i1'/>
</ItemGroup>
</Project>
";
ProjectItemInstance item = GetOneItem(content);
Assert.Equal("i", item.ItemType);
Assert.Equal("i1", item.EvaluatedInclude);
Assert.Equal(false, item.Metadata.GetEnumerator().MoveNext());
Assert.Equal(0 + BuiltInMetadataCount, Helpers.MakeList(item.MetadataNames).Count);
Assert.Equal(0 + BuiltInMetadataCount, item.MetadataCount);
}
/// <summary>
/// Read off metadata
/// </summary>
[Fact]
public void ReadMetadata()
{
string content = @"
<Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' >
<ItemGroup>
<i Include='i1'>
<m1>v1</m1>
<m2>v2</m2>
</i>
</ItemGroup>
</Project>
";
ProjectItemInstance item = GetOneItem(content);
var itemMetadata = Helpers.MakeList(item.Metadata);
Assert.Equal(2, itemMetadata.Count);
Assert.Equal("m1", itemMetadata[0].Name);
Assert.Equal("m2", itemMetadata[1].Name);
Assert.Equal("v1", itemMetadata[0].EvaluatedValue);
Assert.Equal("v2", itemMetadata[1].EvaluatedValue);
Assert.Equal(itemMetadata[0], item.GetMetadata("m1"));
Assert.Equal(itemMetadata[1], item.GetMetadata("m2"));
}
/// <summary>
/// Create a new Microsoft.Build.Utilities.TaskItem from the ProjectItemInstance where the ProjectItemInstance
/// has item definition metadata on it.
///
/// Verify the Utilities task item gets the expanded metadata from the ItemDefintionGroup.
/// </summary>
[Fact]
public void InstanceItemToUtilItemIDG()
{
string content = @"
<Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' >
<ItemDefinitionGroup>
<i>
<m0>;x86;</m0>
<m1>%(FileName).extension</m1>
<m2>;%(FileName).extension;</m2>
<m3>v1</m3>
<m4>%3bx86%3b</m4>
</i>
</ItemDefinitionGroup>
<ItemGroup>
<i Include='foo.proj'/>
</ItemGroup>
</Project>
";
ProjectItemInstance item = GetOneItem(content);
Microsoft.Build.Utilities.TaskItem taskItem = new Microsoft.Build.Utilities.TaskItem(item);
Assert.Equal(";x86;", taskItem.GetMetadata("m0"));
Assert.Equal("foo.extension", taskItem.GetMetadata("m1"));
Assert.Equal(";foo.extension;", taskItem.GetMetadata("m2"));
Assert.Equal("v1", taskItem.GetMetadata("m3"));
Assert.Equal(";x86;", taskItem.GetMetadata("m4"));
}
/// <summary>
/// Get metadata values inherited from item definitions
/// </summary>
[Fact]
public void GetMetadataValuesFromDefinition()
{
string content = @"
<Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' >
<ItemDefinitionGroup>
<i>
<m0>v0</m0>
<m1>v1</m1>
</i>
</ItemDefinitionGroup>
<ItemGroup>
<i Include='i1'>
<m1>v1b</m1>
<m2>v2</m2>
</i>
</ItemGroup>
</Project>
";
ProjectItemInstance item = GetOneItem(content);
Assert.Equal("v0", item.GetMetadataValue("m0"));
Assert.Equal("v1b", item.GetMetadataValue("m1"));
Assert.Equal("v2", item.GetMetadataValue("m2"));
Assert.Equal(3, Helpers.MakeList(item.Metadata).Count);
Assert.Equal(3 + BuiltInMetadataCount, Helpers.MakeList(item.MetadataNames).Count);
Assert.Equal(3 + BuiltInMetadataCount, item.MetadataCount);
}
/// <summary>
/// Exclude against an include with item vectors in it
/// </summary>
[Fact]
public void ExcludeWithIncludeVector()
{
string content = @"
<Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' >
<ItemGroup>
<i Include='a;b;c'>
</i>
</ItemGroup>
<ItemGroup>
<i Include='x;y;z;@(i);u;v;w' Exclude='b;y;v'>
</i>
</ItemGroup>
</Project>
";
IList<ProjectItemInstance> items = GetItems(content);
// Should contain a, b, c, x, z, a, c, u, w
Assert.Equal(9, items.Count);
AssertEvaluatedIncludes(items, new string[] { "a", "b", "c", "x", "z", "a", "c", "u", "w" });
}
/// <summary>
/// Exclude with item vectors against an include with item vectors in it
/// </summary>
[Fact]
public void ExcludeVectorWithIncludeVector()
{
string content = @"
<Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' >
<ItemGroup>
<i Include='a;b;c'>
</i>
<j Include='b;y;v' />
</ItemGroup>
<ItemGroup>
<i Include='x;y;z;@(i);u;v;w' Exclude='x;@(j);w'>
</i>
</ItemGroup>
</Project>
";
IList<ProjectItemInstance> items = GetItems(content);
// Should contain a, b, c, z, a, c, u
Assert.Equal(7, items.Count);
AssertEvaluatedIncludes(items, new string[] { "a", "b", "c", "z", "a", "c", "u" });
}
/// <summary>
/// Metadata on items can refer to metadata above
/// </summary>
[Fact]
public void MetadataReferringToMetadataAbove()
{
string content = @"
<Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' >
<ItemGroup>
<i Include='i1'>
<m1>v1</m1>
<m2>%(m1);v2;%(m0)</m2>
</i>
</ItemGroup>
</Project>
";
ProjectItemInstance item = GetOneItem(content);
var itemMetadata = Helpers.MakeList(item.Metadata);
Assert.Equal(2, itemMetadata.Count);
Assert.Equal("v1;v2;", item.GetMetadataValue("m2"));
}
/// <summary>
/// Built-in metadata should work, too.
/// NOTE: To work properly, this should batch. This is a temporary "patch" to make it work for now.
/// It will only give correct results if there is exactly one item in the Include. Otherwise Batching would be needed.
/// </summary>
[Fact]
public void BuiltInMetadataExpression()
{
string content = @"
<Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' >
<ItemGroup>
<i Include='i1'>
<m>%(Identity)</m>
</i>
</ItemGroup>
</Project>
";
ProjectItemInstance item = GetOneItem(content);
Assert.Equal("i1", item.GetMetadataValue("m"));
}
/// <summary>
/// Qualified built in metadata should work
/// </summary>
[Fact]
public void BuiltInQualifiedMetadataExpression()
{
string content = @"
<Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' >
<ItemGroup>
<i Include='i1'>
<m>%(i.Identity)</m>
</i>
</ItemGroup>
</Project>
";
ProjectItemInstance item = GetOneItem(content);
Assert.Equal("i1", item.GetMetadataValue("m"));
}
/// <summary>
/// Mis-qualified built in metadata should not work
/// </summary>
[Fact]
public void BuiltInMisqualifiedMetadataExpression()
{
string content = @"
<Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' >
<ItemGroup>
<i Include='i1'>
<m>%(j.Identity)</m>
</i>
</ItemGroup>
</Project>
";
ProjectItemInstance item = GetOneItem(content);
Assert.Equal(String.Empty, item.GetMetadataValue("m"));
}
/// <summary>
/// Metadata condition should work correctly with built-in metadata
/// </summary>
[Fact]
public void BuiltInMetadataInMetadataCondition()
{
string content = @"
<Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' >
<ItemGroup>
<i Include='i1'>
<m Condition=""'%(Identity)'=='i1'"">m1</m>
<n Condition=""'%(Identity)'=='i2'"">n1</n>
</i>
</ItemGroup>
</Project>
";
ProjectItemInstance item = GetOneItem(content);
Assert.Equal("m1", item.GetMetadataValue("m"));
Assert.Equal(String.Empty, item.GetMetadataValue("n"));
}
/// <summary>
/// Metadata on item condition not allowed (currently)
/// </summary>
[Fact]
public void BuiltInMetadataInItemCondition()
{
Assert.Throws<InvalidProjectFileException>(() =>
{
string content = @"
<Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' >
<ItemGroup>
<i Include='i1' Condition=""'%(Identity)'=='i1'/>
</ItemGroup>
</Project>
";
GetOneItem(content);
}
);
}
/// <summary>
/// Two items should each get their own values for built-in metadata
/// </summary>
[Fact]
public void BuiltInMetadataTwoItems()
{
string content = @"
<Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' >
<ItemGroup>
<i Include='i1.cpp;c:\bar\i2.cpp'>
<m>%(Filename).obj</m>
</i>
</ItemGroup>
</Project>
";
IList<ProjectItemInstance> items = GetItems(content);
Assert.Equal(@"i1.obj", items[0].GetMetadataValue("m"));
Assert.Equal(@"i2.obj", items[1].GetMetadataValue("m"));
}
/// <summary>
/// Items from another list, but with different metadata
/// </summary>
[Fact]
public void DifferentMetadataItemsFromOtherList()
{
string content = @"
<Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' >
<ItemGroup>
<h Include='h0'>
<m>m1</m>
</h>
<h Include='h1'/>
<i Include='@(h)'>
<m>%(m)</m>
</i>
</ItemGroup>
</Project>
";
IList<ProjectItemInstance> items = GetItems(content);
Assert.Equal(@"m1", items[0].GetMetadataValue("m"));
Assert.Equal(String.Empty, items[1].GetMetadataValue("m"));
}
/// <summary>
/// Items from another list, but with different metadata
/// </summary>
[Fact]
public void DifferentBuiltInMetadataItemsFromOtherList()
{
string content = @"
<Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' >
<ItemGroup>
<h Include='h0.x'/>
<h Include='h1.y'/>
<i Include='@(h)'>
<m>%(extension)</m>
</i>
</ItemGroup>
</Project>
";
IList<ProjectItemInstance> items = GetItems(content);
Assert.Equal(@".x", items[0].GetMetadataValue("m"));
Assert.Equal(@".y", items[1].GetMetadataValue("m"));
}
/// <summary>
/// Two items coming from a transform
/// </summary>
[Fact]
public void BuiltInMetadataTransformInInclude()
{
string content = @"
<Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' >
<ItemGroup>
<h Include='h0'/>
<h Include='h1'/>
<i Include=""@(h->'%(Identity).baz')"">
<m>%(Filename)%(Extension).obj</m>
</i>
</ItemGroup>
</Project>
";
IList<ProjectItemInstance> items = GetItems(content);
Assert.Equal(@"h0.baz.obj", items[0].GetMetadataValue("m"));
Assert.Equal(@"h1.baz.obj", items[1].GetMetadataValue("m"));
}
/// <summary>
/// Transform in the metadata value; no bare metadata involved
/// </summary>
[Fact]
public void BuiltInMetadataTransformInMetadataValue()
{
string content = @"
<Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' >
<ItemGroup>
<h Include='h0'/>
<h Include='h1'/>
<i Include='i0'/>
<i Include='i1;i2'>
<m>@(i);@(h->'%(Filename)')</m>
</i>
</ItemGroup>
</Project>
";
IList<ProjectItemInstance> items = GetItems(content);
Assert.Equal(@"i0;h0;h1", items[1].GetMetadataValue("m"));
Assert.Equal(@"i0;h0;h1", items[2].GetMetadataValue("m"));
}
/// <summary>
/// Transform in the metadata value; bare metadata involved
/// </summary>
[Fact]
public void BuiltInMetadataTransformInMetadataValueBareMetadataPresent()
{
string content = @"
<Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' >
<ItemGroup>
<h Include='h0'/>
<h Include='h1'/>
<i Include='i0.x'/>
<i Include='i1.y;i2'>
<m>@(i);@(h->'%(Filename)');%(Extension)</m>
</i>
</ItemGroup>
</Project>
";
IList<ProjectItemInstance> items = GetItems(content);
Assert.Equal(@"i0.x;h0;h1;.y", items[1].GetMetadataValue("m"));
Assert.Equal(@"i0.x;h0;h1;", items[2].GetMetadataValue("m"));
}
/// <summary>
/// Metadata on items can refer to item lists
/// </summary>
[Fact]
public void MetadataValueReferringToItems()
{
string content = @"
<Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' >
<ItemGroup>
<h Include='h0'/>
<i Include='i0'/>
<i Include='i1'>
<m1>@(h);@(i)</m1>
</i>
</ItemGroup>
</Project>
";
IList<ProjectItemInstance> items = GetItems(content);
Assert.Equal("h0;i0", items[1].GetMetadataValue("m1"));
}
/// <summary>
/// Metadata on items' conditions can refer to item lists
/// </summary>
[Fact]
public void MetadataConditionReferringToItems()
{
string content = @"
<Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' >
<ItemGroup>
<h Include='h0'/>
<i Include='i0'/>
<i Include='i1'>
<m1 Condition=""'@(h)'=='h0' and '@(i)'=='i0'"">v1</m1>
<m2 Condition=""'@(h)'!='h0' or '@(i)'!='i0'"">v2</m2>
</i>
</ItemGroup>
</Project>
";
IList<ProjectItemInstance> items = GetItems(content);
Assert.Equal("v1", items[1].GetMetadataValue("m1"));
Assert.Equal(String.Empty, items[1].GetMetadataValue("m2"));
}
/// <summary>
/// Metadata on items' conditions can refer to other metadata
/// </summary>
[Fact]
public void MetadataConditionReferringToMetadataOnSameItem()
{
string content = @"
<Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' >
<ItemGroup>
<i Include='i1'>
<m0>0</m0>
<m1 Condition=""'%(m0)'=='0'"">1</m1>
<m2 Condition=""'%(m0)'=='3'"">2</m2>
</i>
</ItemGroup>
</Project>
";
IList<ProjectItemInstance> items = GetItems(content);
Assert.Equal("0", items[0].GetMetadataValue("m0"));
Assert.Equal("1", items[0].GetMetadataValue("m1"));
Assert.Equal(String.Empty, items[0].GetMetadataValue("m2"));
}
/// <summary>
/// Gets the first item of type 'i'
/// </summary>
private static ProjectItemInstance GetOneItem(string content)
{
return GetItems(content)[0];
}
/// <summary>
/// Get all items of type 'i'
/// </summary>
private static IList<ProjectItemInstance> GetItems(string content)
{
ProjectRootElement xml = ProjectRootElement.Create(XmlReader.Create(new StringReader(content)));
ProjectInstance project = new ProjectInstance(xml);
return Helpers.MakeList(project.GetItems("i"));
}
/// <summary>
/// Asserts that the list of items has the specified includes.
/// </summary>
private static void AssertEvaluatedIncludes(IList<ProjectItemInstance> items, string[] includes)
{
for (int i = 0; i < includes.Length; i++)
{
Assert.Equal(includes[i], items[i].EvaluatedInclude);
}
}
/// <summary>
/// Get a single item instance
/// </summary>
private static ProjectItemInstance GetItemInstance()
{
Project project = new Project();
ProjectInstance projectInstance = project.CreateProjectInstance();
ProjectItemInstance item = projectInstance.AddItem("i", "i1");
return item;
}
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using Microsoft.CodeAnalysis;
namespace Roslyn.Utilities
{
/// <summary>
/// A class that writes both primitive values and non-cyclical object graphs to a stream that may be
/// later read back using the ObjectReader class.
/// </summary>
internal sealed class ObjectWriter : ObjectReaderWriterBase, IDisposable
{
private readonly BinaryWriter _writer;
private readonly ObjectWriterData _dataMap;
private readonly RecordingObjectBinder _binder;
private readonly CancellationToken _cancellationToken;
internal ObjectWriter(
Stream stream,
ObjectWriterData defaultData = null,
RecordingObjectBinder binder = null,
CancellationToken cancellationToken = default(CancellationToken))
{
// String serialization assumes both reader and writer to be of the same endianness.
// It can be adjusted for BigEndian if needed.
Debug.Assert(BitConverter.IsLittleEndian);
_writer = new BinaryWriter(stream, Encoding.UTF8);
_dataMap = new ObjectWriterData(defaultData);
_binder = binder ?? new SimpleRecordingObjectBinder();
_cancellationToken = cancellationToken;
}
public ObjectBinder Binder
{
get { return _binder; }
}
public void Dispose()
{
_dataMap.Dispose();
}
/// <summary>
/// Writes a Boolean value to the stream.
/// </summary>
public void WriteBoolean(bool value)
{
_writer.Write(value);
}
/// <summary>
/// Writes a Byte value to the stream.
/// </summary>
public void WriteByte(byte value)
{
_writer.Write(value);
}
/// <summary>
/// Writes a Char value to the stream.
/// </summary>
public void WriteChar(char ch)
{
// write as UInt16 because binary writer fails on chars that are unicode surrogates
_writer.Write((ushort)ch);
}
/// <summary>
/// Writes a Decimal value to the stream.
/// </summary>
public void WriteDecimal(decimal value)
{
_writer.Write(value);
}
/// <summary>
/// Writes a Double value to the stream.
/// </summary>
public void WriteDouble(double value)
{
_writer.Write(value);
}
/// <summary>
/// Writes a Single value to the stream.
/// </summary>
public void WriteSingle(float value)
{
_writer.Write(value);
}
/// <summary>
/// Writes a Int32 value to the stream.
/// </summary>
public void WriteInt32(int value)
{
_writer.Write(value);
}
/// <summary>
/// Writes a Int64 value to the stream.
/// </summary>
public void WriteInt64(long value)
{
_writer.Write(value);
}
/// <summary>
/// Writes a SByte value to the stream.
/// </summary>
public void WriteSByte(sbyte value)
{
_writer.Write(value);
}
/// <summary>
/// Writes a Int16 value to the stream.
/// </summary>
public void WriteInt16(short value)
{
_writer.Write(value);
}
/// <summary>
/// Writes a UInt32 value to the stream.
/// </summary>
public void WriteUInt32(uint value)
{
_writer.Write(value);
}
/// <summary>
/// Writes a UInt64 value to the stream.
/// </summary>
public void WriteUInt64(ulong value)
{
_writer.Write(value);
}
/// <summary>
/// Writes a UInt16 value to the stream.
/// </summary>
public void WriteUInt16(ushort value)
{
_writer.Write(value);
}
/// <summary>
/// Writes a DateTime value to the stream.
/// </summary>
public void WriteDateTime(DateTime value)
{
this.WriteInt64(value.ToBinary());
}
/// <summary>
/// Writes a compressed 30 bit integer to the stream. (not 32 bit)
/// </summary>
public void WriteCompressedUInt(uint value)
{
if (value <= (byte.MaxValue >> 2))
{
_writer.Write((byte)value);
}
else if (value <= (ushort.MaxValue >> 2))
{
byte byte0 = (byte)(((value >> 8) & 0xFF) | Byte2Marker);
byte byte1 = (byte)(value & 0xFF);
// high-bytes to low-bytes
_writer.Write(byte0);
_writer.Write(byte1);
}
else if (value <= (uint.MaxValue >> 2))
{
// high-bytes to low-bytes
byte byte0 = (byte)(((value >> 24) & 0xFF) | Byte4Marker);
byte byte1 = (byte)((value >> 16) & 0xFF);
byte byte2 = (byte)((value >> 8) & 0xFF);
byte byte3 = (byte)(value & 0xFF);
// hit-bits with 4-byte marker
_writer.Write(byte0);
_writer.Write(byte1);
_writer.Write(byte2);
_writer.Write(byte3);
}
else
{
#if COMPILERCORE
throw new ArgumentException(CodeAnalysisResources.ValueTooLargeToBeRepresented);
#else
throw new ArgumentException(WorkspacesResources.Value_too_large_to_be_represented_as_a_30_bit_unsigned_integer);
#endif
}
}
/// <summary>
/// Writes a String value to the stream.
/// </summary>
public unsafe void WriteString(string value)
{
if (value == null)
{
_writer.Write((byte)DataKind.Null);
}
else
{
int id;
if (_dataMap.TryGetId(value, out id))
{
Debug.Assert(id >= 0);
if (id <= byte.MaxValue)
{
_writer.Write((byte)DataKind.StringRef_B);
_writer.Write((byte)id);
}
else if (id <= ushort.MaxValue)
{
_writer.Write((byte)DataKind.StringRef_S);
_writer.Write((ushort)id);
}
else
{
_writer.Write((byte)DataKind.StringRef);
_writer.Write(id);
}
}
else
{
_dataMap.Add(value);
if (value.IsValidUnicodeString())
{
// Usual case - the string can be encoded as UTF8:
// We can use the UTF8 encoding of the binary writer.
_writer.Write((byte)DataKind.StringUtf8);
_writer.Write(value);
}
else
{
_writer.Write((byte)DataKind.StringUtf16);
// This is rare, just allocate UTF16 bytes for simplicity.
byte[] bytes = new byte[(uint)value.Length * sizeof(char)];
fixed (char* valuePtr = value)
{
Marshal.Copy((IntPtr)valuePtr, bytes, 0, bytes.Length);
}
WriteCompressedUInt((uint)value.Length);
_writer.Write(bytes);
}
}
}
}
/// <summary>
/// Writes any value (primitive or object graph) to the stream.
/// </summary>
public void WriteValue(object value)
{
if (value == null)
{
_writer.Write((byte)DataKind.Null);
}
else
{
var type = value.GetType();
if (type.GetTypeInfo().IsEnum)
{
WriteEnum(value, type);
}
else if (type == typeof(bool))
{
if ((bool)value)
{
_writer.Write((byte)DataKind.Boolean_T);
}
else
{
_writer.Write((byte)DataKind.Boolean_F);
}
}
else if (type == typeof(int))
{
int v = (int)value;
if (v == 0)
{
_writer.Write((byte)DataKind.Int32_Z);
}
else if (v >= 0 && v < byte.MaxValue)
{
_writer.Write((byte)DataKind.Int32_B);
_writer.Write((byte)v);
}
else if (v >= 0 && v < ushort.MaxValue)
{
_writer.Write((byte)DataKind.Int32_S);
_writer.Write((ushort)v);
}
else
{
_writer.Write((byte)DataKind.Int32);
_writer.Write(v);
}
}
else if (type == typeof(string))
{
this.WriteString((string)value);
}
else if (type == typeof(short))
{
_writer.Write((byte)DataKind.Int16);
_writer.Write((short)value);
}
else if (type == typeof(long))
{
_writer.Write((byte)DataKind.Int64);
_writer.Write((long)value);
}
else if (type == typeof(char))
{
_writer.Write((byte)DataKind.Char);
this.WriteChar((char)value);
}
else if (type == typeof(sbyte))
{
_writer.Write((byte)DataKind.Int8);
_writer.Write((sbyte)value);
}
else if (type == typeof(byte))
{
_writer.Write((byte)DataKind.UInt8);
_writer.Write((byte)value);
}
else if (type == typeof(ushort))
{
_writer.Write((byte)DataKind.UInt16);
_writer.Write((ushort)value);
}
else if (type == typeof(uint))
{
_writer.Write((byte)DataKind.UInt32);
_writer.Write((uint)value);
}
else if (type == typeof(ulong))
{
_writer.Write((byte)DataKind.UInt64);
_writer.Write((ulong)value);
}
else if (type == typeof(decimal))
{
_writer.Write((byte)DataKind.Decimal);
_writer.Write((decimal)value);
}
else if (type == typeof(float))
{
_writer.Write((byte)DataKind.Float4);
_writer.Write((float)value);
}
else if (type == typeof(double))
{
_writer.Write((byte)DataKind.Float8);
_writer.Write((double)value);
}
else if (type == typeof(DateTime))
{
_writer.Write((byte)DataKind.DateTime);
this.WriteDateTime((DateTime)value);
}
else if (type.IsArray)
{
this.WriteArray((Array)value);
}
else if (value is Type)
{
this.WriteType((Type)value);
}
else
{
this.WriteObject(value);
}
}
}
private void WriteEnum(object value, Type enumType)
{
_writer.Write((byte)DataKind.Enum);
this.WriteType(enumType);
var type = Enum.GetUnderlyingType(enumType);
if (type == typeof(int))
{
_writer.Write((int)value);
}
else if (type == typeof(short))
{
_writer.Write((short)value);
}
else if (type == typeof(byte))
{
_writer.Write((byte)value);
}
else if (type == typeof(long))
{
_writer.Write((long)value);
}
else if (type == typeof(sbyte))
{
_writer.Write((sbyte)value);
}
else if (type == typeof(ushort))
{
_writer.Write((ushort)value);
}
else if (type == typeof(uint))
{
_writer.Write((uint)value);
}
else if (type == typeof(ulong))
{
_writer.Write((ulong)value);
}
else
{
throw ExceptionUtilities.UnexpectedValue(type);
}
}
private void WriteArray(Array instance)
{
if (instance.Rank > 1)
{
#if COMPILERCORE
throw new InvalidOperationException(CodeAnalysisResources.ArraysWithMoreThanOneDimensionCannotBeSerialized);
#else
throw new InvalidOperationException(WorkspacesResources.Arrays_with_more_than_one_dimension_cannot_be_serialized);
#endif
}
int length = instance.GetLength(0);
switch (length)
{
case 0:
_writer.Write((byte)DataKind.Array_0);
break;
case 1:
_writer.Write((byte)DataKind.Array_1);
break;
case 2:
_writer.Write((byte)DataKind.Array_2);
break;
case 3:
_writer.Write((byte)DataKind.Array_3);
break;
default:
_writer.Write((byte)DataKind.Array);
this.WriteCompressedUInt((uint)length);
break;
}
// get type of array
var elementType = instance.GetType().GetElementType();
// optimization for primitive type array
DataKind elementKind;
if (s_typeMap.TryGetValue(elementType, out elementKind))
{
this.WritePrimitiveType(elementType, elementKind);
this.WritePrimitiveTypeArrayElements(elementType, elementKind, instance);
return;
}
// custom type case
this.WriteType(elementType);
foreach (var value in instance)
{
this.WriteValue(value);
}
}
private void WritePrimitiveTypeArrayElements(Type type, DataKind kind, Array instance)
{
Debug.Assert(s_typeMap[type] == kind);
// optimization for type underlying binary writer knows about
if (type == typeof(byte))
{
_writer.Write((byte[])instance);
return;
}
if (type == typeof(char))
{
_writer.Write((char[])instance);
return;
}
// optimization for string which object writer has
// its own optimization to reduce repeated string
if (type == typeof(string))
{
WritePrimitiveTypeArrayElements((string[])instance, WriteString);
return;
}
// optimization for bool array
if (type == typeof(bool))
{
WriteBooleanArray((bool[])instance);
return;
}
// otherwise, write elements directly to underlying binary writer
switch (kind)
{
case DataKind.Int8:
WritePrimitiveTypeArrayElements((sbyte[])instance, _writer.Write);
return;
case DataKind.Int16:
WritePrimitiveTypeArrayElements((short[])instance, _writer.Write);
return;
case DataKind.Int32:
WritePrimitiveTypeArrayElements((int[])instance, _writer.Write);
return;
case DataKind.Int64:
WritePrimitiveTypeArrayElements((long[])instance, _writer.Write);
return;
case DataKind.UInt16:
WritePrimitiveTypeArrayElements((ushort[])instance, _writer.Write);
return;
case DataKind.UInt32:
WritePrimitiveTypeArrayElements((uint[])instance, _writer.Write);
return;
case DataKind.UInt64:
WritePrimitiveTypeArrayElements((ulong[])instance, _writer.Write);
return;
case DataKind.Float4:
WritePrimitiveTypeArrayElements((float[])instance, _writer.Write);
return;
case DataKind.Float8:
WritePrimitiveTypeArrayElements((double[])instance, _writer.Write);
return;
case DataKind.Decimal:
WritePrimitiveTypeArrayElements((decimal[])instance, _writer.Write);
return;
default:
throw ExceptionUtilities.UnexpectedValue(kind);
}
}
private void WriteBooleanArray(bool[] array)
{
// convert bool array to bit array
var bits = BitVector.Create(array.Length);
for (var i = 0; i < array.Length; i++)
{
bits[i] = array[i];
}
// send over bit array
foreach (var word in bits.Words())
{
_writer.Write(word);
}
}
private static void WritePrimitiveTypeArrayElements<T>(T[] array, Action<T> write)
{
for (var i = 0; i < array.Length; i++)
{
write(array[i]);
}
}
private void WritePrimitiveType(Type type, DataKind kind)
{
Debug.Assert(s_typeMap[type] == kind);
_writer.Write((byte)kind);
}
private void WriteType(Type type)
{
int id;
if (_dataMap.TryGetId(type, out id))
{
Debug.Assert(id >= 0);
if (id <= byte.MaxValue)
{
_writer.Write((byte)DataKind.TypeRef_B);
_writer.Write((byte)id);
}
else if (id <= ushort.MaxValue)
{
_writer.Write((byte)DataKind.TypeRef_S);
_writer.Write((ushort)id);
}
else
{
_writer.Write((byte)DataKind.TypeRef);
_writer.Write(id);
}
}
else
{
_dataMap.Add(type);
_binder?.Record(type);
_writer.Write((byte)DataKind.Type);
string assemblyName = type.GetTypeInfo().Assembly.FullName;
string typeName = type.FullName;
// assembly name
this.WriteString(assemblyName);
// type name
this.WriteString(typeName);
}
}
private void WriteObject(object instance)
{
_cancellationToken.ThrowIfCancellationRequested();
// write object ref if we already know this instance
int id;
if (_dataMap.TryGetId(instance, out id))
{
Debug.Assert(id >= 0);
if (id <= byte.MaxValue)
{
_writer.Write((byte)DataKind.ObjectRef_B);
_writer.Write((byte)id);
}
else if (id <= ushort.MaxValue)
{
_writer.Write((byte)DataKind.ObjectRef_S);
_writer.Write((ushort)id);
}
else
{
_writer.Write((byte)DataKind.ObjectRef);
_writer.Write(id);
}
}
else
{
// otherwise add this instance to the map
_dataMap.Add(instance);
var iwriteable = instance as IObjectWritable;
if (iwriteable != null)
{
this.WriteWritableObject(iwriteable);
return;
}
throw NotWritableException(instance.GetType().FullName);
}
}
private void WriteWritableObject(IObjectWritable instance)
{
_writer.Write((byte)DataKind.Object_W);
Type type = instance.GetType();
this.WriteType(type);
_binder?.Record(instance);
instance.WriteTo(this);
}
private static Exception NotWritableException(string typeName)
{
#if COMPILERCORE
throw new InvalidOperationException(string.Format(CodeAnalysisResources.NotWritableException, typeName));
#else
throw new InvalidOperationException(string.Format(WorkspacesResources.The_type_0_cannot_be_written_it_does_not_implement_IObjectWritable, typeName));
#endif
}
}
}
| |
#region LGPL License
/*
Axiom Game Engine Library
Copyright (C) 2003 Axiom Project Team
The overall design, and a majority of the core engine and rendering code
contained within this library is a derivative of the open source Object Oriented
Graphics Engine OGRE, which can be found at http://ogre.sourceforge.net.
Many thanks to the OGRE team for maintaining such a high quality project.
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#endregion
using System;
using Axiom.Core;
using Axiom.MathLib;
namespace Axiom.Animating {
/// <summary>
/// A bone in a skeleton.
/// </summary>
/// <remarks>
/// See Skeleton for more information about the principles behind skeletal animation.
/// This class is a node in the joint hierarchy. Mesh vertices also have assignments
/// to bones to define how they move in relation to the skeleton.
/// </remarks>
public class Bone : Node {
#region Fields
/// <summary>Numeric handle of this bone.</summary>
protected ushort handle;
/// <summary>Bones set as manuallyControlled are not reseted in Skeleton.Reset().</summary>
public bool isManuallyControlled;
/// <summary>The skeleton that created this bone.</summary>
protected Skeleton creator;
/// <summary>The inverse derived transform of the bone in the binding pose.</summary>
public Matrix4 bindDerivedInverseTransform;
#endregion Fields
#region Constructors
/// <summary>
/// Constructor, not to be used directly (use Bone.CreateChild or Skeleton.CreateBone)
/// </summary>
public Bone(ushort handle, Skeleton creator) : base() {
this.handle = handle;
this.isManuallyControlled = false;
this.creator = creator;
}
/// <summary>
/// Constructor, not to be used directly (use Bone.CreateChild or Skeleton.CreateBone)
/// </summary>
public Bone(string name, ushort handle, Skeleton creator) : base(name) {
this.handle = handle;
this.isManuallyControlled = false;
this.creator = creator;
}
#endregion
#region Methods
/// <summary>
/// Creates a new Bone as a child of this bone.
/// </summary>
/// <returns></returns>
protected override Node CreateChildImpl() {
return creator.CreateBone();
}
/// <summary>
/// Creates a new Bone as a child of this bone.
/// </summary>
/// <param name="name">Name of the bone to create.</param>
/// <returns></returns>
protected override Node CreateChildImpl(string name) {
return creator.CreateBone(name);
}
/// <summary>
/// Overloaded method. Passes in Zero and Identity for the last 2 params.
/// </summary>
/// <param name="handle">The numeric handle to give the new bone; must be unique within the Skeleton.</param>
/// <returns></returns>
public Bone CreateChild(ushort handle) {
return CreateChild(handle, Vector3.Zero, Quaternion.Identity);
}
/// <summary>
/// Creates a new Bone as a child of this bone.
/// </summary>
/// <param name="handle">The numeric handle to give the new bone; must be unique within the Skeleton.</param>
/// <param name="translate">Initial translation offset of child relative to parent.</param>
/// <param name="rotate">Initial rotation relative to parent.</param>
/// <returns></returns>
public Bone CreateChild(ushort handle, Vector3 translate, Quaternion rotate) {
Bone bone = creator.CreateBone(handle);
bone.Translate(translate);
bone.Rotate(rotate);
this.AddChild(bone);
return bone;
}
/// <summary>
/// Resets the position and orientation of this Bone to the original binding position.
/// </summary>
/// <remarks>
/// Bones are bound to the mesh in a binding pose. They are then modified from this
/// position during animation. This method returns the bone to it's original position and
/// orientation.
/// </remarks>
public void Reset() {
ResetToInitialState();
}
/// <summary>
/// Sets the current position / orientation to be the 'binding pose' ie the layout in which
/// bones were originally bound to a mesh.
/// </summary>
public void SetBindingPose() {
SetInitialState();
// save inverse derived, used for mesh transform later (assumes Update has been called by Skeleton
MakeInverseTransform(
this.DerivedPosition,
Vector3.UnitScale,
this.DerivedOrientation,
ref bindDerivedInverseTransform);
}
#endregion
#region Properties
/// <summary>
/// Determines whether this bone is controlled at runtime.
/// </summary>
public bool IsManuallyControlled {
get { return isManuallyControlled; }
set {
isManuallyControlled = value;
}
}
/// <summary>
/// Gets the inverse transform which takes bone space to origin from the binding pose.
/// </summary>
public Matrix4 BindDerivedInverseTransform {
get {
return bindDerivedInverseTransform;
}
}
/// <summary>
/// Gets the numeric handle of this bone.
/// </summary>
public ushort Handle {
get {
return handle;
}
}
#endregion
}
/// <summary>
/// Records the assignment of a single vertex to a single bone with the corresponding weight.
/// </summary>
/// <remarks>
/// This simple struct simply holds a vertex index, bone index and weight representing the
/// assignment of a vertex to a bone for skeletal animation. There may be many of these
/// per vertex if blended vertex assignments are allowed.
/// This is a class because we need it as a reference type to allow for modification
/// in places where we would only have a copy of the data if it were a struct.
/// </remarks>
public class VertexBoneAssignment {
public int vertexIndex;
public ushort boneIndex;
public float weight;
public VertexBoneAssignment() {
}
public VertexBoneAssignment(VertexBoneAssignment other) {
vertexIndex = other.vertexIndex;
boneIndex = other.boneIndex;
weight = other.weight;
}
}
public class VertexBoneAssignmentWeightComparer : System.Collections.Generic.IComparer<VertexBoneAssignment>
{
/// <summary>Compares two objects and returns a value indicating whether one is less than, equal to or greater than the other.</summary>
/// <returns>Value Condition Less than zero x is less than y. Zero x equals y. Greater than zero x is greater than y. </returns>
/// <param name="y">Second object to compare. </param>
/// <param name="x">First object to compare. </param>
/// <filterpriority>2</filterpriority>
public int Compare(VertexBoneAssignment xVba, VertexBoneAssignment yVba) {
if (xVba == null && yVba == null)
return 0;
else if (xVba == null)
return -1;
else if (yVba == null)
return 1;
else if (xVba.weight == yVba.weight)
return 0;
else if (xVba.weight < yVba.weight)
return -1;
else // if (xVba.weight > yVba.weight)
return 1;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel.Design;
using System.Diagnostics;
using System.Drawing;
using System.Globalization;
using System.Linq;
using System.Reflection;
using System.Threading;
namespace System.ComponentModel
{
/// <summary>
/// This type description provider provides type information through
/// reflection. Unless someone has provided a custom type description
/// provider for a type or instance, or unless an instance implements
/// ICustomTypeDescriptor, any query for type information will go through
/// this class. There should be a single instance of this class associated
/// with "object", as it can provide all type information for any type.
/// </summary>
internal sealed partial class ReflectTypeDescriptionProvider : TypeDescriptionProvider
{
// Hastable of Type -> ReflectedTypeData. ReflectedTypeData contains all
// of the type information we have gathered for a given type.
//
private Hashtable _typeData;
// This is the signature we look for when creating types that are generic, but
// want to know what type they are dealing with. Enums are a good example of this;
// there is one enum converter that can work with all enums, but it needs to know
// the type of enum it is dealing with.
//
private static Type[] s_typeConstructor = new Type[] { typeof(Type) };
// This is where we store the various converters, etc for the intrinsic types.
//
private static Hashtable s_editorTables;
private static Hashtable s_intrinsicTypeConverters;
// For converters, etc that are bound to class attribute data, rather than a class
// type, we have special key sentinel values that we put into the hash table.
//
private static object s_intrinsicReferenceKey = new object();
private static object s_intrinsicNullableKey = new object();
// The key we put into IDictionaryService to store our cache dictionary.
//
private static object s_dictionaryKey = new object();
// This is a cache on top of core reflection. The cache
// builds itself recursively, so if you ask for the properties
// on Control, Component and object are also automatically filled
// in. The keys to the property and event caches are types.
// The keys to the attribute cache are either MemberInfos or types.
//
private static Hashtable s_propertyCache;
private static Hashtable s_eventCache;
private static Hashtable s_attributeCache;
private static Hashtable s_extendedPropertyCache;
// These are keys we stuff into our object cache. We use this
// cache data to store extender provider info for an object.
//
private static readonly Guid s_extenderPropertiesKey = Guid.NewGuid();
private static readonly Guid s_extenderProviderPropertiesKey = Guid.NewGuid();
// These are attributes that, when we discover them on interfaces, we do
// not merge them into the attribute set for a class.
private static readonly Type[] s_skipInterfaceAttributeList = new Type[]
{
#if FEATURE_SKIP_INTERFACE
typeof(System.Runtime.InteropServices.GuidAttribute),
typeof(System.Runtime.InteropServices.InterfaceTypeAttribute)
#endif
typeof(System.Runtime.InteropServices.ComVisibleAttribute),
};
internal static Guid ExtenderProviderKey { get; } = Guid.NewGuid();
private static readonly object s_internalSyncObject = new object();
/// <summary>
/// Creates a new ReflectTypeDescriptionProvider. The type is the
/// type we will obtain type information for.
/// </summary>
internal ReflectTypeDescriptionProvider()
{
}
private static Hashtable EditorTables => LazyInitializer.EnsureInitialized(ref s_editorTables, () => new Hashtable(4));
/// <summary>
/// This is a table we create for intrinsic types.
/// There should be entries here ONLY for intrinsic
/// types, as all other types we should be able to
/// add attributes directly as metadata.
/// </summary>
private static Hashtable IntrinsicTypeConverters => LazyInitializer.EnsureInitialized(ref s_intrinsicTypeConverters, () => new Hashtable
{
// Add the intrinsics
//
[typeof(bool)] = typeof(BooleanConverter),
[typeof(byte)] = typeof(ByteConverter),
[typeof(SByte)] = typeof(SByteConverter),
[typeof(char)] = typeof(CharConverter),
[typeof(double)] = typeof(DoubleConverter),
[typeof(string)] = typeof(StringConverter),
[typeof(int)] = typeof(Int32Converter),
[typeof(short)] = typeof(Int16Converter),
[typeof(long)] = typeof(Int64Converter),
[typeof(float)] = typeof(SingleConverter),
[typeof(UInt16)] = typeof(UInt16Converter),
[typeof(UInt32)] = typeof(UInt32Converter),
[typeof(UInt64)] = typeof(UInt64Converter),
[typeof(object)] = typeof(TypeConverter),
[typeof(void)] = typeof(TypeConverter),
[typeof(CultureInfo)] = typeof(CultureInfoConverter),
[typeof(DateTime)] = typeof(DateTimeConverter),
[typeof(DateTimeOffset)] = typeof(DateTimeOffsetConverter),
[typeof(Decimal)] = typeof(DecimalConverter),
[typeof(TimeSpan)] = typeof(TimeSpanConverter),
[typeof(Guid)] = typeof(GuidConverter),
[typeof(Uri)] = typeof(UriTypeConverter),
[typeof(Color)] = typeof(ColorConverter),
[typeof(Point)] = typeof(PointConverter),
[typeof(Rectangle)] = typeof(RectangleConverter),
[typeof(Size)] = typeof(SizeConverter),
[typeof(SizeF)] = typeof(SizeFConverter),
// Special cases for things that are not bound to a specific type
//
[typeof(Array)] = typeof(ArrayConverter),
[typeof(ICollection)] = typeof(CollectionConverter),
[typeof(Enum)] = typeof(EnumConverter),
[s_intrinsicNullableKey] = typeof(NullableConverter),
});
private static Hashtable PropertyCache => LazyInitializer.EnsureInitialized(ref s_propertyCache, () => new Hashtable());
private static Hashtable EventCache => LazyInitializer.EnsureInitialized(ref s_eventCache, () => new Hashtable());
private static Hashtable AttributeCache => LazyInitializer.EnsureInitialized(ref s_attributeCache, () => new Hashtable());
private static Hashtable ExtendedPropertyCache => LazyInitializer.EnsureInitialized(ref s_extendedPropertyCache, () => new Hashtable());
/// <summary>
/// Adds an editor table for the given editor base type.
/// Typically, editors are specified as metadata on an object. If no metadata for a
/// requested editor base type can be found on an object, however, the
/// TypeDescriptor will search an editor
/// table for the editor type, if one can be found.
/// </summary>
internal static void AddEditorTable(Type editorBaseType, Hashtable table)
{
if (editorBaseType == null)
{
throw new ArgumentNullException(nameof(editorBaseType));
}
if (table == null)
{
Debug.Fail("COMPAT: Editor table should not be null");
// don't throw; RTM didn't so we can't do it either.
}
lock (s_internalSyncObject)
{
Hashtable editorTables = EditorTables;
if (!editorTables.ContainsKey(editorBaseType))
{
editorTables[editorBaseType] = table;
}
}
}
/// <summary>
/// CreateInstance implementation. We delegate to Activator.
/// </summary>
public override object CreateInstance(IServiceProvider provider, Type objectType, Type[] argTypes, object[] args)
{
Debug.Assert(objectType != null, "Should have arg-checked before coming in here");
object obj = null;
if (argTypes != null)
{
obj = objectType.GetConstructor(argTypes)?.Invoke(args);
}
else
{
if (args != null)
{
argTypes = new Type[args.Length];
for (int idx = 0; idx < args.Length; idx++)
{
if (args[idx] != null)
{
argTypes[idx] = args[idx].GetType();
}
else
{
argTypes[idx] = typeof(object);
}
}
}
else
{
argTypes = Array.Empty<Type>();
}
obj = objectType.GetConstructor(argTypes)?.Invoke(args);
}
return obj ?? Activator.CreateInstance(objectType, args);
}
/// <summary>
/// Helper method to create editors and type converters. This checks to see if the
/// type implements a Type constructor, and if it does it invokes that ctor.
/// Otherwise, it just tries to create the type.
/// </summary>
private static object CreateInstance(Type objectType, Type callingType)
{
return objectType.GetConstructor(s_typeConstructor)?.Invoke(new object[] { callingType })
?? Activator.CreateInstance(objectType);
}
/// <summary>
/// Retrieves custom attributes.
/// </summary>
internal AttributeCollection GetAttributes(Type type)
{
ReflectedTypeData td = GetTypeData(type, true);
return td.GetAttributes();
}
/// <summary>
/// Our implementation of GetCache sits on top of IDictionaryService.
/// </summary>
public override IDictionary GetCache(object instance)
{
IComponent comp = instance as IComponent;
if (comp != null && comp.Site != null)
{
IDictionaryService ds = comp.Site.GetService(typeof(IDictionaryService)) as IDictionaryService;
if (ds != null)
{
IDictionary dict = ds.GetValue(s_dictionaryKey) as IDictionary;
if (dict == null)
{
dict = new Hashtable();
ds.SetValue(s_dictionaryKey, dict);
}
return dict;
}
}
return null;
}
/// <summary>
/// Retrieves the class name for our type.
/// </summary>
internal string GetClassName(Type type)
{
ReflectedTypeData td = GetTypeData(type, true);
return td.GetClassName(null);
}
/// <summary>
/// Retrieves the component name from the site.
/// </summary>
internal string GetComponentName(Type type, object instance)
{
ReflectedTypeData td = GetTypeData(type, true);
return td.GetComponentName(instance);
}
/// <summary>
/// Retrieves the type converter. If instance is non-null,
/// it will be used to retrieve attributes. Otherwise, _type
/// will be used.
/// </summary>
internal TypeConverter GetConverter(Type type, object instance)
{
ReflectedTypeData td = GetTypeData(type, true);
return td.GetConverter(instance);
}
/// <summary>
/// Return the default event. The default event is determined by the
/// presence of a DefaultEventAttribute on the class.
/// </summary>
internal EventDescriptor GetDefaultEvent(Type type, object instance)
{
ReflectedTypeData td = GetTypeData(type, true);
return td.GetDefaultEvent(instance);
}
/// <summary>
/// Return the default property.
/// </summary>
internal PropertyDescriptor GetDefaultProperty(Type type, object instance)
{
ReflectedTypeData td = GetTypeData(type, true);
return td.GetDefaultProperty(instance);
}
/// <summary>
/// Retrieves the editor for the given base type.
/// </summary>
internal object GetEditor(Type type, object instance, Type editorBaseType)
{
ReflectedTypeData td = GetTypeData(type, true);
return td.GetEditor(instance, editorBaseType);
}
/// <summary>
/// Retrieves a default editor table for the given editor base type.
/// </summary>
private static Hashtable GetEditorTable(Type editorBaseType)
{
Hashtable editorTables = EditorTables;
object table = editorTables[editorBaseType];
if (table == null)
{
// Before we give up, it is possible that the
// class initializer for editorBaseType hasn't
// actually run.
//
System.Runtime.CompilerServices.RuntimeHelpers.RunClassConstructor(editorBaseType.TypeHandle);
table = editorTables[editorBaseType];
// If the table is still null, then throw a
// sentinel in there so we don't
// go through this again.
//
if (table == null)
{
lock (s_internalSyncObject)
{
table = editorTables[editorBaseType];
if (table == null)
{
editorTables[editorBaseType] = editorTables;
}
}
}
}
// Look for our sentinel value that indicates
// we have already tried and failed to get
// a table.
//
if (table == editorTables)
{
table = null;
}
return (Hashtable)table;
}
/// <summary>
/// Retrieves the events for this type.
/// </summary>
internal EventDescriptorCollection GetEvents(Type type)
{
ReflectedTypeData td = GetTypeData(type, true);
return td.GetEvents();
}
/// <summary>
/// Retrieves custom extender attributes. We don't support
/// extender attributes, so we always return an empty collection.
/// </summary>
internal AttributeCollection GetExtendedAttributes(object instance)
{
return AttributeCollection.Empty;
}
/// <summary>
/// Retrieves the class name for our type.
/// </summary>
internal string GetExtendedClassName(object instance)
{
return GetClassName(instance.GetType());
}
/// <summary>
/// Retrieves the component name from the site.
/// </summary>
internal string GetExtendedComponentName(object instance)
{
return GetComponentName(instance.GetType(), instance);
}
/// <summary>
/// Retrieves the type converter. If instance is non-null,
/// it will be used to retrieve attributes. Otherwise, _type
/// will be used.
/// </summary>
internal TypeConverter GetExtendedConverter(object instance)
{
return GetConverter(instance.GetType(), instance);
}
/// <summary>
/// Return the default event. The default event is determined by the
/// presence of a DefaultEventAttribute on the class.
/// </summary>
internal EventDescriptor GetExtendedDefaultEvent(object instance)
{
return null; // we don't support extended events.
}
/// <summary>
/// Return the default property.
/// </summary>
internal PropertyDescriptor GetExtendedDefaultProperty(object instance)
{
return null; // extender properties are never the default.
}
/// <summary>
/// Retrieves the editor for the given base type.
/// </summary>
internal object GetExtendedEditor(object instance, Type editorBaseType)
{
return GetEditor(instance.GetType(), instance, editorBaseType);
}
/// <summary>
/// Retrieves the events for this type.
/// </summary>
internal EventDescriptorCollection GetExtendedEvents(object instance)
{
return EventDescriptorCollection.Empty;
}
/// <summary>
/// Retrieves the properties for this type.
/// </summary>
internal PropertyDescriptorCollection GetExtendedProperties(object instance)
{
// Is this object a sited component? If not, then it
// doesn't have any extender properties.
//
Type componentType = instance.GetType();
// Check the component for extender providers. We prefer
// IExtenderListService, but will use the container if that's
// all we have. In either case, we check the list of extenders
// against previously stored data in the object cache. If
// the cache is up to date, we just return the extenders in the
// cache.
//
IExtenderProvider[] extenders = GetExtenderProviders(instance);
IDictionary cache = TypeDescriptor.GetCache(instance);
if (extenders.Length == 0)
{
return PropertyDescriptorCollection.Empty;
}
// Ok, we have a set of extenders. Now, check to see if there
// are properties already in our object cache. If there aren't,
// then we will need to create them.
//
PropertyDescriptorCollection properties = null;
if (cache != null)
{
properties = cache[s_extenderPropertiesKey] as PropertyDescriptorCollection;
}
if (properties != null)
{
return properties;
}
// Unlike normal properties, it is fine for there to be properties with
// duplicate names here.
//
List<PropertyDescriptor> propertyList = null;
for (int idx = 0; idx < extenders.Length; idx++)
{
PropertyDescriptor[] propertyArray = ReflectGetExtendedProperties(extenders[idx]);
if (propertyList == null)
{
propertyList = new List<PropertyDescriptor>(propertyArray.Length * extenders.Length);
}
for (int propIdx = 0; propIdx < propertyArray.Length; propIdx++)
{
PropertyDescriptor prop = propertyArray[propIdx];
ExtenderProvidedPropertyAttribute eppa = prop.Attributes[typeof(ExtenderProvidedPropertyAttribute)] as ExtenderProvidedPropertyAttribute;
Debug.Assert(eppa != null, $"Extender property {prop.Name} has no provider attribute. We will skip it.");
if (eppa != null)
{
Type receiverType = eppa.ReceiverType;
if (receiverType != null)
{
if (receiverType.IsAssignableFrom(componentType))
{
propertyList.Add(prop);
}
}
}
}
}
// propertyHash now contains ExtendedPropertyDescriptor objects
// for each extended property.
//
if (propertyList != null)
{
PropertyDescriptor[] fullArray = new PropertyDescriptor[propertyList.Count];
propertyList.CopyTo(fullArray, 0);
properties = new PropertyDescriptorCollection(fullArray, true);
}
else
{
properties = PropertyDescriptorCollection.Empty;
}
if (cache != null)
{
cache[s_extenderPropertiesKey] = properties;
}
return properties;
}
protected internal override IExtenderProvider[] GetExtenderProviders(object instance)
{
if (instance == null)
{
throw new ArgumentNullException(nameof(instance));
}
IComponent component = instance as IComponent;
if (component != null && component.Site != null)
{
IExtenderListService extenderList = component.Site.GetService(typeof(IExtenderListService)) as IExtenderListService;
IDictionary cache = TypeDescriptor.GetCache(instance);
if (extenderList != null)
{
return GetExtenders(extenderList.GetExtenderProviders(), instance, cache);
}
#if FEATURE_COMPONENT_COLLECTION
else
{
IContainer cont = component.Site.Container;
if (cont != null)
{
return GetExtenders(cont.Components, instance, cache);
}
}
#endif
}
return Array.Empty<IExtenderProvider>();
}
/// <summary>
/// GetExtenders builds a list of extender providers from
/// a collection of components. It validates the extenders
/// against any cached collection of extenders in the
/// cache. If there is a discrepancy, this will erase
/// any cached extender properties from the cache and
/// save the updated extender list. If there is no
/// discrepancy this will simply return the cached list.
/// </summary>
private static IExtenderProvider[] GetExtenders(ICollection components, object instance, IDictionary cache)
{
bool newExtenders = false;
int extenderCount = 0;
IExtenderProvider[] existingExtenders = null;
//CanExtend is expensive. We will remember results of CanExtend for the first 64 extenders and using "long canExtend" as a bit vector.
// we want to avoid memory allocation as well so we don't use some more sophisticated data structure like an array of booleans
UInt64 canExtend = 0;
int maxCanExtendResults = 64;
// currentExtenders is what we intend to return. If the caller passed us
// the return value from IExtenderListService, components will already be
// an IExtenderProvider[]. If not, then we must treat components as an
// opaque collection. We spend a great deal of energy here to avoid
// copying or allocating memory because this method is called every
// time a component is asked for its properties.
IExtenderProvider[] currentExtenders = components as IExtenderProvider[];
if (cache != null)
{
existingExtenders = cache[ExtenderProviderKey] as IExtenderProvider[];
}
if (existingExtenders == null)
{
newExtenders = true;
}
int curIdx = 0;
int idx = 0;
if (currentExtenders != null)
{
for (curIdx = 0; curIdx < currentExtenders.Length; curIdx++)
{
if (currentExtenders[curIdx].CanExtend(instance))
{
extenderCount++;
// Performance:We would like to call CanExtend as little as possible therefore we remember its result
if (curIdx < maxCanExtendResults)
canExtend |= (UInt64)1 << curIdx;
if (!newExtenders && (idx >= existingExtenders.Length || currentExtenders[curIdx] != existingExtenders[idx++]))
{
newExtenders = true;
}
}
}
}
else if (components != null)
{
foreach (object obj in components)
{
IExtenderProvider prov = obj as IExtenderProvider;
if (prov != null && prov.CanExtend(instance))
{
extenderCount++;
if (curIdx < maxCanExtendResults)
canExtend |= (UInt64)1 << curIdx;
if (!newExtenders && (idx >= existingExtenders.Length || prov != existingExtenders[idx++]))
{
newExtenders = true;
}
}
curIdx++;
}
}
if (existingExtenders != null && extenderCount != existingExtenders.Length)
{
newExtenders = true;
}
if (newExtenders)
{
if (currentExtenders == null || extenderCount != currentExtenders.Length)
{
IExtenderProvider[] newExtenderArray = new IExtenderProvider[extenderCount];
curIdx = 0;
idx = 0;
if (currentExtenders != null && extenderCount > 0)
{
while (curIdx < currentExtenders.Length)
{
if ((curIdx < maxCanExtendResults && (canExtend & ((UInt64)1 << curIdx)) != 0) ||
(curIdx >= maxCanExtendResults && currentExtenders[curIdx].CanExtend(instance)))
{
Debug.Assert(idx < extenderCount, "There are more extenders than we expect");
newExtenderArray[idx++] = currentExtenders[curIdx];
}
curIdx++;
}
Debug.Assert(idx == extenderCount, "Wrong number of extenders");
}
else if (extenderCount > 0)
{
foreach (var component in components)
{
IExtenderProvider p = component as IExtenderProvider;
if (p != null && ((curIdx < maxCanExtendResults && (canExtend & ((UInt64)1 << curIdx)) != 0) ||
(curIdx >= maxCanExtendResults && p.CanExtend(instance))))
{
Debug.Assert(idx < extenderCount, "There are more extenders than we expect");
newExtenderArray[idx++] = p;
}
curIdx++;
}
Debug.Assert(idx == extenderCount, "Wrong number of extenders");
}
currentExtenders = newExtenderArray;
}
if (cache != null)
{
cache[ExtenderProviderKey] = currentExtenders;
cache.Remove(s_extenderPropertiesKey);
}
}
else
{
currentExtenders = existingExtenders;
}
return currentExtenders;
}
/// <summary>
/// Retrieves the owner for a property.
/// </summary>
internal object GetExtendedPropertyOwner(object instance, PropertyDescriptor pd)
{
return GetPropertyOwner(instance.GetType(), instance, pd);
}
//////////////////////////////////////////////////////////
/// <summary>
/// Provides a type descriptor for the given object. We only support this
/// if the object is a component that
/// </summary>
public override ICustomTypeDescriptor GetExtendedTypeDescriptor(object instance)
{
Debug.Fail("This should never be invoked. TypeDescriptionNode should wrap for us.");
return null;
}
/// <summary>
/// The name of the specified component, or null if the component has no name.
/// In many cases this will return the same value as GetComponentName. If the
/// component resides in a nested container or has other nested semantics, it may
/// return a different fully qualified name.
///
/// If not overridden, the default implementation of this method will call
/// GetComponentName.
/// </summary>
public override string GetFullComponentName(object component)
{
IComponent comp = component as IComponent;
INestedSite ns = comp?.Site as INestedSite;
if (ns != null)
{
return ns.FullName;
}
return TypeDescriptor.GetComponentName(component);
}
/// <summary>
/// Returns an array of types we have populated metadata for that live
/// in the current module.
/// </summary>
internal Type[] GetPopulatedTypes(Module module)
{
List<Type> typeList = new List<Type>();
// Manual use of IDictionaryEnumerator instead of foreach to avoid DictionaryEntry box allocations.
IDictionaryEnumerator e = _typeData.GetEnumerator();
while (e.MoveNext())
{
DictionaryEntry de = e.Entry;
Type type = (Type)de.Key;
ReflectedTypeData typeData = (ReflectedTypeData)de.Value;
if (type.Module == module && typeData.IsPopulated)
{
typeList.Add(type);
}
}
return typeList.ToArray();
}
/// <summary>
/// Retrieves the properties for this type.
/// </summary>
internal PropertyDescriptorCollection GetProperties(Type type)
{
ReflectedTypeData td = GetTypeData(type, true);
return td.GetProperties();
}
/// <summary>
/// Retrieves the owner for a property.
/// </summary>
internal object GetPropertyOwner(Type type, object instance, PropertyDescriptor pd)
{
return TypeDescriptor.GetAssociation(type, instance);
}
/// <summary>
/// Returns an Type for the given type. Since type implements IReflect,
/// we just return objectType.
/// </summary>
public override Type GetReflectionType(Type objectType, object instance)
{
Debug.Assert(objectType != null, "Should have arg-checked before coming in here");
return objectType;
}
/// <summary>
/// Returns the type data for the given type, or
/// null if there is no type data for the type yet and
/// createIfNeeded is false.
/// </summary>
private ReflectedTypeData GetTypeData(Type type, bool createIfNeeded)
{
ReflectedTypeData td = null;
if (_typeData != null)
{
td = (ReflectedTypeData)_typeData[type];
if (td != null)
{
return td;
}
}
lock (s_internalSyncObject)
{
if (_typeData != null)
{
td = (ReflectedTypeData)_typeData[type];
}
if (td == null && createIfNeeded)
{
td = new ReflectedTypeData(type);
if (_typeData == null)
{
_typeData = new Hashtable();
}
_typeData[type] = td;
}
}
return td;
}
/// <summary>
/// This method returns a custom type descriptor for the given type / object.
/// The objectType parameter is always valid, but the instance parameter may
/// be null if no instance was passed to TypeDescriptor. The method should
/// return a custom type descriptor for the object. If the method is not
/// interested in providing type information for the object it should
/// return null.
/// </summary>
public override ICustomTypeDescriptor GetTypeDescriptor(Type objectType, object instance)
{
Debug.Fail("This should never be invoked. TypeDescriptionNode should wrap for us.");
return null;
}
/// <summary>
/// Retrieves a type from a name.
/// </summary>
private static Type GetTypeFromName(string typeName)
{
Type t = Type.GetType(typeName);
if (t == null)
{
int commaIndex = typeName.IndexOf(',');
if (commaIndex != -1)
{
// At design time, it's possible for us to reuse
// an assembly but add new types. The app domain
// will cache the assembly based on identity, however,
// so it could be looking in the previous version
// of the assembly and not finding the type. We work
// around this by looking for the non-assembly qualified
// name, which causes the domain to raise a type
// resolve event.
//
t = Type.GetType(typeName.Substring(0, commaIndex));
}
}
return t;
}
/// <summary>
/// This method returns true if the data cache in this reflection
/// type descriptor has data in it.
/// </summary>
internal bool IsPopulated(Type type)
{
ReflectedTypeData td = GetTypeData(type, false);
if (td != null)
{
return td.IsPopulated;
}
return false;
}
/// <summary>
/// Static helper API around reflection to get and cache
/// custom attributes. This does not recurse, but it will
/// walk interfaces on the type. Interfaces are added
/// to the end, so merging should be done from length - 1
/// to 0.
/// </summary>
internal static Attribute[] ReflectGetAttributes(Type type)
{
Hashtable attributeCache = AttributeCache;
Attribute[] attrs = (Attribute[])attributeCache[type];
if (attrs != null)
{
return attrs;
}
lock (s_internalSyncObject)
{
attrs = (Attribute[])attributeCache[type];
if (attrs == null)
{
// Get the type's attributes.
//
attrs = type.GetCustomAttributes(typeof(Attribute), false).OfType<Attribute>().ToArray();
attributeCache[type] = attrs;
}
}
return attrs;
}
/// <summary>
/// Static helper API around reflection to get and cache
/// custom attributes. This does not recurse to the base class.
/// </summary>
internal static Attribute[] ReflectGetAttributes(MemberInfo member)
{
Hashtable attributeCache = AttributeCache;
Attribute[] attrs = (Attribute[])attributeCache[member];
if (attrs != null)
{
return attrs;
}
lock (s_internalSyncObject)
{
attrs = (Attribute[])attributeCache[member];
if (attrs == null)
{
// Get the member's attributes.
//
attrs = member.GetCustomAttributes(typeof(Attribute), false).OfType<Attribute>().ToArray();
attributeCache[member] = attrs;
}
}
return attrs;
}
/// <summary>
/// Static helper API around reflection to get and cache
/// events. This does not recurse to the base class.
/// </summary>
private static EventDescriptor[] ReflectGetEvents(Type type)
{
Hashtable eventCache = EventCache;
EventDescriptor[] events = (EventDescriptor[])eventCache[type];
if (events != null)
{
return events;
}
lock (s_internalSyncObject)
{
events = (EventDescriptor[])eventCache[type];
if (events == null)
{
BindingFlags bindingFlags = BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.Instance;
// Get the type's events. Events may have their add and
// remove methods individually overridden in a derived
// class, but at some point in the base class chain both
// methods must exist. If we find an event that doesn't
// have both add and remove, we skip it here, because it
// will be picked up in our base class scan.
//
EventInfo[] eventInfos = type.GetEvents(bindingFlags);
events = new EventDescriptor[eventInfos.Length];
int eventCount = 0;
for (int idx = 0; idx < eventInfos.Length; idx++)
{
EventInfo eventInfo = eventInfos[idx];
// GetEvents returns events that are on nonpublic types
// if those types are from our assembly. Screen these.
//
if ((!(eventInfo.DeclaringType.IsPublic || eventInfo.DeclaringType.IsNestedPublic)) && (eventInfo.DeclaringType.Assembly == typeof(ReflectTypeDescriptionProvider).Assembly))
{
Debug.Fail("Hey, assumption holds true. Rip this assert.");
continue;
}
if (eventInfo.AddMethod != null && eventInfo.RemoveMethod != null)
{
events[eventCount++] = new ReflectEventDescriptor(type, eventInfo);
}
}
if (eventCount != events.Length)
{
EventDescriptor[] newEvents = new EventDescriptor[eventCount];
Array.Copy(events, 0, newEvents, 0, eventCount);
events = newEvents;
}
#if DEBUG
foreach (EventDescriptor dbgEvent in events)
{
Debug.Assert(dbgEvent != null, "Holes in event array for type " + type);
}
#endif
eventCache[type] = events;
}
}
return events;
}
/// <summary>
/// This performs the actual reflection needed to discover
/// extender properties. If object caching is supported this
/// will maintain a cache of property descriptors on the
/// extender provider. Extender properties are actually two
/// property descriptors in one. There is a chunk of per-class
/// data in a ReflectPropertyDescriptor that defines the
/// parameter types and get and set methods of the extended property,
/// and there is an ExtendedPropertyDescriptor that combines this
/// with an extender provider object to create what looks like a
/// normal property. ReflectGetExtendedProperties maintains two
/// separate caches for these two sets: a static one for the
/// ReflectPropertyDescriptor values that don't change for each
/// provider instance, and a per-provider cache that contains
/// the ExtendedPropertyDescriptors.
/// </summary>
private static PropertyDescriptor[] ReflectGetExtendedProperties(IExtenderProvider provider)
{
IDictionary cache = TypeDescriptor.GetCache(provider);
PropertyDescriptor[] properties;
if (cache != null)
{
properties = cache[s_extenderProviderPropertiesKey] as PropertyDescriptor[];
if (properties != null)
{
return properties;
}
}
// Our per-instance cache missed. We have never seen this instance of the
// extender provider before. See if we can find our class-based
// property store.
//
Type providerType = provider.GetType();
Hashtable extendedPropertyCache = ExtendedPropertyCache;
ReflectPropertyDescriptor[] extendedProperties = (ReflectPropertyDescriptor[])extendedPropertyCache[providerType];
if (extendedProperties == null)
{
lock (s_internalSyncObject)
{
extendedProperties = (ReflectPropertyDescriptor[])extendedPropertyCache[providerType];
// Our class-based property store failed as well, so we need to build up the set of
// extended properties here.
//
if (extendedProperties == null)
{
AttributeCollection attributes = TypeDescriptor.GetAttributes(providerType);
List<ReflectPropertyDescriptor> extendedList = new List<ReflectPropertyDescriptor>(attributes.Count);
foreach (Attribute attr in attributes)
{
ProvidePropertyAttribute provideAttr = attr as ProvidePropertyAttribute;
if (provideAttr != null)
{
Type receiverType = GetTypeFromName(provideAttr.ReceiverTypeName);
if (receiverType != null)
{
MethodInfo getMethod = providerType.GetMethod("Get" + provideAttr.PropertyName, new Type[] { receiverType });
if (getMethod != null && !getMethod.IsStatic && getMethod.IsPublic)
{
MethodInfo setMethod = providerType.GetMethod("Set" + provideAttr.PropertyName, new Type[] { receiverType, getMethod.ReturnType });
if (setMethod != null && (setMethod.IsStatic || !setMethod.IsPublic))
{
setMethod = null;
}
extendedList.Add(new ReflectPropertyDescriptor(providerType, provideAttr.PropertyName, getMethod.ReturnType, receiverType, getMethod, setMethod, null));
}
}
}
}
extendedProperties = new ReflectPropertyDescriptor[extendedList.Count];
extendedList.CopyTo(extendedProperties, 0);
extendedPropertyCache[providerType] = extendedProperties;
}
}
}
// Now that we have our extended properties we can build up a list of callable properties. These can be
// returned to the user.
//
properties = new PropertyDescriptor[extendedProperties.Length];
for (int idx = 0; idx < extendedProperties.Length; idx++)
{
ReflectPropertyDescriptor rpd = extendedProperties[idx];
properties[idx] = new ExtendedPropertyDescriptor(rpd, rpd.ExtenderGetReceiverType(), provider, null);
}
if (cache != null)
{
cache[s_extenderProviderPropertiesKey] = properties;
}
return properties;
}
/// <summary>
/// Static helper API around reflection to get and cache
/// properties. This does not recurse to the base class.
/// </summary>
private static PropertyDescriptor[] ReflectGetProperties(Type type)
{
Hashtable propertyCache = PropertyCache;
PropertyDescriptor[] properties = (PropertyDescriptor[])propertyCache[type];
if (properties != null)
{
return properties;
}
lock (s_internalSyncObject)
{
properties = (PropertyDescriptor[])propertyCache[type];
if (properties == null)
{
BindingFlags bindingFlags = BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.Instance;
// Get the type's properties. Properties may have their
// get and set methods individually overridden in a derived
// class, so if we find a missing method we need to walk
// down the base class chain to find it. We actually merge
// "new" properties of the same name, so we must preserve
// the member info for each method individually.
//
PropertyInfo[] propertyInfos = type.GetProperties(bindingFlags);
properties = new PropertyDescriptor[propertyInfos.Length];
int propertyCount = 0;
for (int idx = 0; idx < propertyInfos.Length; idx++)
{
PropertyInfo propertyInfo = propertyInfos[idx];
// Today we do not support parameterized properties.
//
if (propertyInfo.GetIndexParameters().Length > 0)
{
continue;
}
MethodInfo getMethod = propertyInfo.GetMethod;
MethodInfo setMethod = propertyInfo.SetMethod;
string name = propertyInfo.Name;
// If the property only overrode "set", then we don't
// pick it up here. Rather, we just merge it in from
// the base class list.
// If a property had at least a get method, we consider it. We don't
// consider write-only properties.
//
if (getMethod != null)
{
properties[propertyCount++] = new ReflectPropertyDescriptor(type, name,
propertyInfo.PropertyType,
propertyInfo, getMethod,
setMethod, null);
}
}
if (propertyCount != properties.Length)
{
PropertyDescriptor[] newProperties = new PropertyDescriptor[propertyCount];
Array.Copy(properties, 0, newProperties, 0, propertyCount);
properties = newProperties;
}
Debug.Assert(!properties.Any(dbgProp => dbgProp == null), $"Holes in property array for type {type}");
propertyCache[type] = properties;
}
}
return properties;
}
/// <summary>
/// Refreshes the contents of this type descriptor. This does not
/// actually requery, but it will clear our state so the next
/// query re-populates.
/// </summary>
internal void Refresh(Type type)
{
ReflectedTypeData td = GetTypeData(type, false);
td?.Refresh();
}
/// <summary>
/// Searches the provided intrinsic hashtable for a match with the object type.
/// At the beginning, the hashtable contains types for the various converters.
/// As this table is searched, the types for these objects
/// are replaced with instances, so we only create as needed. This method
/// does the search up the base class hierarchy and will create instances
/// for types as needed. These instances are stored back into the table
/// for the base type, and for the original component type, for fast access.
/// </summary>
private static object SearchIntrinsicTable(Hashtable table, Type callingType)
{
object hashEntry = null;
// We take a lock on this table. Nothing in this code calls out to
// other methods that lock, so it should be fairly safe to grab this
// lock. Also, this allows multiple intrinsic tables to be searched
// at once.
//
lock (table)
{
Type baseType = callingType;
while (baseType != null && baseType != typeof(object))
{
hashEntry = table[baseType];
// If the entry is a late-bound type, then try to
// resolve it.
//
string typeString = hashEntry as string;
if (typeString != null)
{
hashEntry = Type.GetType(typeString);
if (hashEntry != null)
{
table[baseType] = hashEntry;
}
}
if (hashEntry != null)
{
break;
}
baseType = baseType.BaseType;
}
// Now make a scan through each value in the table, looking for interfaces.
// If we find one, see if the object implements the interface.
//
if (hashEntry == null)
{
// Manual use of IDictionaryEnumerator instead of foreach to avoid DictionaryEntry box allocations.
IDictionaryEnumerator e = table.GetEnumerator();
while (e.MoveNext())
{
DictionaryEntry de = e.Entry;
Type keyType = de.Key as Type;
if (keyType != null && keyType.IsInterface && keyType.IsAssignableFrom(callingType))
{
hashEntry = de.Value;
string typeString = hashEntry as string;
if (typeString != null)
{
hashEntry = Type.GetType(typeString);
if (hashEntry != null)
{
table[callingType] = hashEntry;
}
}
if (hashEntry != null)
{
break;
}
}
}
}
// Special case converters
//
if (hashEntry == null)
{
if (callingType.IsGenericType && callingType.GetGenericTypeDefinition() == typeof(Nullable<>))
{
// Check if it is a nullable value
hashEntry = table[s_intrinsicNullableKey];
}
else if (callingType.IsInterface)
{
// Finally, check to see if the component type is some unknown interface.
// We have a custom converter for that.
hashEntry = table[s_intrinsicReferenceKey];
}
}
// Interfaces do not derive from object, so we
// must handle the case of no hash entry here.
//
if (hashEntry == null)
{
hashEntry = table[typeof(object)];
}
// If the entry is a type, create an instance of it and then
// replace the entry. This way we only need to create once.
// We can only do this if the object doesn't want a type
// in its constructor.
//
Type type = hashEntry as Type;
if (type != null)
{
hashEntry = CreateInstance(type, callingType);
if (type.GetConstructor(s_typeConstructor) == null)
{
table[callingType] = hashEntry;
}
}
}
return hashEntry;
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Orleans.Configuration;
using Orleans.Providers;
using Orleans.Runtime;
using Orleans.Storage.Internal;
namespace Orleans.Storage
{
/// <summary>
/// This is a simple in-memory grain implementation of a storage provider.
/// </summary>
/// <remarks>
/// This storage provider is ONLY intended for simple in-memory Development / Unit Test scenarios.
/// This class should NOT be used in Production environment,
/// because [by-design] it does not provide any resilience
/// or long-term persistence capabilities.
/// </remarks>
/// <example>
/// Example configuration for this storage provider in OrleansConfiguration.xml file:
/// <code>
/// <OrleansConfiguration xmlns="urn:orleans">
/// <Globals>
/// <StorageProviders>
/// <Provider Type="Orleans.Storage.MemoryStorage" Name="MemoryStore" />
/// </StorageProviders>
/// </code>
/// </example>
[DebuggerDisplay("MemoryStore:{Name}")]
public class MemoryGrainStorage : IGrainStorage, IDisposable
{
private MemoryGrainStorageOptions options;
private const string STATE_STORE_NAME = "MemoryStorage";
private Lazy<IMemoryStorageGrain>[] storageGrains;
private ILogger logger;
private IGrainFactory grainFactory;
/// <summary> Name of this storage provider instance. </summary>
private readonly string name;
/// <summary> Default constructor. </summary>
public MemoryGrainStorage(string name, MemoryGrainStorageOptions options, ILoggerFactory loggerFactory, IGrainFactory grainFactory)
{
this.options = options;
this.name = name;
this.logger = loggerFactory.CreateLogger($"{this.GetType().FullName}.{name}");
this.grainFactory = grainFactory;
//Init
logger.Info("Init: Name={0} NumStorageGrains={1}", name, this.options.NumStorageGrains);
storageGrains = new Lazy<IMemoryStorageGrain>[this.options.NumStorageGrains];
for (int i = 0; i < this.options.NumStorageGrains; i++)
{
int idx = i; // Capture variable to avoid modified closure error
storageGrains[idx] = new Lazy<IMemoryStorageGrain>(() => this.grainFactory.GetGrain<IMemoryStorageGrain>(idx));
}
}
/// <summary> Read state data function for this storage provider. </summary>
/// <see cref="IStorageProvider.ReadStateAsync"/>
public virtual async Task ReadStateAsync(string grainType, GrainReference grainReference, IGrainState grainState)
{
IList<Tuple<string, string>> keys = MakeKeys(grainType, grainReference).ToList();
if (logger.IsEnabled(LogLevel.Trace)) logger.Trace("Read Keys={0}", StorageProviderUtils.PrintKeys(keys));
string id = HierarchicalKeyStore.MakeStoreKey(keys);
IMemoryStorageGrain storageGrain = GetStorageGrain(id);
var state = await storageGrain.ReadStateAsync(STATE_STORE_NAME, id);
if (state != null && state.State != null)
{
grainState.ETag = state.ETag;
grainState.State = state.State;
}
}
/// <summary> Write state data function for this storage provider. </summary>
/// <see cref="IStorageProvider.WriteStateAsync"/>
public virtual async Task WriteStateAsync(string grainType, GrainReference grainReference, IGrainState grainState)
{
IList<Tuple<string, string>> keys = MakeKeys(grainType, grainReference).ToList();
string key = HierarchicalKeyStore.MakeStoreKey(keys);
if (logger.IsEnabled(LogLevel.Trace)) logger.Trace("Write {0} ", StorageProviderUtils.PrintOneWrite(keys, grainState.State, grainState.ETag));
IMemoryStorageGrain storageGrain = GetStorageGrain(key);
try
{
grainState.ETag = await storageGrain.WriteStateAsync(STATE_STORE_NAME, key, grainState);
}
catch (MemoryStorageEtagMismatchException e)
{
throw e.AsInconsistentStateException();
}
}
/// <summary> Delete / Clear state data function for this storage provider. </summary>
/// <see cref="IStorageProvider.ClearStateAsync"/>
public virtual async Task ClearStateAsync(string grainType, GrainReference grainReference, IGrainState grainState)
{
IList<Tuple<string, string>> keys = MakeKeys(grainType, grainReference).ToList();
if (logger.IsEnabled(LogLevel.Trace)) logger.Trace("Delete Keys={0} Etag={1}", StorageProviderUtils.PrintKeys(keys), grainState.ETag);
string key = HierarchicalKeyStore.MakeStoreKey(keys);
IMemoryStorageGrain storageGrain = GetStorageGrain(key);
try
{
await storageGrain.DeleteStateAsync(STATE_STORE_NAME, key, grainState.ETag);
grainState.ETag = null;
}
catch (MemoryStorageEtagMismatchException e)
{
throw e.AsInconsistentStateException();
}
}
private static IEnumerable<Tuple<string, string>> MakeKeys(string grainType, GrainReference grain)
{
return new[]
{
Tuple.Create("GrainType", grainType),
Tuple.Create("GrainId", grain.ToKeyString())
};
}
private IMemoryStorageGrain GetStorageGrain(string id)
{
int idx = StorageProviderUtils.PositiveHash(id.GetHashCode(), this.options.NumStorageGrains);
IMemoryStorageGrain storageGrain = storageGrains[idx].Value;
return storageGrain;
}
internal static Func<IDictionary<string, object>, bool> GetComparer<T>(string rangeParamName, T fromValue, T toValue) where T : IComparable
{
Comparer comparer = Comparer.DefaultInvariant;
bool sameRange = comparer.Compare(fromValue, toValue) == 0; // FromValue == ToValue
bool insideRange = comparer.Compare(fromValue, toValue) < 0; // FromValue < ToValue
Func<IDictionary<string, object>, bool> compareClause;
if (sameRange)
{
compareClause = data =>
{
if (data == null || data.Count <= 0) return false;
if (!data.ContainsKey(rangeParamName))
{
var error = string.Format("Cannot find column '{0}' for range query from {1} to {2} in Data={3}",
rangeParamName, fromValue, toValue, StorageProviderUtils.PrintData(data));
throw new KeyNotFoundException(error);
}
T obj = (T) data[rangeParamName];
return comparer.Compare(obj, fromValue) == 0;
};
}
else if (insideRange)
{
compareClause = data =>
{
if (data == null || data.Count <= 0) return false;
if (!data.ContainsKey(rangeParamName))
{
var error = string.Format("Cannot find column '{0}' for range query from {1} to {2} in Data={3}",
rangeParamName, fromValue, toValue, StorageProviderUtils.PrintData(data));
throw new KeyNotFoundException(error);
}
T obj = (T) data[rangeParamName];
return comparer.Compare(obj, fromValue) >= 0 && comparer.Compare(obj, toValue) <= 0;
};
}
else
{
compareClause = data =>
{
if (data == null || data.Count <= 0) return false;
if (!data.ContainsKey(rangeParamName))
{
var error = string.Format("Cannot find column '{0}' for range query from {1} to {2} in Data={3}",
rangeParamName, fromValue, toValue, StorageProviderUtils.PrintData(data));
throw new KeyNotFoundException(error);
}
T obj = (T) data[rangeParamName];
return comparer.Compare(obj, fromValue) >= 0 || comparer.Compare(obj, toValue) <= 0;
};
}
return compareClause;
}
public void Dispose()
{
for (int i = 0; i < this.options.NumStorageGrains; i++)
storageGrains[i] = null;
}
}
/// <summary>
/// Factory for creating MemoryGrainStorage
/// </summary>
public class MemoryGrainStorageFactory
{
public static IGrainStorage Create(IServiceProvider services, string name)
{
return ActivatorUtilities.CreateInstance<MemoryGrainStorage>(services,
services.GetRequiredService<IOptionsSnapshot<MemoryGrainStorageOptions>>().Get(name), name);
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.Encodings.Web;
using System.Text.Unicode;
using Xunit;
namespace Microsoft.Framework.WebEncoders
{
public static class TextEncoderSettingsExtensions
{
public static bool IsCharacterAllowed(this TextEncoderSettings settings, char character)
{
var bitmap = settings.GetAllowedCharacters();
return bitmap.IsCharacterAllowed(character);
}
}
public class TextEncoderSettingsTests
{
[Fact]
public void Ctor_Parameterless_CreatesEmptyFilter()
{
var filter = new TextEncoderSettings();
Assert.Equal(0, filter.GetAllowedCodePoints().Count());
}
[Fact]
public void Ctor_OtherTextEncoderSettingsAsInterface()
{
// Arrange
var originalFilter = new OddTextEncoderSettings();
// Act
var newFilter = new TextEncoderSettings(originalFilter);
// Assert
for (int i = 0; i <= Char.MaxValue; i++)
{
Assert.Equal((i % 2) == 1, newFilter.IsCharacterAllowed((char)i));
}
}
[Fact]
public void Ctor_OtherTextEncoderSettingsAsConcreteType_Clones()
{
// Arrange
var originalFilter = new TextEncoderSettings();
originalFilter.AllowCharacter('x');
// Act
var newFilter = new TextEncoderSettings(originalFilter);
newFilter.AllowCharacter('y');
// Assert
Assert.True(originalFilter.IsCharacterAllowed('x'));
Assert.False(originalFilter.IsCharacterAllowed('y'));
Assert.True(newFilter.IsCharacterAllowed('x'));
Assert.True(newFilter.IsCharacterAllowed('y'));
}
[Fact]
public void Ctor_UnicodeRanges()
{
// Act
var filter = new TextEncoderSettings(UnicodeRanges.LatinExtendedA, UnicodeRanges.LatinExtendedC);
// Assert
for (int i = 0; i < 0x0100; i++)
{
Assert.False(filter.IsCharacterAllowed((char)i));
}
for (int i = 0x0100; i <= 0x017F; i++)
{
Assert.True(filter.IsCharacterAllowed((char)i));
}
for (int i = 0x0180; i < 0x2C60; i++)
{
Assert.False(filter.IsCharacterAllowed((char)i));
}
for (int i = 0x2C60; i <= 0x2C7F; i++)
{
Assert.True(filter.IsCharacterAllowed((char)i));
}
for (int i = 0x2C80; i <= Char.MaxValue; i++)
{
Assert.False(filter.IsCharacterAllowed((char)i));
}
}
[Fact]
public void Ctor_Null_UnicodeRanges()
{
Assert.Throws<ArgumentNullException>("allowedRanges", () => new TextEncoderSettings(default(UnicodeRange[])));
}
[Fact]
public void Ctor_Null_TextEncoderSettings()
{
Assert.Throws<ArgumentNullException>("other", () => new TextEncoderSettings(default(TextEncoderSettings)));
}
[Fact]
public void AllowChar()
{
// Arrange
var filter = new TextEncoderSettings();
filter.AllowCharacter('\u0100');
// Assert
Assert.True(filter.IsCharacterAllowed('\u0100'));
Assert.False(filter.IsCharacterAllowed('\u0101'));
}
[Fact]
public void AllowChars_Array()
{
// Arrange
var filter = new TextEncoderSettings();
filter.AllowCharacters('\u0100', '\u0102');
// Assert
Assert.True(filter.IsCharacterAllowed('\u0100'));
Assert.False(filter.IsCharacterAllowed('\u0101'));
Assert.True(filter.IsCharacterAllowed('\u0102'));
Assert.False(filter.IsCharacterAllowed('\u0103'));
}
[Fact]
public void AllowChars_String()
{
// Arrange
var filter = new TextEncoderSettings();
filter.AllowCharacters('\u0100', '\u0102');
// Assert
Assert.True(filter.IsCharacterAllowed('\u0100'));
Assert.False(filter.IsCharacterAllowed('\u0101'));
Assert.True(filter.IsCharacterAllowed('\u0102'));
Assert.False(filter.IsCharacterAllowed('\u0103'));
}
[Fact]
public void AllowChars_Null()
{
TextEncoderSettings filter = new TextEncoderSettings();
Assert.Throws<ArgumentNullException>("characters", () => filter.AllowCharacters(null));
}
[Fact]
public void AllowFilter()
{
// Arrange
var filter = new TextEncoderSettings(UnicodeRanges.BasicLatin);
filter.AllowCodePoints(new OddTextEncoderSettings().GetAllowedCodePoints());
// Assert
for (int i = 0; i <= 0x007F; i++)
{
Assert.True(filter.IsCharacterAllowed((char)i));
}
for (int i = 0x0080; i <= Char.MaxValue; i++)
{
Assert.Equal((i % 2) == 1, filter.IsCharacterAllowed((char)i));
}
}
[Fact]
public void AllowFilter_NullCodePoints()
{
TextEncoderSettings filter = new TextEncoderSettings(UnicodeRanges.BasicLatin);
Assert.Throws<ArgumentNullException>("codePoints", () => filter.AllowCodePoints(null));
}
[Fact]
public void AllowFilter_NonBMP()
{
TextEncoderSettings filter = new TextEncoderSettings();
filter.AllowCodePoints(Enumerable.Range(0x10000, 20));
Assert.Empty(filter.GetAllowedCodePoints());
}
[Fact]
public void AllowRange()
{
// Arrange
var filter = new TextEncoderSettings();
filter.AllowRange(UnicodeRanges.LatinExtendedA);
// Assert
for (int i = 0; i < 0x0100; i++)
{
Assert.False(filter.IsCharacterAllowed((char)i));
}
for (int i = 0x0100; i <= 0x017F; i++)
{
Assert.True(filter.IsCharacterAllowed((char)i));
}
for (int i = 0x0180; i <= Char.MaxValue; i++)
{
Assert.False(filter.IsCharacterAllowed((char)i));
}
}
[Fact]
public void AllowRange_NullRange()
{
TextEncoderSettings filter = new TextEncoderSettings();
Assert.Throws<ArgumentNullException>("range", () => filter.AllowRange(null));
}
[Fact]
public void AllowRanges()
{
// Arrange
var filter = new TextEncoderSettings();
filter.AllowRanges(UnicodeRanges.LatinExtendedA, UnicodeRanges.LatinExtendedC);
// Assert
for (int i = 0; i < 0x0100; i++)
{
Assert.False(filter.IsCharacterAllowed((char)i));
}
for (int i = 0x0100; i <= 0x017F; i++)
{
Assert.True(filter.IsCharacterAllowed((char)i));
}
for (int i = 0x0180; i < 0x2C60; i++)
{
Assert.False(filter.IsCharacterAllowed((char)i));
}
for (int i = 0x2C60; i <= 0x2C7F; i++)
{
Assert.True(filter.IsCharacterAllowed((char)i));
}
for (int i = 0x2C80; i <= Char.MaxValue; i++)
{
Assert.False(filter.IsCharacterAllowed((char)i));
}
}
[Fact]
public void AllowRanges_NullRange()
{
TextEncoderSettings filter = new TextEncoderSettings();
Assert.Throws<ArgumentNullException>("ranges", () => filter.AllowRanges(null));
}
[Fact]
public void Clear()
{
// Arrange
var filter = new TextEncoderSettings();
for (int i = 1; i <= Char.MaxValue; i++)
{
filter.AllowCharacter((char)i);
}
// Act
filter.Clear();
// Assert
for (int i = 0; i <= Char.MaxValue; i++)
{
Assert.False(filter.IsCharacterAllowed((char)i));
}
}
[Fact]
public void ForbidChar()
{
// Arrange
var filter = new TextEncoderSettings(UnicodeRanges.BasicLatin);
filter.ForbidCharacter('x');
// Assert
Assert.True(filter.IsCharacterAllowed('w'));
Assert.False(filter.IsCharacterAllowed('x'));
Assert.True(filter.IsCharacterAllowed('y'));
Assert.True(filter.IsCharacterAllowed('z'));
}
[Fact]
public void ForbidChars_Array()
{
// Arrange
var filter = new TextEncoderSettings(UnicodeRanges.BasicLatin);
filter.ForbidCharacters('x', 'z');
// Assert
Assert.True(filter.IsCharacterAllowed('w'));
Assert.False(filter.IsCharacterAllowed('x'));
Assert.True(filter.IsCharacterAllowed('y'));
Assert.False(filter.IsCharacterAllowed('z'));
}
[Fact]
public void ForbidChars_String()
{
// Arrange
var filter = new TextEncoderSettings(UnicodeRanges.BasicLatin);
filter.ForbidCharacters('x', 'z');
// Assert
Assert.True(filter.IsCharacterAllowed('w'));
Assert.False(filter.IsCharacterAllowed('x'));
Assert.True(filter.IsCharacterAllowed('y'));
Assert.False(filter.IsCharacterAllowed('z'));
}
[Fact]
public void ForbidChars_Null()
{
TextEncoderSettings filter = new TextEncoderSettings(UnicodeRanges.BasicLatin);
Assert.Throws<ArgumentNullException>("characters", () => filter.ForbidCharacters(null));
}
[Fact]
public void ForbidRange()
{
// Arrange
var filter = new TextEncoderSettings(new OddTextEncoderSettings());
filter.ForbidRange(UnicodeRanges.Specials);
// Assert
for (int i = 0; i <= 0xFFEF; i++)
{
Assert.Equal((i % 2) == 1, filter.IsCharacterAllowed((char)i));
}
for (int i = 0xFFF0; i <= Char.MaxValue; i++)
{
Assert.False(filter.IsCharacterAllowed((char)i));
}
}
[Fact]
public void ForbidRange_Null()
{
TextEncoderSettings filter = new TextEncoderSettings();
Assert.Throws<ArgumentNullException>("range", () => filter.ForbidRange(null));
}
[Fact]
public void ForbidRanges()
{
// Arrange
var filter = new TextEncoderSettings(new OddTextEncoderSettings());
filter.ForbidRanges(UnicodeRanges.BasicLatin, UnicodeRanges.Specials);
// Assert
for (int i = 0; i <= 0x007F; i++)
{
Assert.False(filter.IsCharacterAllowed((char)i));
}
for (int i = 0x0080; i <= 0xFFEF; i++)
{
Assert.Equal((i % 2) == 1, filter.IsCharacterAllowed((char)i));
}
for (int i = 0xFFF0; i <= Char.MaxValue; i++)
{
Assert.False(filter.IsCharacterAllowed((char)i));
}
}
[Fact]
public void ForbidRanges_Null()
{
TextEncoderSettings filter = new TextEncoderSettings(new OddTextEncoderSettings());
Assert.Throws<ArgumentNullException>("ranges", () => filter.ForbidRanges(null));
}
[Fact]
public void GetAllowedCodePoints()
{
// Arrange
var expected = Enumerable.Range(UnicodeRanges.BasicLatin.FirstCodePoint, UnicodeRanges.BasicLatin.Length)
.Concat(Enumerable.Range(UnicodeRanges.Specials.FirstCodePoint, UnicodeRanges.Specials.Length))
.Except(new int[] { 'x' })
.OrderBy(i => i)
.ToArray();
var filter = new TextEncoderSettings(UnicodeRanges.BasicLatin, UnicodeRanges.Specials);
filter.ForbidCharacter('x');
// Act
var retVal = filter.GetAllowedCodePoints().OrderBy(i => i).ToArray();
// Assert
Assert.Equal<int>(expected, retVal);
}
// a code point filter which allows only odd code points through
private sealed class OddTextEncoderSettings : TextEncoderSettings
{
public override IEnumerable<int> GetAllowedCodePoints()
{
for (int i = 1; i <= Char.MaxValue; i += 2)
{
yield return i;
}
}
}
}
}
| |
// <copyright file="ImageButtonRenderer.cs" company="">
// All rights reserved.
// </copyright>
// <author>https://github.com/XLabs/Xamarin-Forms-Labs</author>
using Android.Content;
using Android.Graphics;
using System;
using System.Collections.Generic;
using Xamarin.Forms;
using Xamarin.Forms.Platform.Android;
namespace Anuracode.Forms.Controls.Droid
{
/// <summary>
/// Interface of TypefaceCaches
/// </summary>
public interface ITypefaceCache
{
void RemoveTypeface(string key);
Typeface RetrieveTypeface(string key);
/// <summary>
/// Removes typeface from cache
/// </summary>
/// <param name="key">Key.</param>
/// <param name="typeface">Typeface.</param>
void StoreTypeface(string key, Typeface typeface);
}
/// <summary>
/// Andorid specific extensions for Font class.
/// </summary>
public static class FontExtensions
{
/// <summary>
/// This method returns typeface for given typeface using following rules:
/// 1. Lookup in the cache
/// 2. If not found, look in the assets in the fonts folder. Save your font under its FontFamily name.
/// If no extension is written in the family name .ttf is asumed
/// 3. If not found look in the files under fonts/ folder
/// If no extension is written in the family name .ttf is asumed
/// 4. If not found, try to return typeface from Xamarin.Forms ToTypeface() method
/// 5. If not successfull, return Typeface.Default
/// </summary>
/// <returns>The extended typeface.</returns>
/// <param name="font">Font</param>
/// <param name="context">Android Context</param>
public static Typeface ToExtendedTypeface(this Font font, Context context)
{
Typeface typeface = null;
//1. Lookup in the cache
var hashKey = font.ToHasmapKey();
typeface = TypefaceCache.SharedCache.RetrieveTypeface(hashKey);
#if DEBUG
if (typeface != null)
Console.WriteLine("Typeface for font {0} found in cache", font);
#endif
//2. If not found, try custom asset folder
if (typeface == null && !string.IsNullOrEmpty(font.FontFamily))
{
string filename = font.FontFamily;
//if no extension given then assume and add .ttf
if (filename.LastIndexOf(".", System.StringComparison.Ordinal) != filename.Length - 4)
{
filename = string.Format("{0}.ttf", filename);
}
try
{
var path = "fonts/" + filename;
#if DEBUG
Console.WriteLine("Lookking for font file: {0}", path);
#endif
typeface = Typeface.CreateFromAsset(context.Assets, path);
#if DEBUG
Console.WriteLine("Found in assets and cached.");
#endif
}
catch (Exception ex)
{
#if DEBUG
Console.WriteLine("not found in assets. Exception: {0}", ex);
Console.WriteLine("Trying creation from file");
#endif
try
{
typeface = Typeface.CreateFromFile("fonts/" + filename);
#if DEBUG
Console.WriteLine("Found in file and cached.");
#endif
}
catch (Exception ex1)
{
#if DEBUG
Console.WriteLine("not found by file. Exception: {0}", ex1);
Console.WriteLine("Trying creation using Xamarin.Forms implementation");
#endif
}
}
}
//3. If not found, fall back to default Xamarin.Forms implementation to load system font
if (typeface == null)
{
typeface = font.ToTypeface();
}
if (typeface == null)
{
#if DEBUG
Console.WriteLine("Falling back to default typeface");
#endif
typeface = Typeface.Default;
}
//Store in cache
TypefaceCache.SharedCache.StoreTypeface(hashKey, typeface);
return typeface;
}
/// <summary>
/// Provides unique identifier for the given font.
/// </summary>
/// <returns>Unique string identifier for the given font</returns>
/// <param name="font">Font.</param>
private static string ToHasmapKey(this Font font)
{
return string.Format("{0}.{1}.{2}.{3}", font.FontFamily, font.FontSize, font.NamedSize, (int)font.FontAttributes);
}
}
/// <summary>
/// TypefaceCache caches used typefaces for performance and memory reasons.
/// Typeface cache is singleton shared through execution of the application.
/// You can replace default implementation of the cache by implementing ITypefaceCache
/// interface and setting instance of your cache to static property SharedCache of this class
/// </summary>
public static class TypefaceCache
{
private static ITypefaceCache sharedCache;
/// <summary>
/// Returns the shared typeface cache.
/// </summary>
/// <value>The shared cache.</value>
public static ITypefaceCache SharedCache
{
get
{
if (sharedCache == null)
{
sharedCache = new DefaultTypefaceCache();
}
return sharedCache;
}
set
{
if (sharedCache != null && sharedCache.GetType() == typeof(DefaultTypefaceCache))
{
((DefaultTypefaceCache)sharedCache).PurgeCache();
}
sharedCache = value;
}
}
}
/// <summary>
/// Default implementation of the typeface cache.
/// </summary>
internal class DefaultTypefaceCache : ITypefaceCache
{
private Dictionary<string, Typeface> _cacheDict;
public DefaultTypefaceCache()
{
_cacheDict = new Dictionary<string, Typeface>();
}
public void PurgeCache()
{
_cacheDict = new Dictionary<string, Typeface>();
}
public void RemoveTypeface(string key)
{
_cacheDict.Remove(key);
}
public Typeface RetrieveTypeface(string key)
{
if (_cacheDict.ContainsKey(key))
{
return _cacheDict[key];
}
else
{
return null;
}
}
public void StoreTypeface(string key, Typeface typeface)
{
_cacheDict[key] = typeface;
}
}
}
| |
// Copyright 2004-2009 Castle Project - http://www.castleproject.org/
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
namespace Castle.Components.Validator
{
using System;
using System.Collections;
/// <summary>
/// Specifies the data type the <see cref="RangeValidator"/>
/// is dealing with.
/// </summary>
public enum RangeValidationType
{
/// <summary>
/// <see cref="RangeValidator"/> is dealing with a range of integers
/// </summary>
Integer,
/// <summary>
/// <see cref="RangeValidator"/> is dealing with a range of longs
/// </summary>
Long,
/// <summary>
/// <see cref="RangeValidator"/> is dealing with a range of decimals
/// </summary>
Decimal,
/// <summary>
/// <see cref="RangeValidator"/> is dealing with a range of dates
/// </summary>
DateTime,
/// <summary>
/// <see cref="RangeValidator"/> is dealing with a range of strings
/// </summary>
String
}
/// <summary>
/// Ensures that a property's string representation
/// is within the desired value limitations.
/// </summary>
[Serializable]
public class RangeValidator : AbstractValidator
{
private object min, max;
private RangeValidationType type;
/// <summary>
/// Initializes an integer-based range validator.
/// </summary>
/// <param name="min">The minimum value, or <c>int.MinValue</c> if this should not be tested.</param>
/// <param name="max">The maximum value, or <c>int.MaxValue</c> if this should not be tested.</param>
public RangeValidator(int min, int max)
{
AssertValid(max, min);
type = RangeValidationType.Integer;
this.min = min;
this.max = max;
}
/// <summary>
/// Initializes an long-based (<see cref="long"/>) range validator.
/// </summary>
/// <param name="min">The minimum value, or <c>long.MinValue</c> if this should not be tested.</param>
/// <param name="max">The maximum value, or <c>long.MaxValue</c> if this should not be tested.</param>
public RangeValidator(long min, long max)
{
AssertValid(max, min);
type = RangeValidationType.Long;
this.min = min;
this.max = max;
}
/// <summary>
/// Initializes an decimal-based range validator.
/// </summary>
/// <param name="min">The minimum value, or <c>decimal.MinValue</c> if this should not be tested.</param>
/// <param name="max">The maximum value, or <c>decimal.MaxValue</c> if this should not be tested.</param>
public RangeValidator(decimal min, decimal max)
{
AssertValid(max, min);
type = RangeValidationType.Decimal;
this.min = min;
this.max = max;
}
/// <summary>
/// Initializes a DateTime-based range validator.
/// </summary>
/// <param name="min">The minimum value, or <c>DateTime.MinValue</c> if this should not be tested.</param>
/// <param name="max">The maximum value, or <c>DateTime.MaxValue</c> if this should not be tested.</param>
public RangeValidator(DateTime min, DateTime max)
{
AssertValid(max, min);
type = RangeValidationType.DateTime;
this.min = min;
this.max = max;
}
/// <summary>
/// Initializes a string-based range validator.
/// </summary>
/// <param name="min">The minimum value, or <c>String.Empty</c> if this should not be tested.</param>
/// <param name="max">The maximum value, or <c>String.Empty</c> if this should not be tested.</param>
public RangeValidator(string min, string max)
{
AssertValid(max, min);
type = RangeValidationType.String;
this.min = min;
this.max = max;
}
/// <summary>
/// Initializes a range validator of the given type with the given minimum and maximum values.
/// </summary>
/// <param name="type">The type of range validator.</param>
/// <param name="min">The minimum value, or <c>null</c> if this should not be tested.</param>
/// <param name="max">The maximum value, or <c>null</c> if this should not be tested.</param>
public RangeValidator(RangeValidationType type, object min, object max)
{
this.type = type;
this.min = GetMinValue(min);
this.max = GetMaxValue(max);
}
/// <summary>
/// Gets or sets the range validation type for this validator. If the type is changed,
/// the minimum and maximum values are reset to null-equivalent values (i.e. appropriate
/// minimum and maximum values for the data type).
/// </summary>
public RangeValidationType Type
{
get { return type; }
set
{
if (value != type)
{
type = value;
min = GetMinValue(null);
max = GetMaxValue(null);
}
}
}
/// <summary>
/// Internal method that checks a given maximum value's data type and converts
/// null values to the proper maximum value for the data type.
/// </summary>
/// <param name="max">The maximum value to be processed.</param>
/// <returns>The maximum value with appropriate null-converted minimum values.</returns>
private object GetMaxValue(object max)
{
try
{
//check properties for valid types
switch(type)
{
case RangeValidationType.Integer:
return GetIntValue(max, int.MaxValue);
case RangeValidationType.Long:
return GetLongValue(max, int.MaxValue);
case RangeValidationType.Decimal:
return GetDecimalValue(max, decimal.MaxValue);
case RangeValidationType.DateTime:
return GetDateTimeValue(max, DateTime.MaxValue);
case RangeValidationType.String:
return (max == null || String.IsNullOrEmpty(max.ToString()) ? String.Empty : max.ToString());
default:
throw new ArgumentException("Unknown RangeValidatorType found.");
}
}
catch(InvalidCastException)
{
throw new ArgumentException(
"RangeValidator's maximum value data type is incompatible with the RangeValidationType specified.");
}
}
/// <summary>
/// Validate that the property value matches the value requirements.
/// </summary>
/// <param name="instance"></param>
/// <param name="fieldValue"></param>
/// <returns><c>true</c> if the field is OK</returns>
public override bool IsValid(object instance, object fieldValue)
{
if ((fieldValue == null) || (String.IsNullOrEmpty(fieldValue.ToString())))
{
return true;
}
bool valid = false;
try
{
switch(type)
{
case RangeValidationType.Integer:
int intValue;
try
{
intValue = (int) fieldValue;
valid = intValue >= (int) min && intValue <= (int) max;
}
catch
{
if (int.TryParse(fieldValue.ToString(), out intValue))
{
valid = intValue >= (int) min && intValue <= (int) max;
}
}
break;
case RangeValidationType.Long:
long longValue;
try
{
longValue = (long)fieldValue;
valid = longValue >= (long)min && longValue <= (long)max;
}
catch
{
if (long.TryParse(fieldValue.ToString(), out longValue))
{
valid = longValue >= (long)min && longValue <= (long)max;
}
}
break;
case RangeValidationType.Decimal:
decimal decimalValue;
try
{
decimalValue = (decimal) fieldValue;
valid = decimalValue >= (decimal) min && decimalValue <= (decimal) max;
}
catch
{
if (decimal.TryParse(fieldValue.ToString(), out decimalValue))
{
valid = decimalValue >= (decimal) min && decimalValue <= (decimal) max;
}
}
break;
case RangeValidationType.DateTime:
DateTime dtValue;
try
{
dtValue = (DateTime) fieldValue;
valid = dtValue >= (DateTime) min && dtValue <= (DateTime) max;
}
catch
{
if (DateTime.TryParse(fieldValue.ToString(), out dtValue))
{
valid = dtValue >= (DateTime) min && dtValue <= (DateTime) max;
}
}
break;
case RangeValidationType.String:
string stringValue = fieldValue.ToString();
string minv = min.ToString();
string maxv = max.ToString();
valid = (
(String.IsNullOrEmpty(minv) ||
String.Compare(stringValue, minv, StringComparison.InvariantCultureIgnoreCase) >= 0)
&&
(String.IsNullOrEmpty(maxv) ||
String.Compare(stringValue, maxv, StringComparison.InvariantCultureIgnoreCase) <= 0)
);
break;
default:
valid = false;
break;
}
}
catch
{
}
return valid;
}
/// <summary>
/// Gets a value indicating whether this validator supports browser validation.
/// </summary>
/// <value>
/// <see langword="true"/> if browser validation is supported; otherwise, <see langword="false"/>.
/// </value>
public override bool SupportsBrowserValidation
{
get { return true; }
}
/// <summary>
/// Applies the browser validation by setting up one or
/// more input rules on <see cref="IBrowserValidationGenerator"/>.
/// </summary>
/// <param name="config">The config.</param>
/// <param name="inputType">Type of the input.</param>
/// <param name="generator">The generator.</param>
/// <param name="attributes">The attributes.</param>
/// <param name="target">The target.</param>
public override void ApplyBrowserValidation(BrowserValidationConfiguration config, InputElementType inputType,
IBrowserValidationGenerator generator, IDictionary attributes,
string target)
{
base.ApplyBrowserValidation(config, inputType, generator, attributes, target);
switch(type)
{
case RangeValidationType.Integer:
generator.SetValueRange(target, (int) min, (int) max, BuildErrorMessage());
break;
case RangeValidationType.Long:
generator.SetValueRange(target, (long)min, (long)max, BuildErrorMessage());
break;
case RangeValidationType.Decimal:
generator.SetValueRange(target, (decimal) min, (decimal) max, BuildErrorMessage());
break;
case RangeValidationType.DateTime:
generator.SetValueRange(target, (DateTime) min, (DateTime) max, BuildErrorMessage());
break;
case RangeValidationType.String:
generator.SetValueRange(target, (string) min, (string) max, BuildErrorMessage());
break;
default:
throw new ArgumentOutOfRangeException();
}
}
/// <summary>
/// Builds the error message.
/// </summary>
/// <returns></returns>
protected override string BuildErrorMessage()
{
if (!String.IsNullOrEmpty(ErrorMessage))
{
return ErrorMessage;
}
if (type == RangeValidationType.DateTime)
{
return BuildDateTimeErrorMessage((DateTime) min, (DateTime) max);
}
if (type == RangeValidationType.String)
{
return BuildStringErrorMessage(min.ToString(), max.ToString());
}
if (type == RangeValidationType.Integer)
{
return BuildIntegerErrorMessage((int) min, (int) max);
}
if (type == RangeValidationType.Long)
{
return BuildLongErrorMessage((long)min, (long)max);
}
if (type == RangeValidationType.Decimal)
{
return BuildDecimalErrorMessage((decimal) min, (decimal) max);
}
throw new InvalidOperationException();
}
/// <summary>
/// Gets the error message string for Integer validation
/// </summary>
/// <returns>an error message</returns>
protected string BuildIntegerErrorMessage(int min, int max)
{
if (min == int.MinValue && max != int.MaxValue)
{
// range against max value only
return string.Format(GetString(MessageConstants.RangeTooHighMessage), max);
}
else if (min != int.MinValue && max == int.MaxValue)
{
// range against min value only
return string.Format(GetString(MessageConstants.RangeTooLowMessage), min);
}
else if (min != int.MinValue || max != int.MaxValue)
{
return string.Format(GetString(MessageConstants.RangeTooHighOrLowMessage), min, max);
}
else
{
throw new InvalidOperationException();
}
}
/// <summary>
/// Gets the error message string for long validation
/// </summary>
/// <returns>an error message</returns>
protected string BuildLongErrorMessage(long min, long max)
{
if (min == long.MinValue && max != long.MaxValue)
{
// range against max value only
return string.Format(GetString(MessageConstants.RangeTooHighMessage), max);
}
else if (min != long.MinValue && max == long.MaxValue)
{
// range against min value only
return string.Format(GetString(MessageConstants.RangeTooLowMessage), min);
}
else if (min != long.MinValue || max != long.MaxValue)
{
return string.Format(GetString(MessageConstants.RangeTooHighOrLowMessage), min, max);
}
else
{
throw new InvalidOperationException();
}
}
/// <summary>
/// Gets the error message string for Decimal validation
/// </summary>
/// <returns>an error message</returns>
protected string BuildDecimalErrorMessage(decimal min, decimal max)
{
if (min == decimal.MinValue && max != decimal.MaxValue)
{
// range against max value only
return string.Format(GetString(MessageConstants.RangeTooHighMessage), max);
}
else if (min != decimal.MinValue && max == decimal.MaxValue)
{
// range against min value only
return string.Format(GetString(MessageConstants.RangeTooLowMessage), min);
}
else if (min != decimal.MinValue || max != decimal.MaxValue)
{
return string.Format(GetString(MessageConstants.RangeTooHighOrLowMessage), min, max);
}
else
{
throw new InvalidOperationException();
}
}
/// <summary>
/// Gets the error message string for DateTime validation
/// </summary>
/// <returns>an error message</returns>
protected string BuildDateTimeErrorMessage(DateTime min, DateTime max)
{
if (min == DateTime.MinValue && max != DateTime.MaxValue)
{
// range against max value only
return string.Format(GetString(MessageConstants.RangeTooHighMessage), max);
}
else if (min != DateTime.MinValue && max == DateTime.MaxValue)
{
// range against min value only
return string.Format(GetString(MessageConstants.RangeTooLowMessage), min);
}
else if (min != DateTime.MinValue || max != DateTime.MaxValue)
{
return string.Format(GetString(MessageConstants.RangeTooHighOrLowMessage), min, max);
}
else
{
throw new InvalidOperationException();
}
}
/// <summary>
/// Gets the error message string for string validation
/// </summary>
/// <returns>an error message</returns>
protected string BuildStringErrorMessage(string min, string max)
{
if (String.IsNullOrEmpty(min) && !String.IsNullOrEmpty(max))
{
// range against max value only
return string.Format(GetString(MessageConstants.RangeTooHighMessage), max);
}
else if (!String.IsNullOrEmpty(min) && String.IsNullOrEmpty(max))
{
// range against min value only
return string.Format(GetString(MessageConstants.RangeTooLowMessage), min);
}
else if (!String.IsNullOrEmpty(min) || !String.IsNullOrEmpty(max))
{
return string.Format(GetString(MessageConstants.RangeTooHighOrLowMessage), min, max);
}
else
{
throw new InvalidOperationException();
}
}
/// <summary>
/// Returns the key used to internationalize error messages
/// </summary>
/// <value></value>
protected override string MessageKey
{
get { return MessageConstants.InvalidRangeMessage; }
}
private static void AssertValid(string max, string min)
{
if (String.IsNullOrEmpty(min) && String.IsNullOrEmpty(max))
{
throw new ArgumentException(
"Both min and max were set in such as way that neither would be tested. At least one must be tested.");
}
}
private static void AssertValid(int max, int min)
{
if (min == int.MinValue && max == int.MaxValue)
{
throw new ArgumentException(
"Both min and max were set in such as way that neither would be tested. At least one must be tested.");
}
if (min > max)
{
throw new ArgumentException("The min parameter must be less than or equal to the max parameter.");
}
if (max < min)
{
throw new ArgumentException("The max parameter must be greater than or equal to the min parameter.");
}
}
private static void AssertValid(long max, long min)
{
if (min == long.MinValue && max == long.MaxValue)
{
throw new ArgumentException(
"Both min and max were set in such as way that neither would be tested. At least one must be tested.");
}
if (min > max)
{
throw new ArgumentException("The min parameter must be less than or equal to the max parameter.");
}
if (max < min)
{
throw new ArgumentException("The max parameter must be greater than or equal to the min parameter.");
}
}
private static void AssertValid(decimal max, decimal min)
{
if (min == decimal.MinValue && max == decimal.MaxValue)
{
throw new ArgumentException(
"Both min and max were set in such as way that neither would be tested. At least one must be tested.");
}
if (min > max)
{
throw new ArgumentException("The min parameter must be less than or equal to the max parameter.");
}
if (max < min)
{
throw new ArgumentException("The max parameter must be greater than or equal to the min parameter.");
}
}
private static void AssertValid(DateTime max, DateTime min)
{
if (min == DateTime.MinValue && max == DateTime.MaxValue)
{
throw new ArgumentException(
"Both min and max were set in such as way that neither would be tested. At least one must be tested.");
}
if (min > max)
{
throw new ArgumentException("The min parameter must be less than or equal to the max parameter.");
}
if (max < min)
{
throw new ArgumentException("The max parameter must be greater than or equal to the min parameter.");
}
}
/// <summary>
/// Internal method that checks a given minimum value's data type and converts
/// null values to the proper minimum value for the data type.
/// </summary>
/// <param name="min">The minimum value to be processed.</param>
/// <returns>The minimum value with appropriate null-converted minimum values.</returns>
private object GetMinValue(object min)
{
try
{
//check properties for valid types
switch(type)
{
case RangeValidationType.Integer:
return GetIntValue(min, int.MinValue);
case RangeValidationType.Long:
return GetLongValue(min, long.MinValue);
case RangeValidationType.Decimal:
return GetDecimalValue(min, decimal.MinValue);
case RangeValidationType.DateTime:
return GetDateTimeValue(min, DateTime.MinValue);
case RangeValidationType.String:
return (min == null || String.IsNullOrEmpty(min.ToString()) ? String.Empty : min.ToString());
default:
throw new ArgumentException("Unknown RangeValidatorType found.");
}
}
catch(InvalidCastException)
{
throw new ArgumentException(
"RangeValidator's mininum value data type is incompatible with the RangeValidationType specified.");
}
}
private int GetIntValue(object value, int defaultValue)
{
int intValue = defaultValue;
try
{
intValue = (int) value;
}
catch
{
if (value == null || !int.TryParse(value.ToString(), out intValue))
value = defaultValue;
}
return intValue;
}
private long GetLongValue(object value, long defaultValue)
{
long longValue = defaultValue;
try
{
longValue = (long)value;
}
catch
{
if (value == null || !long.TryParse(value.ToString(), out longValue))
value = defaultValue;
}
return longValue;
}
private decimal GetDecimalValue(object value, decimal defaultValue)
{
decimal decimalValue = defaultValue;
if (value == null || !decimal.TryParse(value.ToString(), out decimalValue))
value = defaultValue;
return decimalValue;
}
private DateTime GetDateTimeValue(object value, DateTime defaultValue)
{
DateTime dtValue = defaultValue;
try
{
dtValue = (DateTime) value;
}
catch
{
if (value == null || !DateTime.TryParse(value.ToString(), out dtValue))
value = defaultValue;
}
return dtValue;
}
}
}
| |
// Reflector.cs
//
// Author:
// Lluis Sanchez Gual <lluis@novell.com>
//
// Copyright (c) 2007 Novell, Inc (http://www.novell.com)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
//
//#define ASSEMBLY_LOAD_STATS
using System;
using System.Collections;
using System.Collections.Generic;
using System.Reflection;
using Mono.Addins;
using Mono.Addins.Database;
using Mono.Cecil;
using CustomAttribute = Mono.Cecil.CustomAttribute;
using MA = Mono.Addins.Database;
using System.Linq;
namespace Mono.Addins.CecilReflector
{
public class Reflector: IAssemblyReflector, IDisposable
{
IAssemblyLocator locator;
Dictionary<string, AssemblyDefinition> cachedAssemblies = new Dictionary<string, AssemblyDefinition> ();
DefaultAssemblyResolver defaultAssemblyResolver;
public void Initialize (IAssemblyLocator locator)
{
this.locator = locator;
defaultAssemblyResolver = new DefaultAssemblyResolver ();
defaultAssemblyResolver.ResolveFailure += delegate (object sender, AssemblyNameReference reference) {
var file = locator.GetAssemblyLocation (reference.FullName);
if (file != null)
return LoadAssembly (file, true);
else
return null;
};
}
public object[] GetCustomAttributes (object obj, Type type, bool inherit)
{
Mono.Cecil.ICustomAttributeProvider aprov = obj as Mono.Cecil.ICustomAttributeProvider;
if (aprov == null)
return new object [0];
ArrayList atts = new ArrayList ();
foreach (CustomAttribute att in aprov.CustomAttributes) {
object catt = ConvertAttribute (att, type);
if (catt != null)
atts.Add (catt);
}
if (inherit && (obj is TypeDefinition)) {
TypeDefinition td = (TypeDefinition) obj;
if (td.BaseType != null && td.BaseType.FullName != "System.Object") {
// The base type may be in an assembly that doesn't reference Mono.Addins, even though it may reference
// other assemblies that do reference Mono.Addins. So the Mono.Addins filter can't be applied here.
TypeDefinition bt = FindTypeDefinition (td.Module.Assembly, td.BaseType, assembliesReferencingMonoAddinsOnly: false);
if (bt != null)
atts.AddRange (GetCustomAttributes (bt, type, true));
}
}
return atts.ToArray ();
}
object ConvertAttribute (CustomAttribute att, Type expectedType)
{
Type attype = typeof(IAssemblyReflector).Assembly.GetType (att.Constructor.DeclaringType.FullName);
if (attype == null || !expectedType.IsAssignableFrom (attype))
return null;
object ob;
if (att.ConstructorArguments.Count > 0) {
object[] cargs = new object [att.ConstructorArguments.Count];
List<int> typeParameters = null;
// Constructor parameters of type System.Type can't be set because types from the assembly
// can't be loaded. The parameter value will be set later using a type name property.
for (int n=0; n<cargs.Length; n++) {
var atype = Type.GetType (att.Constructor.Parameters[n].ParameterType.FullName);
if (atype == null)
atype = typeof(IAssemblyReflector).Assembly.GetType (att.Constructor.Parameters[n].ParameterType.FullName);
if (atype.IsEnum)
cargs [n] = Enum.ToObject (atype, att.ConstructorArguments [n].Value);
else
cargs [n] = att.ConstructorArguments [n].Value;
if (typeof(System.Type).IsAssignableFrom (atype)) {
if (typeParameters == null)
typeParameters = new List<int> ();
cargs [n] = typeof(object);
typeParameters.Add (n);
}
}
ob = Activator.CreateInstance (attype, cargs);
// If there are arguments of type System.Type, set them using the property
if (typeParameters != null) {
Type[] ptypes = new Type [cargs.Length];
for (int n=0; n<cargs.Length; n++) {
ptypes [n] = cargs [n].GetType ();
}
ConstructorInfo ci = attype.GetConstructor (ptypes);
ParameterInfo[] ciParams = ci.GetParameters ();
for (int n=0; n<typeParameters.Count; n++) {
int ip = typeParameters [n];
string propName = ciParams[ip].Name;
propName = char.ToUpper (propName [0]) + propName.Substring (1);
SetTypeNameAndAssemblyName (propName, attype, ob, (TypeReference)att.ConstructorArguments[ip].Value);
}
}
} else {
ob = Activator.CreateInstance (attype);
}
foreach (Mono.Cecil.CustomAttributeNamedArgument namedArgument in att.Properties) {
string pname = namedArgument.Name;
PropertyInfo prop = attype.GetProperty (pname);
if (prop != null) {
if (prop.PropertyType == typeof(System.Type)) {
SetTypeNameAndAssemblyName (pname, attype, ob, (TypeReference)namedArgument.Argument.Value);
} else
prop.SetValue (ob, namedArgument.Argument.Value, null);
}
}
return ob;
}
static void SetTypeNameAndAssemblyName (string basePropName, Type attype, object ob, TypeReference typeReference)
{
// We can't load the type. We have to use the typeName and typeAssemblyName properties instead.
var typeNameProp = basePropName + "Name";
var prop = attype.GetProperty (typeNameProp, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
if (prop == null)
throw new InvalidOperationException ("Property '" + typeNameProp + "' not found in type '" + attype + "'.");
var assemblyName = typeReference.Resolve().Module.Assembly.FullName;
prop.SetValue (ob, typeReference.FullName + ", " + assemblyName, null);
prop = attype.GetProperty(basePropName + "FullName", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
if (prop != null)
prop.SetValue(ob, typeReference.FullName, null);
}
public List<MA.CustomAttribute> GetRawCustomAttributes (object obj, Type type, bool inherit)
{
List<MA.CustomAttribute> atts = new List<MA.CustomAttribute> ();
Mono.Cecil.ICustomAttributeProvider aprov = obj as Mono.Cecil.ICustomAttributeProvider;
if (aprov == null)
return atts;
foreach (CustomAttribute att in aprov.CustomAttributes) {
// The class of the attribute is always a subclass of a Mono.Addins class
MA.CustomAttribute catt = ConvertToRawAttribute (att, type.FullName, baseIsMonoAddinsType: true);
if (catt != null)
atts.Add (catt);
}
if (inherit && (obj is TypeDefinition)) {
TypeDefinition td = (TypeDefinition) obj;
if (td.BaseType != null && td.BaseType.FullName != "System.Object") {
// The base type may be in an assembly that doesn't reference Mono.Addins, even though it may reference
// other assemblies that do reference Mono.Addins. So the Mono.Addins filter can't be applied here.
TypeDefinition bt = FindTypeDefinition (td.Module.Assembly, td.BaseType, assembliesReferencingMonoAddinsOnly: false);
if (bt != null)
atts.AddRange (GetRawCustomAttributes (bt, type, true));
}
}
return atts;
}
MA.CustomAttribute ConvertToRawAttribute (CustomAttribute att, string expectedType, bool baseIsMonoAddinsType)
{
// If the class of the attribute is a subclass of a Mono.Addins class, then the assembly where this
// custom attribute type is defined must reference Mono.Addins.
TypeDefinition attType = FindTypeDefinition (att.Constructor.DeclaringType.Module.Assembly, att.Constructor.DeclaringType, assembliesReferencingMonoAddinsOnly: baseIsMonoAddinsType);
if (attType == null || !TypeIsAssignableFrom (expectedType, attType, baseIsMonoAddinsType))
return null;
MA.CustomAttribute mat = new MA.CustomAttribute ();
mat.TypeName = att.Constructor.DeclaringType.FullName;
if (att.ConstructorArguments.Count > 0) {
var arguments = att.ConstructorArguments;
MethodReference constructor = FindConstructor (att, attType);
if (constructor == null)
throw new InvalidOperationException ("Custom attribute constructor not found");
for (int n=0; n<arguments.Count; n++) {
ParameterDefinition par = constructor.Parameters[n];
object val = arguments [n].Value;
if (val != null) {
string name = par.Name;
NodeAttributeAttribute bat = (NodeAttributeAttribute) GetCustomAttribute (par, typeof(NodeAttributeAttribute), false);
if (bat != null)
name = bat.Name;
mat.Add (name, Convert.ToString (val, System.Globalization.CultureInfo.InvariantCulture));
}
}
}
List<TypeDefinition> inheritanceChain = null;
foreach (Mono.Cecil.CustomAttributeNamedArgument namedArgument in att.Properties) {
string pname = namedArgument.Name;
object val = namedArgument.Argument.Value;
if (val == null)
continue;
if (inheritanceChain == null)
inheritanceChain = GetInheritanceChain (attType, baseIsMonoAddinsType).ToList ();
foreach (TypeDefinition td in inheritanceChain) {
PropertyDefinition prop = GetMember (td.Properties, pname);
if (prop == null)
continue;
NodeAttributeAttribute bat = (NodeAttributeAttribute) GetCustomAttribute (prop, typeof(NodeAttributeAttribute), false);
if (bat != null) {
string name = string.IsNullOrEmpty (bat.Name) ? prop.Name : bat.Name;
mat.Add (name, Convert.ToString (val, System.Globalization.CultureInfo.InvariantCulture));
}
}
}
foreach (Mono.Cecil.CustomAttributeNamedArgument namedArgument in att.Fields) {
string pname = namedArgument.Name;
object val = namedArgument.Argument.Value;
if (val == null)
continue;
if (inheritanceChain == null)
inheritanceChain = GetInheritanceChain (attType, baseIsMonoAddinsType).ToList ();
foreach (TypeDefinition td in inheritanceChain) {
FieldDefinition field = GetMember (td.Fields, pname);
if (field != null) {
NodeAttributeAttribute bat = (NodeAttributeAttribute) GetCustomAttribute (field, typeof(NodeAttributeAttribute), false);
if (bat != null) {
string name = string.IsNullOrEmpty (bat.Name) ? field.Name : bat.Name;
mat.Add (name, Convert.ToString (val, System.Globalization.CultureInfo.InvariantCulture));
}
}
}
}
return mat;
}
static TMember GetMember<TMember> (ICollection<TMember> members, string name) where TMember : class, IMemberDefinition
{
foreach (var member in members)
if (member.Name == name)
return member;
return null;
}
IEnumerable<TypeDefinition> GetInheritanceChain (TypeDefinition td, bool baseIsMonoAddinsType)
{
yield return td;
while (td != null && td.BaseType != null && td.BaseType.FullName != "System.Object") {
// If the class we are looking for is a subclass of a Mono.Addins class, then the assembly where this
// class is defined must reference Mono.Addins.
td = FindTypeDefinition (td.Module.Assembly, td.BaseType, assembliesReferencingMonoAddinsOnly: baseIsMonoAddinsType);
if (td != null)
yield return td;
}
}
MethodReference FindConstructor (CustomAttribute att, TypeDefinition atd)
{
// The constructor provided by CustomAttribute.Constructor is lacking some information, such as the parameter
// name and custom attributes. Since we need the full info, we have to look it up in the declaring type.
foreach (MethodReference met in atd.Methods) {
if (met.Name != ".ctor")
continue;
if (met.Parameters.Count == att.Constructor.Parameters.Count) {
for (int n = met.Parameters.Count - 1; n >= 0; n--) {
if (met.Parameters[n].ParameterType.FullName != att.Constructor.Parameters[n].ParameterType.FullName)
break;
if (n == 0)
return met;
}
}
}
return null;
}
public object LoadAssembly (string file)
{
return LoadAssembly (file, true);
}
public AssemblyDefinition LoadAssembly (string file, bool cache)
{
AssemblyDefinition adef;
if (cachedAssemblies.TryGetValue (file, out adef))
return adef;
var rp = new ReaderParameters (ReadingMode.Deferred);
rp.AssemblyResolver = defaultAssemblyResolver;
adef = AssemblyDefinition.ReadAssembly (file, rp);
if (adef != null) {
if (cache)
cachedAssemblies [file] = adef;
// Since the assembly is loaded, we can quickly check now if it references Mono.Addins.
// This information may be useful later on.
if (adef.Name.Name != "Mono.Addins" && !adef.MainModule.AssemblyReferences.Any (r => r.Name == "Mono.Addins"))
assembliesNotReferencingMonoAddins.Add (adef.FullName);
}
#if ASSEMBLY_LOAD_STATS
loadCounter.TryGetValue (file, out int num);
loadCounter [file] = num + 1;
#endif
return adef;
}
#if ASSEMBLY_LOAD_STATS
static Dictionary<string, int> loadCounter = new Dictionary<string, int> ();
#endif
public void UnloadAssembly (object assembly)
{
var adef = (AssemblyDefinition)assembly;
cachedAssemblies.Remove (adef.MainModule.FileName);
adef.Dispose ();
}
public string GetAssemblyName (object assembly)
{
var adef = (AssemblyDefinition)assembly;
return adef.Name.Name;
}
bool FoundToNotReferenceMonoAddins (AssemblyNameReference aref)
{
// Quick check to find out if an assembly references Mono.Addins, based only on cached information.
return assembliesNotReferencingMonoAddins.Contains (aref.FullName);
}
bool CheckHasMonoAddinsReference (AssemblyDefinition adef)
{
// Maybe the assembly is already in the blacklist
if (assembliesNotReferencingMonoAddins.Contains (adef.FullName))
return false;
if (adef.Name.Name != "Mono.Addins" && !adef.MainModule.AssemblyReferences.Any (r => r.Name == "Mono.Addins")) {
assembliesNotReferencingMonoAddins.Add (adef.FullName);
return false;
}
return true;
}
HashSet<string> assembliesNotReferencingMonoAddins = new HashSet<string> (StringComparer.Ordinal);
public string [] GetResourceNames (object asm)
{
AssemblyDefinition adef = (AssemblyDefinition)asm;
List<string> names = new List<string> (adef.MainModule.Resources.Count);
foreach (Resource res in adef.MainModule.Resources) {
if (res is EmbeddedResource)
names.Add (res.Name);
}
return names.ToArray ();
}
public System.IO.Stream GetResourceStream (object asm, string resourceName)
{
AssemblyDefinition adef = (AssemblyDefinition) asm;
foreach (Resource res in adef.MainModule.Resources) {
EmbeddedResource r = res as EmbeddedResource;
if (r != null && r.Name == resourceName)
return r.GetResourceStream ();
}
throw new InvalidOperationException ("Resource not found: " + resourceName);
}
public object LoadAssemblyFromReference (object asmReference)
{
// The scanner only uses this method when looking for an extension node type, which is
// a subclass of a Mono.Addins type, so it must be defined in an assembly that references Mono.Addins.
return LoadAssemblyFromReference ((AssemblyNameReference)asmReference, assembliesReferencingMonoAddinsOnly: true);
}
AssemblyDefinition LoadAssemblyFromReference (AssemblyNameReference aref, bool assembliesReferencingMonoAddinsOnly)
{
// Fast check for Mono.Addins reference that sometimes will avoid loading the assembly
if (assembliesReferencingMonoAddinsOnly && FoundToNotReferenceMonoAddins (aref))
return null;
string loc = locator.GetAssemblyLocation (aref.FullName);
if (loc == null)
return null;
AssemblyDefinition asm = LoadAssembly (loc, true);
// Check for Mono.Addins references first, that will update the cache.
if (!CheckHasMonoAddinsReference (asm) && assembliesReferencingMonoAddinsOnly) {
// We loaded an assembly we are not interested in, so we could unload it now.
// We already cached the information about whether it has a Mono.Addins reference
// or not, so the next we try to load the reference, the check can be done
// without loading. However, empirical tests should that the cache size doesn't
// increase much, while redundant assembly loads are significanly reduced.
//UnloadAssembly (asm);
return null;
}
return asm;
}
public System.Collections.IEnumerable GetAssemblyTypes (object asm)
{
return ((AssemblyDefinition)asm).MainModule.Types;
}
public System.Collections.IEnumerable GetAssemblyReferences (object asm)
{
return ((AssemblyDefinition)asm).MainModule.AssemblyReferences;
}
public object GetType (object asm, string typeName)
{
if (typeName.IndexOf ('`') != -1) {
foreach (TypeDefinition td in ((AssemblyDefinition)asm).MainModule.Types) {
if (td.FullName == typeName) {
return td;
}
}
}
TypeDefinition t = ((AssemblyDefinition)asm).MainModule.GetType (typeName);
if (t != null) {
return t;
} else {
return null;
}
}
public object GetCustomAttribute (object obj, Type type, bool inherit)
{
foreach (object att in GetCustomAttributes (obj, type, inherit))
if (type.IsInstanceOfType (att))
return att;
return null;
}
public string GetTypeName (object type)
{
return ((TypeDefinition)type).Name;
}
public string GetTypeFullName (object type)
{
return ((TypeDefinition)type).FullName;
}
public string GetTypeAssemblyQualifiedName (object type)
{
AssemblyDefinition asm = GetAssemblyDefinition ((TypeDefinition)type);
return ((TypeDefinition)type).FullName + ", " + asm.Name.FullName;
}
AssemblyDefinition GetAssemblyDefinition (TypeDefinition t)
{
return t.Module.Assembly;
}
public System.Collections.IEnumerable GetBaseTypeFullNameList (object type)
{
// The base type can be any type, so we can apply the Mono.Addins optimization in this case.
return GetBaseTypeFullNameList ((TypeDefinition)type, baseIsMonoAddinsType: false, includeInterfaces: true);
}
public System.Collections.IEnumerable GetBaseTypeFullNameList (TypeDefinition type, bool baseIsMonoAddinsType, bool includeInterfaces)
{
AssemblyDefinition asm = GetAssemblyDefinition (type);
var list = new List<string> ();
Hashtable visited = new Hashtable ();
GetBaseTypeFullNameList (visited, list, asm, type, baseIsMonoAddinsType, includeInterfaces);
list.Remove (type.FullName);
return list;
}
void GetBaseTypeFullNameList (Hashtable visited, List<string> list, AssemblyDefinition asm, TypeReference tr, bool baseIsMonoAddinsType, bool includeInterfaces)
{
if (tr.FullName == "System.Object" || visited.Contains (tr.FullName))
return;
visited [tr.FullName] = tr;
list.Add (tr.FullName);
TypeDefinition type = FindTypeDefinition (asm, tr, assembliesReferencingMonoAddinsOnly: baseIsMonoAddinsType);
if (type == null)
return;
asm = GetAssemblyDefinition (type);
if (type.BaseType != null)
GetBaseTypeFullNameList (visited, list, asm, type.BaseType, baseIsMonoAddinsType, includeInterfaces);
if (includeInterfaces) {
foreach (InterfaceImplementation ii in type.Interfaces) {
TypeReference interf = ii.InterfaceType;
GetBaseTypeFullNameList (visited, list, asm, interf, baseIsMonoAddinsType, includeInterfaces);
}
}
}
TypeDefinition FindTypeDefinition (AssemblyDefinition referencer, TypeReference rt, bool assembliesReferencingMonoAddinsOnly)
{
if (rt is TypeDefinition)
return (TypeDefinition)rt;
string name = rt.FullName;
TypeDefinition td = GetType (referencer, name) as TypeDefinition;
if (td != null)
return td;
int i = name.IndexOf ('<');
if (i != -1) {
name = name.Substring (0, i);
td = GetType (referencer, name) as TypeDefinition;
if (td != null)
return td;
}
foreach (AssemblyNameReference aref in referencer.MainModule.AssemblyReferences) {
try {
AssemblyDefinition asm = LoadAssemblyFromReference (aref, assembliesReferencingMonoAddinsOnly);
if (asm == null)
continue;
td = GetType (asm, name) as TypeDefinition;
if (td != null)
return td;
} catch {
Console.WriteLine ("Could not scan dependency '{0}'. Ignoring for now.", aref.FullName);
}
}
return null;
}
public bool TypeIsAssignableFrom (object baseType, object type)
{
string baseName = ((TypeDefinition)baseType).FullName;
foreach (string bt in GetBaseTypeFullNameList (type))
if (bt == baseName)
return true;
return false;
}
public bool TypeIsAssignableFrom (string baseTypeName, object type, bool baseIsMonoAddinsClass)
{
// If the base is a Mono.Addins class then there is no need to include interfaces when getting
// the base type list (since we are looking for a class, not for an interface).
foreach (string bt in GetBaseTypeFullNameList ((TypeDefinition)type, baseIsMonoAddinsClass, !baseIsMonoAddinsClass))
if (bt == baseTypeName)
return true;
return false;
}
public IEnumerable GetFields (object type)
{
return ((TypeDefinition)type).Fields;
}
public string GetFieldName (object field)
{
return ((FieldDefinition)field).Name;
}
public string GetFieldTypeFullName (object field)
{
return GetTypeAssemblyQualifiedName(((FieldDefinition)field).FieldType.Resolve());
}
public void Dispose ()
{
foreach (AssemblyDefinition asm in cachedAssemblies.Values)
asm.Dispose ();
#if ASSEMBLY_LOAD_STATS
Console.WriteLine ("Total assemblies: " + loadCounter.Count);
Console.WriteLine ("Assembly cache size: {0} ({1}%)", cachedAssemblies.Count, (cachedAssemblies.Count * 100) / loadCounter.Count);
Console.WriteLine ("Total assembly loads: " + loadCounter.Values.Sum ());
var redundant = loadCounter.Where (c => c.Value > 1).Select (c => c.Value - 1).Sum ();
Console.WriteLine ("Redundant loads: {0} ({1}%)", redundant, ((redundant * 100) / loadCounter.Count));
#endif
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq.Expressions;
using System.Runtime.CompilerServices;
using System.Threading;
namespace System.Linq.Expressions.Interpreter
{
internal abstract class OffsetInstruction : Instruction
{
internal const int Unknown = Int32.MinValue;
internal const int CacheSize = 32;
// the offset to jump to (relative to this instruction):
protected int _offset = Unknown;
public int Offset { get { return _offset; } }
public abstract Instruction[] Cache { get; }
public override string InstructionName
{
get { return "Offset"; }
}
public Instruction Fixup(int offset)
{
Debug.Assert(_offset == Unknown && offset != Unknown);
_offset = offset;
var cache = Cache;
if (cache != null && offset >= 0 && offset < cache.Length)
{
return cache[offset] ?? (cache[offset] = this);
}
return this;
}
public override string ToDebugString(int instructionIndex, object cookie, Func<int, int> labelIndexer, IList<object> objects)
{
return ToString() + (_offset != Unknown ? " -> " + (instructionIndex + _offset) : "");
}
public override string ToString()
{
return InstructionName + (_offset == Unknown ? "(?)" : "(" + _offset + ")");
}
}
internal sealed class BranchFalseInstruction : OffsetInstruction
{
private static Instruction[] s_cache;
public override string InstructionName
{
get { return "BranchFalse"; }
}
public override Instruction[] Cache
{
get
{
if (s_cache == null)
{
s_cache = new Instruction[CacheSize];
}
return s_cache;
}
}
internal BranchFalseInstruction()
{
}
public override int ConsumedStack { get { return 1; } }
public override int Run(InterpretedFrame frame)
{
Debug.Assert(_offset != Unknown);
if (!(bool)frame.Pop())
{
return _offset;
}
return +1;
}
}
internal sealed class BranchTrueInstruction : OffsetInstruction
{
private static Instruction[] s_cache;
public override string InstructionName
{
get { return "BranchTrue"; }
}
public override Instruction[] Cache
{
get
{
if (s_cache == null)
{
s_cache = new Instruction[CacheSize];
}
return s_cache;
}
}
internal BranchTrueInstruction()
{
}
public override int ConsumedStack { get { return 1; } }
public override int Run(InterpretedFrame frame)
{
Debug.Assert(_offset != Unknown);
if ((bool)frame.Pop())
{
return _offset;
}
return +1;
}
}
internal sealed class CoalescingBranchInstruction : OffsetInstruction
{
private static Instruction[] s_cache;
public override string InstructionName
{
get { return "CoalescingBranch"; }
}
public override Instruction[] Cache
{
get
{
if (s_cache == null)
{
s_cache = new Instruction[CacheSize];
}
return s_cache;
}
}
internal CoalescingBranchInstruction()
{
}
public override int ConsumedStack { get { return 1; } }
public override int ProducedStack { get { return 1; } }
public override int Run(InterpretedFrame frame)
{
Debug.Assert(_offset != Unknown);
if (frame.Peek() != null)
{
return _offset;
}
return +1;
}
}
internal class BranchInstruction : OffsetInstruction
{
private static Instruction[][][] s_caches;
public override string InstructionName
{
get { return "Branch"; }
}
public override Instruction[] Cache
{
get
{
if (s_caches == null)
{
s_caches = new Instruction[2][][] { new Instruction[2][], new Instruction[2][] };
}
return s_caches[ConsumedStack][ProducedStack] ?? (s_caches[ConsumedStack][ProducedStack] = new Instruction[CacheSize]);
}
}
internal readonly bool _hasResult;
internal readonly bool _hasValue;
internal BranchInstruction()
: this(false, false)
{
}
public BranchInstruction(bool hasResult, bool hasValue)
{
_hasResult = hasResult;
_hasValue = hasValue;
}
public override int ConsumedStack
{
get { return _hasValue ? 1 : 0; }
}
public override int ProducedStack
{
get { return _hasResult ? 1 : 0; }
}
public override int Run(InterpretedFrame frame)
{
Debug.Assert(_offset != Unknown);
return _offset;
}
}
internal abstract class IndexedBranchInstruction : Instruction
{
protected const int CacheSize = 32;
public override string InstructionName
{
get { return "IndexedBranch"; }
}
internal readonly int _labelIndex;
public IndexedBranchInstruction(int labelIndex)
{
_labelIndex = labelIndex;
}
public RuntimeLabel GetLabel(InterpretedFrame frame)
{
Debug.Assert(_labelIndex != UnknownInstrIndex);
return frame.Interpreter._labels[_labelIndex];
}
public override string ToDebugString(int instructionIndex, object cookie, Func<int, int> labelIndexer, IList<object> objects)
{
Debug.Assert(_labelIndex != UnknownInstrIndex);
int targetIndex = labelIndexer(_labelIndex);
return ToString() + (targetIndex != BranchLabel.UnknownIndex ? " -> " + targetIndex : "");
}
public override string ToString()
{
Debug.Assert(_labelIndex != UnknownInstrIndex);
return InstructionName + "[" + _labelIndex + "]";
}
}
/// <summary>
/// This instruction implements a goto expression that can jump out of any expression.
/// It pops values (arguments) from the evaluation stack that the expression tree nodes in between
/// the goto expression and the target label node pushed and not consumed yet.
/// A goto expression can jump into a node that evaluates arguments only if it carries
/// a value and jumps right after the first argument (the carried value will be used as the first argument).
/// Goto can jump into an arbitrary child of a BlockExpression since the block doesn't accumulate values
/// on evaluation stack as its child expressions are being evaluated.
///
/// Goto needs to execute any finally blocks on the way to the target label.
/// <example>
/// {
/// f(1, 2, try { g(3, 4, try { goto L } finally { ... }, 6) } finally { ... }, 7, 8)
/// L: ...
/// }
/// </example>
/// The goto expression here jumps to label L while having 4 items on evaluation stack (1, 2, 3 and 4).
/// The jump needs to execute both finally blocks, the first one on stack level 4 the
/// second one on stack level 2. So, it needs to jump the first finally block, pop 2 items from the stack,
/// run second finally block and pop another 2 items from the stack and set instruction pointer to label L.
///
/// Goto also needs to rethrow ThreadAbortException iff it jumps out of a catch handler and
/// the current thread is in "abort requested" state.
/// </summary>
internal sealed class GotoInstruction : IndexedBranchInstruction
{
private const int Variants = 8;
private static readonly GotoInstruction[] s_cache = new GotoInstruction[Variants * CacheSize];
public override string InstructionName
{
get { return "Goto"; }
}
private readonly bool _hasResult;
private readonly bool _hasValue;
private readonly bool _labelTargetGetsValue;
// The values should technically be Consumed = 1, Produced = 1 for gotos that target a label whose continuation depth
// is different from the current continuation depth. This is because we will consume one continuation from the _continuations
// and at meantime produce a new _pendingContinuation. However, in case of forward gotos, we don't not know that is the
// case until the label is emitted. By then the consumed and produced stack information is useless.
// The important thing here is that the stack balance is 0.
public override int ConsumedContinuations { get { return 0; } }
public override int ProducedContinuations { get { return 0; } }
public override int ConsumedStack
{
get { return _hasValue ? 1 : 0; }
}
public override int ProducedStack
{
get { return _hasResult ? 1 : 0; }
}
private GotoInstruction(int targetIndex, bool hasResult, bool hasValue, bool labelTargetGetsValue)
: base(targetIndex)
{
_hasResult = hasResult;
_hasValue = hasValue;
_labelTargetGetsValue = labelTargetGetsValue;
}
internal static GotoInstruction Create(int labelIndex, bool hasResult, bool hasValue, bool labelTargetGetsValue)
{
if (labelIndex < CacheSize)
{
var index = Variants * labelIndex | (labelTargetGetsValue ? 4 : 0) | (hasResult ? 2 : 0) | (hasValue ? 1 : 0);
return s_cache[index] ?? (s_cache[index] = new GotoInstruction(labelIndex, hasResult, hasValue, labelTargetGetsValue));
}
return new GotoInstruction(labelIndex, hasResult, hasValue, labelTargetGetsValue);
}
public override int Run(InterpretedFrame frame)
{
// Are we jumping out of catch/finally while aborting the current thread?
#if FEATURE_THREAD_ABORT
Interpreter.AbortThreadIfRequested(frame, _labelIndex);
#endif
// goto the target label or the current finally continuation:
object value = _hasValue ? frame.Pop() : Interpreter.NoValue;
return frame.Goto(_labelIndex, _labelTargetGetsValue ? value : Interpreter.NoValue, gotoExceptionHandler: false);
}
}
internal sealed class EnterTryCatchFinallyInstruction : IndexedBranchInstruction
{
private readonly bool _hasFinally = false;
private TryCatchFinallyHandler _tryHandler;
internal void SetTryHandler(TryCatchFinallyHandler tryHandler)
{
Debug.Assert(_tryHandler == null && tryHandler != null, "the tryHandler can be set only once");
_tryHandler = tryHandler;
}
public override int ProducedContinuations { get { return _hasFinally ? 1 : 0; } }
private EnterTryCatchFinallyInstruction(int targetIndex, bool hasFinally)
: base(targetIndex)
{
_hasFinally = hasFinally;
}
internal static EnterTryCatchFinallyInstruction CreateTryFinally(int labelIndex)
{
return new EnterTryCatchFinallyInstruction(labelIndex, true);
}
internal static EnterTryCatchFinallyInstruction CreateTryCatch()
{
return new EnterTryCatchFinallyInstruction(UnknownInstrIndex, false);
}
public override int Run(InterpretedFrame frame)
{
Debug.Assert(_tryHandler != null, "the tryHandler must be set already");
if (_hasFinally)
{
// Push finally.
frame.PushContinuation(_labelIndex);
}
int prevInstrIndex = frame.InstructionIndex;
frame.InstructionIndex++;
// Start to run the try/catch/finally blocks
var instructions = frame.Interpreter.Instructions.Instructions;
try
{
// run the try block
int index = frame.InstructionIndex;
while (index >= _tryHandler.TryStartIndex && index < _tryHandler.TryEndIndex)
{
index += instructions[index].Run(frame);
frame.InstructionIndex = index;
}
// we finish the try block and is about to jump out of the try/catch blocks
if (index == _tryHandler.GotoEndTargetIndex)
{
// run the 'Goto' that jumps out of the try/catch/finally blocks
Debug.Assert(instructions[index] is GotoInstruction, "should be the 'Goto' instruction that jumpes out the try/catch/finally");
frame.InstructionIndex += instructions[index].Run(frame);
}
}
catch (RethrowException)
{
// a rethrow instruction in the try handler gets to run
throw;
}
catch (Exception exception)
{
frame.SaveTraceToException(exception);
// rethrow if there is no catch blocks defined for this try block
if (!_tryHandler.IsCatchBlockExist) { throw; }
// Search for the best handler in the TryCatchFianlly block. If no suitable handler is found, rethrow
ExceptionHandler exHandler;
frame.InstructionIndex += _tryHandler.GotoHandler(frame, exception, out exHandler);
if (exHandler == null) { throw; }
#if FEATURE_THREAD_ABORT
// stay in the current catch so that ThreadAbortException is not rethrown by CLR:
var abort = exception as ThreadAbortException;
if (abort != null)
{
Interpreter.AnyAbortException = abort;
frame.CurrentAbortHandler = exHandler;
}
#endif
bool rethrow = false;
try
{
// run the catch block
int index = frame.InstructionIndex;
while (index >= exHandler.HandlerStartIndex && index < exHandler.HandlerEndIndex)
{
index += instructions[index].Run(frame);
frame.InstructionIndex = index;
}
// we finish the catch block and is about to jump out of the try/catch blocks
if (index == _tryHandler.GotoEndTargetIndex)
{
// run the 'Goto' that jumps out of the try/catch/finally blocks
Debug.Assert(instructions[index] is GotoInstruction, "should be the 'Goto' instruction that jumpes out the try/catch/finally");
frame.InstructionIndex += instructions[index].Run(frame);
}
}
catch (RethrowException)
{
// a rethrow instruction in a catch block gets to run
rethrow = true;
}
if (rethrow) { throw; }
}
finally
{
if (_tryHandler.IsFinallyBlockExist)
{
// We get to the finally block in two paths:
// 1. Jump from the try/catch blocks. This includes two sub-routes:
// a. 'Goto' instruction in the middle of try/catch block
// b. try/catch block runs to its end. Then the 'Goto(end)' will be trigger to jump out of the try/catch block
// 2. Exception thrown from the try/catch blocks
// In the first path, the continuation mechanism works and frame.InstructionIndex will be updated to point to the first instruction of the finally block
// In the second path, the continuation mechanism is not involved and frame.InstructionIndex is not updated
#if DEBUG
bool isFromJump = frame.IsJumpHappened();
Debug.Assert(!isFromJump || (isFromJump && _tryHandler.FinallyStartIndex == frame.InstructionIndex), "we should already jump to the first instruction of the finally");
#endif
// run the finally block
// we cannot jump out of the finally block, and we cannot have an immediate rethrow in it
int index = frame.InstructionIndex = _tryHandler.FinallyStartIndex;
while (index >= _tryHandler.FinallyStartIndex && index < _tryHandler.FinallyEndIndex)
{
index += instructions[index].Run(frame);
frame.InstructionIndex = index;
}
}
}
return frame.InstructionIndex - prevInstrIndex;
}
public override string InstructionName
{
get { return _hasFinally ? "EnterTryFinally" : "EnterTryCatch"; }
}
public override string ToString()
{
return _hasFinally ? "EnterTryFinally[" + _labelIndex + "]" : "EnterTryCatch";
}
}
/// <summary>
/// The first instruction of finally block.
/// </summary>
internal sealed class EnterFinallyInstruction : IndexedBranchInstruction
{
private readonly static EnterFinallyInstruction[] s_cache = new EnterFinallyInstruction[CacheSize];
public override string InstructionName
{
get { return "EnterFinally"; }
}
public override int ProducedStack { get { return 2; } }
public override int ConsumedContinuations { get { return 1; } }
private EnterFinallyInstruction(int labelIndex)
: base(labelIndex)
{
}
internal static EnterFinallyInstruction Create(int labelIndex)
{
if (labelIndex < CacheSize)
{
return s_cache[labelIndex] ?? (s_cache[labelIndex] = new EnterFinallyInstruction(labelIndex));
}
return new EnterFinallyInstruction(labelIndex);
}
public override int Run(InterpretedFrame frame)
{
// If _pendingContinuation == -1 then we were getting into the finally block because an exception was thrown
// in this case we need to set the stack depth
// Else we were getting into this finnaly block from a 'Goto' jump, and the stack depth is alreayd set properly
if (!frame.IsJumpHappened())
{
frame.SetStackDepth(GetLabel(frame).StackDepth);
}
frame.PushPendingContinuation();
frame.RemoveContinuation();
return 1;
}
}
/// <summary>
/// The last instruction of finally block.
/// </summary>
internal sealed class LeaveFinallyInstruction : Instruction
{
internal static readonly Instruction Instance = new LeaveFinallyInstruction();
public override int ConsumedStack { get { return 2; } }
public override string InstructionName
{
get { return "LeaveFinally"; }
}
private LeaveFinallyInstruction()
{
}
public override int Run(InterpretedFrame frame)
{
frame.PopPendingContinuation();
// If _pendingContinuation == -1 then we were getting into the finally block because an exception was thrown
// In this case we just return 1, and the the real instruction index will be calculated by GotoHandler later
if (!frame.IsJumpHappened()) { return 1; }
// jump to goto target or to the next finally:
return frame.YieldToPendingContinuation();
}
}
// no-op: we need this just to balance the stack depth.
internal sealed class EnterExceptionHandlerInstruction : Instruction
{
internal static readonly EnterExceptionHandlerInstruction Void = new EnterExceptionHandlerInstruction(false);
internal static readonly EnterExceptionHandlerInstruction NonVoid = new EnterExceptionHandlerInstruction(true);
// True if try-expression is non-void.
private readonly bool _hasValue;
public override string InstructionName
{
get { return "EnterExceptionHandler"; }
}
private EnterExceptionHandlerInstruction(bool hasValue)
{
_hasValue = hasValue;
}
// If an exception is throws in try-body the expression result of try-body is not evaluated and loaded to the stack.
// So the stack doesn't contain the try-body's value when we start executing the handler.
// However, while emitting instructions try block falls thru the catch block with a value on stack.
// We need to declare it consumed so that the stack state upon entry to the handler corresponds to the real
// stack depth after throw jumped to this catch block.
public override int ConsumedStack { get { return _hasValue ? 1 : 0; } }
// A variable storing the current exception is pushed to the stack by exception handling.
// Catch handlers: The value is immediately popped and stored into a local.
// Fault handlers: The value is kept on stack during fault handler evaluation.
public override int ProducedStack { get { return 1; } }
public override int Run(InterpretedFrame frame)
{
// nop (the exception value is pushed by the interpreter in HandleCatch)
return 1;
}
}
/// <summary>
/// The last instruction of a catch exception handler.
/// </summary>
internal sealed class LeaveExceptionHandlerInstruction : IndexedBranchInstruction
{
private static LeaveExceptionHandlerInstruction[] s_cache = new LeaveExceptionHandlerInstruction[2 * CacheSize];
private readonly bool _hasValue;
public override string InstructionName
{
get { return "LeaveExceptionHandler"; }
}
// The catch block yields a value if the body is non-void. This value is left on the stack.
public override int ConsumedStack
{
get { return _hasValue ? 1 : 0; }
}
public override int ProducedStack
{
get { return _hasValue ? 1 : 0; }
}
private LeaveExceptionHandlerInstruction(int labelIndex, bool hasValue)
: base(labelIndex)
{
_hasValue = hasValue;
}
internal static LeaveExceptionHandlerInstruction Create(int labelIndex, bool hasValue)
{
if (labelIndex < CacheSize)
{
int index = (2 * labelIndex) | (hasValue ? 1 : 0);
return s_cache[index] ?? (s_cache[index] = new LeaveExceptionHandlerInstruction(labelIndex, hasValue));
}
return new LeaveExceptionHandlerInstruction(labelIndex, hasValue);
}
public override int Run(InterpretedFrame frame)
{
// CLR rethrows ThreadAbortException when leaving catch handler if abort is requested on the current thread.
#if FEATURE_THREAD_ABORT
Interpreter.AbortThreadIfRequested(frame, _labelIndex);
#endif
return GetLabel(frame).Index - frame.InstructionIndex;
}
}
/// <summary>
/// The last instruction of a fault exception handler.
/// </summary>
internal sealed class LeaveFaultInstruction : Instruction
{
internal static readonly Instruction NonVoid = new LeaveFaultInstruction(true);
internal static readonly Instruction Void = new LeaveFaultInstruction(false);
private readonly bool _hasValue;
public override string InstructionName
{
get { return "LeaveFault"; }
}
// The fault block has a value if the body is non-void, but the value is never used.
// We compile the body of a fault block as void.
// However, we keep the exception object that was pushed upon entering the fault block on the stack during execution of the block
// and pop it at the end.
public override int ConsumedStack
{
get { return 1; }
}
// While emitting instructions a non-void try-fault expression is expected to produce a value.
public override int ProducedStack
{
get { return _hasValue ? 1 : 0; }
}
private LeaveFaultInstruction(bool hasValue)
{
_hasValue = hasValue;
}
public override int Run(InterpretedFrame frame)
{
object exception = frame.Pop();
throw new RethrowException();
}
}
internal sealed class ThrowInstruction : Instruction
{
internal static readonly ThrowInstruction Throw = new ThrowInstruction(true, false);
internal static readonly ThrowInstruction VoidThrow = new ThrowInstruction(false, false);
internal static readonly ThrowInstruction Rethrow = new ThrowInstruction(true, true);
internal static readonly ThrowInstruction VoidRethrow = new ThrowInstruction(false, true);
private readonly bool _hasResult, _rethrow;
public override string InstructionName
{
get { return "Throw"; }
}
private ThrowInstruction(bool hasResult, bool isRethrow)
{
_hasResult = hasResult;
_rethrow = isRethrow;
}
public override int ProducedStack
{
get { return _hasResult ? 1 : 0; }
}
public override int ConsumedStack
{
get
{
return 1;
}
}
public override int Run(InterpretedFrame frame)
{
var ex = (Exception)frame.Pop();
if (_rethrow)
{
throw new RethrowException();
}
throw ex;
}
}
internal sealed class IntSwitchInstruction<T> : Instruction
{
private readonly Dictionary<T, int> _cases;
public override string InstructionName
{
get { return "IntSwitch"; }
}
internal IntSwitchInstruction(Dictionary<T, int> cases)
{
Assert.NotNull(cases);
_cases = cases;
}
public override int ConsumedStack { get { return 1; } }
public override int ProducedStack { get { return 0; } }
public override int Run(InterpretedFrame frame)
{
int target;
return _cases.TryGetValue((T)frame.Pop(), out target) ? target : 1;
}
}
internal sealed class StringSwitchInstruction : Instruction
{
private readonly Dictionary<string, int> _cases;
private readonly StrongBox<int> _nullCase;
public override string InstructionName
{
get { return "StringSwitch"; }
}
internal StringSwitchInstruction(Dictionary<string, int> cases, StrongBox<int> nullCase)
{
Assert.NotNull(cases);
Assert.NotNull(nullCase);
_cases = cases;
_nullCase = nullCase;
}
public override int ConsumedStack { get { return 1; } }
public override int ProducedStack { get { return 0; } }
public override int Run(InterpretedFrame frame)
{
object value = frame.Pop();
if (value == null)
{
return _nullCase.Value;
}
int target;
return _cases.TryGetValue((string)value, out target) ? target : 1;
}
}
internal sealed class EnterLoopInstruction : Instruction
{
private readonly int _instructionIndex;
private Dictionary<ParameterExpression, LocalVariable> _variables;
private Dictionary<ParameterExpression, LocalVariable> _closureVariables;
private LoopExpression _loop;
private int _loopEnd;
public override string InstructionName
{
get { return "EnterLoop"; }
}
internal EnterLoopInstruction(LoopExpression loop, LocalVariables locals, int instructionIndex)
{
_loop = loop;
_variables = locals.CopyLocals();
_closureVariables = locals.ClosureVariables;
_instructionIndex = instructionIndex;
}
internal void FinishLoop(int loopEnd)
{
_loopEnd = loopEnd;
}
public override int Run(InterpretedFrame frame)
{
return 1;
}
private bool Compiled
{
get { return _loop == null; }
}
private void Compile(object frameObj)
{
}
}
}
| |
#region License
//
// The Open Toolkit Library License
//
// Copyright (c) 2006 - 2009 the Open Toolkit library.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights to
// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
// the Software, and to permit persons to whom the Software is furnished to do
// so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
//
#endregion
using System;
namespace OpenTK.Graphics.ES11
{
#pragma warning disable 1591
public enum All : int
{
False = ((int)0),
NoError = ((int)0),
NoneOes = ((int)0),
Zero = ((int)0),
Points = ((int)0x0000),
DepthBufferBit = ((int)0x00000100),
StencilBufferBit = ((int)0x00000400),
ColorBufferBit = ((int)0x00004000),
Lines = ((int)0x0001),
LineLoop = ((int)0x0002),
LineStrip = ((int)0x0003),
Triangles = ((int)0x0004),
TriangleStrip = ((int)0x0005),
TriangleFan = ((int)0x0006),
Add = ((int)0x0104),
Never = ((int)0x0200),
Less = ((int)0x0201),
Equal = ((int)0x0202),
Lequal = ((int)0x0203),
Greater = ((int)0x0204),
Notequal = ((int)0x0205),
Gequal = ((int)0x0206),
Always = ((int)0x0207),
SrcColor = ((int)0x0300),
OneMinusSrcColor = ((int)0x0301),
SrcAlpha = ((int)0x0302),
OneMinusSrcAlpha = ((int)0x0303),
DstAlpha = ((int)0x0304),
OneMinusDstAlpha = ((int)0x0305),
DstColor = ((int)0x0306),
OneMinusDstColor = ((int)0x0307),
SrcAlphaSaturate = ((int)0x0308),
Front = ((int)0x0404),
Back = ((int)0x0405),
FrontAndBack = ((int)0x0408),
InvalidEnum = ((int)0x0500),
InvalidValue = ((int)0x0501),
InvalidOperation = ((int)0x0502),
StackOverflow = ((int)0x0503),
StackUnderflow = ((int)0x0504),
OutOfMemory = ((int)0x0505),
InvalidFramebufferOperationOes = ((int)0x0506),
Exp = ((int)0x0800),
Exp2 = ((int)0x0801),
Cw = ((int)0x0900),
Ccw = ((int)0x0901),
CurrentColor = ((int)0x0B00),
CurrentNormal = ((int)0x0B02),
CurrentTextureCoords = ((int)0x0B03),
PointSmooth = ((int)0x0B10),
PointSize = ((int)0x0B11),
SmoothPointSizeRange = ((int)0x0B12),
LineSmooth = ((int)0x0B20),
LineWidth = ((int)0x0B21),
SmoothLineWidthRange = ((int)0x0B22),
CullFace = ((int)0x0B44),
CullFaceMode = ((int)0x0B45),
FrontFace = ((int)0x0B46),
Lighting = ((int)0x0B50),
LightModelTwoSide = ((int)0x0B52),
LightModelAmbient = ((int)0x0B53),
ShadeModel = ((int)0x0B54),
ColorMaterial = ((int)0x0B57),
Fog = ((int)0x0B60),
FogDensity = ((int)0x0B62),
FogStart = ((int)0x0B63),
FogEnd = ((int)0x0B64),
FogMode = ((int)0x0B65),
FogColor = ((int)0x0B66),
DepthRange = ((int)0x0B70),
DepthTest = ((int)0x0B71),
DepthWritemask = ((int)0x0B72),
DepthClearValue = ((int)0x0B73),
DepthFunc = ((int)0x0B74),
StencilTest = ((int)0x0B90),
StencilClearValue = ((int)0x0B91),
StencilFunc = ((int)0x0B92),
StencilValueMask = ((int)0x0B93),
StencilFail = ((int)0x0B94),
StencilPassDepthFail = ((int)0x0B95),
StencilPassDepthPass = ((int)0x0B96),
StencilRef = ((int)0x0B97),
StencilWritemask = ((int)0x0B98),
MatrixMode = ((int)0x0BA0),
Normalize = ((int)0x0BA1),
Viewport = ((int)0x0BA2),
ModelviewStackDepth = ((int)0x0BA3),
ProjectionStackDepth = ((int)0x0BA4),
TextureStackDepth = ((int)0x0BA5),
ModelviewMatrix = ((int)0x0BA6),
ProjectionMatrix = ((int)0x0BA7),
TextureMatrix = ((int)0x0BA8),
AlphaTest = ((int)0x0BC0),
AlphaTestFunc = ((int)0x0BC1),
AlphaTestRef = ((int)0x0BC2),
Dither = ((int)0x0BD0),
BlendDst = ((int)0x0BE0),
BlendSrc = ((int)0x0BE1),
Blend = ((int)0x0BE2),
LogicOpMode = ((int)0x0BF0),
ColorLogicOp = ((int)0x0BF2),
ScissorBox = ((int)0x0C10),
ScissorTest = ((int)0x0C11),
ColorClearValue = ((int)0x0C22),
ColorWritemask = ((int)0x0C23),
PerspectiveCorrectionHint = ((int)0x0C50),
PointSmoothHint = ((int)0x0C51),
LineSmoothHint = ((int)0x0C52),
FogHint = ((int)0x0C54),
UnpackAlignment = ((int)0x0CF5),
PackAlignment = ((int)0x0D05),
AlphaScale = ((int)0x0D1C),
MaxLights = ((int)0x0D31),
MaxClipPlanes = ((int)0x0D32),
MaxClipPlanesImg = ((int)0x0D32),
MaxTextureSize = ((int)0x0D33),
MaxModelviewStackDepth = ((int)0x0D36),
MaxProjectionStackDepth = ((int)0x0D38),
MaxTextureStackDepth = ((int)0x0D39),
MaxViewportDims = ((int)0x0D3A),
SubpixelBits = ((int)0x0D50),
RedBits = ((int)0x0D52),
GreenBits = ((int)0x0D53),
BlueBits = ((int)0x0D54),
AlphaBits = ((int)0x0D55),
DepthBits = ((int)0x0D56),
StencilBits = ((int)0x0D57),
Texture2D = ((int)0x0DE1),
DontCare = ((int)0x1100),
Fastest = ((int)0x1101),
Nicest = ((int)0x1102),
Ambient = ((int)0x1200),
Diffuse = ((int)0x1201),
Specular = ((int)0x1202),
Position = ((int)0x1203),
SpotDirection = ((int)0x1204),
SpotExponent = ((int)0x1205),
SpotCutoff = ((int)0x1206),
ConstantAttenuation = ((int)0x1207),
LinearAttenuation = ((int)0x1208),
QuadraticAttenuation = ((int)0x1209),
Byte = ((int)0x1400),
UnsignedByte = ((int)0x1401),
Short = ((int)0x1402),
UnsignedShort = ((int)0x1403),
Float = ((int)0x1406),
Fixed = ((int)0x140C),
FixedOes = ((int)0x140C),
Clear = ((int)0x1500),
And = ((int)0x1501),
AndReverse = ((int)0x1502),
Copy = ((int)0x1503),
AndInverted = ((int)0x1504),
Noop = ((int)0x1505),
Xor = ((int)0x1506),
Or = ((int)0x1507),
Nor = ((int)0x1508),
Equiv = ((int)0x1509),
Invert = ((int)0x150A),
OrReverse = ((int)0x150B),
CopyInverted = ((int)0x150C),
OrInverted = ((int)0x150D),
Nand = ((int)0x150E),
Set = ((int)0x150F),
Emission = ((int)0x1600),
Shininess = ((int)0x1601),
AmbientAndDiffuse = ((int)0x1602),
Modelview = ((int)0x1700),
Projection = ((int)0x1701),
Texture = ((int)0x1702),
Alpha = ((int)0x1906),
Rgb = ((int)0x1907),
Rgba = ((int)0x1908),
Luminance = ((int)0x1909),
LuminanceAlpha = ((int)0x190A),
Flat = ((int)0x1D00),
Smooth = ((int)0x1D01),
Keep = ((int)0x1E00),
Replace = ((int)0x1E01),
Incr = ((int)0x1E02),
Decr = ((int)0x1E03),
Vendor = ((int)0x1F00),
Renderer = ((int)0x1F01),
Version = ((int)0x1F02),
Extensions = ((int)0x1F03),
Modulate = ((int)0x2100),
Decal = ((int)0x2101),
TextureEnvMode = ((int)0x2200),
TextureEnvColor = ((int)0x2201),
TextureEnv = ((int)0x2300),
TextureGenModeOes = ((int)0x2500),
Nearest = ((int)0x2600),
Linear = ((int)0x2601),
NearestMipmapNearest = ((int)0x2700),
LinearMipmapNearest = ((int)0x2701),
NearestMipmapLinear = ((int)0x2702),
LinearMipmapLinear = ((int)0x2703),
TextureMagFilter = ((int)0x2800),
TextureMinFilter = ((int)0x2801),
TextureWrapS = ((int)0x2802),
TextureWrapT = ((int)0x2803),
Repeat = ((int)0x2901),
PolygonOffsetUnits = ((int)0x2A00),
ClipPlane0 = ((int)0x3000),
ClipPlane0Img = ((int)0x3000),
ClipPlane1 = ((int)0x3001),
ClipPlane1Img = ((int)0x3001),
ClipPlane2 = ((int)0x3002),
ClipPlane2Img = ((int)0x3002),
ClipPlane3 = ((int)0x3003),
ClipPlane3Img = ((int)0x3003),
ClipPlane4 = ((int)0x3004),
ClipPlane4Img = ((int)0x3004),
ClipPlane5 = ((int)0x3005),
ClipPlane5Img = ((int)0x3005),
Light0 = ((int)0x4000),
Light1 = ((int)0x4001),
Light2 = ((int)0x4002),
Light3 = ((int)0x4003),
Light4 = ((int)0x4004),
Light5 = ((int)0x4005),
Light6 = ((int)0x4006),
Light7 = ((int)0x4007),
FuncAddOes = ((int)0x8006),
BlendEquationOes = ((int)0x8009),
BlendEquationRgbOes = ((int)0x8009),
FuncSubtractOes = ((int)0x800A),
FuncReverseSubtractOes = ((int)0x800B),
UnsignedShort4444 = ((int)0x8033),
UnsignedShort5551 = ((int)0x8034),
PolygonOffsetFill = ((int)0x8037),
PolygonOffsetFactor = ((int)0x8038),
RescaleNormal = ((int)0x803A),
Rgb8Oes = ((int)0x8051),
Rgba4Oes = ((int)0x8056),
Rgb5A1Oes = ((int)0x8057),
Rgba8Oes = ((int)0x8058),
TextureBinding2D = ((int)0x8069),
VertexArray = ((int)0x8074),
NormalArray = ((int)0x8075),
ColorArray = ((int)0x8076),
TextureCoordArray = ((int)0x8078),
VertexArraySize = ((int)0x807A),
VertexArrayType = ((int)0x807B),
VertexArrayStride = ((int)0x807C),
NormalArrayType = ((int)0x807E),
NormalArrayStride = ((int)0x807F),
ColorArraySize = ((int)0x8081),
ColorArrayType = ((int)0x8082),
ColorArrayStride = ((int)0x8083),
TextureCoordArraySize = ((int)0x8088),
TextureCoordArrayType = ((int)0x8089),
TextureCoordArrayStride = ((int)0x808A),
VertexArrayPointer = ((int)0x808E),
NormalArrayPointer = ((int)0x808F),
ColorArrayPointer = ((int)0x8090),
TextureCoordArrayPointer = ((int)0x8092),
Multisample = ((int)0x809D),
SampleAlphaToCoverage = ((int)0x809E),
SampleAlphaToOne = ((int)0x809F),
SampleCoverage = ((int)0x80A0),
SampleBuffers = ((int)0x80A8),
Samples = ((int)0x80A9),
SampleCoverageValue = ((int)0x80AA),
SampleCoverageInvert = ((int)0x80AB),
BlendDstRgbOes = ((int)0x80C8),
BlendSrcRgbOes = ((int)0x80C9),
BlendDstAlphaOes = ((int)0x80CA),
BlendSrcAlphaOes = ((int)0x80CB),
Bgra = ((int)0x80E1),
PointSizeMin = ((int)0x8126),
PointSizeMax = ((int)0x8127),
PointFadeThresholdSize = ((int)0x8128),
PointDistanceAttenuation = ((int)0x8129),
ClampToEdge = ((int)0x812F),
GenerateMipmap = ((int)0x8191),
GenerateMipmapHint = ((int)0x8192),
DepthComponent16Oes = ((int)0x81A5),
DepthComponent24Oes = ((int)0x81A6),
DepthComponent32Oes = ((int)0x81A7),
UnsignedShort565 = ((int)0x8363),
UnsignedShort4444Rev = ((int)0x8365),
UnsignedShort1555Rev = ((int)0x8366),
MirroredRepeatOes = ((int)0x8370),
AliasedPointSizeRange = ((int)0x846D),
AliasedLineWidthRange = ((int)0x846E),
Texture0 = ((int)0x84C0),
Texture1 = ((int)0x84C1),
Texture2 = ((int)0x84C2),
Texture3 = ((int)0x84C3),
Texture4 = ((int)0x84C4),
Texture5 = ((int)0x84C5),
Texture6 = ((int)0x84C6),
Texture7 = ((int)0x84C7),
Texture8 = ((int)0x84C8),
Texture9 = ((int)0x84C9),
Texture10 = ((int)0x84CA),
Texture11 = ((int)0x84CB),
Texture12 = ((int)0x84CC),
Texture13 = ((int)0x84CD),
Texture14 = ((int)0x84CE),
Texture15 = ((int)0x84CF),
Texture16 = ((int)0x84D0),
Texture17 = ((int)0x84D1),
Texture18 = ((int)0x84D2),
Texture19 = ((int)0x84D3),
Texture20 = ((int)0x84D4),
Texture21 = ((int)0x84D5),
Texture22 = ((int)0x84D6),
Texture23 = ((int)0x84D7),
Texture24 = ((int)0x84D8),
Texture25 = ((int)0x84D9),
Texture26 = ((int)0x84DA),
Texture27 = ((int)0x84DB),
Texture28 = ((int)0x84DC),
Texture29 = ((int)0x84DD),
Texture30 = ((int)0x84DE),
Texture31 = ((int)0x84DF),
ActiveTexture = ((int)0x84E0),
ClientActiveTexture = ((int)0x84E1),
MaxTextureUnits = ((int)0x84E2),
Subtract = ((int)0x84E7),
MaxRenderbufferSizeOes = ((int)0x84E8),
AllCompletedNv = ((int)0x84F2),
FenceStatusNv = ((int)0x84F3),
FenceConditionNv = ((int)0x84F4),
DepthStencilOes = ((int)0x84F9),
UnsignedInt248Oes = ((int)0x84FA),
TextureMaxAnisotropyExt = ((int)0x84FE),
MaxTextureMaxAnisotropyExt = ((int)0x84FF),
IncrWrapOes = ((int)0x8507),
DecrWrapOes = ((int)0x8508),
NormalMapOes = ((int)0x8511),
ReflectionMapOes = ((int)0x8512),
TextureCubeMapOes = ((int)0x8513),
TextureBindingCubeMapOes = ((int)0x8514),
TextureCubeMapPositiveXOes = ((int)0x8515),
TextureCubeMapNegativeXOes = ((int)0x8516),
TextureCubeMapPositiveYOes = ((int)0x8517),
TextureCubeMapNegativeYOes = ((int)0x8518),
TextureCubeMapPositiveZOes = ((int)0x8519),
TextureCubeMapNegativeZOes = ((int)0x851A),
MaxCubeMapTextureSizeOes = ((int)0x851C),
Combine = ((int)0x8570),
CombineRgb = ((int)0x8571),
CombineAlpha = ((int)0x8572),
RgbScale = ((int)0x8573),
AddSigned = ((int)0x8574),
Interpolate = ((int)0x8575),
Constant = ((int)0x8576),
PrimaryColor = ((int)0x8577),
Previous = ((int)0x8578),
Src0Rgb = ((int)0x8580),
Src1Rgb = ((int)0x8581),
Src2Rgb = ((int)0x8582),
Src0Alpha = ((int)0x8588),
Src1Alpha = ((int)0x8589),
Src2Alpha = ((int)0x858A),
Operand0Rgb = ((int)0x8590),
Operand1Rgb = ((int)0x8591),
Operand2Rgb = ((int)0x8592),
Operand0Alpha = ((int)0x8598),
Operand1Alpha = ((int)0x8599),
Operand2Alpha = ((int)0x859A),
NumCompressedTextureFormats = ((int)0x86A2),
CompressedTextureFormats = ((int)0x86A3),
MaxVertexUnitsOes = ((int)0x86A4),
WeightArrayTypeOes = ((int)0x86A9),
WeightArrayStrideOes = ((int)0x86AA),
WeightArraySizeOes = ((int)0x86AB),
WeightArrayPointerOes = ((int)0x86AC),
WeightArrayOes = ((int)0x86AD),
Dot3Rgb = ((int)0x86AE),
Dot3Rgba = ((int)0x86AF),
Dot3RgbaImg = ((int)0x86AF),
BufferSize = ((int)0x8764),
BufferUsage = ((int)0x8765),
AtcRgbaInterpolatedAlphaAmd = ((int)0x87EE),
Gl3DcXAmd = ((int)0x87F9),
Gl3DcXyAmd = ((int)0x87FA),
BlendEquationAlphaOes = ((int)0x883D),
MatrixPaletteOes = ((int)0x8840),
MaxPaletteMatricesOes = ((int)0x8842),
CurrentPaletteMatrixOes = ((int)0x8843),
MatrixIndexArrayOes = ((int)0x8844),
MatrixIndexArraySizeOes = ((int)0x8846),
MatrixIndexArrayTypeOes = ((int)0x8847),
MatrixIndexArrayStrideOes = ((int)0x8848),
MatrixIndexArrayPointerOes = ((int)0x8849),
PointSpriteOes = ((int)0x8861),
CoordReplaceOes = ((int)0x8862),
ArrayBuffer = ((int)0x8892),
ElementArrayBuffer = ((int)0x8893),
ArrayBufferBinding = ((int)0x8894),
ElementArrayBufferBinding = ((int)0x8895),
VertexArrayBufferBinding = ((int)0x8896),
NormalArrayBufferBinding = ((int)0x8897),
ColorArrayBufferBinding = ((int)0x8898),
TextureCoordArrayBufferBinding = ((int)0x889A),
WeightArrayBufferBindingOes = ((int)0x889E),
WriteOnlyOes = ((int)0x88B9),
BufferAccessOes = ((int)0x88BB),
BufferMappedOes = ((int)0x88BC),
BufferMapPointerOes = ((int)0x88BD),
StaticDraw = ((int)0x88E4),
DynamicDraw = ((int)0x88E8),
Depth24Stencil8Oes = ((int)0x88F0),
PointSizeArrayTypeOes = ((int)0x898A),
PointSizeArrayStrideOes = ((int)0x898B),
PointSizeArrayPointerOes = ((int)0x898C),
ModelviewMatrixFloatAsIntBitsOes = ((int)0x898D),
ProjectionMatrixFloatAsIntBitsOes = ((int)0x898E),
TextureMatrixFloatAsIntBitsOes = ((int)0x898F),
Palette4Rgb8Oes = ((int)0x8B90),
Palette4Rgba8Oes = ((int)0x8B91),
Palette4R5G6B5Oes = ((int)0x8B92),
Palette4Rgba4Oes = ((int)0x8B93),
Palette4Rgb5A1Oes = ((int)0x8B94),
Palette8Rgb8Oes = ((int)0x8B95),
Palette8Rgba8Oes = ((int)0x8B96),
Palette8R5G6B5Oes = ((int)0x8B97),
Palette8Rgba4Oes = ((int)0x8B98),
Palette8Rgb5A1Oes = ((int)0x8B99),
ImplementationColorReadTypeOes = ((int)0x8B9A),
ImplementationColorReadFormatOes = ((int)0x8B9B),
PointSizeArrayOes = ((int)0x8B9C),
TextureCropRectOes = ((int)0x8B9D),
MatrixIndexArrayBufferBindingOes = ((int)0x8B9E),
PointSizeArrayBufferBindingOes = ((int)0x8B9F),
CompressedRgbPvrtc4Bppv1Img = ((int)0x8C00),
CompressedRgbPvrtc2Bppv1Img = ((int)0x8C01),
CompressedRgbaPvrtc4Bppv1Img = ((int)0x8C02),
CompressedRgbaPvrtc2Bppv1Img = ((int)0x8C03),
ModulateColorImg = ((int)0x8C04),
RecipAddSignedAlphaImg = ((int)0x8C05),
TextureAlphaModulateImg = ((int)0x8C06),
FactorAlphaModulateImg = ((int)0x8C07),
FragmentAlphaModulateImg = ((int)0x8C08),
AddBlendImg = ((int)0x8C09),
AtcRgbAmd = ((int)0x8C92),
AtcRgbaExplicitAlphaAmd = ((int)0x8C93),
FramebufferBindingOes = ((int)0x8CA6),
RenderbufferBindingOes = ((int)0x8CA7),
FramebufferAttachmentObjectTypeOes = ((int)0x8CD0),
FramebufferAttachmentObjectNameOes = ((int)0x8CD1),
FramebufferAttachmentTextureLevelOes = ((int)0x8CD2),
FramebufferAttachmentTextureCubeMapFaceOes = ((int)0x8CD3),
FramebufferCompleteOes = ((int)0x8CD5),
FramebufferIncompleteAttachmentOes = ((int)0x8CD6),
FramebufferIncompleteMissingAttachmentOes = ((int)0x8CD7),
FramebufferIncompleteDimensionsOes = ((int)0x8CD9),
FramebufferIncompleteFormatsOes = ((int)0x8CDA),
FramebufferUnsupportedOes = ((int)0x8CDD),
ColorAttachment0Oes = ((int)0x8CE0),
DepthAttachmentOes = ((int)0x8D00),
StencilAttachmentOes = ((int)0x8D20),
FramebufferOes = ((int)0x8D40),
RenderbufferOes = ((int)0x8D41),
RenderbufferWidthOes = ((int)0x8D42),
RenderbufferHeightOes = ((int)0x8D43),
RenderbufferInternalFormatOes = ((int)0x8D44),
StencilIndex1Oes = ((int)0x8D46),
StencilIndex4Oes = ((int)0x8D47),
StencilIndex8Oes = ((int)0x8D48),
RenderbufferRedSizeOes = ((int)0x8D50),
RenderbufferGreenSizeOes = ((int)0x8D51),
RenderbufferBlueSizeOes = ((int)0x8D52),
RenderbufferAlphaSizeOes = ((int)0x8D53),
RenderbufferDepthSizeOes = ((int)0x8D54),
RenderbufferStencilSizeOes = ((int)0x8D55),
TextureGenStrOes = ((int)0x8D60),
Rgb565Oes = ((int)0x8D62),
Etc1Rgb8Oes = ((int)0x8D64),
PerfmonGlobalModeQcom = ((int)0x8FA0),
AmdCompressed3DcTexture = ((int)1),
AmdCompressedAtcTexture = ((int)1),
ExtTextureFilterAnisotropic = ((int)1),
ExtTextureFormatBgra8888 = ((int)1),
ImgReadFormat = ((int)1),
ImgTextureCompressionPvrtc = ((int)1),
ImgTextureEnvEnhancedFixedFunction = ((int)1),
ImgUserClipPlane = ((int)1),
NvFence = ((int)1),
OesBlendEquationSeparate = ((int)1),
OesBlendFuncSeparate = ((int)1),
OesBlendSubtract = ((int)1),
OesByteCoordinates = ((int)1),
OesCompressedEtc1Rgb8Texture = ((int)1),
OesCompressedPalettedTexture = ((int)1),
OesDepth24 = ((int)1),
OesDepth32 = ((int)1),
OesDrawTexture = ((int)1),
OesEglImage = ((int)1),
OesElementIndexUint = ((int)1),
OesExtendedMatrixPalette = ((int)1),
OesFboRenderMipmap = ((int)1),
OesFixedPoint = ((int)1),
OesFramebufferObject = ((int)1),
OesMapbuffer = ((int)1),
OesMatrixGet = ((int)1),
OesMatrixPalette = ((int)1),
OesPackedDepthStencil = ((int)1),
OesPointSizeArray = ((int)1),
OesPointSprite = ((int)1),
OesQueryMatrix = ((int)1),
OesReadFormat = ((int)1),
OesRgb8Rgba8 = ((int)1),
OesSinglePrecision = ((int)1),
OesStencil1 = ((int)1),
OesStencil4 = ((int)1),
OesStencil8 = ((int)1),
OesStencilWrap = ((int)1),
OesTextureCubeMap = ((int)1),
OesTextureEnvCrossbar = ((int)1),
OesTextureMirroredRepeat = ((int)1),
One = ((int)1),
QcomDriverControl = ((int)1),
QcomPerfmonGlobalMode = ((int)1),
True = ((int)1),
VersionEsCl10 = ((int)1),
VersionEsCl11 = ((int)1),
VersionEsCm10 = ((int)1),
VersionEsCm11 = ((int)1),
}
public enum AlphaFunction : int
{
Never = ((int)0x0200),
Less = ((int)0x0201),
Equal = ((int)0x0202),
Lequal = ((int)0x0203),
Greater = ((int)0x0204),
Notequal = ((int)0x0205),
Gequal = ((int)0x0206),
Always = ((int)0x0207),
}
public enum AmdCompressed3Dctexture : int
{
Gl3DcXAmd = ((int)0x87F9),
Gl3DcXyAmd = ((int)0x87FA),
AmdCompressed3DcTexture = ((int)1),
}
public enum AmdCompressedAtctexture : int
{
AtcRgbaInterpolatedAlphaAmd = ((int)0x87EE),
AtcRgbAmd = ((int)0x8C92),
AtcRgbaExplicitAlphaAmd = ((int)0x8C93),
AmdCompressedAtcTexture = ((int)1),
}
public enum BeginMode : int
{
Points = ((int)0x0000),
Lines = ((int)0x0001),
LineLoop = ((int)0x0002),
LineStrip = ((int)0x0003),
Triangles = ((int)0x0004),
TriangleStrip = ((int)0x0005),
TriangleFan = ((int)0x0006),
}
public enum BlendingFactorDest : int
{
Zero = ((int)0),
SrcColor = ((int)0x0300),
OneMinusSrcColor = ((int)0x0301),
SrcAlpha = ((int)0x0302),
OneMinusSrcAlpha = ((int)0x0303),
DstAlpha = ((int)0x0304),
OneMinusDstAlpha = ((int)0x0305),
One = ((int)1),
}
public enum BlendingFactorSrc : int
{
DstColor = ((int)0x0306),
OneMinusDstColor = ((int)0x0307),
SrcAlphaSaturate = ((int)0x0308),
}
public enum Boolean : int
{
False = ((int)0),
True = ((int)1),
}
public enum BufferObjects : int
{
BufferSize = ((int)0x8764),
BufferUsage = ((int)0x8765),
ArrayBuffer = ((int)0x8892),
ElementArrayBuffer = ((int)0x8893),
ArrayBufferBinding = ((int)0x8894),
ElementArrayBufferBinding = ((int)0x8895),
VertexArrayBufferBinding = ((int)0x8896),
NormalArrayBufferBinding = ((int)0x8897),
ColorArrayBufferBinding = ((int)0x8898),
TextureCoordArrayBufferBinding = ((int)0x889A),
StaticDraw = ((int)0x88E4),
DynamicDraw = ((int)0x88E8),
}
[Flags]
public enum ClearBufferMask : int
{
DepthBufferBit = ((int)0x00000100),
StencilBufferBit = ((int)0x00000400),
ColorBufferBit = ((int)0x00004000),
}
public enum ClipPlaneName : int
{
ClipPlane0 = ((int)0x3000),
ClipPlane1 = ((int)0x3001),
ClipPlane2 = ((int)0x3002),
ClipPlane3 = ((int)0x3003),
ClipPlane4 = ((int)0x3004),
ClipPlane5 = ((int)0x3005),
}
public enum CullFaceMode : int
{
Front = ((int)0x0404),
Back = ((int)0x0405),
FrontAndBack = ((int)0x0408),
}
public enum DataType : int
{
Byte = ((int)0x1400),
UnsignedByte = ((int)0x1401),
Short = ((int)0x1402),
UnsignedShort = ((int)0x1403),
Float = ((int)0x1406),
Fixed = ((int)0x140C),
}
public enum EnableCap : int
{
PointSmooth = ((int)0x0B10),
LineSmooth = ((int)0x0B20),
CullFace = ((int)0x0B44),
Lighting = ((int)0x0B50),
ColorMaterial = ((int)0x0B57),
Fog = ((int)0x0B60),
DepthTest = ((int)0x0B71),
StencilTest = ((int)0x0B90),
Normalize = ((int)0x0BA1),
AlphaTest = ((int)0x0BC0),
Dither = ((int)0x0BD0),
Blend = ((int)0x0BE2),
ColorLogicOp = ((int)0x0BF2),
ScissorTest = ((int)0x0C11),
Texture2D = ((int)0x0DE1),
PolygonOffsetFill = ((int)0x8037),
RescaleNormal = ((int)0x803A),
VertexArray = ((int)0x8074),
NormalArray = ((int)0x8075),
ColorArray = ((int)0x8076),
TextureCoordArray = ((int)0x8078),
Multisample = ((int)0x809D),
SampleAlphaToCoverage = ((int)0x809E),
SampleAlphaToOne = ((int)0x809F),
SampleCoverage = ((int)0x80A0),
}
public enum ErrorCode : int
{
NoError = ((int)0),
InvalidEnum = ((int)0x0500),
InvalidValue = ((int)0x0501),
InvalidOperation = ((int)0x0502),
StackOverflow = ((int)0x0503),
StackUnderflow = ((int)0x0504),
OutOfMemory = ((int)0x0505),
}
public enum ExtTextureFilterAnisotropic : int
{
TextureMaxAnisotropyExt = ((int)0x84FE),
MaxTextureMaxAnisotropyExt = ((int)0x84FF),
ExtTextureFilterAnisotropic = ((int)1),
}
public enum ExtTextureFormatBgra8888 : int
{
Bgra = ((int)0x80E1),
ExtTextureFormatBgra8888 = ((int)1),
}
public enum FogMode : int
{
Exp = ((int)0x0800),
Exp2 = ((int)0x0801),
}
public enum FogParameter : int
{
FogDensity = ((int)0x0B62),
FogStart = ((int)0x0B63),
FogEnd = ((int)0x0B64),
FogMode = ((int)0x0B65),
FogColor = ((int)0x0B66),
}
public enum FrontFaceDirection : int
{
Cw = ((int)0x0900),
Ccw = ((int)0x0901),
}
public enum GetPName : int
{
CurrentColor = ((int)0x0B00),
CurrentNormal = ((int)0x0B02),
CurrentTextureCoords = ((int)0x0B03),
PointSize = ((int)0x0B11),
SmoothPointSizeRange = ((int)0x0B12),
LineWidth = ((int)0x0B21),
SmoothLineWidthRange = ((int)0x0B22),
CullFaceMode = ((int)0x0B45),
FrontFace = ((int)0x0B46),
ShadeModel = ((int)0x0B54),
DepthRange = ((int)0x0B70),
DepthWritemask = ((int)0x0B72),
DepthClearValue = ((int)0x0B73),
DepthFunc = ((int)0x0B74),
StencilClearValue = ((int)0x0B91),
StencilFunc = ((int)0x0B92),
StencilValueMask = ((int)0x0B93),
StencilFail = ((int)0x0B94),
StencilPassDepthFail = ((int)0x0B95),
StencilPassDepthPass = ((int)0x0B96),
StencilRef = ((int)0x0B97),
StencilWritemask = ((int)0x0B98),
MatrixMode = ((int)0x0BA0),
Viewport = ((int)0x0BA2),
ModelviewStackDepth = ((int)0x0BA3),
ProjectionStackDepth = ((int)0x0BA4),
TextureStackDepth = ((int)0x0BA5),
ModelviewMatrix = ((int)0x0BA6),
ProjectionMatrix = ((int)0x0BA7),
TextureMatrix = ((int)0x0BA8),
AlphaTestFunc = ((int)0x0BC1),
AlphaTestRef = ((int)0x0BC2),
BlendDst = ((int)0x0BE0),
BlendSrc = ((int)0x0BE1),
LogicOpMode = ((int)0x0BF0),
ScissorBox = ((int)0x0C10),
ScissorTest = ((int)0x0C11),
ColorClearValue = ((int)0x0C22),
ColorWritemask = ((int)0x0C23),
UnpackAlignment = ((int)0x0CF5),
PackAlignment = ((int)0x0D05),
MaxLights = ((int)0x0D31),
MaxClipPlanes = ((int)0x0D32),
MaxTextureSize = ((int)0x0D33),
MaxModelviewStackDepth = ((int)0x0D36),
MaxProjectionStackDepth = ((int)0x0D38),
MaxTextureStackDepth = ((int)0x0D39),
MaxViewportDims = ((int)0x0D3A),
SubpixelBits = ((int)0x0D50),
RedBits = ((int)0x0D52),
GreenBits = ((int)0x0D53),
BlueBits = ((int)0x0D54),
AlphaBits = ((int)0x0D55),
DepthBits = ((int)0x0D56),
StencilBits = ((int)0x0D57),
PolygonOffsetUnits = ((int)0x2A00),
PolygonOffsetFill = ((int)0x8037),
PolygonOffsetFactor = ((int)0x8038),
TextureBinding2D = ((int)0x8069),
VertexArraySize = ((int)0x807A),
VertexArrayType = ((int)0x807B),
VertexArrayStride = ((int)0x807C),
NormalArrayType = ((int)0x807E),
NormalArrayStride = ((int)0x807F),
ColorArraySize = ((int)0x8081),
ColorArrayType = ((int)0x8082),
ColorArrayStride = ((int)0x8083),
TextureCoordArraySize = ((int)0x8088),
TextureCoordArrayType = ((int)0x8089),
TextureCoordArrayStride = ((int)0x808A),
VertexArrayPointer = ((int)0x808E),
NormalArrayPointer = ((int)0x808F),
ColorArrayPointer = ((int)0x8090),
TextureCoordArrayPointer = ((int)0x8092),
SampleBuffers = ((int)0x80A8),
Samples = ((int)0x80A9),
SampleCoverageValue = ((int)0x80AA),
SampleCoverageInvert = ((int)0x80AB),
PointSizeMin = ((int)0x8126),
PointSizeMax = ((int)0x8127),
PointFadeThresholdSize = ((int)0x8128),
PointDistanceAttenuation = ((int)0x8129),
AliasedPointSizeRange = ((int)0x846D),
AliasedLineWidthRange = ((int)0x846E),
MaxTextureUnits = ((int)0x84E2),
}
public enum GetTextureParameter : int
{
NumCompressedTextureFormats = ((int)0x86A2),
CompressedTextureFormats = ((int)0x86A3),
}
public enum HintMode : int
{
DontCare = ((int)0x1100),
Fastest = ((int)0x1101),
Nicest = ((int)0x1102),
}
public enum HintTarget : int
{
PerspectiveCorrectionHint = ((int)0x0C50),
PointSmoothHint = ((int)0x0C51),
LineSmoothHint = ((int)0x0C52),
FogHint = ((int)0x0C54),
GenerateMipmapHint = ((int)0x8192),
}
public enum ImgreadFormat : int
{
Bgra = ((int)0x80E1),
UnsignedShort4444Rev = ((int)0x8365),
UnsignedShort1555Rev = ((int)0x8366),
ImgReadFormat = ((int)1),
}
public enum ImgtextureCompressionPvrtc : int
{
CompressedRgbPvrtc4Bppv1Img = ((int)0x8C00),
CompressedRgbPvrtc2Bppv1Img = ((int)0x8C01),
CompressedRgbaPvrtc4Bppv1Img = ((int)0x8C02),
CompressedRgbaPvrtc2Bppv1Img = ((int)0x8C03),
ImgTextureCompressionPvrtc = ((int)1),
}
public enum ImgtextureEnvEnhancedFixedFunction : int
{
Dot3RgbaImg = ((int)0x86AF),
ModulateColorImg = ((int)0x8C04),
RecipAddSignedAlphaImg = ((int)0x8C05),
TextureAlphaModulateImg = ((int)0x8C06),
FactorAlphaModulateImg = ((int)0x8C07),
FragmentAlphaModulateImg = ((int)0x8C08),
AddBlendImg = ((int)0x8C09),
ImgTextureEnvEnhancedFixedFunction = ((int)1),
}
public enum ImguserClipPlane : int
{
MaxClipPlanesImg = ((int)0x0D32),
ClipPlane0Img = ((int)0x3000),
ClipPlane1Img = ((int)0x3001),
ClipPlane2Img = ((int)0x3002),
ClipPlane3Img = ((int)0x3003),
ClipPlane4Img = ((int)0x3004),
ClipPlane5Img = ((int)0x3005),
ImgUserClipPlane = ((int)1),
}
public enum LightModelParameter : int
{
LightModelTwoSide = ((int)0x0B52),
LightModelAmbient = ((int)0x0B53),
}
public enum LightName : int
{
Light0 = ((int)0x4000),
Light1 = ((int)0x4001),
Light2 = ((int)0x4002),
Light3 = ((int)0x4003),
Light4 = ((int)0x4004),
Light5 = ((int)0x4005),
Light6 = ((int)0x4006),
Light7 = ((int)0x4007),
}
public enum LightParameter : int
{
Ambient = ((int)0x1200),
Diffuse = ((int)0x1201),
Specular = ((int)0x1202),
Position = ((int)0x1203),
SpotDirection = ((int)0x1204),
SpotExponent = ((int)0x1205),
SpotCutoff = ((int)0x1206),
ConstantAttenuation = ((int)0x1207),
LinearAttenuation = ((int)0x1208),
QuadraticAttenuation = ((int)0x1209),
}
public enum LogicOp : int
{
Clear = ((int)0x1500),
And = ((int)0x1501),
AndReverse = ((int)0x1502),
Copy = ((int)0x1503),
AndInverted = ((int)0x1504),
Noop = ((int)0x1505),
Xor = ((int)0x1506),
Or = ((int)0x1507),
Nor = ((int)0x1508),
Equiv = ((int)0x1509),
Invert = ((int)0x150A),
OrReverse = ((int)0x150B),
CopyInverted = ((int)0x150C),
OrInverted = ((int)0x150D),
Nand = ((int)0x150E),
Set = ((int)0x150F),
}
public enum MaterialParameter : int
{
Emission = ((int)0x1600),
Shininess = ((int)0x1601),
AmbientAndDiffuse = ((int)0x1602),
}
public enum MatrixMode : int
{
Modelview = ((int)0x1700),
Projection = ((int)0x1701),
Texture = ((int)0x1702),
}
public enum Nvfence : int
{
AllCompletedNv = ((int)0x84F2),
FenceStatusNv = ((int)0x84F3),
FenceConditionNv = ((int)0x84F4),
NvFence = ((int)1),
}
public enum OesBlendEquationSeparate : int
{
BlendEquationRgbOes = ((int)0x8009),
BlendEquationAlphaOes = ((int)0x883D),
OesBlendEquationSeparate = ((int)1),
}
public enum OesBlendFuncSeparate : int
{
BlendDstRgbOes = ((int)0x80C8),
BlendSrcRgbOes = ((int)0x80C9),
BlendDstAlphaOes = ((int)0x80CA),
BlendSrcAlphaOes = ((int)0x80CB),
OesBlendFuncSeparate = ((int)1),
}
public enum OesBlendSubtract : int
{
FuncAddOes = ((int)0x8006),
BlendEquationOes = ((int)0x8009),
FuncSubtractOes = ((int)0x800A),
FuncReverseSubtractOes = ((int)0x800B),
OesBlendSubtract = ((int)1),
}
public enum OesByteCoordinates : int
{
OesByteCoordinates = ((int)1),
}
public enum OesCompressedEtc1Rgb8Texture : int
{
Etc1Rgb8Oes = ((int)0x8D64),
OesCompressedEtc1Rgb8Texture = ((int)1),
}
public enum OesCompressedPalettedTexture : int
{
Palette4Rgb8Oes = ((int)0x8B90),
Palette4Rgba8Oes = ((int)0x8B91),
Palette4R5G6B5Oes = ((int)0x8B92),
Palette4Rgba4Oes = ((int)0x8B93),
Palette4Rgb5A1Oes = ((int)0x8B94),
Palette8Rgb8Oes = ((int)0x8B95),
Palette8Rgba8Oes = ((int)0x8B96),
Palette8R5G6B5Oes = ((int)0x8B97),
Palette8Rgba4Oes = ((int)0x8B98),
Palette8Rgb5A1Oes = ((int)0x8B99),
OesCompressedPalettedTexture = ((int)1),
}
public enum OesDepth24 : int
{
DepthComponent24Oes = ((int)0x81A6),
OesDepth24 = ((int)1),
}
public enum OesDepth32 : int
{
DepthComponent32Oes = ((int)0x81A7),
OesDepth32 = ((int)1),
}
public enum OesDrawTexture : int
{
TextureCropRectOes = ((int)0x8B9D),
OesDrawTexture = ((int)1),
}
public enum OesEglimage : int
{
OesEglImage = ((int)1),
}
public enum OesElementIndexUint : int
{
OesElementIndexUint = ((int)1),
}
public enum OesExtendedMatrixPalette : int
{
OesExtendedMatrixPalette = ((int)1),
}
public enum OesFboRenderMipmap : int
{
OesFboRenderMipmap = ((int)1),
}
public enum OesFixedPoint : int
{
FixedOes = ((int)0x140C),
OesFixedPoint = ((int)1),
}
public enum OesFramebufferObject : int
{
NoneOes = ((int)0),
InvalidFramebufferOperationOes = ((int)0x0506),
Rgba4Oes = ((int)0x8056),
Rgb5A1Oes = ((int)0x8057),
DepthComponent16Oes = ((int)0x81A5),
MaxRenderbufferSizeOes = ((int)0x84E8),
FramebufferBindingOes = ((int)0x8CA6),
RenderbufferBindingOes = ((int)0x8CA7),
FramebufferAttachmentObjectTypeOes = ((int)0x8CD0),
FramebufferAttachmentObjectNameOes = ((int)0x8CD1),
FramebufferAttachmentTextureLevelOes = ((int)0x8CD2),
FramebufferAttachmentTextureCubeMapFaceOes = ((int)0x8CD3),
FramebufferCompleteOes = ((int)0x8CD5),
FramebufferIncompleteAttachmentOes = ((int)0x8CD6),
FramebufferIncompleteMissingAttachmentOes = ((int)0x8CD7),
FramebufferIncompleteDimensionsOes = ((int)0x8CD9),
FramebufferIncompleteFormatsOes = ((int)0x8CDA),
FramebufferUnsupportedOes = ((int)0x8CDD),
ColorAttachment0Oes = ((int)0x8CE0),
DepthAttachmentOes = ((int)0x8D00),
StencilAttachmentOes = ((int)0x8D20),
FramebufferOes = ((int)0x8D40),
RenderbufferOes = ((int)0x8D41),
RenderbufferWidthOes = ((int)0x8D42),
RenderbufferHeightOes = ((int)0x8D43),
RenderbufferInternalFormatOes = ((int)0x8D44),
RenderbufferRedSizeOes = ((int)0x8D50),
RenderbufferGreenSizeOes = ((int)0x8D51),
RenderbufferBlueSizeOes = ((int)0x8D52),
RenderbufferAlphaSizeOes = ((int)0x8D53),
RenderbufferDepthSizeOes = ((int)0x8D54),
RenderbufferStencilSizeOes = ((int)0x8D55),
Rgb565Oes = ((int)0x8D62),
OesFramebufferObject = ((int)1),
}
public enum OesMapbuffer : int
{
WriteOnlyOes = ((int)0x88B9),
BufferAccessOes = ((int)0x88BB),
BufferMappedOes = ((int)0x88BC),
BufferMapPointerOes = ((int)0x88BD),
OesMapbuffer = ((int)1),
}
public enum OesMatrixGet : int
{
ModelviewMatrixFloatAsIntBitsOes = ((int)0x898D),
ProjectionMatrixFloatAsIntBitsOes = ((int)0x898E),
TextureMatrixFloatAsIntBitsOes = ((int)0x898F),
OesMatrixGet = ((int)1),
}
public enum OesMatrixPalette : int
{
MaxVertexUnitsOes = ((int)0x86A4),
WeightArrayTypeOes = ((int)0x86A9),
WeightArrayStrideOes = ((int)0x86AA),
WeightArraySizeOes = ((int)0x86AB),
WeightArrayPointerOes = ((int)0x86AC),
WeightArrayOes = ((int)0x86AD),
MatrixPaletteOes = ((int)0x8840),
MaxPaletteMatricesOes = ((int)0x8842),
CurrentPaletteMatrixOes = ((int)0x8843),
MatrixIndexArrayOes = ((int)0x8844),
MatrixIndexArraySizeOes = ((int)0x8846),
MatrixIndexArrayTypeOes = ((int)0x8847),
MatrixIndexArrayStrideOes = ((int)0x8848),
MatrixIndexArrayPointerOes = ((int)0x8849),
WeightArrayBufferBindingOes = ((int)0x889E),
MatrixIndexArrayBufferBindingOes = ((int)0x8B9E),
OesMatrixPalette = ((int)1),
}
public enum OesPackedDepthStencil : int
{
DepthStencilOes = ((int)0x84F9),
UnsignedInt248Oes = ((int)0x84FA),
Depth24Stencil8Oes = ((int)0x88F0),
OesPackedDepthStencil = ((int)1),
}
public enum OesPointSizeArray : int
{
PointSizeArrayTypeOes = ((int)0x898A),
PointSizeArrayStrideOes = ((int)0x898B),
PointSizeArrayPointerOes = ((int)0x898C),
PointSizeArrayOes = ((int)0x8B9C),
PointSizeArrayBufferBindingOes = ((int)0x8B9F),
OesPointSizeArray = ((int)1),
}
public enum OesPointSprite : int
{
PointSpriteOes = ((int)0x8861),
CoordReplaceOes = ((int)0x8862),
OesPointSprite = ((int)1),
}
public enum OesQueryMatrix : int
{
OesQueryMatrix = ((int)1),
}
public enum OesReadFormat : int
{
ImplementationColorReadTypeOes = ((int)0x8B9A),
ImplementationColorReadFormatOes = ((int)0x8B9B),
OesReadFormat = ((int)1),
}
public enum OesRgb8Rgba8 : int
{
Rgb8Oes = ((int)0x8051),
Rgba8Oes = ((int)0x8058),
OesRgb8Rgba8 = ((int)1),
}
public enum OesSinglePrecision : int
{
OesSinglePrecision = ((int)1),
}
public enum OesStencil1 : int
{
StencilIndex1Oes = ((int)0x8D46),
OesStencil1 = ((int)1),
}
public enum OesStencil4 : int
{
StencilIndex4Oes = ((int)0x8D47),
OesStencil4 = ((int)1),
}
public enum OesStencil8 : int
{
StencilIndex8Oes = ((int)0x8D48),
OesStencil8 = ((int)1),
}
public enum OesStencilWrap : int
{
IncrWrapOes = ((int)0x8507),
DecrWrapOes = ((int)0x8508),
OesStencilWrap = ((int)1),
}
public enum OesTextureCubeMap : int
{
TextureGenModeOes = ((int)0x2500),
NormalMapOes = ((int)0x8511),
ReflectionMapOes = ((int)0x8512),
TextureCubeMapOes = ((int)0x8513),
TextureBindingCubeMapOes = ((int)0x8514),
TextureCubeMapPositiveXOes = ((int)0x8515),
TextureCubeMapNegativeXOes = ((int)0x8516),
TextureCubeMapPositiveYOes = ((int)0x8517),
TextureCubeMapNegativeYOes = ((int)0x8518),
TextureCubeMapPositiveZOes = ((int)0x8519),
TextureCubeMapNegativeZOes = ((int)0x851A),
MaxCubeMapTextureSizeOes = ((int)0x851C),
TextureGenStrOes = ((int)0x8D60),
OesTextureCubeMap = ((int)1),
}
public enum OesTextureEnvCrossbar : int
{
OesTextureEnvCrossbar = ((int)1),
}
public enum OesTextureMirroredRepeat : int
{
MirroredRepeatOes = ((int)0x8370),
OesTextureMirroredRepeat = ((int)1),
}
public enum OpenGlescoreVersions : int
{
VersionEsCl10 = ((int)1),
VersionEsCl11 = ((int)1),
VersionEsCm10 = ((int)1),
VersionEsCm11 = ((int)1),
}
public enum PixelFormat : int
{
Alpha = ((int)0x1906),
Rgb = ((int)0x1907),
Rgba = ((int)0x1908),
Luminance = ((int)0x1909),
LuminanceAlpha = ((int)0x190A),
}
public enum PixelStoreParameter : int
{
UnpackAlignment = ((int)0x0CF5),
PackAlignment = ((int)0x0D05),
}
public enum PixelType : int
{
UnsignedShort4444 = ((int)0x8033),
UnsignedShort5551 = ((int)0x8034),
UnsignedShort565 = ((int)0x8363),
}
public enum QcomDriverControl : int
{
QcomDriverControl = ((int)1),
}
public enum QcomPerfmonGlobalMode : int
{
PerfmonGlobalModeQcom = ((int)0x8FA0),
QcomPerfmonGlobalMode = ((int)1),
}
public enum ShadingModel : int
{
Flat = ((int)0x1D00),
Smooth = ((int)0x1D01),
}
public enum StencilOp : int
{
Keep = ((int)0x1E00),
Replace = ((int)0x1E01),
Incr = ((int)0x1E02),
Decr = ((int)0x1E03),
}
public enum StringName : int
{
Vendor = ((int)0x1F00),
Renderer = ((int)0x1F01),
Version = ((int)0x1F02),
Extensions = ((int)0x1F03),
}
public enum TextureCombineDot3 : int
{
AlphaScale = ((int)0x0D1C),
Subtract = ((int)0x84E7),
Combine = ((int)0x8570),
CombineRgb = ((int)0x8571),
CombineAlpha = ((int)0x8572),
RgbScale = ((int)0x8573),
AddSigned = ((int)0x8574),
Interpolate = ((int)0x8575),
Constant = ((int)0x8576),
PrimaryColor = ((int)0x8577),
Previous = ((int)0x8578),
Src0Rgb = ((int)0x8580),
Src1Rgb = ((int)0x8581),
Src2Rgb = ((int)0x8582),
Src0Alpha = ((int)0x8588),
Src1Alpha = ((int)0x8589),
Src2Alpha = ((int)0x858A),
Operand0Rgb = ((int)0x8590),
Operand1Rgb = ((int)0x8591),
Operand2Rgb = ((int)0x8592),
Operand0Alpha = ((int)0x8598),
Operand1Alpha = ((int)0x8599),
Operand2Alpha = ((int)0x859A),
Dot3Rgb = ((int)0x86AE),
Dot3Rgba = ((int)0x86AF),
}
public enum TextureEnvMode : int
{
Add = ((int)0x0104),
Modulate = ((int)0x2100),
Decal = ((int)0x2101),
}
public enum TextureEnvParameter : int
{
TextureEnvMode = ((int)0x2200),
TextureEnvColor = ((int)0x2201),
}
public enum TextureEnvTarget : int
{
TextureEnv = ((int)0x2300),
}
public enum TextureMagFilter : int
{
Nearest = ((int)0x2600),
Linear = ((int)0x2601),
}
public enum TextureMinFilter : int
{
NearestMipmapNearest = ((int)0x2700),
LinearMipmapNearest = ((int)0x2701),
NearestMipmapLinear = ((int)0x2702),
LinearMipmapLinear = ((int)0x2703),
}
public enum TextureParameterName : int
{
TextureMagFilter = ((int)0x2800),
TextureMinFilter = ((int)0x2801),
TextureWrapS = ((int)0x2802),
TextureWrapT = ((int)0x2803),
GenerateMipmap = ((int)0x8191),
}
public enum TextureUnit : int
{
Texture0 = ((int)0x84C0),
Texture1 = ((int)0x84C1),
Texture2 = ((int)0x84C2),
Texture3 = ((int)0x84C3),
Texture4 = ((int)0x84C4),
Texture5 = ((int)0x84C5),
Texture6 = ((int)0x84C6),
Texture7 = ((int)0x84C7),
Texture8 = ((int)0x84C8),
Texture9 = ((int)0x84C9),
Texture10 = ((int)0x84CA),
Texture11 = ((int)0x84CB),
Texture12 = ((int)0x84CC),
Texture13 = ((int)0x84CD),
Texture14 = ((int)0x84CE),
Texture15 = ((int)0x84CF),
Texture16 = ((int)0x84D0),
Texture17 = ((int)0x84D1),
Texture18 = ((int)0x84D2),
Texture19 = ((int)0x84D3),
Texture20 = ((int)0x84D4),
Texture21 = ((int)0x84D5),
Texture22 = ((int)0x84D6),
Texture23 = ((int)0x84D7),
Texture24 = ((int)0x84D8),
Texture25 = ((int)0x84D9),
Texture26 = ((int)0x84DA),
Texture27 = ((int)0x84DB),
Texture28 = ((int)0x84DC),
Texture29 = ((int)0x84DD),
Texture30 = ((int)0x84DE),
Texture31 = ((int)0x84DF),
ActiveTexture = ((int)0x84E0),
ClientActiveTexture = ((int)0x84E1),
}
public enum TextureWrapMode : int
{
Repeat = ((int)0x2901),
ClampToEdge = ((int)0x812F),
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.CodeFixes;
using Microsoft.CodeAnalysis.Editing;
using Microsoft.CodeAnalysis.FindSymbols;
using Microsoft.CodeAnalysis.Formatting;
using Microsoft.CodeAnalysis.Formatting.Rules;
using Microsoft.CodeAnalysis.Rename;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.UseAutoProperty
{
internal abstract class AbstractUseAutoPropertyCodeFixProvider<TPropertyDeclaration, TFieldDeclaration, TVariableDeclarator, TConstructorDeclaration, TExpression> : CodeFixProvider
where TPropertyDeclaration : SyntaxNode
where TFieldDeclaration : SyntaxNode
where TVariableDeclarator : SyntaxNode
where TConstructorDeclaration : SyntaxNode
where TExpression : SyntaxNode
{
protected static SyntaxAnnotation SpecializedFormattingAnnotation = new SyntaxAnnotation();
public sealed override ImmutableArray<string> FixableDiagnosticIds => ImmutableArray.Create(
AbstractUseAutoPropertyAnalyzer<TPropertyDeclaration, TFieldDeclaration, TVariableDeclarator, TExpression>.UseAutoProperty);
public sealed override FixAllProvider GetFixAllProvider() => WellKnownFixAllProviders.BatchFixer;
protected abstract SyntaxNode GetNodeToRemove(TVariableDeclarator declarator);
protected abstract IEnumerable<IFormattingRule> GetFormattingRules(Document document);
protected abstract Task<SyntaxNode> UpdatePropertyAsync(
Document propertyDocument, Compilation compilation, IFieldSymbol fieldSymbol, IPropertySymbol propertySymbol,
TPropertyDeclaration propertyDeclaration, bool isWrittenOutsideConstructor, CancellationToken cancellationToken);
public sealed override Task RegisterCodeFixesAsync(CodeFixContext context)
{
foreach (var diagnostic in context.Diagnostics)
{
var equivalenceKey = diagnostic.Properties["SymbolEquivalenceKey"];
context.RegisterCodeFix(
new UseAutoPropertyCodeAction(
FeaturesResources.Use_auto_property,
c => ProcessResult(context, diagnostic, c),
equivalenceKey),
diagnostic);
}
return SpecializedTasks.EmptyTask;
}
private async Task<Solution> ProcessResult(CodeFixContext context, Diagnostic diagnostic, CancellationToken cancellationToken)
{
var locations = diagnostic.AdditionalLocations;
var propertyLocation = locations[0];
var declaratorLocation = locations[1];
var declarator = declaratorLocation.FindToken(cancellationToken).Parent.FirstAncestorOrSelf<TVariableDeclarator>();
var fieldDocument = context.Document.Project.GetDocument(declarator.SyntaxTree);
var fieldSemanticModel = await fieldDocument.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false);
var fieldSymbol = (IFieldSymbol)fieldSemanticModel.GetDeclaredSymbol(declarator);
var property = propertyLocation.FindToken(cancellationToken).Parent.FirstAncestorOrSelf<TPropertyDeclaration>();
var propertyDocument = context.Document.Project.GetDocument(property.SyntaxTree);
var propertySemanticModel = await propertyDocument.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false);
var propertySymbol = (IPropertySymbol)propertySemanticModel.GetDeclaredSymbol(property);
Debug.Assert(fieldDocument.Project == propertyDocument.Project);
var project = fieldDocument.Project;
var compilation = await project.GetCompilationAsync(cancellationToken).ConfigureAwait(false);
var solution = context.Document.Project.Solution;
var fieldLocations = await Renamer.GetRenameLocationsAsync(
solution, SymbolAndProjectId.Create(fieldSymbol, fieldDocument.Project.Id),
solution.Options, cancellationToken).ConfigureAwait(false);
// First, create the updated property we want to replace the old property with
var isWrittenToOutsideOfConstructor = IsWrittenToOutsideOfConstructorOrProperty(fieldSymbol, fieldLocations, property, cancellationToken);
var updatedProperty = await UpdatePropertyAsync(propertyDocument, compilation, fieldSymbol, propertySymbol, property,
isWrittenToOutsideOfConstructor, cancellationToken).ConfigureAwait(false);
// Now, rename all usages of the field to point at the property. Except don't actually
// rename the field itself. We want to be able to find it again post rename.
var updatedSolution = await Renamer.RenameAsync(fieldLocations, propertySymbol.Name,
location => !location.SourceSpan.IntersectsWith(declaratorLocation.SourceSpan),
symbols => HasConflict(symbols, propertySymbol, compilation, cancellationToken),
cancellationToken).ConfigureAwait(false);
solution = updatedSolution;
// Now find the field and property again post rename.
fieldDocument = solution.GetDocument(fieldDocument.Id);
propertyDocument = solution.GetDocument(propertyDocument.Id);
Debug.Assert(fieldDocument.Project == propertyDocument.Project);
compilation = await fieldDocument.Project.GetCompilationAsync(cancellationToken).ConfigureAwait(false);
fieldSymbol = (IFieldSymbol)fieldSymbol.GetSymbolKey().Resolve(compilation, cancellationToken: cancellationToken).Symbol;
propertySymbol = (IPropertySymbol)propertySymbol.GetSymbolKey().Resolve(compilation, cancellationToken: cancellationToken).Symbol;
Debug.Assert(fieldSymbol != null && propertySymbol != null);
declarator = (TVariableDeclarator)await fieldSymbol.DeclaringSyntaxReferences[0].GetSyntaxAsync(cancellationToken).ConfigureAwait(false);
var temp = await propertySymbol.DeclaringSyntaxReferences[0].GetSyntaxAsync(cancellationToken).ConfigureAwait(false);
property = temp.FirstAncestorOrSelf<TPropertyDeclaration>();
var nodeToRemove = GetNodeToRemove(declarator);
const SyntaxRemoveOptions options = SyntaxRemoveOptions.KeepUnbalancedDirectives | SyntaxRemoveOptions.AddElasticMarker;
if (fieldDocument == propertyDocument)
{
// Same file. Have to do this in a slightly complicated fashion.
var declaratorTreeRoot = await fieldDocument.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
var editor = new SyntaxEditor(declaratorTreeRoot, fieldDocument.Project.Solution.Workspace);
editor.RemoveNode(nodeToRemove, options);
editor.ReplaceNode(property, updatedProperty);
var newRoot = editor.GetChangedRoot();
newRoot = await FormatAsync(newRoot, fieldDocument, cancellationToken).ConfigureAwait(false);
return solution.WithDocumentSyntaxRoot(
fieldDocument.Id, newRoot);
}
else
{
// In different files. Just update both files.
var fieldTreeRoot = await fieldDocument.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
var propertyTreeRoot = await propertyDocument.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
var newFieldTreeRoot = fieldTreeRoot.RemoveNode(nodeToRemove, options);
var newPropertyTreeRoot = propertyTreeRoot.ReplaceNode(property, updatedProperty);
newFieldTreeRoot = await FormatAsync(newFieldTreeRoot, fieldDocument, cancellationToken).ConfigureAwait(false);
newPropertyTreeRoot = await FormatAsync(newPropertyTreeRoot, propertyDocument, cancellationToken).ConfigureAwait(false);
updatedSolution = solution.WithDocumentSyntaxRoot(fieldDocument.Id, newFieldTreeRoot);
updatedSolution = updatedSolution.WithDocumentSyntaxRoot(propertyDocument.Id, newPropertyTreeRoot);
return updatedSolution;
}
}
private async Task<SyntaxNode> FormatAsync(SyntaxNode newRoot, Document document, CancellationToken cancellationToken)
{
var formattingRules = GetFormattingRules(document);
if (formattingRules == null)
{
return newRoot;
}
return await Formatter.FormatAsync(newRoot, SpecializedFormattingAnnotation, document.Project.Solution.Workspace, options: null, rules: formattingRules, cancellationToken: cancellationToken).ConfigureAwait(false);
}
private static bool IsWrittenToOutsideOfConstructorOrProperty(
IFieldSymbol field, RenameLocations renameLocations, TPropertyDeclaration propertyDeclaration, CancellationToken cancellationToken)
{
var constructorNodes = field.ContainingType.GetMembers()
.Where(m => m.IsConstructor())
.SelectMany(c => c.DeclaringSyntaxReferences)
.Select(s => s.GetSyntax(cancellationToken))
.Select(n => n.FirstAncestorOrSelf<TConstructorDeclaration>())
.WhereNotNull()
.ToSet();
return renameLocations.Locations.Any(
loc => IsWrittenToOutsideOfConstructorOrProperty(loc, propertyDeclaration, constructorNodes, cancellationToken));
}
private static bool IsWrittenToOutsideOfConstructorOrProperty(
RenameLocation location, TPropertyDeclaration propertyDeclaration, ISet<TConstructorDeclaration> constructorNodes, CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();
if (!location.IsWrittenTo)
{
// We don't need a setter if we're not writing to this field.
return false;
}
var node = location.Location.FindToken(cancellationToken).Parent;
while (node != null)
{
if (node == propertyDeclaration)
{
// Not a write outside the property declaration.
return false;
}
if (constructorNodes.Contains(node))
{
// Not a write outside a constructor of the field's class
return false;
}
node = node.Parent;
}
// We do need a setter
return true;
}
private bool? HasConflict(IEnumerable<ISymbol> symbols, IPropertySymbol property, Compilation compilation, CancellationToken cancellationToken)
{
// We're asking the rename API to update a bunch of references to an existing field to
// the same name as an existing property. Rename will often flag this situation as
// an unresolvable conflict because the new name won't bind to the field anymore.
//
// To address this, we let rename know that there is no conflict if the new symbol it
// resolves to is the same as the property we're trying to get the references pointing
// to.
foreach (var symbol in symbols)
{
var otherProperty = symbol as IPropertySymbol;
if (otherProperty != null)
{
var mappedProperty = otherProperty.GetSymbolKey().Resolve(compilation, cancellationToken: cancellationToken).Symbol as IPropertySymbol;
if (property.Equals(mappedProperty))
{
// No conflict.
return false;
}
}
}
// Just do the default check.
return null;
}
private class UseAutoPropertyCodeAction : CodeAction.SolutionChangeAction
{
public UseAutoPropertyCodeAction(string title, Func<CancellationToken, Task<Solution>> createChangedSolution, string equivalenceKey)
: base(title, createChangedSolution, equivalenceKey)
{
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO.Pipelines;
using System.Net;
using System.Runtime.CompilerServices;
using System.Threading;
using System.Threading.Channels;
using System.Threading.Tasks;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Orleans.Networking.Shared;
namespace Orleans.Runtime.Messaging
{
internal abstract class Connection
{
public static readonly Func<ConnectionContext, Task> OnConnectedDelegate = context => OnConnectedAsync(context);
public static readonly object ContextItemKey = new object();
private static readonly UnboundedChannelOptions OutgoingMessageChannelOptions = new UnboundedChannelOptions
{
SingleReader = true,
SingleWriter = false,
AllowSynchronousContinuations = false
};
private readonly ConnectionDelegate middleware;
private readonly IServiceProvider serviceProvider;
private readonly Channel<Message> outgoingMessages;
private readonly ChannelWriter<Message> outgoingMessageWriter;
private readonly object lockObj = new object();
private readonly List<Message> inflight = new List<Message>(4);
protected Connection(
ConnectionContext connection,
ConnectionDelegate middleware,
IServiceProvider serviceProvider,
INetworkingTrace trace)
{
this.Context = connection ?? throw new ArgumentNullException(nameof(connection));
this.middleware = middleware;
this.serviceProvider = serviceProvider;
this.Log = trace;
this.outgoingMessages = Channel.CreateUnbounded<Message>(OutgoingMessageChannelOptions);
this.outgoingMessageWriter = this.outgoingMessages.Writer;
// Set the connection on the connection context so that it can be retrieved by the middleware.
this.Context.Features.Set<Connection>(this);
this.IsValid = true;
}
public ConnectionContext Context { get; }
protected INetworkingTrace Log { get; }
protected abstract IMessageCenter MessageCenter { get; }
public virtual EndPoint RemoteEndpoint => this.Context.RemoteEndPoint;
public virtual EndPoint LocalEndpoint => this.Context.LocalEndPoint;
public bool IsValid { get; private set; }
public static void ConfigureBuilder(ConnectionBuilder builder) => builder.Run(OnConnectedDelegate);
public static async Task OnConnectedAsync(ConnectionContext context)
{
var connection = context.Features.Get<Connection>();
context.ConnectionClosed.Register(
state => ((Connection)state).CloseInternal(new ConnectionAbortedException("Connection closed")),
connection);
await connection.RunInternal();
}
public async Task Run()
{
Exception error = default;
try
{
await this.middleware(this.Context);
}
catch (Exception exception)
{
error = exception;
}
try
{
if (error is ConnectionAbortedException abortedException)
{
this.CloseInternal(abortedException);
}
else if (error != null)
{
this.CloseInternal(new ConnectionAbortedException(
$"Connection aborted. See {nameof(Exception.InnerException)}",
error));
}
else if (error == null)
{
this.CloseInternal(new ConnectionAbortedException("Connection processing completed without error"));
}
await this.Context.DisposeAsync();
}
catch
{
// Swallow any exceptions here.
}
_ = this.RerouteMessages();
}
protected virtual async Task RunInternal()
{
var outgoingTask = Task.Run(this.ProcessOutgoing);
var incomingTask = Task.Run(this.ProcessIncoming);
await Task.WhenAll(outgoingTask, incomingTask);
}
public void Close(ConnectionAbortedException exception = default)
{
if (this.Log.IsEnabled(LogLevel.Information))
{
this.Log.LogInformation(
"Closing connection with remote endpoint {EndPoint}",
this.RemoteEndpoint);
}
this.CloseInternal(exception);
}
/// <summary>
/// Called immediately prior to transporting a message.
/// </summary>
/// <param name="msg"></param>
/// <returns>Whether or not to continue transporting the message.</returns>
protected abstract bool PrepareMessageForSend(Message msg);
protected abstract void OnMessageSerializationFailure(Message msg, Exception exc);
protected abstract void RetryMessage(Message msg, Exception ex = null);
private void CloseInternal(ConnectionAbortedException exception)
{
try
{
if (!this.IsValid) return;
lock (this.lockObj)
{
if (!this.IsValid) return;
this.IsValid = false;
}
// Try to gracefully stop the reader/writer loops.
this.Context.Transport.Input.CancelPendingRead();
this.Context.Transport.Output.CancelPendingFlush();
this.outgoingMessageWriter.TryComplete();
if (exception == null)
{
this.Context.Abort();
}
else
{
this.Context.Abort(exception);
}
}
catch
{
}
}
public void Send(Message message)
{
if (!this.outgoingMessageWriter.TryWrite(message))
{
this.RerouteMessage(message);
}
}
protected abstract void OnReceivedMessage(Message message);
protected abstract void OnReceiveMessageFailure(Message message, Exception exception);
protected abstract void OnSendMessageFailure(Message message, string error);
private async Task ProcessIncoming()
{
PipeReader input = default;
var serializer = this.serviceProvider.GetRequiredService<IMessageSerializer>();
try
{
if (this.Log.IsEnabled(LogLevel.Debug))
{
this.Log.LogDebug(
"Starting to process messages from remote endpoint {RemoteEndPoint} to local endpoint {LocalEndPoint}",
this.RemoteEndpoint,
this.LocalEndpoint);
}
input = this.Context.Transport.Input;
var requiredBytes = 0;
Message message = default;
while (true)
{
var readResult = await input.ReadAsync();
var buffer = readResult.Buffer;
if (buffer.Length >= requiredBytes)
{
do
{
try
{
requiredBytes = serializer.TryRead(ref buffer, out message);
if (requiredBytes == 0)
{
this.OnReceivedMessage(message);
message = null;
}
}
catch (Exception exception)
{
this.Log.LogWarning(
"Exception reading message {Message} from remote endpoint {RemoteEndPoint} to local endpoint {LocalEndPoint}: {Exception}",
message,
this.RemoteEndpoint,
this.LocalEndpoint,
exception);
this.OnReceiveMessageFailure(message, exception);
break;
}
} while (requiredBytes == 0);
}
if (readResult.IsCanceled || readResult.IsCompleted) break;
input.AdvanceTo(buffer.Start, buffer.End);
}
}
catch (ConnectionAbortedException) { }
finally
{
input.Complete();
if (this.Log.IsEnabled(LogLevel.Debug))
{
this.Log.LogDebug(
"Completed processing messages from remote endpoint {EndPoint}",
this.RemoteEndpoint);
}
}
}
private async Task ProcessOutgoing()
{
PipeWriter output = default;
var serializer = this.serviceProvider.GetRequiredService<IMessageSerializer>();
var connectionClosed = this.Context.ConnectionClosed;
try
{
output = this.Context.Transport.Output;
var reader = this.outgoingMessages.Reader;
if (this.Log.IsEnabled(LogLevel.Debug))
{
this.Log.LogDebug(
"Starting to process messages from local endpoint {LocalEndPoint} to remote endpoint {RemoteEndPoint}",
this.LocalEndpoint,
this.RemoteEndpoint);
}
while (true)
{
var more = await reader.WaitToReadAsync();
if (!more)
{
break;
}
Message message = default;
try
{
while (inflight.Count < inflight.Capacity && reader.TryRead(out message) && this.PrepareMessageForSend(message))
{
inflight.Add(message);
serializer.Write(ref output, message);
}
}
catch (Exception exception) when (message != default)
{
this.Log.LogWarning(
"Exception writing message {Message} to remote endpoint {EndPoint}: {Exception}",
message,
this.RemoteEndpoint,
exception);
this.OnMessageSerializationFailure(message, exception);
}
var flushResult = await output.FlushAsync();
if (flushResult.IsCompleted || flushResult.IsCanceled || connectionClosed.IsCancellationRequested)
{
break;
}
inflight.Clear();
}
}
catch (ConnectionAbortedException) { }
finally
{
output.Complete();
if (this.Log.IsEnabled(LogLevel.Debug))
{
this.Log.LogDebug(
"Completed processing messages to remote endpoint {EndPoint}",
this.RemoteEndpoint);
}
}
}
private async Task RerouteMessages()
{
var i = 0;
foreach (var message in this.inflight)
{
this.OnSendMessageFailure(message, "Connection terminated");
}
this.inflight.Clear();
while (this.outgoingMessages.Reader.TryRead(out var message))
{
if (i == 0)
{
if (this.Log.IsEnabled(LogLevel.Information))
{
this.Log.LogInformation(
"Rerouting messages from remote endpoint {EndPoint}",
this.RemoteEndpoint?.ToString() ?? "(never connected)");
}
// Wait some time before re-sending the first time around.
await Task.Delay(TimeSpan.FromSeconds(2));
}
++i;
this.RetryMessage(message);
}
if (i > 0 && this.Log.IsEnabled(LogLevel.Information))
{
this.Log.LogInformation(
"Rerouted {Count} messages from remote endpoint {EndPoint}",
i,
this.RemoteEndpoint?.ToString() ?? "(never connected)");
}
}
private void RerouteMessage(Message message)
{
if (this.Log.IsEnabled(LogLevel.Debug))
{
this.Log.LogDebug(
"Rerouting message {Message} from remote endpoint {EndPoint}",
message,
this.RemoteEndpoint?.ToString() ?? "(never connected)");
}
ThreadPool.UnsafeQueueUserWorkItem(
msg => this.RetryMessage((Message)msg),
message);
}
}
}
| |
// DocumentSerialize SDK Sample - Util.cs
// Copyright (c) Microsoft Corporation. All rights reserved.
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Windows.Markup;
using System.Windows.Threading;
using System.Windows.Documents;
using System.Windows.Media;
using System.Windows;
using System.Xml;
using System.Security;
namespace DocumentSerialization
{
public static class Util
{
public static Stream ConvertTextToStream(string text)
{
System.Text.Encoding encoding = System.Text.Encoding.Unicode;
byte[] encodedBytes = encoding.GetBytes(text);
byte[] preamble = encoding.GetPreamble();
byte[] identifiableContent;
if (preamble.Length == 0)
{
identifiableContent = encodedBytes;
}
else
{
identifiableContent = new byte[preamble.Length + encodedBytes.Length];
preamble.CopyTo(identifiableContent, 0);
encodedBytes.CopyTo(identifiableContent, preamble.Length);
}
return new MemoryStream(identifiableContent);
}
public static object DeSerializeObjectTree(string xaml)
{
Stream stream = ConvertTextToStream(xaml);
ParserContext parserContext = new ParserContext();
parserContext.BaseUri = new Uri("pack://siteoforigin:,,,/");
return XamlReader.Load(stream, parserContext);
}
public static string SerializeObjectTree(object objectTree, XamlWriterMode expressionMode)
{
StringBuilder sb = new StringBuilder();
TextWriter writer = new StringWriter(sb);
XmlTextWriter xmlWriter = null;
try
{
// Create XmlTextWriter
xmlWriter = new XmlTextWriter(writer);
// Set serialization mode
XamlDesignerSerializationManager manager = new XamlDesignerSerializationManager(xmlWriter);
manager.XamlWriterMode = expressionMode;
// Serialize
System.Windows.Markup.XamlWriter.Save(objectTree, manager);
}
finally
{
if (xmlWriter != null)
xmlWriter.Close();
}
return sb.ToString();
}
public static string GetSavedDataPath(string savedXamlFileName)
{
string path = null;
path = Directory.GetCurrentDirectory();
path = System.IO.Path.Combine(path, savedXamlFileName);
return path;
}
public static FileStream GetStreamForSavedXamlFile(string savedDataPath, FileMode mode)
{
#if XamlPadExpressApp
// Get a store from Isolated Storage and see if xamlpad_saved.xaml exists
// for this user/application.
IsolatedStorageFile isoStore;
try
{
isoStore = IsolatedStorageFile.GetUserStoreForApplication();
}
catch (SecurityException)
{
// Just return null as if the saved file wasn't there.
return null;
}
// Get a stream for this file
try
{
IsolatedStorageFileStream stream = new IsolatedStorageFileStream(
savedXamlFileName,
mode,
isoStore);
return stream;
}
catch (FileNotFoundException)
{
// We are trying to open an existing file but it's not there.
// Just return null and we'll default to the initial content.
return null;
}
catch (IsolatedStorageException e)
{
// Isolated Storage permissions may not be granted to this user.
return null;
}
#else
// Use the rules for reading/writing the saved file -- if the app was deployed
// with ClickOnce, it goes to/from the user's desktop, otherwise the current
// directory is used.
try
{
FileStream stream = new FileStream(savedDataPath, mode);
return stream;
}
catch (UnauthorizedAccessException)
{
return null;
}
catch (SecurityException)
{
return null;
}
catch (FileNotFoundException)
{
return null;
}
catch (IOException)
{
return null;
}
#endif
}
public static void FlushDispatcher()
{
FlushDispatcher(Dispatcher.CurrentDispatcher);
}
/// <summary></summary>
/// <param name="ctx"></param>
public static void FlushDispatcher(Dispatcher ctx)
{
FlushDispatcher(ctx, DispatcherPriority.SystemIdle);
}
/// <summary></summary>
/// <param name="ctx"></param>
/// <param name="priority"></param>
public static void FlushDispatcher(Dispatcher ctx, DispatcherPriority priority)
{
ctx.Invoke(priority, new DispatcherOperationCallback(delegate { return null; }), null);
}
public static string GetIndentedXAML(string designXAML)
{
if (designXAML.Trim() == "") return "";
TextReader treader = new StringReader(designXAML);
XmlReader xmlReader = XmlReader.Create(treader);
xmlReader.Read();
string indentedXAML = "";
while (!xmlReader.EOF)
{
switch (xmlReader.NodeType)
{
case XmlNodeType.Element:
string tabs = "";
for (int i = 0; i < xmlReader.Depth; i++) tabs += " ";
if ((xmlReader.XmlSpace == XmlSpace.Preserve))
{
indentedXAML += "\n" + tabs + xmlReader.ReadOuterXml();
continue;
}
indentedXAML += "\n" + tabs + "<" + xmlReader.Name;
bool emptyElement = xmlReader.IsEmptyElement;
if (xmlReader.HasAttributes)
{
for (int i = 0; i < xmlReader.AttributeCount; i++)
{
xmlReader.MoveToAttribute(i);
indentedXAML += " " + xmlReader.Name + "=\"" + xmlReader.Value + "\"";
}
}
if (emptyElement) indentedXAML += "/";
indentedXAML += ">";
xmlReader.Read();
break;
case XmlNodeType.Text:
string origValue = xmlReader.Value;
origValue = origValue.Replace("&", "&");
origValue = origValue.Replace("<", "<");
origValue = origValue.Replace(">", ">");
origValue = origValue.Replace("\"", """);
indentedXAML += origValue;
xmlReader.Read();
break;
case XmlNodeType.EndElement:
tabs = "";
for (int i = 0; i < xmlReader.Depth; i++) tabs += " ";
indentedXAML += "\n" + tabs + "</" + xmlReader.Name + ">";
xmlReader.Read();
break;
case XmlNodeType.Whitespace:
//indentedXAML += xmlReader.Value;
xmlReader.Read();
break;
default:
xmlReader.Read();
break;
}
}
// remove the first \n
string realText = indentedXAML.Substring(1, indentedXAML.Length - 1);
indentedXAML = realText;
return indentedXAML;
}
private static void InsertBlockWithinParagraph(Paragraph origP, TextPointer _caretPosition, Block objectToInsert)
{
if (IsParagraphEmpty(origP))
{
FlowDocument fd = origP.Parent as FlowDocument;
if (fd != null)
{
fd.Blocks.InsertAfter(origP, objectToInsert);
fd.Blocks.Remove(origP);
return;
}
ListItem li = origP.Parent as ListItem;
if (li != null)
{
li.Blocks.InsertAfter(origP, objectToInsert);
li.Blocks.Remove(origP);
return;
}
}
_caretPosition.InsertParagraphBreak();
origP.SiblingBlocks.InsertAfter(origP, objectToInsert);
}
public static string GetFileName(string path)
{
string[] values = path.Split('/');
foreach (string s in values)
{
if (s.ToLower().Contains(".jpg") || s.ToLower().Contains(".bmp") || s.ToLower().Contains(".png") || s.ToLower().Contains(".gif"))
{
return s;
}
}
return "";
}
public static string FindNumeric(string content)
{
string[] values = content.Split(' ');
if (values != null)
{
return values[0];
}
return "none";
}
public static string GetBrushesFromString(string value)
{
if (string.Compare(value, Brushes.AliceBlue.ToString()) == 0) return "AliceBlue";
if (string.Compare(value, Brushes.AntiqueWhite.ToString()) == 0) return "AntiqueWhite";
if (string.Compare(value, Brushes.Aqua.ToString()) == 0) return "Aqua";
if (string.Compare(value, Brushes.Aquamarine.ToString()) == 0) return "Aquamarine";
if (string.Compare(value, Brushes.Azure.ToString()) == 0) return "Azure";
if (string.Compare(value, Brushes.Beige.ToString()) == 0) return "Beige";
if (string.Compare(value, Brushes.Bisque.ToString()) == 0) return "Bisque";
if (string.Compare(value, Brushes.Black.ToString()) == 0) return "Black";
if (string.Compare(value, Brushes.BlanchedAlmond.ToString()) == 0) return "BlanchedAlmond";
if (string.Compare(value, Brushes.Blue.ToString()) == 0) return "Blue";
if (string.Compare(value, Brushes.BlueViolet.ToString()) == 0) return "BlueViolet";
if (string.Compare(value, Brushes.Brown.ToString()) == 0) return "Brown";
if (string.Compare(value, Brushes.BurlyWood.ToString()) == 0) return "BurlyWood";
if (string.Compare(value, Brushes.CadetBlue.ToString()) == 0) return "CadetBlue";
if (string.Compare(value, Brushes.Chartreuse.ToString()) == 0) return "Chartreuse";
if (string.Compare(value, Brushes.Chocolate.ToString()) == 0) return "Chocolate";
if (string.Compare(value, Brushes.Coral.ToString()) == 0) return "Coral";
if (string.Compare(value, Brushes.CornflowerBlue.ToString()) == 0) return "CornflowerBlue";
if (string.Compare(value, Brushes.Cornsilk.ToString()) == 0) return "Cornsilk";
if (string.Compare(value, Brushes.Crimson.ToString()) == 0) return "Crimson";
if (string.Compare(value, Brushes.Cyan.ToString()) == 0) return "Cyan";
if (string.Compare(value, Brushes.DarkBlue.ToString()) == 0) return "DarkBlue";
if (string.Compare(value, Brushes.DarkCyan.ToString()) == 0) return "DarkCyan";
if (string.Compare(value, Brushes.DarkGoldenrod.ToString()) == 0) return "DarkGoldenrod";
if (string.Compare(value, Brushes.DarkGray.ToString()) == 0) return "DarkGray";
if (string.Compare(value, Brushes.DarkGreen.ToString()) == 0) return "DarkGreen";
if (string.Compare(value, Brushes.DarkKhaki.ToString()) == 0) return "DarkKhaki";
if (string.Compare(value, Brushes.DarkMagenta.ToString()) == 0) return "DarkMagenta";
if (string.Compare(value, Brushes.DarkOliveGreen.ToString()) == 0) return "DarkOliveGreen";
if (string.Compare(value, Brushes.DarkOrange.ToString()) == 0) return "DarkOrange";
if (string.Compare(value, Brushes.DarkOrchid.ToString()) == 0) return "DarkOrchid";
if (string.Compare(value, Brushes.DarkRed.ToString()) == 0) return "DarkRed";
if (string.Compare(value, Brushes.DarkSalmon.ToString()) == 0) return "DarkSalmon";
if (string.Compare(value, Brushes.DarkSeaGreen.ToString()) == 0) return "DarkSeaGreen";
if (string.Compare(value, Brushes.DarkSlateBlue.ToString()) == 0) return "DarkSlateBlue";
if (string.Compare(value, Brushes.DarkSlateGray.ToString()) == 0) return "DarkSlateGray";
if (string.Compare(value, Brushes.DarkTurquoise.ToString()) == 0) return "DarkTurquoise";
if (string.Compare(value, Brushes.DarkViolet.ToString()) == 0) return "DarkViolet";
if (string.Compare(value, Brushes.DeepPink.ToString()) == 0) return "DeepPink";
if (string.Compare(value, Brushes.DeepSkyBlue.ToString()) == 0) return "DeepSkyBlue";
if (string.Compare(value, Brushes.DimGray.ToString()) == 0) return "DimGray";
if (string.Compare(value, Brushes.DodgerBlue.ToString()) == 0) return "DodgerBlue";
if (string.Compare(value, Brushes.Firebrick.ToString()) == 0) return "Firebrick";
if (string.Compare(value, Brushes.FloralWhite.ToString()) == 0) return "FloralWhite";
if (string.Compare(value, Brushes.ForestGreen.ToString()) == 0) return "ForestGreen";
if (string.Compare(value, Brushes.Fuchsia.ToString()) == 0) return "Fuchsia";
if (string.Compare(value, Brushes.Gainsboro.ToString()) == 0) return "Gainsboro";
if (string.Compare(value, Brushes.GhostWhite.ToString()) == 0) return "GhostWhite";
if (string.Compare(value, Brushes.Gold.ToString()) == 0) return "Gold";
if (string.Compare(value, Brushes.Goldenrod.ToString()) == 0) return "Goldenrod";
if (string.Compare(value, Brushes.Gray.ToString()) == 0) return "Gray";
if (string.Compare(value, Brushes.Green.ToString()) == 0) return "Green";
if (string.Compare(value, Brushes.GreenYellow.ToString()) == 0) return "GreenYellow";
if (string.Compare(value, Brushes.Honeydew.ToString()) == 0) return "Honeydew";
if (string.Compare(value, Brushes.HotPink.ToString()) == 0) return "HotPink";
if (string.Compare(value, Brushes.IndianRed.ToString()) == 0) return "IndianRed";
if (string.Compare(value, Brushes.Indigo.ToString()) == 0) return "Indigo";
if (string.Compare(value, Brushes.Ivory.ToString()) == 0) return "Ivory";
if (string.Compare(value, Brushes.Khaki.ToString()) == 0) return "Khaki";
if (string.Compare(value, Brushes.Lavender.ToString()) == 0) return "Lavender";
if (string.Compare(value, Brushes.LavenderBlush.ToString()) == 0) return "LavenderBlush";
if (string.Compare(value, Brushes.LawnGreen.ToString()) == 0) return "LawnGreen";
if (string.Compare(value, Brushes.LemonChiffon.ToString()) == 0) return "LemonChiffon";
if (string.Compare(value, Brushes.LightBlue.ToString()) == 0) return "LightBlue";
if (string.Compare(value, Brushes.LightCoral.ToString()) == 0) return "LightCoral";
if (string.Compare(value, Brushes.LightCyan.ToString()) == 0) return "LightCyan";
if (string.Compare(value, Brushes.LightGoldenrodYellow.ToString()) == 0) return "LightGoldenrodYellow";
if (string.Compare(value, Brushes.LightGray.ToString()) == 0) return "LightGray";
if (string.Compare(value, Brushes.LightGreen.ToString()) == 0) return "LightGreen";
if (string.Compare(value, Brushes.LightPink.ToString()) == 0) return "LightPink";
if (string.Compare(value, Brushes.LightSalmon.ToString()) == 0) return "LightSalmon";
if (string.Compare(value, Brushes.LightSeaGreen.ToString()) == 0) return "LightSeaGreen";
if (string.Compare(value, Brushes.LightSkyBlue.ToString()) == 0) return "LightSkyBlue";
if (string.Compare(value, Brushes.LightSlateGray.ToString()) == 0) return "LightSlateGray";
if (string.Compare(value, Brushes.LightSteelBlue.ToString()) == 0) return "LightSteelBlue";
if (string.Compare(value, Brushes.LightYellow.ToString()) == 0) return "LightYellow";
if (string.Compare(value, Brushes.Lime.ToString()) == 0) return "Lime";
if (string.Compare(value, Brushes.LimeGreen.ToString()) == 0) return "LimeGreen";
if (string.Compare(value, Brushes.Linen.ToString()) == 0) return "Linen";
if (string.Compare(value, Brushes.Magenta.ToString()) == 0) return "Magenta";
if (string.Compare(value, Brushes.Maroon.ToString()) == 0) return "Maroon";
if (string.Compare(value, Brushes.MediumAquamarine.ToString()) == 0) return "MediumAquamarine";
if (string.Compare(value, Brushes.MediumBlue.ToString()) == 0) return "MediumBlue";
if (string.Compare(value, Brushes.MediumOrchid.ToString()) == 0) return "MediumOrchid";
if (string.Compare(value, Brushes.MediumPurple.ToString()) == 0) return "MediumPurple";
if (string.Compare(value, Brushes.MediumSeaGreen.ToString()) == 0) return "MediumSeaGreen";
if (string.Compare(value, Brushes.MediumSlateBlue.ToString()) == 0) return "MediumSlateBlue";
if (string.Compare(value, Brushes.MediumSpringGreen.ToString()) == 0) return "MediumSpringGreen";
if (string.Compare(value, Brushes.MediumTurquoise.ToString()) == 0) return "MediumTurquoise";
if (string.Compare(value, Brushes.MediumVioletRed.ToString()) == 0) return "MediumVioletRed";
if (string.Compare(value, Brushes.MidnightBlue.ToString()) == 0) return "MidnightBlue";
if (string.Compare(value, Brushes.MintCream.ToString()) == 0) return "MintCream";
if (string.Compare(value, Brushes.MistyRose.ToString()) == 0) return "MistyRose";
if (string.Compare(value, Brushes.Moccasin.ToString()) == 0) return "Moccasin";
if (string.Compare(value, Brushes.NavajoWhite.ToString()) == 0) return "NavajoWhite";
if (string.Compare(value, Brushes.Navy.ToString()) == 0) return "Navy";
if (string.Compare(value, Brushes.OldLace.ToString()) == 0) return "OldLace";
if (string.Compare(value, Brushes.Olive.ToString()) == 0) return "Olive";
if (string.Compare(value, Brushes.OliveDrab.ToString()) == 0) return "OliveDrab";
if (string.Compare(value, Brushes.Orange.ToString()) == 0) return "Orange";
if (string.Compare(value, Brushes.OrangeRed.ToString()) == 0) return "OrangeRed";
if (string.Compare(value, Brushes.Orchid.ToString()) == 0) return "Orchid";
if (string.Compare(value, Brushes.PaleGoldenrod.ToString()) == 0) return "PaleGoldenrod";
if (string.Compare(value, Brushes.PaleGreen.ToString()) == 0) return "AntiqueWhite";
if (string.Compare(value, Brushes.PaleTurquoise.ToString()) == 0) return "PaleGreen";
if (string.Compare(value, Brushes.PaleVioletRed.ToString()) == 0) return "PaleVioletRed";
if (string.Compare(value, Brushes.PapayaWhip.ToString()) == 0) return "PapayaWhip";
if (string.Compare(value, Brushes.PeachPuff.ToString()) == 0) return "PeachPuff";
if (string.Compare(value, Brushes.Peru.ToString()) == 0) return "Peru";
if (string.Compare(value, Brushes.Pink.ToString()) == 0) return "Pink";
if (string.Compare(value, Brushes.Plum.ToString()) == 0) return "Plum";
if (string.Compare(value, Brushes.PowderBlue.ToString()) == 0) return "PowderBlue";
if (string.Compare(value, Brushes.Purple.ToString()) == 0) return "Purple";
if (string.Compare(value, Brushes.Red.ToString()) == 0) return "Red";
if (string.Compare(value, Brushes.RosyBrown.ToString()) == 0) return "RosyBrown";
if (string.Compare(value, Brushes.RoyalBlue.ToString()) == 0) return "RoyalBlue";
if (string.Compare(value, Brushes.SaddleBrown.ToString()) == 0) return "SaddleBrown";
if (string.Compare(value, Brushes.Salmon.ToString()) == 0) return "Salmon";
if (string.Compare(value, Brushes.SandyBrown.ToString()) == 0) return "SandyBrown";
if (string.Compare(value, Brushes.SeaGreen.ToString()) == 0) return "SeaGreen";
if (string.Compare(value, Brushes.SeaShell.ToString()) == 0) return "SeaShell";
if (string.Compare(value, Brushes.Sienna.ToString()) == 0) return "Sienna";
if (string.Compare(value, Brushes.Silver.ToString()) == 0) return "Silver";
if (string.Compare(value, Brushes.SkyBlue.ToString()) == 0) return "SkyBlue";
if (string.Compare(value, Brushes.SlateBlue.ToString()) == 0) return "SlateBlue";
if (string.Compare(value, Brushes.SlateGray.ToString()) == 0) return "SlateGray";
if (string.Compare(value, Brushes.Snow.ToString()) == 0) return "Snow";
if (string.Compare(value, Brushes.SpringGreen.ToString()) == 0) return "SpringGreen";
if (string.Compare(value, Brushes.SteelBlue.ToString()) == 0) return "SteelBlue";
if (string.Compare(value, Brushes.Tan.ToString()) == 0) return "Tan";
if (string.Compare(value, Brushes.Teal.ToString()) == 0) return "Teal";
if (string.Compare(value, Brushes.Thistle.ToString()) == 0) return "Thistle";
if (string.Compare(value, Brushes.Tomato.ToString()) == 0) return "Tomato";
if (string.Compare(value, Brushes.Transparent.ToString()) == 0) return "Transparent";
if (string.Compare(value, Brushes.Turquoise.ToString()) == 0) return "Turquoise";
if (string.Compare(value, Brushes.Violet.ToString()) == 0) return "Violet";
if (string.Compare(value, Brushes.Wheat.ToString()) == 0) return "Wheat";
if (string.Compare(value, Brushes.White.ToString()) == 0) return "White";
if (string.Compare(value, Brushes.WhiteSmoke.ToString()) == 0) return "WhiteSmoke";
if (string.Compare(value, Brushes.Yellow.ToString()) == 0) return "Yellow";
if (string.Compare(value, Brushes.YellowGreen.ToString()) == 0) return "YellowGreen";
return "color not specified";
}
public static SolidColorBrush ColorStringToBrushes(string colorString)
{
colorString = colorString.Trim();
if (null != colorString)
{
// We use invariant culture because we don't globalize our color names
string colorUpper = colorString.ToUpper(System.Globalization.CultureInfo.InvariantCulture);
// Use String.Equals because it does explicit equality
// StartsWith/EndsWith are culture sensitive and are 4-7 times slower than Equals
switch (colorUpper.Length)
{
case 3:
if (colorUpper.Equals("RED")) return Brushes.Red;
if (colorUpper.Equals("TAN")) return Brushes.Tan;
break;
case 4:
switch (colorUpper[0])
{
case 'A':
if (colorUpper.Equals("AQUA")) return Brushes.Aqua;
break;
case 'B':
if (colorUpper.Equals("BLUE")) return Brushes.Blue;
break;
case 'C':
if (colorUpper.Equals("CYAN")) return Brushes.Cyan;
break;
case 'G':
if (colorUpper.Equals("GOLD")) return Brushes.Gold;
if (colorUpper.Equals("GRAY")) return Brushes.Gray;
break;
case 'L':
if (colorUpper.Equals("LIME")) return Brushes.Lime;
break;
case 'N':
if (colorUpper.Equals("NAVY")) return Brushes.Navy;
break;
case 'P':
if (colorUpper.Equals("PERU")) return Brushes.Peru;
if (colorUpper.Equals("PINK")) return Brushes.Pink;
if (colorUpper.Equals("PLUM")) return Brushes.Plum;
break;
case 'S':
if (colorUpper.Equals("SNOW")) return Brushes.Snow;
break;
case 'T':
if (colorUpper.Equals("TEAL")) return Brushes.Teal;
break;
}
break;
case 5:
switch (colorUpper[0])
{
case 'A':
if (colorUpper.Equals("AZURE")) return Brushes.Azure;
break;
case 'B':
if (colorUpper.Equals("BEIGE")) return Brushes.Beige;
if (colorUpper.Equals("BLACK")) return Brushes.Black;
if (colorUpper.Equals("BROWN")) return Brushes.Brown;
break;
case 'C':
if (colorUpper.Equals("CORAL")) return Brushes.Coral;
break;
case 'G':
if (colorUpper.Equals("GREEN")) return Brushes.Green;
break;
case 'I':
if (colorUpper.Equals("IVORY")) return Brushes.Ivory;
break;
case 'K':
if (colorUpper.Equals("KHAKI")) return Brushes.Khaki;
break;
case 'L':
if (colorUpper.Equals("LINEN")) return Brushes.Linen;
break;
case 'O':
if (colorUpper.Equals("OLIVE")) return Brushes.Olive;
break;
case 'W':
if (colorUpper.Equals("WHEAT")) return Brushes.Wheat;
if (colorUpper.Equals("WHITE")) return Brushes.White;
break;
}
break;
case 6:
switch (colorUpper[0])
{
case 'B':
if (colorUpper.Equals("BISQUE")) return Brushes.Bisque;
break;
case 'I':
if (colorUpper.Equals("INDIGO")) return Brushes.Indigo;
break;
case 'M':
if (colorUpper.Equals("MAROON")) return Brushes.Maroon;
break;
case 'O':
if (colorUpper.Equals("ORANGE")) return Brushes.Orange;
if (colorUpper.Equals("ORCHID")) return Brushes.Orchid;
break;
case 'P':
if (colorUpper.Equals("PURPLE")) return Brushes.Purple;
break;
case 'S':
if (colorUpper.Equals("SALMON")) return Brushes.Salmon;
if (colorUpper.Equals("SIENNA")) return Brushes.Sienna;
if (colorUpper.Equals("SILVER")) return Brushes.Silver;
break;
case 'T':
if (colorUpper.Equals("TOMATO")) return Brushes.Tomato;
break;
case 'V':
if (colorUpper.Equals("VIOLET")) return Brushes.Violet;
break;
case 'Y':
if (colorUpper.Equals("YELLOW")) return Brushes.Yellow;
break;
}
break;
case 7:
switch (colorUpper[0])
{
case 'C':
if (colorUpper.Equals("CRIMSON")) return Brushes.Crimson;
break;
case 'D':
if (colorUpper.Equals("DARKRED")) return Brushes.DarkRed;
if (colorUpper.Equals("DIMGRAY")) return Brushes.DimGray;
break;
case 'F':
if (colorUpper.Equals("FUCHSIA")) return Brushes.Fuchsia;
break;
case 'H':
if (colorUpper.Equals("HOTPINK")) return Brushes.HotPink;
break;
case 'M':
if (colorUpper.Equals("MAGENTA")) return Brushes.Magenta;
break;
case 'O':
if (colorUpper.Equals("OLDLACE")) return Brushes.OldLace;
break;
case 'S':
if (colorUpper.Equals("SKYBLUE")) return Brushes.SkyBlue;
break;
case 'T':
if (colorUpper.Equals("THISTLE")) return Brushes.Thistle;
break;
}
break;
case 8:
switch (colorUpper[0])
{
case 'C':
if (colorUpper.Equals("CORNSILK")) return Brushes.Cornsilk;
break;
case 'D':
if (colorUpper.Equals("DARKBLUE")) return Brushes.DarkBlue;
if (colorUpper.Equals("DARKCYAN")) return Brushes.DarkCyan;
if (colorUpper.Equals("DARKGRAY")) return Brushes.DarkGray;
if (colorUpper.Equals("DEEPPINK")) return Brushes.DeepPink;
break;
case 'H':
if (colorUpper.Equals("HONEYDEW")) return Brushes.Honeydew;
break;
case 'L':
if (colorUpper.Equals("LAVENDER")) return Brushes.Lavender;
break;
case 'M':
if (colorUpper.Equals("MOCCASIN")) return Brushes.Moccasin;
break;
case 'S':
if (colorUpper.Equals("SEAGREEN")) return Brushes.SeaGreen;
if (colorUpper.Equals("SEASHELL")) return Brushes.SeaShell;
break;
}
break;
case 9:
switch (colorUpper[0])
{
case 'A':
if (colorUpper.Equals("ALICEBLUE")) return Brushes.AliceBlue;
break;
case 'B':
if (colorUpper.Equals("BURLYWOOD")) return Brushes.BurlyWood;
break;
case 'C':
if (colorUpper.Equals("CADETBLUE")) return Brushes.CadetBlue;
if (colorUpper.Equals("CHOCOLATE")) return Brushes.Chocolate;
break;
case 'D':
if (colorUpper.Equals("DARKGREEN")) return Brushes.DarkGreen;
if (colorUpper.Equals("DARKKHAKI")) return Brushes.DarkKhaki;
break;
case 'F':
if (colorUpper.Equals("FIREBRICK")) return Brushes.Firebrick;
break;
case 'G':
if (colorUpper.Equals("GAINSBORO")) return Brushes.Gainsboro;
if (colorUpper.Equals("GOLDENROD")) return Brushes.Goldenrod;
break;
case 'I':
if (colorUpper.Equals("INDIANRED")) return Brushes.IndianRed;
break;
case 'L':
if (colorUpper.Equals("LAWNGREEN")) return Brushes.LawnGreen;
if (colorUpper.Equals("LIGHTBLUE")) return Brushes.LightBlue;
if (colorUpper.Equals("LIGHTCYAN")) return Brushes.LightCyan;
if (colorUpper.Equals("LIGHTGRAY")) return Brushes.LightGray;
if (colorUpper.Equals("LIGHTPINK")) return Brushes.LightPink;
if (colorUpper.Equals("LIMEGREEN")) return Brushes.LimeGreen;
break;
case 'M':
if (colorUpper.Equals("MINTCREAM")) return Brushes.MintCream;
if (colorUpper.Equals("MISTYROSE")) return Brushes.MistyRose;
break;
case 'O':
if (colorUpper.Equals("OLIVEDRAB")) return Brushes.OliveDrab;
if (colorUpper.Equals("ORANGERED")) return Brushes.OrangeRed;
break;
case 'P':
if (colorUpper.Equals("PALEGREEN")) return Brushes.PaleGreen;
if (colorUpper.Equals("PEACHPUFF")) return Brushes.PeachPuff;
break;
case 'R':
if (colorUpper.Equals("ROSYBROWN")) return Brushes.RosyBrown;
if (colorUpper.Equals("ROYALBLUE")) return Brushes.RoyalBlue;
break;
case 'S':
if (colorUpper.Equals("SLATEBLUE")) return Brushes.SlateBlue;
if (colorUpper.Equals("SLATEGRAY")) return Brushes.SlateGray;
if (colorUpper.Equals("STEELBLUE")) return Brushes.SteelBlue;
break;
case 'T':
if (colorUpper.Equals("TURQUOISE")) return Brushes.Turquoise;
break;
}
break;
case 10:
switch (colorUpper[0])
{
case 'A':
if (colorUpper.Equals("AQUAMARINE")) return Brushes.Aquamarine;
break;
case 'B':
if (colorUpper.Equals("BLUEVIOLET")) return Brushes.BlueViolet;
break;
case 'C':
if (colorUpper.Equals("CHARTREUSE")) return Brushes.Chartreuse;
break;
case 'D':
if (colorUpper.Equals("DARKORANGE")) return Brushes.DarkOrange;
if (colorUpper.Equals("DARKORCHID")) return Brushes.DarkOrchid;
if (colorUpper.Equals("DARKSALMON")) return Brushes.DarkSalmon;
if (colorUpper.Equals("DARKVIOLET")) return Brushes.DarkViolet;
if (colorUpper.Equals("DODGERBLUE")) return Brushes.DodgerBlue;
break;
case 'G':
if (colorUpper.Equals("GHOSTWHITE")) return Brushes.GhostWhite;
break;
case 'L':
if (colorUpper.Equals("LIGHTCORAL")) return Brushes.LightCoral;
if (colorUpper.Equals("LIGHTGREEN")) return Brushes.LightGreen;
break;
case 'M':
if (colorUpper.Equals("MEDIUMBLUE")) return Brushes.MediumBlue;
break;
case 'P':
if (colorUpper.Equals("PAPAYAWHIP")) return Brushes.PapayaWhip;
if (colorUpper.Equals("POWDERBLUE")) return Brushes.PowderBlue;
break;
case 'S':
if (colorUpper.Equals("SANDYBROWN")) return Brushes.SandyBrown;
break;
case 'W':
if (colorUpper.Equals("WHITESMOKE")) return Brushes.WhiteSmoke;
break;
}
break;
case 11:
switch (colorUpper[0])
{
case 'D':
if (colorUpper.Equals("DARKMAGENTA")) return Brushes.DarkMagenta;
if (colorUpper.Equals("DEEPSKYBLUE")) return Brushes.DeepSkyBlue;
break;
case 'F':
if (colorUpper.Equals("FLORALWHITE")) return Brushes.FloralWhite;
if (colorUpper.Equals("FORESTGREEN")) return Brushes.ForestGreen;
break;
case 'G':
if (colorUpper.Equals("GREENYELLOW")) return Brushes.GreenYellow;
break;
case 'L':
if (colorUpper.Equals("LIGHTSALMON")) return Brushes.LightSalmon;
if (colorUpper.Equals("LIGHTYELLOW")) return Brushes.LightYellow;
break;
case 'N':
if (colorUpper.Equals("NAVAJOWHITE")) return Brushes.NavajoWhite;
break;
case 'S':
if (colorUpper.Equals("SADDLEBROWN")) return Brushes.SaddleBrown;
if (colorUpper.Equals("SPRINGGREEN")) return Brushes.SpringGreen;
break;
case 'T':
if (colorUpper.Equals("TRANSPARENT")) return Brushes.Transparent;
break;
case 'Y':
if (colorUpper.Equals("YELLOWGREEN")) return Brushes.YellowGreen;
break;
}
break;
case 12:
switch (colorUpper[0])
{
case 'A':
if (colorUpper.Equals("ANTIQUEWHITE")) return Brushes.AntiqueWhite;
break;
case 'D':
if (colorUpper.Equals("DARKSEAGREEN")) return Brushes.DarkSeaGreen;
break;
case 'L':
if (colorUpper.Equals("LIGHTSKYBLUE")) return Brushes.LightSkyBlue;
if (colorUpper.Equals("LEMONCHIFFON")) return Brushes.LemonChiffon;
break;
case 'M':
if (colorUpper.Equals("MEDIUMORCHID")) return Brushes.MediumOrchid;
if (colorUpper.Equals("MEDIUMPURPLE")) return Brushes.MediumPurple;
if (colorUpper.Equals("MIDNIGHTBLUE")) return Brushes.MidnightBlue;
break;
}
break;
case 13:
switch (colorUpper[0])
{
case 'D':
if (colorUpper.Equals("DARKSLATEBLUE")) return Brushes.DarkSlateBlue;
if (colorUpper.Equals("DARKSLATEGRAY")) return Brushes.DarkSlateGray;
if (colorUpper.Equals("DARKGOLDENROD")) return Brushes.DarkGoldenrod;
if (colorUpper.Equals("DARKTURQUOISE")) return Brushes.DarkTurquoise;
break;
case 'L':
if (colorUpper.Equals("LIGHTSEAGREEN")) return Brushes.LightSeaGreen;
if (colorUpper.Equals("LAVENDERBLUSH")) return Brushes.LavenderBlush;
break;
case 'P':
if (colorUpper.Equals("PALEGOLDENROD")) return Brushes.PaleGoldenrod;
if (colorUpper.Equals("PALETURQUOISE")) return Brushes.PaleTurquoise;
if (colorUpper.Equals("PALEVIOLETRED")) return Brushes.PaleVioletRed;
break;
}
break;
case 14:
switch (colorUpper[0])
{
case 'B':
if (colorUpper.Equals("BLANCHEDALMOND")) return Brushes.BlanchedAlmond;
break;
case 'C':
if (colorUpper.Equals("CORNFLOWERBLUE")) return Brushes.CornflowerBlue;
break;
case 'D':
if (colorUpper.Equals("DARKOLIVEGREEN")) return Brushes.DarkOliveGreen;
break;
case 'L':
if (colorUpper.Equals("LIGHTSLATEGRAY")) return Brushes.LightSlateGray;
if (colorUpper.Equals("LIGHTSTEELBLUE")) return Brushes.LightSteelBlue;
break;
case 'M':
if (colorUpper.Equals("MEDIUMSEAGREEN")) return Brushes.MediumSeaGreen;
break;
}
break;
case 15:
if (colorUpper.Equals("MEDIUMSLATEBLUE")) return Brushes.MediumSlateBlue;
if (colorUpper.Equals("MEDIUMTURQUOISE")) return Brushes.MediumTurquoise;
if (colorUpper.Equals("MEDIUMVIOLETRED")) return Brushes.MediumVioletRed;
break;
case 16:
if (colorUpper.Equals("MEDIUMAQUAMARINE")) return Brushes.MediumAquamarine;
break;
case 17:
if (colorUpper.Equals("MEDIUMSPRINGGREEN")) return Brushes.MediumSpringGreen;
break;
case 20:
if (colorUpper.Equals("LIGHTGOLDENRODYELLOW")) return Brushes.LightGoldenrodYellow;
break;
}
}
return null;
}
public static List<UIElement> UIElementsInElement(FrameworkContentElement parent)
{
List<UIElement> UIEresults = new List<UIElement>();
GetUIElementsRecursively(parent as DependencyObject, UIEresults);
return UIEresults;
}
static void GetUIElementsRecursively(DependencyObject dObj, List<UIElement> UIresults)
{
if (dObj == null)
{
return;
}
UIElement uiElement = dObj as UIElement;
if (uiElement != null)
{
UIresults.Add(uiElement);
}
foreach (object o in LogicalTreeHelper.GetChildren(dObj))
{
GetUIElementsRecursively(o as DependencyObject, UIresults);
}
}
static void GetContentElementsRecursively(DependencyObject dObj, List<ContentElement> CEresults)
{
if (dObj == null)
{
return;
}
ContentElement ceElement = dObj as ContentElement;
if (ceElement != null)
{
CEresults.Add(ceElement);
}
foreach (object o in LogicalTreeHelper.GetChildren(dObj))
{
GetContentElementsRecursively(o as DependencyObject, CEresults);
}
}
static public bool IsParagraphEmpty(Paragraph suspect)
{
if (suspect.Inlines.Count == 0)
return true;
if (suspect.Inlines.Count == 1)
{
Run r = suspect.Inlines.FirstInline as Run;
if (r != null)
{
if (r.Text == "")
{
return true;
}
}
}
return false;
}
static void FindParentParagraph(Span child, ref Paragraph parent)
{
if (child.Parent is Paragraph)
{
parent = child.Parent as Paragraph;
return;
}
else
{
FindParentParagraph(child.Parent as Span, ref parent);
}
}
}
}
| |
// Engine r29
#define RunUo2_0
using System;
using System.Collections.Generic;
using Server;
using Server.Gumps;
using Server.Network;
using Server.Commands;
namespace Server.Gumps
{
public class SpawnUOMLGump : Gump
{
Mobile caller;
public static void Initialize()
{
#if(RunUo2_0)
CommandSystem.Register("SpawnUOML", AccessLevel.Administrator, new CommandEventHandler(SpawnUOML_OnCommand));
#else
Register("SpawnUOML", AccessLevel.Administrator, new CommandEventHandler(SpawnUOML_OnCommand));
#endif
}
[Usage("SpawnUOML")]
[Description("Generate PremiumSpawners around the world with a gump.")]
public static void SpawnUOML_OnCommand(CommandEventArgs e)
{
Mobile from = e.Mobile;
if (from.HasGump(typeof(SpawnUOMLGump)))
from.CloseGump(typeof(SpawnUOMLGump));
from.SendGump(new SpawnUOMLGump(from));
}
public SpawnUOMLGump(Mobile from) : this()
{
caller = from;
}
public void AddBlackAlpha( int x, int y, int width, int height )
{
AddImageTiled( x, y, width, height, 2624 );
AddAlphaRegion( x, y, width, height );
}
public SpawnUOMLGump() : base( 30, 30 )
{
this.Closable=true;
this.Disposable=true;
this.Dragable=true;
AddPage(1);
AddBackground(58, 22, 474, 540, 9200);
AddImage(305, 306, 1418); // Castle
AddBlackAlpha(66, 30, 458, 33);
AddLabel(213, 37, 52, @"SELECT MAPS TO SPAWN");
AddBlackAlpha(66, 87, 239, 447);
AddLabel(69, 67, 200, @"DUNGEONS");
AddLabel(69, 90, 52, @"Blighted Grove");
AddLabel(69, 112, 52, @"Britain Sewer");
AddLabel(69, 133, 52, @"Covetous");
AddLabel(69, 154, 52, @"Deceit");
AddLabel(69, 174, 52, @"Despise");
AddLabel(69, 196, 52, @"Destard");
AddLabel(69, 217, 52, @"Fire");
AddLabel(69, 237, 52, @"Graveyards");
AddLabel(69, 258, 52, @"Hythloth");
AddLabel(69, 280, 52, @"Ice");
AddLabel(69, 301, 52, @"Khaldun");
AddLabel(69, 322, 52, @"Orc Caves");
AddLabel(69, 343, 52, @"Painted Caves");
AddLabel(69, 363, 52, @"Palace of Paroxysmus");
AddLabel(69, 384, 52, @"Prism of Light");
AddLabel(69, 405, 52, @"Sanctuary");
AddLabel(69, 427, 52, @"Shame");
AddLabel(69, 448, 52, @"Solen Hive");
AddLabel(69, 469, 52, @"Terathan Keep");
AddLabel(69, 489, 52, @"Trinsic Passage");
AddLabel(69, 510, 52, @"Wrong");
AddLabel(194, 66, 200, @"Felucca");
AddCheck(210, 91, 210, 211, true, 201);
AddCheck(210, 112, 210, 211, true, 202);
AddCheck(210, 133, 210, 211, true, 203);
AddCheck(210, 154, 210, 211, true, 204);
AddCheck(210, 175, 210, 211, true, 205);
AddCheck(210, 196, 210, 211, true, 206);
AddCheck(210, 217, 210, 211, true, 207);
AddCheck(210, 238, 210, 211, true, 208);
AddCheck(210, 259, 210, 211, true, 209);
AddCheck(210, 280, 210, 211, true, 210);
AddCheck(210, 301, 210, 211, true, 228);
AddCheck(210, 322, 210, 211, true, 212);
AddCheck(210, 343, 210, 211, true, 214);
AddCheck(210, 364, 210, 211, true, 215);
AddCheck(210, 385, 210, 211, true, 216);
AddCheck(210, 406, 210, 211, true, 217);
AddCheck(210, 427, 210, 211, true, 219);
AddCheck(210, 448, 210, 211, true, 220);
AddCheck(210, 469, 210, 211, true, 221);
AddCheck(210, 490, 210, 211, true, 224);
AddCheck(210, 511, 210, 211, true, 227);
AddLabel(250, 66, 200, @"Trammel");
AddCheck(268, 91, 210, 211, true, 101);
AddCheck(268, 112, 210, 211, true, 102);
AddCheck(268, 133, 210, 211, true, 103);
AddCheck(268, 154, 210, 211, true, 104);
AddCheck(268, 175, 210, 211, true, 105);
AddCheck(268, 196, 210, 211, true, 106);
AddCheck(268, 217, 210, 211, true, 107);
AddCheck(268, 238, 210, 211, true, 108);
AddCheck(268, 259, 210, 211, true, 109);
AddCheck(268, 280, 210, 211, true, 110);
//There is no Khaldun in Trammel (ID 128 reserved)
AddCheck(268, 322, 210, 211, true, 112);
AddCheck(268, 343, 210, 211, true, 114);
AddCheck(268, 364, 210, 211, true, 115);
AddCheck(268, 385, 210, 211, true, 116);
AddCheck(268, 406, 210, 211, true, 117);
AddCheck(268, 427, 210, 211, true, 119);
AddCheck(268, 448, 210, 211, true, 120);
AddCheck(268, 469, 210, 211, true, 121);
AddCheck(268, 490, 210, 211, true, 124);
AddCheck(268, 511, 210, 211, true, 127);
AddBlackAlpha(311, 87, 213, 70);
AddLabel(315, 67, 200, @"TOWNS");
AddLabel(315, 91, 52, @"Animals");
AddLabel(315, 112, 52, @"People (*)");
AddLabel(315, 133, 52, @"Vendors");
AddLabel(413, 66, 200, @"Felucca");
AddCheck(429, 91, 210, 211, true, 222);
AddCheck(429, 112, 210, 211, true, 223);
AddCheck(429, 133, 210, 211, true, 225);
AddLabel(469, 66, 200, @"Trammel");
AddCheck(487, 91, 210, 211, true, 122);
AddCheck(487, 112, 210, 211, true, 123);
AddCheck(487, 133, 210, 211, true, 125);
AddBlackAlpha(311, 183, 213, 114);
AddLabel(315, 162, 200, @"OUTDOORS");
AddLabel(316, 187, 52, @"Animals");
AddLabel(316, 207, 52, @"Lost Lands");
AddLabel(316, 229, 52, @"Monsters");
AddLabel(316, 249, 52, @"Reagents");
AddLabel(316, 270, 52, @"Sea Life");
AddLabel(413, 162, 200, @"Felucca");
AddCheck(429, 187, 210, 211, true, 226);
AddCheck(429, 208, 210, 211, true, 211);
AddCheck(429, 229, 210, 211, true, 213);
AddCheck(429, 250, 210, 211, true, 229);
AddCheck(429, 271, 210, 211, true, 218);
AddLabel(469, 162, 200, @"Trammel");
AddCheck(487, 187, 210, 211, true, 126);
AddCheck(487, 208, 210, 211, true, 111);
AddCheck(487, 229, 210, 211, true, 113);
AddCheck(487, 250, 210, 211, true, 129);
AddCheck(487, 271, 210, 211, true, 118);
AddLabel(316, 305, 200, @"(*) Escortables, Hireables,");
AddLabel(316, 324, 200, @"Town Criers, Order and Chaos");
AddLabel(316, 344, 200, @"guards etc.");
// END
AddLabel(361, 453, 52, @"Page: 1/2"); //Page
AddButton(423, 455, 5601, 5605, 0, GumpButtonType.Page, 2); // Change Page
//PAGE 2
AddPage(2);
AddBackground(58, 22, 474, 540, 9200);
AddImage(305, 306, 1418); // Castle
AddBlackAlpha(66, 30, 458, 33);
AddLabel(213, 37, 52, @"SELECT MAPS TO SPAWN");
AddBlackAlpha(66, 87, 174, 300);
AddLabel(74, 67, 200, @"ILSHENAR");
AddLabel(74, 90, 52, @"Ancient Lair");
AddLabel(74, 112, 52, @"Ankh");
AddLabel(74, 133, 52, @"Blood");
AddLabel(74, 154, 52, @"Exodus");
AddLabel(74, 174, 52, @"Mushroom");
AddLabel(74, 196, 52, @"Outdoors");
AddLabel(74, 217, 52, @"Ratman Cave");
AddLabel(74, 237, 52, @"Rock");
AddLabel(74, 258, 52, @"Sorcerers");
AddLabel(74, 280, 52, @"Spectre");
AddLabel(74, 301, 52, @"Towns");
AddLabel(74, 322, 52, @"Twisted Weald");
AddLabel(74, 343, 52, @"Vendors");
AddLabel(74, 363, 52, @"Wisp");
AddCheck(215, 91, 210, 211, true, 301);
AddCheck(215, 112, 210, 211, true, 302);
AddCheck(215, 133, 210, 211, true, 303);
AddCheck(215, 154, 210, 211, true, 304);
AddCheck(215, 175, 210, 211, true, 305);
AddCheck(215, 196, 210, 211, true, 306);
AddCheck(215, 217, 210, 211, true, 307);
AddCheck(215, 238, 210, 211, true, 308);
AddCheck(215, 259, 210, 211, true, 309);
AddCheck(215, 280, 210, 211, true, 310);
AddCheck(215, 301, 210, 211, true, 311);
AddCheck(215, 322, 210, 211, true, 314);
AddCheck(215, 343, 210, 211, true, 312);
AddCheck(215, 364, 210, 211, true, 313);
AddBlackAlpha(66, 414, 174, 133);
AddLabel(74, 393, 200, @"TOKUNO");
AddLabel(74, 416, 52, @"Fan Dancers Dojo");
AddLabel(74, 438, 52, @"Outdoors");
AddLabel(74, 459, 52, @"Towns Life");
AddLabel(74, 480, 52, @"Vendors");
AddLabel(74, 500, 52, @"Wild Life");
AddLabel(74, 522, 52, @"Yomutso Mines");
AddCheck(215, 417, 210, 211, true, 501);
AddCheck(215, 438, 210, 211, true, 502);
AddCheck(215, 459, 210, 211, true, 503);
AddCheck(215, 480, 210, 211, true, 504);
AddCheck(215, 501, 210, 211, true, 505);
AddCheck(215, 522, 210, 211, true, 506);
AddBlackAlpha(246, 87, 174, 156);
AddLabel(253, 67, 200, @"MALAS");
AddLabel(253, 90, 52, @"Citadel");
AddLabel(253, 112, 52, @"Doom");
AddLabel(253, 133, 52, @"Labyrinth");
AddLabel(253, 154, 52, @"North (*)");
AddLabel(253, 174, 52, @"Orc Forts");
AddLabel(253, 196, 52, @"South (*)");
AddLabel(253, 217, 52, @"Vendors");
AddCheck(394, 91, 210, 211, true, 406);
AddCheck(394, 112, 210, 211, true, 401);
AddCheck(394, 133, 210, 211, true, 407);
AddCheck(394, 154, 210, 211, true, 402);
AddCheck(394, 175, 210, 211, true, 403);
AddCheck(394, 196, 210, 211, true, 404);
AddCheck(394, 217, 210, 211, true, 405);
AddLabel(428, 91, 200, @"(*) Wild");
AddLabel(428, 109, 200, @"Animals and");
AddLabel(428, 129, 200, @"monsters.");
//END
AddLabel(381, 453, 52, @"Page: 2/2"); //Page
AddButton(361, 455, 5603, 5607, 0, GumpButtonType.Page, 1); //Change Page
AddButton(282, 452, 240, 239, 1, GumpButtonType.Reply, 0); // Apply
}
public static void SpawnThis( Mobile from, List<int> ListSwitches, int switche, int map, string mapfile)
{
string folder = "";
if( map == 1 )
folder = "felucca";
else if( map == 2)
folder = "trammel";
else if( map == 3)
folder = "ilshenar";
else if( map == 4)
folder = "malas";
else if( map == 5)
folder = "tokuno";
string prefix = Server.Commands.CommandSystem.Prefix;
if( ListSwitches.Contains( switche ) == true )
CommandSystem.Handle( from, String.Format( "{0}Spawngen uoml/{1}/{2}.map", prefix, folder, mapfile ) );
}
public override void OnResponse(NetState sender, RelayInfo info)
{
Mobile from = sender.Mobile;
switch(info.ButtonID)
{
case 0: //Closed or Cancel
{
break;
}
default:
{
// Make sure that the APPLY button was pressed
if( info.ButtonID == 1 )
{
// Get the array of switches selected
List<int> Selections = new List<int>( info.Switches );
//TRAMMEL
from.Say( "SPAWNING TRAMMEL..." );
// DUNGEONS
SpawnThis(from, Selections, 101, 2, "BlightedGrove");
SpawnThis(from, Selections, 102, 2, "BritainSewer");
SpawnThis(from, Selections, 103, 2, "Covetous");
SpawnThis(from, Selections, 104, 2, "Deceit");
SpawnThis(from, Selections, 105, 2, "Despise");
SpawnThis(from, Selections, 106, 2, "Destard");
SpawnThis(from, Selections, 107, 2, "Fire");
SpawnThis(from, Selections, 108, 2, "Graveyards");
SpawnThis(from, Selections, 109, 2, "Hythloth");
SpawnThis(from, Selections, 110, 2, "Ice");
//There is no Khaldun (118)
SpawnThis(from, Selections, 112, 2, "OrcCaves");
SpawnThis(from, Selections, 114, 2, "PaintedCaves");
SpawnThis(from, Selections, 115, 2, "PalaceOfParoxysmus");
SpawnThis(from, Selections, 116, 2, "PrismOfLight");
SpawnThis(from, Selections, 117, 2, "Sanctuary");
SpawnThis(from, Selections, 119, 2, "Shame");
SpawnThis(from, Selections, 120, 2, "SolenHive");
SpawnThis(from, Selections, 121, 2, "TerathanKeep");
SpawnThis(from, Selections, 124, 2, "TrinsicPassage");
SpawnThis(from, Selections, 127, 2, "Wrong");
//TOWNS
SpawnThis(from, Selections, 122, 2, "TownsLife");
SpawnThis(from, Selections, 123, 2, "TownsPeople");
SpawnThis(from, Selections, 125, 2, "Vendors");
//OUTDOORS
SpawnThis(from, Selections, 126, 2, "WildLife");
SpawnThis(from, Selections, 111, 2, "LostLands");
SpawnThis(from, Selections, 113, 2, "Outdoors");
SpawnThis(from, Selections, 129, 2, "Reagents");
SpawnThis(from, Selections, 118, 2, "SeaLife");
//FELUCCA
from.Say( "SPAWNING FELUCCA..." );
// DUNGEONS
SpawnThis(from, Selections, 201, 1, "BlightedGrove");
SpawnThis(from, Selections, 202, 1, "BritainSewer");
SpawnThis(from, Selections, 203, 1, "Covetous");
SpawnThis(from, Selections, 204, 1, "Deceit");
SpawnThis(from, Selections, 205, 1, "Despise");
SpawnThis(from, Selections, 206, 1, "Destard");
SpawnThis(from, Selections, 207, 1, "Fire");
SpawnThis(from, Selections, 208, 1, "Graveyards");
SpawnThis(from, Selections, 209, 1, "Hythloth");
SpawnThis(from, Selections, 210, 1, "Ice");
SpawnThis(from, Selections, 229, 1, "Khaldun");
SpawnThis(from, Selections, 212, 1, "OrcCaves");
SpawnThis(from, Selections, 214, 1, "PaintedCaves");
SpawnThis(from, Selections, 215, 1, "PalaceOfParoxysmus");
SpawnThis(from, Selections, 216, 1, "PrismOfLight");
SpawnThis(from, Selections, 217, 1, "Sanctuary");
SpawnThis(from, Selections, 219, 1, "Shame");
SpawnThis(from, Selections, 220, 1, "SolenHive");
SpawnThis(from, Selections, 221, 1, "TerathanKeep");
SpawnThis(from, Selections, 224, 1, "TrinsicPassage");
SpawnThis(from, Selections, 227, 1, "Wrong");
//TOWNS
SpawnThis(from, Selections, 222, 1, "TownsLife");
SpawnThis(from, Selections, 223, 1, "TownsPeople");
SpawnThis(from, Selections, 225, 1, "Vendors");
//OUTDOORS
SpawnThis(from, Selections, 226, 1, "WildLife");
SpawnThis(from, Selections, 211, 1, "LostLands");
SpawnThis(from, Selections, 213, 1, "Outdoors");
SpawnThis(from, Selections, 229, 1, "Reagents");
SpawnThis(from, Selections, 218, 1, "SeaLife");
//ILSHENAR
from.Say( "SPAWNING ILSHENAR..." );
SpawnThis(from, Selections, 301, 3, "Ancientlair");
SpawnThis(from, Selections, 302, 3, "Ankh");
SpawnThis(from, Selections, 303, 3, "Blood");
SpawnThis(from, Selections, 304, 3, "Exodus");
SpawnThis(from, Selections, 305, 3, "Mushroom");
SpawnThis(from, Selections, 306, 3, "Outdoors");
SpawnThis(from, Selections, 307, 3, "Ratmancave");
SpawnThis(from, Selections, 308, 3, "Rock");
SpawnThis(from, Selections, 309, 3, "Sorcerers");
SpawnThis(from, Selections, 310, 3, "Spectre");
SpawnThis(from, Selections, 311, 3, "Towns");
SpawnThis(from, Selections, 314, 3, "TwistedWeald");
SpawnThis(from, Selections, 312, 3, "Vendors");
SpawnThis(from, Selections, 313, 3, "Wisp");
//MALAS
from.Say( "SPAWNING MALAS..." );
SpawnThis(from, Selections, 406, 4, "Citadel");
SpawnThis(from, Selections, 401, 4, "Doom");
SpawnThis(from, Selections, 407, 4, "Labyrinth");
SpawnThis(from, Selections, 402, 4, "North");
SpawnThis(from, Selections, 403, 4, "OrcForts");
SpawnThis(from, Selections, 404, 4, "South");
SpawnThis(from, Selections, 405, 4, "Vendors");
//TOKUNO
from.Say( "SPAWNING TOKUNO..." );
SpawnThis(from, Selections, 501, 5, "FanDancersDojo");
SpawnThis(from, Selections, 502, 5, "Outdoors");
SpawnThis(from, Selections, 503, 5, "TownsLife");
SpawnThis(from, Selections, 504, 5, "Vendors");
SpawnThis(from, Selections, 505, 5, "WildLife");
SpawnThis(from, Selections, 506, 5, "YomutsoMines");
from.Say( "SPAWN GENERATION COMPLETED" );
}
break;
}
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
/*============================================================
**
**
**
**
**
** Purpose: class to sort arrays
**
**
===========================================================*/
using System;
using System.Globalization;
using System.Runtime.CompilerServices;
using System.Diagnostics;
using System.Runtime.Versioning;
namespace System.Collections.Generic
{
#region ArraySortHelper for single arrays
internal interface IArraySortHelper<TKey>
{
void Sort(TKey[] keys, int index, int length, IComparer<TKey> comparer);
int BinarySearch(TKey[] keys, int index, int length, TKey value, IComparer<TKey> comparer);
}
internal static class IntrospectiveSortUtilities
{
// This is the threshold where Introspective sort switches to Insertion sort.
// Empirically, 16 seems to speed up most cases without slowing down others, at least for integers.
// Large value types may benefit from a smaller number.
internal const int IntrosortSizeThreshold = 16;
internal static int FloorLog2PlusOne(int n)
{
int result = 0;
while (n >= 1)
{
result++;
n = n / 2;
}
return result;
}
internal static void ThrowOrIgnoreBadComparer(Object comparer)
{
throw new ArgumentException(SR.Format(SR.Arg_BogusIComparer, comparer));
}
}
[TypeDependencyAttribute("System.Collections.Generic.GenericArraySortHelper`1")]
internal class ArraySortHelper<T>
: IArraySortHelper<T>
{
private static volatile IArraySortHelper<T> defaultArraySortHelper;
public static IArraySortHelper<T> Default
{
get
{
IArraySortHelper<T> sorter = defaultArraySortHelper;
if (sorter == null)
sorter = CreateArraySortHelper();
return sorter;
}
}
private static IArraySortHelper<T> CreateArraySortHelper()
{
if (typeof(IComparable<T>).IsAssignableFrom(typeof(T)))
{
defaultArraySortHelper = (IArraySortHelper<T>)RuntimeTypeHandle.Allocate(typeof(GenericArraySortHelper<string>).TypeHandle.Instantiate(new Type[] { typeof(T) }));
}
else
{
defaultArraySortHelper = new ArraySortHelper<T>();
}
return defaultArraySortHelper;
}
#region IArraySortHelper<T> Members
public void Sort(T[] keys, int index, int length, IComparer<T> comparer)
{
Debug.Assert(keys != null, "Check the arguments in the caller!");
Debug.Assert(index >= 0 && length >= 0 && (keys.Length - index >= length), "Check the arguments in the caller!");
// Add a try block here to detect IComparers (or their
// underlying IComparables, etc) that are bogus.
try
{
if (comparer == null)
{
comparer = Comparer<T>.Default;
}
IntrospectiveSort(keys, index, length, comparer.Compare);
}
catch (IndexOutOfRangeException)
{
IntrospectiveSortUtilities.ThrowOrIgnoreBadComparer(comparer);
}
catch (Exception e)
{
throw new InvalidOperationException(SR.InvalidOperation_IComparerFailed, e);
}
}
public int BinarySearch(T[] array, int index, int length, T value, IComparer<T> comparer)
{
try
{
if (comparer == null)
{
comparer = Comparer<T>.Default;
}
return InternalBinarySearch(array, index, length, value, comparer);
}
catch (Exception e)
{
throw new InvalidOperationException(SR.InvalidOperation_IComparerFailed, e);
}
}
#endregion
internal static void Sort(T[] keys, int index, int length, Comparison<T> comparer)
{
Debug.Assert(keys != null, "Check the arguments in the caller!");
Debug.Assert(index >= 0 && length >= 0 && (keys.Length - index >= length), "Check the arguments in the caller!");
Debug.Assert(comparer != null, "Check the arguments in the caller!");
// Add a try block here to detect bogus comparisons
try
{
IntrospectiveSort(keys, index, length, comparer);
}
catch (IndexOutOfRangeException)
{
IntrospectiveSortUtilities.ThrowOrIgnoreBadComparer(comparer);
}
catch (Exception e)
{
throw new InvalidOperationException(SR.InvalidOperation_IComparerFailed, e);
}
}
internal static int InternalBinarySearch(T[] array, int index, int length, T value, IComparer<T> comparer)
{
Debug.Assert(array != null, "Check the arguments in the caller!");
Debug.Assert(index >= 0 && length >= 0 && (array.Length - index >= length), "Check the arguments in the caller!");
int lo = index;
int hi = index + length - 1;
while (lo <= hi)
{
int i = lo + ((hi - lo) >> 1);
int order = comparer.Compare(array[i], value);
if (order == 0) return i;
if (order < 0)
{
lo = i + 1;
}
else
{
hi = i - 1;
}
}
return ~lo;
}
private static void SwapIfGreater(T[] keys, Comparison<T> comparer, int a, int b)
{
if (a != b)
{
if (comparer(keys[a], keys[b]) > 0)
{
T key = keys[a];
keys[a] = keys[b];
keys[b] = key;
}
}
}
private static void Swap(T[] a, int i, int j)
{
if (i != j)
{
T t = a[i];
a[i] = a[j];
a[j] = t;
}
}
internal static void IntrospectiveSort(T[] keys, int left, int length, Comparison<T> comparer)
{
Debug.Assert(keys != null);
Debug.Assert(comparer != null);
Debug.Assert(left >= 0);
Debug.Assert(length >= 0);
Debug.Assert(length <= keys.Length);
Debug.Assert(length + left <= keys.Length);
if (length < 2)
return;
IntroSort(keys, left, length + left - 1, 2 * IntrospectiveSortUtilities.FloorLog2PlusOne(length), comparer);
}
private static void IntroSort(T[] keys, int lo, int hi, int depthLimit, Comparison<T> comparer)
{
Debug.Assert(keys != null);
Debug.Assert(comparer != null);
Debug.Assert(lo >= 0);
Debug.Assert(hi < keys.Length);
while (hi > lo)
{
int partitionSize = hi - lo + 1;
if (partitionSize <= IntrospectiveSortUtilities.IntrosortSizeThreshold)
{
if (partitionSize == 1)
{
return;
}
if (partitionSize == 2)
{
SwapIfGreater(keys, comparer, lo, hi);
return;
}
if (partitionSize == 3)
{
SwapIfGreater(keys, comparer, lo, hi - 1);
SwapIfGreater(keys, comparer, lo, hi);
SwapIfGreater(keys, comparer, hi - 1, hi);
return;
}
InsertionSort(keys, lo, hi, comparer);
return;
}
if (depthLimit == 0)
{
Heapsort(keys, lo, hi, comparer);
return;
}
depthLimit--;
int p = PickPivotAndPartition(keys, lo, hi, comparer);
// Note we've already partitioned around the pivot and do not have to move the pivot again.
IntroSort(keys, p + 1, hi, depthLimit, comparer);
hi = p - 1;
}
}
private static int PickPivotAndPartition(T[] keys, int lo, int hi, Comparison<T> comparer)
{
Debug.Assert(keys != null);
Debug.Assert(comparer != null);
Debug.Assert(lo >= 0);
Debug.Assert(hi > lo);
Debug.Assert(hi < keys.Length);
// Compute median-of-three. But also partition them, since we've done the comparison.
int middle = lo + ((hi - lo) / 2);
// Sort lo, mid and hi appropriately, then pick mid as the pivot.
SwapIfGreater(keys, comparer, lo, middle); // swap the low with the mid point
SwapIfGreater(keys, comparer, lo, hi); // swap the low with the high
SwapIfGreater(keys, comparer, middle, hi); // swap the middle with the high
T pivot = keys[middle];
Swap(keys, middle, hi - 1);
int left = lo, right = hi - 1; // We already partitioned lo and hi and put the pivot in hi - 1. And we pre-increment & decrement below.
while (left < right)
{
while (comparer(keys[++left], pivot) < 0) ;
while (comparer(pivot, keys[--right]) < 0) ;
if (left >= right)
break;
Swap(keys, left, right);
}
// Put pivot in the right location.
Swap(keys, left, (hi - 1));
return left;
}
private static void Heapsort(T[] keys, int lo, int hi, Comparison<T> comparer)
{
Debug.Assert(keys != null);
Debug.Assert(comparer != null);
Debug.Assert(lo >= 0);
Debug.Assert(hi > lo);
Debug.Assert(hi < keys.Length);
int n = hi - lo + 1;
for (int i = n / 2; i >= 1; i = i - 1)
{
DownHeap(keys, i, n, lo, comparer);
}
for (int i = n; i > 1; i = i - 1)
{
Swap(keys, lo, lo + i - 1);
DownHeap(keys, 1, i - 1, lo, comparer);
}
}
private static void DownHeap(T[] keys, int i, int n, int lo, Comparison<T> comparer)
{
Debug.Assert(keys != null);
Debug.Assert(comparer != null);
Debug.Assert(lo >= 0);
Debug.Assert(lo < keys.Length);
T d = keys[lo + i - 1];
int child;
while (i <= n / 2)
{
child = 2 * i;
if (child < n && comparer(keys[lo + child - 1], keys[lo + child]) < 0)
{
child++;
}
if (!(comparer(d, keys[lo + child - 1]) < 0))
break;
keys[lo + i - 1] = keys[lo + child - 1];
i = child;
}
keys[lo + i - 1] = d;
}
private static void InsertionSort(T[] keys, int lo, int hi, Comparison<T> comparer)
{
Debug.Assert(keys != null);
Debug.Assert(lo >= 0);
Debug.Assert(hi >= lo);
Debug.Assert(hi <= keys.Length);
int i, j;
T t;
for (i = lo; i < hi; i++)
{
j = i;
t = keys[i + 1];
while (j >= lo && comparer(t, keys[j]) < 0)
{
keys[j + 1] = keys[j];
j--;
}
keys[j + 1] = t;
}
}
}
internal class GenericArraySortHelper<T>
: IArraySortHelper<T>
where T : IComparable<T>
{
// Do not add a constructor to this class because ArraySortHelper<T>.CreateSortHelper will not execute it
#region IArraySortHelper<T> Members
public void Sort(T[] keys, int index, int length, IComparer<T> comparer)
{
Debug.Assert(keys != null, "Check the arguments in the caller!");
Debug.Assert(index >= 0 && length >= 0 && (keys.Length - index >= length), "Check the arguments in the caller!");
try
{
if (comparer == null || comparer == Comparer<T>.Default)
{
IntrospectiveSort(keys, index, length);
}
else
{
ArraySortHelper<T>.IntrospectiveSort(keys, index, length, comparer.Compare);
}
}
catch (IndexOutOfRangeException)
{
IntrospectiveSortUtilities.ThrowOrIgnoreBadComparer(comparer);
}
catch (Exception e)
{
throw new InvalidOperationException(SR.InvalidOperation_IComparerFailed, e);
}
}
public int BinarySearch(T[] array, int index, int length, T value, IComparer<T> comparer)
{
Debug.Assert(array != null, "Check the arguments in the caller!");
Debug.Assert(index >= 0 && length >= 0 && (array.Length - index >= length), "Check the arguments in the caller!");
try
{
if (comparer == null || comparer == Comparer<T>.Default)
{
return BinarySearch(array, index, length, value);
}
else
{
return ArraySortHelper<T>.InternalBinarySearch(array, index, length, value, comparer);
}
}
catch (Exception e)
{
throw new InvalidOperationException(SR.InvalidOperation_IComparerFailed, e);
}
}
#endregion
// This function is called when the user doesn't specify any comparer.
// Since T is constrained here, we can call IComparable<T>.CompareTo here.
// We can avoid boxing for value type and casting for reference types.
private static int BinarySearch(T[] array, int index, int length, T value)
{
int lo = index;
int hi = index + length - 1;
while (lo <= hi)
{
int i = lo + ((hi - lo) >> 1);
int order;
if (array[i] == null)
{
order = (value == null) ? 0 : -1;
}
else
{
order = array[i].CompareTo(value);
}
if (order == 0)
{
return i;
}
if (order < 0)
{
lo = i + 1;
}
else
{
hi = i - 1;
}
}
return ~lo;
}
private static void SwapIfGreaterWithItems(T[] keys, int a, int b)
{
Debug.Assert(keys != null);
Debug.Assert(0 <= a && a < keys.Length);
Debug.Assert(0 <= b && b < keys.Length);
if (a != b)
{
if (keys[a] != null && keys[a].CompareTo(keys[b]) > 0)
{
T key = keys[a];
keys[a] = keys[b];
keys[b] = key;
}
}
}
private static void Swap(T[] a, int i, int j)
{
if (i != j)
{
T t = a[i];
a[i] = a[j];
a[j] = t;
}
}
internal static void IntrospectiveSort(T[] keys, int left, int length)
{
Debug.Assert(keys != null);
Debug.Assert(left >= 0);
Debug.Assert(length >= 0);
Debug.Assert(length <= keys.Length);
Debug.Assert(length + left <= keys.Length);
if (length < 2)
return;
IntroSort(keys, left, length + left - 1, 2 * IntrospectiveSortUtilities.FloorLog2PlusOne(length));
}
private static void IntroSort(T[] keys, int lo, int hi, int depthLimit)
{
Debug.Assert(keys != null);
Debug.Assert(lo >= 0);
Debug.Assert(hi < keys.Length);
while (hi > lo)
{
int partitionSize = hi - lo + 1;
if (partitionSize <= IntrospectiveSortUtilities.IntrosortSizeThreshold)
{
if (partitionSize == 1)
{
return;
}
if (partitionSize == 2)
{
SwapIfGreaterWithItems(keys, lo, hi);
return;
}
if (partitionSize == 3)
{
SwapIfGreaterWithItems(keys, lo, hi - 1);
SwapIfGreaterWithItems(keys, lo, hi);
SwapIfGreaterWithItems(keys, hi - 1, hi);
return;
}
InsertionSort(keys, lo, hi);
return;
}
if (depthLimit == 0)
{
Heapsort(keys, lo, hi);
return;
}
depthLimit--;
int p = PickPivotAndPartition(keys, lo, hi);
// Note we've already partitioned around the pivot and do not have to move the pivot again.
IntroSort(keys, p + 1, hi, depthLimit);
hi = p - 1;
}
}
private static int PickPivotAndPartition(T[] keys, int lo, int hi)
{
Debug.Assert(keys != null);
Debug.Assert(lo >= 0);
Debug.Assert(hi > lo);
Debug.Assert(hi < keys.Length);
// Compute median-of-three. But also partition them, since we've done the comparison.
int middle = lo + ((hi - lo) / 2);
// Sort lo, mid and hi appropriately, then pick mid as the pivot.
SwapIfGreaterWithItems(keys, lo, middle); // swap the low with the mid point
SwapIfGreaterWithItems(keys, lo, hi); // swap the low with the high
SwapIfGreaterWithItems(keys, middle, hi); // swap the middle with the high
T pivot = keys[middle];
Swap(keys, middle, hi - 1);
int left = lo, right = hi - 1; // We already partitioned lo and hi and put the pivot in hi - 1. And we pre-increment & decrement below.
while (left < right)
{
if (pivot == null)
{
while (left < (hi - 1) && keys[++left] == null) ;
while (right > lo && keys[--right] != null) ;
}
else
{
while (pivot.CompareTo(keys[++left]) > 0) ;
while (pivot.CompareTo(keys[--right]) < 0) ;
}
if (left >= right)
break;
Swap(keys, left, right);
}
// Put pivot in the right location.
Swap(keys, left, (hi - 1));
return left;
}
private static void Heapsort(T[] keys, int lo, int hi)
{
Debug.Assert(keys != null);
Debug.Assert(lo >= 0);
Debug.Assert(hi > lo);
Debug.Assert(hi < keys.Length);
int n = hi - lo + 1;
for (int i = n / 2; i >= 1; i = i - 1)
{
DownHeap(keys, i, n, lo);
}
for (int i = n; i > 1; i = i - 1)
{
Swap(keys, lo, lo + i - 1);
DownHeap(keys, 1, i - 1, lo);
}
}
private static void DownHeap(T[] keys, int i, int n, int lo)
{
Debug.Assert(keys != null);
Debug.Assert(lo >= 0);
Debug.Assert(lo < keys.Length);
T d = keys[lo + i - 1];
int child;
while (i <= n / 2)
{
child = 2 * i;
if (child < n && (keys[lo + child - 1] == null || keys[lo + child - 1].CompareTo(keys[lo + child]) < 0))
{
child++;
}
if (keys[lo + child - 1] == null || keys[lo + child - 1].CompareTo(d) < 0)
break;
keys[lo + i - 1] = keys[lo + child - 1];
i = child;
}
keys[lo + i - 1] = d;
}
private static void InsertionSort(T[] keys, int lo, int hi)
{
Debug.Assert(keys != null);
Debug.Assert(lo >= 0);
Debug.Assert(hi >= lo);
Debug.Assert(hi <= keys.Length);
int i, j;
T t;
for (i = lo; i < hi; i++)
{
j = i;
t = keys[i + 1];
while (j >= lo && (t == null || t.CompareTo(keys[j]) < 0))
{
keys[j + 1] = keys[j];
j--;
}
keys[j + 1] = t;
}
}
}
#endregion
#region ArraySortHelper for paired key and value arrays
internal interface IArraySortHelper<TKey, TValue>
{
void Sort(TKey[] keys, TValue[] values, int index, int length, IComparer<TKey> comparer);
}
[TypeDependencyAttribute("System.Collections.Generic.GenericArraySortHelper`2")]
internal class ArraySortHelper<TKey, TValue>
: IArraySortHelper<TKey, TValue>
{
private static volatile IArraySortHelper<TKey, TValue> defaultArraySortHelper;
public static IArraySortHelper<TKey, TValue> Default
{
get
{
IArraySortHelper<TKey, TValue> sorter = defaultArraySortHelper;
if (sorter == null)
sorter = CreateArraySortHelper();
return sorter;
}
}
private static IArraySortHelper<TKey, TValue> CreateArraySortHelper()
{
if (typeof(IComparable<TKey>).IsAssignableFrom(typeof(TKey)))
{
defaultArraySortHelper = (IArraySortHelper<TKey, TValue>)RuntimeTypeHandle.Allocate(typeof(GenericArraySortHelper<string, string>).TypeHandle.Instantiate(new Type[] { typeof(TKey), typeof(TValue) }));
}
else
{
defaultArraySortHelper = new ArraySortHelper<TKey, TValue>();
}
return defaultArraySortHelper;
}
public void Sort(TKey[] keys, TValue[] values, int index, int length, IComparer<TKey> comparer)
{
Debug.Assert(keys != null, "Check the arguments in the caller!"); // Precondition on interface method
Debug.Assert(values != null, "Check the arguments in the caller!");
Debug.Assert(index >= 0 && length >= 0 && (keys.Length - index >= length), "Check the arguments in the caller!");
// Add a try block here to detect IComparers (or their
// underlying IComparables, etc) that are bogus.
try
{
if (comparer == null || comparer == Comparer<TKey>.Default)
{
comparer = Comparer<TKey>.Default;
}
IntrospectiveSort(keys, values, index, length, comparer);
}
catch (IndexOutOfRangeException)
{
IntrospectiveSortUtilities.ThrowOrIgnoreBadComparer(comparer);
}
catch (Exception e)
{
throw new InvalidOperationException(SR.InvalidOperation_IComparerFailed, e);
}
}
private static void SwapIfGreaterWithItems(TKey[] keys, TValue[] values, IComparer<TKey> comparer, int a, int b)
{
Debug.Assert(keys != null);
Debug.Assert(values != null && values.Length >= keys.Length);
Debug.Assert(comparer != null);
Debug.Assert(0 <= a && a < keys.Length);
Debug.Assert(0 <= b && b < keys.Length);
if (a != b)
{
if (comparer.Compare(keys[a], keys[b]) > 0)
{
TKey key = keys[a];
keys[a] = keys[b];
keys[b] = key;
TValue value = values[a];
values[a] = values[b];
values[b] = value;
}
}
}
private static void Swap(TKey[] keys, TValue[] values, int i, int j)
{
if (i != j)
{
TKey k = keys[i];
keys[i] = keys[j];
keys[j] = k;
TValue v = values[i];
values[i] = values[j];
values[j] = v;
}
}
internal static void IntrospectiveSort(TKey[] keys, TValue[] values, int left, int length, IComparer<TKey> comparer)
{
Debug.Assert(keys != null);
Debug.Assert(values != null);
Debug.Assert(comparer != null);
Debug.Assert(left >= 0);
Debug.Assert(length >= 0);
Debug.Assert(length <= keys.Length);
Debug.Assert(length + left <= keys.Length);
Debug.Assert(length + left <= values.Length);
if (length < 2)
return;
IntroSort(keys, values, left, length + left - 1, 2 * IntrospectiveSortUtilities.FloorLog2PlusOne(length), comparer);
}
private static void IntroSort(TKey[] keys, TValue[] values, int lo, int hi, int depthLimit, IComparer<TKey> comparer)
{
Debug.Assert(keys != null);
Debug.Assert(values != null);
Debug.Assert(comparer != null);
Debug.Assert(lo >= 0);
Debug.Assert(hi < keys.Length);
while (hi > lo)
{
int partitionSize = hi - lo + 1;
if (partitionSize <= IntrospectiveSortUtilities.IntrosortSizeThreshold)
{
if (partitionSize == 1)
{
return;
}
if (partitionSize == 2)
{
SwapIfGreaterWithItems(keys, values, comparer, lo, hi);
return;
}
if (partitionSize == 3)
{
SwapIfGreaterWithItems(keys, values, comparer, lo, hi - 1);
SwapIfGreaterWithItems(keys, values, comparer, lo, hi);
SwapIfGreaterWithItems(keys, values, comparer, hi - 1, hi);
return;
}
InsertionSort(keys, values, lo, hi, comparer);
return;
}
if (depthLimit == 0)
{
Heapsort(keys, values, lo, hi, comparer);
return;
}
depthLimit--;
int p = PickPivotAndPartition(keys, values, lo, hi, comparer);
// Note we've already partitioned around the pivot and do not have to move the pivot again.
IntroSort(keys, values, p + 1, hi, depthLimit, comparer);
hi = p - 1;
}
}
private static int PickPivotAndPartition(TKey[] keys, TValue[] values, int lo, int hi, IComparer<TKey> comparer)
{
Debug.Assert(keys != null);
Debug.Assert(values != null);
Debug.Assert(comparer != null);
Debug.Assert(lo >= 0);
Debug.Assert(hi > lo);
Debug.Assert(hi < keys.Length);
// Compute median-of-three. But also partition them, since we've done the comparison.
int middle = lo + ((hi - lo) / 2);
// Sort lo, mid and hi appropriately, then pick mid as the pivot.
SwapIfGreaterWithItems(keys, values, comparer, lo, middle); // swap the low with the mid point
SwapIfGreaterWithItems(keys, values, comparer, lo, hi); // swap the low with the high
SwapIfGreaterWithItems(keys, values, comparer, middle, hi); // swap the middle with the high
TKey pivot = keys[middle];
Swap(keys, values, middle, hi - 1);
int left = lo, right = hi - 1; // We already partitioned lo and hi and put the pivot in hi - 1. And we pre-increment & decrement below.
while (left < right)
{
while (comparer.Compare(keys[++left], pivot) < 0) ;
while (comparer.Compare(pivot, keys[--right]) < 0) ;
if (left >= right)
break;
Swap(keys, values, left, right);
}
// Put pivot in the right location.
Swap(keys, values, left, (hi - 1));
return left;
}
private static void Heapsort(TKey[] keys, TValue[] values, int lo, int hi, IComparer<TKey> comparer)
{
Debug.Assert(keys != null);
Debug.Assert(values != null);
Debug.Assert(comparer != null);
Debug.Assert(lo >= 0);
Debug.Assert(hi > lo);
Debug.Assert(hi < keys.Length);
int n = hi - lo + 1;
for (int i = n / 2; i >= 1; i = i - 1)
{
DownHeap(keys, values, i, n, lo, comparer);
}
for (int i = n; i > 1; i = i - 1)
{
Swap(keys, values, lo, lo + i - 1);
DownHeap(keys, values, 1, i - 1, lo, comparer);
}
}
private static void DownHeap(TKey[] keys, TValue[] values, int i, int n, int lo, IComparer<TKey> comparer)
{
Debug.Assert(keys != null);
Debug.Assert(values != null);
Debug.Assert(comparer != null);
Debug.Assert(lo >= 0);
Debug.Assert(lo < keys.Length);
TKey d = keys[lo + i - 1];
TValue dValue = values[lo + i - 1];
int child;
while (i <= n / 2)
{
child = 2 * i;
if (child < n && comparer.Compare(keys[lo + child - 1], keys[lo + child]) < 0)
{
child++;
}
if (!(comparer.Compare(d, keys[lo + child - 1]) < 0))
break;
keys[lo + i - 1] = keys[lo + child - 1];
values[lo + i - 1] = values[lo + child - 1];
i = child;
}
keys[lo + i - 1] = d;
values[lo + i - 1] = dValue;
}
private static void InsertionSort(TKey[] keys, TValue[] values, int lo, int hi, IComparer<TKey> comparer)
{
Debug.Assert(keys != null);
Debug.Assert(values != null);
Debug.Assert(comparer != null);
Debug.Assert(lo >= 0);
Debug.Assert(hi >= lo);
Debug.Assert(hi <= keys.Length);
int i, j;
TKey t;
TValue tValue;
for (i = lo; i < hi; i++)
{
j = i;
t = keys[i + 1];
tValue = values[i + 1];
while (j >= lo && comparer.Compare(t, keys[j]) < 0)
{
keys[j + 1] = keys[j];
values[j + 1] = values[j];
j--;
}
keys[j + 1] = t;
values[j + 1] = tValue;
}
}
}
internal class GenericArraySortHelper<TKey, TValue>
: IArraySortHelper<TKey, TValue>
where TKey : IComparable<TKey>
{
public void Sort(TKey[] keys, TValue[] values, int index, int length, IComparer<TKey> comparer)
{
Debug.Assert(keys != null, "Check the arguments in the caller!");
Debug.Assert(index >= 0 && length >= 0 && (keys.Length - index >= length), "Check the arguments in the caller!");
// Add a try block here to detect IComparers (or their
// underlying IComparables, etc) that are bogus.
try
{
if (comparer == null || comparer == Comparer<TKey>.Default)
{
IntrospectiveSort(keys, values, index, length);
}
else
{
ArraySortHelper<TKey, TValue>.IntrospectiveSort(keys, values, index, length, comparer);
}
}
catch (IndexOutOfRangeException)
{
IntrospectiveSortUtilities.ThrowOrIgnoreBadComparer(comparer);
}
catch (Exception e)
{
throw new InvalidOperationException(SR.InvalidOperation_IComparerFailed, e);
}
}
private static void SwapIfGreaterWithItems(TKey[] keys, TValue[] values, int a, int b)
{
if (a != b)
{
if (keys[a] != null && keys[a].CompareTo(keys[b]) > 0)
{
TKey key = keys[a];
keys[a] = keys[b];
keys[b] = key;
TValue value = values[a];
values[a] = values[b];
values[b] = value;
}
}
}
private static void Swap(TKey[] keys, TValue[] values, int i, int j)
{
if (i != j)
{
TKey k = keys[i];
keys[i] = keys[j];
keys[j] = k;
TValue v = values[i];
values[i] = values[j];
values[j] = v;
}
}
internal static void IntrospectiveSort(TKey[] keys, TValue[] values, int left, int length)
{
Debug.Assert(keys != null);
Debug.Assert(values != null);
Debug.Assert(left >= 0);
Debug.Assert(length >= 0);
Debug.Assert(length <= keys.Length);
Debug.Assert(length + left <= keys.Length);
Debug.Assert(length + left <= values.Length);
if (length < 2)
return;
IntroSort(keys, values, left, length + left - 1, 2 * IntrospectiveSortUtilities.FloorLog2PlusOne(length));
}
private static void IntroSort(TKey[] keys, TValue[] values, int lo, int hi, int depthLimit)
{
Debug.Assert(keys != null);
Debug.Assert(values != null);
Debug.Assert(lo >= 0);
Debug.Assert(hi < keys.Length);
while (hi > lo)
{
int partitionSize = hi - lo + 1;
if (partitionSize <= IntrospectiveSortUtilities.IntrosortSizeThreshold)
{
if (partitionSize == 1)
{
return;
}
if (partitionSize == 2)
{
SwapIfGreaterWithItems(keys, values, lo, hi);
return;
}
if (partitionSize == 3)
{
SwapIfGreaterWithItems(keys, values, lo, hi - 1);
SwapIfGreaterWithItems(keys, values, lo, hi);
SwapIfGreaterWithItems(keys, values, hi - 1, hi);
return;
}
InsertionSort(keys, values, lo, hi);
return;
}
if (depthLimit == 0)
{
Heapsort(keys, values, lo, hi);
return;
}
depthLimit--;
int p = PickPivotAndPartition(keys, values, lo, hi);
// Note we've already partitioned around the pivot and do not have to move the pivot again.
IntroSort(keys, values, p + 1, hi, depthLimit);
hi = p - 1;
}
}
private static int PickPivotAndPartition(TKey[] keys, TValue[] values, int lo, int hi)
{
Debug.Assert(keys != null);
Debug.Assert(values != null);
Debug.Assert(lo >= 0);
Debug.Assert(hi > lo);
Debug.Assert(hi < keys.Length);
// Compute median-of-three. But also partition them, since we've done the comparison.
int middle = lo + ((hi - lo) / 2);
// Sort lo, mid and hi appropriately, then pick mid as the pivot.
SwapIfGreaterWithItems(keys, values, lo, middle); // swap the low with the mid point
SwapIfGreaterWithItems(keys, values, lo, hi); // swap the low with the high
SwapIfGreaterWithItems(keys, values, middle, hi); // swap the middle with the high
TKey pivot = keys[middle];
Swap(keys, values, middle, hi - 1);
int left = lo, right = hi - 1; // We already partitioned lo and hi and put the pivot in hi - 1. And we pre-increment & decrement below.
while (left < right)
{
if (pivot == null)
{
while (left < (hi - 1) && keys[++left] == null) ;
while (right > lo && keys[--right] != null) ;
}
else
{
while (pivot.CompareTo(keys[++left]) > 0) ;
while (pivot.CompareTo(keys[--right]) < 0) ;
}
if (left >= right)
break;
Swap(keys, values, left, right);
}
// Put pivot in the right location.
Swap(keys, values, left, (hi - 1));
return left;
}
private static void Heapsort(TKey[] keys, TValue[] values, int lo, int hi)
{
Debug.Assert(keys != null);
Debug.Assert(values != null);
Debug.Assert(lo >= 0);
Debug.Assert(hi > lo);
Debug.Assert(hi < keys.Length);
int n = hi - lo + 1;
for (int i = n / 2; i >= 1; i = i - 1)
{
DownHeap(keys, values, i, n, lo);
}
for (int i = n; i > 1; i = i - 1)
{
Swap(keys, values, lo, lo + i - 1);
DownHeap(keys, values, 1, i - 1, lo);
}
}
private static void DownHeap(TKey[] keys, TValue[] values, int i, int n, int lo)
{
Debug.Assert(keys != null);
Debug.Assert(lo >= 0);
Debug.Assert(lo < keys.Length);
TKey d = keys[lo + i - 1];
TValue dValue = values[lo + i - 1];
int child;
while (i <= n / 2)
{
child = 2 * i;
if (child < n && (keys[lo + child - 1] == null || keys[lo + child - 1].CompareTo(keys[lo + child]) < 0))
{
child++;
}
if (keys[lo + child - 1] == null || keys[lo + child - 1].CompareTo(d) < 0)
break;
keys[lo + i - 1] = keys[lo + child - 1];
values[lo + i - 1] = values[lo + child - 1];
i = child;
}
keys[lo + i - 1] = d;
values[lo + i - 1] = dValue;
}
private static void InsertionSort(TKey[] keys, TValue[] values, int lo, int hi)
{
Debug.Assert(keys != null);
Debug.Assert(values != null);
Debug.Assert(lo >= 0);
Debug.Assert(hi >= lo);
Debug.Assert(hi <= keys.Length);
int i, j;
TKey t;
TValue tValue;
for (i = lo; i < hi; i++)
{
j = i;
t = keys[i + 1];
tValue = values[i + 1];
while (j >= lo && (t == null || t.CompareTo(keys[j]) < 0))
{
keys[j + 1] = keys[j];
values[j + 1] = values[j];
j--;
}
keys[j + 1] = t;
values[j + 1] = tValue;
}
}
}
#endregion
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics;
namespace System.Reflection
{
#if CORERT
[System.Runtime.CompilerServices.ReflectionBlocked]
public // Needs to be public so that Reflection.Core can see it.
#else
internal
#endif
static class SignatureTypeExtensions
{
/// <summary>
/// This is semantically identical to
///
/// parameter.ParameterType == pattern.TryResolveAgainstGenericMethod(parameter.Member)
///
/// but without the allocation overhead of TryResolve.
/// </summary>
public static bool MatchesParameterTypeExactly(this Type pattern, ParameterInfo parameter)
{
if (pattern is SignatureType signatureType)
return signatureType.MatchesExactly(parameter.ParameterType);
else
return pattern == (object)(parameter.ParameterType);
}
/// <summary>
/// This is semantically identical to
///
/// actual == pattern.TryResolveAgainstGenericMethod(parameterMember)
///
/// but without the allocation overhead of TryResolve.
/// </summary>
internal static bool MatchesExactly(this SignatureType pattern, Type actual)
{
if (pattern.IsSZArray)
{
return actual.IsSZArray && pattern.ElementType!.MatchesExactly(actual.GetElementType()!);
}
else if (pattern.IsVariableBoundArray)
{
return actual.IsVariableBoundArray && pattern.GetArrayRank() == actual.GetArrayRank() && pattern.ElementType!.MatchesExactly(actual.GetElementType()!);
}
else if (pattern.IsByRef)
{
return actual.IsByRef && pattern.ElementType!.MatchesExactly(actual.GetElementType()!);
}
else if (pattern.IsPointer)
{
return actual.IsPointer && pattern.ElementType!.MatchesExactly(actual.GetElementType()!);
}
else if (pattern.IsConstructedGenericType)
{
if (!actual.IsConstructedGenericType)
return false;
if (!(pattern.GetGenericTypeDefinition() == actual.GetGenericTypeDefinition()))
return false;
Type[] patternGenericTypeArguments = pattern.GenericTypeArguments;
Type[] actualGenericTypeArguments = actual.GenericTypeArguments;
int count = patternGenericTypeArguments.Length;
if (count != actualGenericTypeArguments.Length)
return false;
for (int i = 0; i < count; i++)
{
Type patternGenericTypeArgument = patternGenericTypeArguments[i];
if (patternGenericTypeArgument is SignatureType signatureType)
{
if (!signatureType.MatchesExactly(actualGenericTypeArguments[i]))
return false;
}
else
{
if (patternGenericTypeArgument != actualGenericTypeArguments[i])
return false;
}
}
return true;
}
else if (pattern.IsGenericMethodParameter)
{
if (!actual.IsGenericMethodParameter)
return false;
if (pattern.GenericParameterPosition != actual.GenericParameterPosition)
return false;
return true;
}
else
{
return false;
}
}
/// <summary>
/// Translates a SignatureType into its equivalent resolved Type by recursively substituting all generic parameter references
/// with its corresponding generic parameter definition. This is slow so MatchesExactly or MatchesParameterTypeExactly should be
/// substituted instead whenever possible. This is only used by the DefaultBinder when its fast-path checks have been exhausted and
/// it needs to call non-trivial methods like IsAssignableFrom which SignatureTypes will never support.
///
/// Because this method is used to eliminate method candidates in a GetMethod() lookup, it is entirely possible that the Type
/// might not be creatable due to conflicting generic constraints. Since this merely implies that this candidate is not
/// the method we're looking for, we return null rather than let the TypeLoadException bubble up. The DefaultBinder will catch
/// the null and continue its search for a better candidate.
/// </summary>
internal static Type? TryResolveAgainstGenericMethod(this SignatureType signatureType, MethodInfo genericMethod)
{
return signatureType.TryResolve(genericMethod.GetGenericArguments());
}
private static Type? TryResolve(this SignatureType signatureType, Type[] genericMethodParameters)
{
if (signatureType.IsSZArray)
{
return signatureType.ElementType!.TryResolve(genericMethodParameters)?.TryMakeArrayType();
}
else if (signatureType.IsVariableBoundArray)
{
return signatureType.ElementType!.TryResolve(genericMethodParameters)?.TryMakeArrayType(signatureType.GetArrayRank());
}
else if (signatureType.IsByRef)
{
return signatureType.ElementType!.TryResolve(genericMethodParameters)?.TryMakeByRefType();
}
else if (signatureType.IsPointer)
{
return signatureType.ElementType!.TryResolve(genericMethodParameters)?.TryMakePointerType();
}
else if (signatureType.IsConstructedGenericType)
{
Type[] genericTypeArguments = signatureType.GenericTypeArguments;
int count = genericTypeArguments.Length;
Type?[] newGenericTypeArguments = new Type[count];
for (int i = 0; i < count; i++)
{
Type genericTypeArgument = genericTypeArguments[i];
if (genericTypeArgument is SignatureType signatureGenericTypeArgument)
{
newGenericTypeArguments[i] = signatureGenericTypeArgument.TryResolve(genericMethodParameters);
if (newGenericTypeArguments[i] == null)
return null;
}
else
{
newGenericTypeArguments[i] = genericTypeArgument;
}
}
return signatureType.GetGenericTypeDefinition().TryMakeGenericType(newGenericTypeArguments!);
}
else if (signatureType.IsGenericMethodParameter)
{
int position = signatureType.GenericParameterPosition;
if (position >= genericMethodParameters.Length)
return null;
return genericMethodParameters[position];
}
else
{
return null;
}
}
private static Type? TryMakeArrayType(this Type type)
{
try
{
return type.MakeArrayType();
}
catch
{
return null;
}
}
private static Type? TryMakeArrayType(this Type type, int rank)
{
try
{
return type.MakeArrayType(rank);
}
catch
{
return null;
}
}
private static Type? TryMakeByRefType(this Type type)
{
try
{
return type.MakeByRefType();
}
catch
{
return null;
}
}
private static Type? TryMakePointerType(this Type type)
{
try
{
return type.MakePointerType();
}
catch
{
return null;
}
}
private static Type? TryMakeGenericType(this Type type, Type[] instantiation)
{
try
{
return type.MakeGenericType(instantiation);
}
catch
{
return null;
}
}
}
}
| |
using UnityEngine;
using System.Collections;
[AddComponentMenu("2D Toolkit/Sprite/tk2d9SliceSprite")]
[RequireComponent(typeof(MeshRenderer))]
[RequireComponent(typeof(MeshFilter))]
[ExecuteInEditMode]
/// <summary>
/// Sprite implementation that implements 9-slice scaling. Doesn't support diced sprites.
/// The interface takes care of sprite unit conversions for border[Top|Bottom|Left|Right]
/// </summary>
public class tk2dSlicedSprite : tk2dBaseSprite
{
Mesh mesh;
Vector2[] meshUvs;
Vector3[] meshVertices;
Color32[] meshColors;
int[] meshIndices;
[SerializeField]
Vector2 _dimensions = new Vector2(50.0f, 50.0f);
[SerializeField]
Anchor _anchor = Anchor.LowerLeft;
[SerializeField]
bool _borderOnly = false;
/// <summary>
/// Legacy mode (uses scale to adjust overall size).
/// Newly created sprites should have this set to false.
/// </summary>
public bool legacyMode = true;
/// <summary>
/// Gets or sets border only. When true, the quad in the middle of the
/// sliced sprite is omitted, thus only drawing a border and saving fillrate
/// </summary>
public bool BorderOnly
{
get { return _borderOnly; }
set
{
if (value != _borderOnly)
{
_borderOnly = value;
UpdateIndices();
}
}
}
/// <summary>
/// Gets or sets the dimensions.
/// </summary>
/// <value>
/// Use this to change the dimensions of the sliced sprite in pixel units
/// </value>
public Vector2 dimensions
{
get { return _dimensions; }
set
{
if (value != _dimensions)
{
_dimensions = value;
UpdateVertices();
UpdateCollider();
}
}
}
/// <summary>
/// The anchor position for this sliced sprite
/// </summary>
public Anchor anchor
{
get { return _anchor; }
set
{
if (value != _anchor)
{
_anchor = value;
UpdateVertices();
UpdateCollider();
}
}
}
/// <summary>
/// Top border in sprite fraction (0 - Top, 1 - Bottom)
/// </summary>
public float borderTop = 0.2f;
/// <summary>
/// Bottom border in sprite fraction (0 - Bottom, 1 - Top)
/// </summary>
public float borderBottom = 0.2f;
/// <summary>
/// Left border in sprite fraction (0 - Left, 1 - Right)
/// </summary>
public float borderLeft = 0.2f;
/// <summary>
/// Right border in sprite fraction (1 - Right, 0 - Left)
/// </summary>
public float borderRight = 0.2f;
[SerializeField]
protected bool _createBoxCollider = false;
/// <summary>
/// Create a trimmed box collider for this sprite
/// </summary>
public bool CreateBoxCollider {
get { return _createBoxCollider; }
set {
if (_createBoxCollider != value) {
_createBoxCollider = value;
UpdateCollider();
}
}
}
new void Awake()
{
base.Awake();
// Create mesh, independently to everything else
mesh = new Mesh();
mesh.hideFlags = HideFlags.DontSave;
GetComponent<MeshFilter>().mesh = mesh;
// Cache box collider
if (boxCollider == null) {
boxCollider = GetComponent<BoxCollider>();
}
// This will not be set when instantiating in code
// In that case, Build will need to be called
if (Collection)
{
// reset spriteId if outside bounds
// this is when the sprite collection data is corrupt
if (_spriteId < 0 || _spriteId >= Collection.Count)
_spriteId = 0;
Build();
}
}
protected void OnDestroy()
{
if (mesh)
{
#if UNITY_EDITOR
DestroyImmediate(mesh);
#else
Destroy(mesh);
#endif
}
}
new protected void SetColors(Color32[] dest)
{
Color c = _color;
if (collectionInst.premultipliedAlpha) { c.r *= c.a; c.g *= c.a; c.b *= c.a; }
Color c32 = c;
for (int i = 0; i < dest.Length; ++i)
dest[i] = c32;
}
// Calculated center and extents
Vector3 boundsCenter = Vector3.zero, boundsExtents = Vector3.zero;
protected void SetGeometry(Vector3[] vertices, Vector2[] uvs)
{
var sprite = collectionInst.spriteDefinitions[spriteId];
if (sprite.positions.Length == 4)
{
if (legacyMode)
{
// in legacy mode, scale is used to determine the total size of the sliced sprite
float sx = _scale.x;
float sy = _scale.y;
Vector3[] srcVert = sprite.positions;
Vector3 dx = srcVert[1] - srcVert[0];
Vector3 dy = srcVert[2] - srcVert[0];
Vector2[] srcUv = sprite.uvs;
Vector2 duvx = sprite.uvs[1] - sprite.uvs[0];
Vector2 duvy = sprite.uvs[2] - sprite.uvs[0];
Vector3 origin = new Vector3(srcVert[0].x * sx, srcVert[0].y * sy, srcVert[0].z * _scale.z);
Vector3[] originPoints = new Vector3[4] {
origin,
origin + dy * borderBottom,
origin + dy * (sy - borderTop),
origin + dy * sy
};
Vector2[] originUvs = new Vector2[4] {
srcUv[0],
srcUv[0] + duvy * borderBottom,
srcUv[0] + duvy * (1 - borderTop),
srcUv[0] + duvy,
};
for (int i = 0; i < 4; ++i)
{
meshVertices[i * 4 + 0] = originPoints[i];
meshVertices[i * 4 + 1] = originPoints[i] + dx * borderLeft;
meshVertices[i * 4 + 2] = originPoints[i] + dx * (sx - borderRight);
meshVertices[i * 4 + 3] = originPoints[i] + dx * sx;
meshUvs[i * 4 + 0] = originUvs[i];
meshUvs[i * 4 + 1] = originUvs[i] + duvx * borderLeft;
meshUvs[i * 4 + 2] = originUvs[i] + duvx * (1 - borderRight);
meshUvs[i * 4 + 3] = originUvs[i] + duvx;
}
}
else
{
float sx = sprite.texelSize.x;
float sy = sprite.texelSize.y;
Vector3[] srcVert = sprite.positions;
float dx = (srcVert[1].x - srcVert[0].x);
float dy = (srcVert[2].y - srcVert[0].y);
float borderTopPixels = borderTop * dy;
float borderBottomPixels = borderBottom * dy;
float borderRightPixels = borderRight * dx;
float borderLeftPixels = borderLeft * dx;
float dimXPixels = dimensions.x * sx;
float dimYPixels = dimensions.y * sy;
float anchorOffsetX = 0.0f;
float anchorOffsetY = 0.0f;
switch (anchor)
{
case Anchor.LowerLeft: case Anchor.MiddleLeft: case Anchor.UpperLeft:
break;
case Anchor.LowerCenter: case Anchor.MiddleCenter: case Anchor.UpperCenter:
anchorOffsetX = -(int)(dimensions.x / 2.0f); break;
case Anchor.LowerRight: case Anchor.MiddleRight: case Anchor.UpperRight:
anchorOffsetX = -(int)(dimensions.x); break;
}
switch (anchor)
{
case Anchor.LowerLeft: case Anchor.LowerCenter: case Anchor.LowerRight:
break;
case Anchor.MiddleLeft: case Anchor.MiddleCenter: case Anchor.MiddleRight:
anchorOffsetY = -(int)(dimensions.y / 2.0f); break;
case Anchor.UpperLeft: case Anchor.UpperCenter: case Anchor.UpperRight:
anchorOffsetY = -(int)dimensions.y; break;
}
// scale back to sprite coordinates
// do it after the cast above, as we're trying to align to pixel
anchorOffsetX *= sx;
anchorOffsetY *= sy;
float colliderOffsetZ = ( boxCollider != null ) ? ( boxCollider.center.z ) : 0.0f;
float colliderExtentZ = ( boxCollider != null ) ? ( boxCollider.size.z * 0.5f ) : 0.5f;
boundsCenter.Set(_scale.x * (dimXPixels * 0.5f + anchorOffsetX), _scale.y * (dimYPixels * 0.5f + anchorOffsetY), colliderOffsetZ);
boundsExtents.Set(_scale.x * (dimXPixels * 0.5f), _scale.y * (dimYPixels * 0.5f), colliderExtentZ);
Vector2[] srcUv = sprite.uvs;
Vector2 duvx = sprite.uvs[1] - sprite.uvs[0];
Vector2 duvy = sprite.uvs[2] - sprite.uvs[0];
Vector3 origin = new Vector3(srcVert[0].x, srcVert[0].y, srcVert[0].z);
origin = new Vector3(anchorOffsetX, anchorOffsetY, 0);
Vector3[] originPoints = new Vector3[4] {
origin,
origin + new Vector3(0, borderBottomPixels, 0),
origin + new Vector3(0, dimYPixels - borderTopPixels, 0),
origin + new Vector3(0, dimYPixels, 0),
};
Vector2[] originUvs = new Vector2[4] {
srcUv[0],
srcUv[0] + duvy * borderBottom,
srcUv[0] + duvy * (1 - borderTop),
srcUv[0] + duvy,
};
for (int i = 0; i < 4; ++i)
{
meshVertices[i * 4 + 0] = originPoints[i];
meshVertices[i * 4 + 1] = originPoints[i] + new Vector3(borderLeftPixels, 0, 0);
meshVertices[i * 4 + 2] = originPoints[i] + new Vector3(dimXPixels - borderRightPixels, 0, 0);
meshVertices[i * 4 + 3] = originPoints[i] + new Vector3(dimXPixels, 0, 0);
for (int j = 0; j < 4; ++j) {
meshVertices[i * 4 + j] = Vector3.Scale(meshVertices[i * 4 + j], _scale);
}
meshUvs[i * 4 + 0] = originUvs[i];
meshUvs[i * 4 + 1] = originUvs[i] + duvx * borderLeft;
meshUvs[i * 4 + 2] = originUvs[i] + duvx * (1 - borderRight);
meshUvs[i * 4 + 3] = originUvs[i] + duvx;
}
}
}
else
{
for (int i = 0; i < vertices.Length; ++i)
vertices[i] = Vector3.zero;
}
}
void SetIndices()
{
meshIndices = new int[9 * 6] {
0, 4, 1, 1, 4, 5,
1, 5, 2, 2, 5, 6,
2, 6, 3, 3, 6, 7,
4, 8, 5, 5, 8, 9,
5, 9, 6, 6, 9, 10, // middle bit
6, 10, 7, 7, 10, 11,
8, 12, 9, 9, 12, 13,
9, 13, 10, 10, 13, 14,
10, 14, 11, 11, 14, 15
};
if (_borderOnly) {
for (int i = 24; i < 30; ++i) {
meshIndices[i] = 0;
}
}
}
public override void Build()
{
meshUvs = new Vector2[16];
meshVertices = new Vector3[16];
meshColors = new Color32[16];
SetIndices();
SetGeometry(meshVertices, meshUvs);
SetColors(meshColors);
if (mesh == null)
{
mesh = new Mesh();
mesh.hideFlags = HideFlags.DontSave;
}
else
{
mesh.Clear();
}
mesh.vertices = meshVertices;
mesh.colors32 = meshColors;
mesh.uv = meshUvs;
mesh.triangles = meshIndices;
mesh.RecalculateBounds();
GetComponent<MeshFilter>().mesh = mesh;
UpdateCollider();
UpdateMaterial();
}
protected override void UpdateGeometry() { UpdateGeometryImpl(); }
protected override void UpdateColors() { UpdateColorsImpl(); }
protected override void UpdateVertices() { UpdateGeometryImpl(); }
void UpdateIndices() {
if (mesh != null) {
SetIndices();
mesh.triangles = meshIndices;
}
}
protected void UpdateColorsImpl()
{
#if UNITY_EDITOR
// This can happen with prefabs in the inspector
if (meshColors == null || meshColors.Length == 0)
return;
#endif
if (meshColors == null || meshColors.Length == 0) {
Build();
}
else {
SetColors(meshColors);
mesh.colors32 = meshColors;
}
}
protected void UpdateGeometryImpl()
{
#if UNITY_EDITOR
// This can happen with prefabs in the inspector
if (mesh == null)
return;
#endif
if (meshVertices == null || meshVertices.Length == 0) {
Build();
}
else {
SetGeometry(meshVertices, meshUvs);
mesh.vertices = meshVertices;
mesh.uv = meshUvs;
mesh.RecalculateBounds();
UpdateCollider();
}
}
#region Collider
protected override void UpdateCollider()
{
if (CreateBoxCollider) {
if (boxCollider == null) {
boxCollider = GetComponent<BoxCollider>();
if (boxCollider == null) {
boxCollider = gameObject.AddComponent<BoxCollider>();
}
}
boxCollider.extents = boundsExtents;
boxCollider.center = boundsCenter;
} else {
#if UNITY_EDITOR
boxCollider = GetComponent<BoxCollider>();
if (boxCollider != null) {
DestroyImmediate(boxCollider);
}
#else
if (boxCollider != null) {
Destroy(boxCollider);
}
#endif
}
}
protected override void CreateCollider() {
UpdateCollider();
}
#if UNITY_EDITOR
public override void EditMode__CreateCollider() {
UpdateCollider();
}
#endif
#endregion
protected override void UpdateMaterial()
{
if (renderer.sharedMaterial != collectionInst.spriteDefinitions[spriteId].materialInst)
renderer.material = collectionInst.spriteDefinitions[spriteId].materialInst;
}
protected override int GetCurrentVertexCount()
{
#if UNITY_EDITOR
if (meshVertices == null)
return 0;
#endif
return 16;
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
// ------------------------------------------------------------------------------
// Changes to this file must follow the http://aka.ms/api-review process.
// ------------------------------------------------------------------------------
namespace System
{
public static partial class BitConverter
{
public static readonly bool IsLittleEndian;
public static long DoubleToInt64Bits(double value) { return default(long); }
public static byte[] GetBytes(bool value) { return default(byte[]); }
public static byte[] GetBytes(char value) { return default(byte[]); }
public static byte[] GetBytes(double value) { return default(byte[]); }
public static byte[] GetBytes(short value) { return default(byte[]); }
public static byte[] GetBytes(int value) { return default(byte[]); }
public static byte[] GetBytes(long value) { return default(byte[]); }
public static byte[] GetBytes(float value) { return default(byte[]); }
[System.CLSCompliantAttribute(false)]
public static byte[] GetBytes(ushort value) { return default(byte[]); }
[System.CLSCompliantAttribute(false)]
public static byte[] GetBytes(uint value) { return default(byte[]); }
[System.CLSCompliantAttribute(false)]
public static byte[] GetBytes(ulong value) { return default(byte[]); }
public static double Int64BitsToDouble(long value) { return default(double); }
public static bool ToBoolean(byte[] value, int startIndex) { return default(bool); }
public static char ToChar(byte[] value, int startIndex) { return default(char); }
public static double ToDouble(byte[] value, int startIndex) { return default(double); }
public static short ToInt16(byte[] value, int startIndex) { return default(short); }
public static int ToInt32(byte[] value, int startIndex) { return default(int); }
public static long ToInt64(byte[] value, int startIndex) { return default(long); }
public static float ToSingle(byte[] value, int startIndex) { return default(float); }
public static string ToString(byte[] value) { return default(string); }
public static string ToString(byte[] value, int startIndex) { return default(string); }
public static string ToString(byte[] value, int startIndex, int length) { return default(string); }
[System.CLSCompliantAttribute(false)]
public static ushort ToUInt16(byte[] value, int startIndex) { return default(ushort); }
[System.CLSCompliantAttribute(false)]
public static uint ToUInt32(byte[] value, int startIndex) { return default(uint); }
[System.CLSCompliantAttribute(false)]
public static ulong ToUInt64(byte[] value, int startIndex) { return default(ulong); }
}
public static partial class Convert
{
public static object ChangeType(object value, System.Type conversionType) { return default(object); }
public static object ChangeType(object value, System.Type conversionType, System.IFormatProvider provider) { return default(object); }
public static object ChangeType(object value, System.TypeCode typeCode, System.IFormatProvider provider) { return default(object); }
public static byte[] FromBase64CharArray(char[] inArray, int offset, int length) { return default(byte[]); }
public static byte[] FromBase64String(string s) { return default(byte[]); }
public static System.TypeCode GetTypeCode(object value) { return default(System.TypeCode); }
public static int ToBase64CharArray(byte[] inArray, int offsetIn, int length, char[] outArray, int offsetOut) { return default(int); }
public static string ToBase64String(byte[] inArray) { return default(string); }
public static string ToBase64String(byte[] inArray, int offset, int length) { return default(string); }
public static bool ToBoolean(bool value) { return default(bool); }
public static bool ToBoolean(byte value) { return default(bool); }
public static bool ToBoolean(decimal value) { return default(bool); }
public static bool ToBoolean(double value) { return default(bool); }
public static bool ToBoolean(short value) { return default(bool); }
public static bool ToBoolean(int value) { return default(bool); }
public static bool ToBoolean(long value) { return default(bool); }
public static bool ToBoolean(object value) { return default(bool); }
public static bool ToBoolean(object value, System.IFormatProvider provider) { return default(bool); }
[System.CLSCompliantAttribute(false)]
public static bool ToBoolean(sbyte value) { return default(bool); }
public static bool ToBoolean(float value) { return default(bool); }
public static bool ToBoolean(string value) { return default(bool); }
public static bool ToBoolean(string value, System.IFormatProvider provider) { return default(bool); }
[System.CLSCompliantAttribute(false)]
public static bool ToBoolean(ushort value) { return default(bool); }
[System.CLSCompliantAttribute(false)]
public static bool ToBoolean(uint value) { return default(bool); }
[System.CLSCompliantAttribute(false)]
public static bool ToBoolean(ulong value) { return default(bool); }
public static byte ToByte(bool value) { return default(byte); }
public static byte ToByte(byte value) { return default(byte); }
public static byte ToByte(char value) { return default(byte); }
public static byte ToByte(decimal value) { return default(byte); }
public static byte ToByte(double value) { return default(byte); }
public static byte ToByte(short value) { return default(byte); }
public static byte ToByte(int value) { return default(byte); }
public static byte ToByte(long value) { return default(byte); }
public static byte ToByte(object value) { return default(byte); }
public static byte ToByte(object value, System.IFormatProvider provider) { return default(byte); }
[System.CLSCompliantAttribute(false)]
public static byte ToByte(sbyte value) { return default(byte); }
public static byte ToByte(float value) { return default(byte); }
public static byte ToByte(string value) { return default(byte); }
public static byte ToByte(string value, System.IFormatProvider provider) { return default(byte); }
public static byte ToByte(string value, int fromBase) { return default(byte); }
[System.CLSCompliantAttribute(false)]
public static byte ToByte(ushort value) { return default(byte); }
[System.CLSCompliantAttribute(false)]
public static byte ToByte(uint value) { return default(byte); }
[System.CLSCompliantAttribute(false)]
public static byte ToByte(ulong value) { return default(byte); }
public static char ToChar(byte value) { return default(char); }
public static char ToChar(short value) { return default(char); }
public static char ToChar(int value) { return default(char); }
public static char ToChar(long value) { return default(char); }
public static char ToChar(object value) { return default(char); }
public static char ToChar(object value, System.IFormatProvider provider) { return default(char); }
[System.CLSCompliantAttribute(false)]
public static char ToChar(sbyte value) { return default(char); }
public static char ToChar(string value) { return default(char); }
public static char ToChar(string value, System.IFormatProvider provider) { return default(char); }
[System.CLSCompliantAttribute(false)]
public static char ToChar(ushort value) { return default(char); }
[System.CLSCompliantAttribute(false)]
public static char ToChar(uint value) { return default(char); }
[System.CLSCompliantAttribute(false)]
public static char ToChar(ulong value) { return default(char); }
public static System.DateTime ToDateTime(object value) { return default(System.DateTime); }
public static System.DateTime ToDateTime(object value, System.IFormatProvider provider) { return default(System.DateTime); }
public static System.DateTime ToDateTime(string value) { return default(System.DateTime); }
public static System.DateTime ToDateTime(string value, System.IFormatProvider provider) { return default(System.DateTime); }
public static decimal ToDecimal(bool value) { return default(decimal); }
public static decimal ToDecimal(byte value) { return default(decimal); }
public static decimal ToDecimal(decimal value) { return default(decimal); }
public static decimal ToDecimal(double value) { return default(decimal); }
public static decimal ToDecimal(short value) { return default(decimal); }
public static decimal ToDecimal(int value) { return default(decimal); }
public static decimal ToDecimal(long value) { return default(decimal); }
public static decimal ToDecimal(object value) { return default(decimal); }
public static decimal ToDecimal(object value, System.IFormatProvider provider) { return default(decimal); }
[System.CLSCompliantAttribute(false)]
public static decimal ToDecimal(sbyte value) { return default(decimal); }
public static decimal ToDecimal(float value) { return default(decimal); }
public static decimal ToDecimal(string value) { return default(decimal); }
public static decimal ToDecimal(string value, System.IFormatProvider provider) { return default(decimal); }
[System.CLSCompliantAttribute(false)]
public static decimal ToDecimal(ushort value) { return default(decimal); }
[System.CLSCompliantAttribute(false)]
public static decimal ToDecimal(uint value) { return default(decimal); }
[System.CLSCompliantAttribute(false)]
public static decimal ToDecimal(ulong value) { return default(decimal); }
public static double ToDouble(bool value) { return default(double); }
public static double ToDouble(byte value) { return default(double); }
public static double ToDouble(decimal value) { return default(double); }
public static double ToDouble(double value) { return default(double); }
public static double ToDouble(short value) { return default(double); }
public static double ToDouble(int value) { return default(double); }
public static double ToDouble(long value) { return default(double); }
public static double ToDouble(object value) { return default(double); }
public static double ToDouble(object value, System.IFormatProvider provider) { return default(double); }
[System.CLSCompliantAttribute(false)]
public static double ToDouble(sbyte value) { return default(double); }
public static double ToDouble(float value) { return default(double); }
public static double ToDouble(string value) { return default(double); }
public static double ToDouble(string value, System.IFormatProvider provider) { return default(double); }
[System.CLSCompliantAttribute(false)]
public static double ToDouble(ushort value) { return default(double); }
[System.CLSCompliantAttribute(false)]
public static double ToDouble(uint value) { return default(double); }
[System.CLSCompliantAttribute(false)]
public static double ToDouble(ulong value) { return default(double); }
public static short ToInt16(bool value) { return default(short); }
public static short ToInt16(byte value) { return default(short); }
public static short ToInt16(char value) { return default(short); }
public static short ToInt16(decimal value) { return default(short); }
public static short ToInt16(double value) { return default(short); }
public static short ToInt16(short value) { return default(short); }
public static short ToInt16(int value) { return default(short); }
public static short ToInt16(long value) { return default(short); }
public static short ToInt16(object value) { return default(short); }
public static short ToInt16(object value, System.IFormatProvider provider) { return default(short); }
[System.CLSCompliantAttribute(false)]
public static short ToInt16(sbyte value) { return default(short); }
public static short ToInt16(float value) { return default(short); }
public static short ToInt16(string value) { return default(short); }
public static short ToInt16(string value, System.IFormatProvider provider) { return default(short); }
public static short ToInt16(string value, int fromBase) { return default(short); }
[System.CLSCompliantAttribute(false)]
public static short ToInt16(ushort value) { return default(short); }
[System.CLSCompliantAttribute(false)]
public static short ToInt16(uint value) { return default(short); }
[System.CLSCompliantAttribute(false)]
public static short ToInt16(ulong value) { return default(short); }
public static int ToInt32(bool value) { return default(int); }
public static int ToInt32(byte value) { return default(int); }
public static int ToInt32(char value) { return default(int); }
public static int ToInt32(decimal value) { return default(int); }
public static int ToInt32(double value) { return default(int); }
public static int ToInt32(short value) { return default(int); }
public static int ToInt32(int value) { return default(int); }
public static int ToInt32(long value) { return default(int); }
public static int ToInt32(object value) { return default(int); }
public static int ToInt32(object value, System.IFormatProvider provider) { return default(int); }
[System.CLSCompliantAttribute(false)]
public static int ToInt32(sbyte value) { return default(int); }
public static int ToInt32(float value) { return default(int); }
public static int ToInt32(string value) { return default(int); }
public static int ToInt32(string value, System.IFormatProvider provider) { return default(int); }
public static int ToInt32(string value, int fromBase) { return default(int); }
[System.CLSCompliantAttribute(false)]
public static int ToInt32(ushort value) { return default(int); }
[System.CLSCompliantAttribute(false)]
public static int ToInt32(uint value) { return default(int); }
[System.CLSCompliantAttribute(false)]
public static int ToInt32(ulong value) { return default(int); }
public static long ToInt64(bool value) { return default(long); }
public static long ToInt64(byte value) { return default(long); }
public static long ToInt64(char value) { return default(long); }
public static long ToInt64(decimal value) { return default(long); }
public static long ToInt64(double value) { return default(long); }
public static long ToInt64(short value) { return default(long); }
public static long ToInt64(int value) { return default(long); }
public static long ToInt64(long value) { return default(long); }
public static long ToInt64(object value) { return default(long); }
public static long ToInt64(object value, System.IFormatProvider provider) { return default(long); }
[System.CLSCompliantAttribute(false)]
public static long ToInt64(sbyte value) { return default(long); }
public static long ToInt64(float value) { return default(long); }
public static long ToInt64(string value) { return default(long); }
public static long ToInt64(string value, System.IFormatProvider provider) { return default(long); }
public static long ToInt64(string value, int fromBase) { return default(long); }
[System.CLSCompliantAttribute(false)]
public static long ToInt64(ushort value) { return default(long); }
[System.CLSCompliantAttribute(false)]
public static long ToInt64(uint value) { return default(long); }
[System.CLSCompliantAttribute(false)]
public static long ToInt64(ulong value) { return default(long); }
[System.CLSCompliantAttribute(false)]
public static sbyte ToSByte(bool value) { return default(sbyte); }
[System.CLSCompliantAttribute(false)]
public static sbyte ToSByte(byte value) { return default(sbyte); }
[System.CLSCompliantAttribute(false)]
public static sbyte ToSByte(char value) { return default(sbyte); }
[System.CLSCompliantAttribute(false)]
public static sbyte ToSByte(decimal value) { return default(sbyte); }
[System.CLSCompliantAttribute(false)]
public static sbyte ToSByte(double value) { return default(sbyte); }
[System.CLSCompliantAttribute(false)]
public static sbyte ToSByte(short value) { return default(sbyte); }
[System.CLSCompliantAttribute(false)]
public static sbyte ToSByte(int value) { return default(sbyte); }
[System.CLSCompliantAttribute(false)]
public static sbyte ToSByte(long value) { return default(sbyte); }
[System.CLSCompliantAttribute(false)]
public static sbyte ToSByte(object value) { return default(sbyte); }
[System.CLSCompliantAttribute(false)]
public static sbyte ToSByte(object value, System.IFormatProvider provider) { return default(sbyte); }
[System.CLSCompliantAttribute(false)]
public static sbyte ToSByte(sbyte value) { return default(sbyte); }
[System.CLSCompliantAttribute(false)]
public static sbyte ToSByte(float value) { return default(sbyte); }
[System.CLSCompliantAttribute(false)]
public static sbyte ToSByte(string value) { return default(sbyte); }
[System.CLSCompliantAttribute(false)]
public static sbyte ToSByte(string value, System.IFormatProvider provider) { return default(sbyte); }
[System.CLSCompliantAttribute(false)]
public static sbyte ToSByte(string value, int fromBase) { return default(sbyte); }
[System.CLSCompliantAttribute(false)]
public static sbyte ToSByte(ushort value) { return default(sbyte); }
[System.CLSCompliantAttribute(false)]
public static sbyte ToSByte(uint value) { return default(sbyte); }
[System.CLSCompliantAttribute(false)]
public static sbyte ToSByte(ulong value) { return default(sbyte); }
public static float ToSingle(bool value) { return default(float); }
public static float ToSingle(byte value) { return default(float); }
public static float ToSingle(decimal value) { return default(float); }
public static float ToSingle(double value) { return default(float); }
public static float ToSingle(short value) { return default(float); }
public static float ToSingle(int value) { return default(float); }
public static float ToSingle(long value) { return default(float); }
public static float ToSingle(object value) { return default(float); }
public static float ToSingle(object value, System.IFormatProvider provider) { return default(float); }
[System.CLSCompliantAttribute(false)]
public static float ToSingle(sbyte value) { return default(float); }
public static float ToSingle(float value) { return default(float); }
public static float ToSingle(string value) { return default(float); }
public static float ToSingle(string value, System.IFormatProvider provider) { return default(float); }
[System.CLSCompliantAttribute(false)]
public static float ToSingle(ushort value) { return default(float); }
[System.CLSCompliantAttribute(false)]
public static float ToSingle(uint value) { return default(float); }
[System.CLSCompliantAttribute(false)]
public static float ToSingle(ulong value) { return default(float); }
public static string ToString(bool value) { return default(string); }
public static string ToString(bool value, System.IFormatProvider provider) { return default(string); }
public static string ToString(byte value) { return default(string); }
public static string ToString(byte value, System.IFormatProvider provider) { return default(string); }
public static string ToString(byte value, int toBase) { return default(string); }
public static string ToString(char value) { return default(string); }
public static string ToString(char value, System.IFormatProvider provider) { return default(string); }
public static string ToString(System.DateTime value) { return default(string); }
public static string ToString(System.DateTime value, System.IFormatProvider provider) { return default(string); }
public static string ToString(decimal value) { return default(string); }
public static string ToString(decimal value, System.IFormatProvider provider) { return default(string); }
public static string ToString(double value) { return default(string); }
public static string ToString(double value, System.IFormatProvider provider) { return default(string); }
public static string ToString(short value) { return default(string); }
public static string ToString(short value, System.IFormatProvider provider) { return default(string); }
public static string ToString(short value, int toBase) { return default(string); }
public static string ToString(int value) { return default(string); }
public static string ToString(int value, System.IFormatProvider provider) { return default(string); }
public static string ToString(int value, int toBase) { return default(string); }
public static string ToString(long value) { return default(string); }
public static string ToString(long value, System.IFormatProvider provider) { return default(string); }
public static string ToString(long value, int toBase) { return default(string); }
public static string ToString(object value) { return default(string); }
public static string ToString(object value, System.IFormatProvider provider) { return default(string); }
[System.CLSCompliantAttribute(false)]
public static string ToString(sbyte value) { return default(string); }
[System.CLSCompliantAttribute(false)]
public static string ToString(sbyte value, System.IFormatProvider provider) { return default(string); }
public static string ToString(float value) { return default(string); }
public static string ToString(float value, System.IFormatProvider provider) { return default(string); }
[System.CLSCompliantAttribute(false)]
public static string ToString(ushort value) { return default(string); }
[System.CLSCompliantAttribute(false)]
public static string ToString(ushort value, System.IFormatProvider provider) { return default(string); }
[System.CLSCompliantAttribute(false)]
public static string ToString(uint value) { return default(string); }
[System.CLSCompliantAttribute(false)]
public static string ToString(uint value, System.IFormatProvider provider) { return default(string); }
[System.CLSCompliantAttribute(false)]
public static string ToString(ulong value) { return default(string); }
[System.CLSCompliantAttribute(false)]
public static string ToString(ulong value, System.IFormatProvider provider) { return default(string); }
[System.CLSCompliantAttribute(false)]
public static ushort ToUInt16(bool value) { return default(ushort); }
[System.CLSCompliantAttribute(false)]
public static ushort ToUInt16(byte value) { return default(ushort); }
[System.CLSCompliantAttribute(false)]
public static ushort ToUInt16(char value) { return default(ushort); }
[System.CLSCompliantAttribute(false)]
public static ushort ToUInt16(decimal value) { return default(ushort); }
[System.CLSCompliantAttribute(false)]
public static ushort ToUInt16(double value) { return default(ushort); }
[System.CLSCompliantAttribute(false)]
public static ushort ToUInt16(short value) { return default(ushort); }
[System.CLSCompliantAttribute(false)]
public static ushort ToUInt16(int value) { return default(ushort); }
[System.CLSCompliantAttribute(false)]
public static ushort ToUInt16(long value) { return default(ushort); }
[System.CLSCompliantAttribute(false)]
public static ushort ToUInt16(object value) { return default(ushort); }
[System.CLSCompliantAttribute(false)]
public static ushort ToUInt16(object value, System.IFormatProvider provider) { return default(ushort); }
[System.CLSCompliantAttribute(false)]
public static ushort ToUInt16(sbyte value) { return default(ushort); }
[System.CLSCompliantAttribute(false)]
public static ushort ToUInt16(float value) { return default(ushort); }
[System.CLSCompliantAttribute(false)]
public static ushort ToUInt16(string value) { return default(ushort); }
[System.CLSCompliantAttribute(false)]
public static ushort ToUInt16(string value, System.IFormatProvider provider) { return default(ushort); }
[System.CLSCompliantAttribute(false)]
public static ushort ToUInt16(string value, int fromBase) { return default(ushort); }
[System.CLSCompliantAttribute(false)]
public static ushort ToUInt16(ushort value) { return default(ushort); }
[System.CLSCompliantAttribute(false)]
public static ushort ToUInt16(uint value) { return default(ushort); }
[System.CLSCompliantAttribute(false)]
public static ushort ToUInt16(ulong value) { return default(ushort); }
[System.CLSCompliantAttribute(false)]
public static uint ToUInt32(bool value) { return default(uint); }
[System.CLSCompliantAttribute(false)]
public static uint ToUInt32(byte value) { return default(uint); }
[System.CLSCompliantAttribute(false)]
public static uint ToUInt32(char value) { return default(uint); }
[System.CLSCompliantAttribute(false)]
public static uint ToUInt32(decimal value) { return default(uint); }
[System.CLSCompliantAttribute(false)]
public static uint ToUInt32(double value) { return default(uint); }
[System.CLSCompliantAttribute(false)]
public static uint ToUInt32(short value) { return default(uint); }
[System.CLSCompliantAttribute(false)]
public static uint ToUInt32(int value) { return default(uint); }
[System.CLSCompliantAttribute(false)]
public static uint ToUInt32(long value) { return default(uint); }
[System.CLSCompliantAttribute(false)]
public static uint ToUInt32(object value) { return default(uint); }
[System.CLSCompliantAttribute(false)]
public static uint ToUInt32(object value, System.IFormatProvider provider) { return default(uint); }
[System.CLSCompliantAttribute(false)]
public static uint ToUInt32(sbyte value) { return default(uint); }
[System.CLSCompliantAttribute(false)]
public static uint ToUInt32(float value) { return default(uint); }
[System.CLSCompliantAttribute(false)]
public static uint ToUInt32(string value) { return default(uint); }
[System.CLSCompliantAttribute(false)]
public static uint ToUInt32(string value, System.IFormatProvider provider) { return default(uint); }
[System.CLSCompliantAttribute(false)]
public static uint ToUInt32(string value, int fromBase) { return default(uint); }
[System.CLSCompliantAttribute(false)]
public static uint ToUInt32(ushort value) { return default(uint); }
[System.CLSCompliantAttribute(false)]
public static uint ToUInt32(uint value) { return default(uint); }
[System.CLSCompliantAttribute(false)]
public static uint ToUInt32(ulong value) { return default(uint); }
[System.CLSCompliantAttribute(false)]
public static ulong ToUInt64(bool value) { return default(ulong); }
[System.CLSCompliantAttribute(false)]
public static ulong ToUInt64(byte value) { return default(ulong); }
[System.CLSCompliantAttribute(false)]
public static ulong ToUInt64(char value) { return default(ulong); }
[System.CLSCompliantAttribute(false)]
public static ulong ToUInt64(decimal value) { return default(ulong); }
[System.CLSCompliantAttribute(false)]
public static ulong ToUInt64(double value) { return default(ulong); }
[System.CLSCompliantAttribute(false)]
public static ulong ToUInt64(short value) { return default(ulong); }
[System.CLSCompliantAttribute(false)]
public static ulong ToUInt64(int value) { return default(ulong); }
[System.CLSCompliantAttribute(false)]
public static ulong ToUInt64(long value) { return default(ulong); }
[System.CLSCompliantAttribute(false)]
public static ulong ToUInt64(object value) { return default(ulong); }
[System.CLSCompliantAttribute(false)]
public static ulong ToUInt64(object value, System.IFormatProvider provider) { return default(ulong); }
[System.CLSCompliantAttribute(false)]
public static ulong ToUInt64(sbyte value) { return default(ulong); }
[System.CLSCompliantAttribute(false)]
public static ulong ToUInt64(float value) { return default(ulong); }
[System.CLSCompliantAttribute(false)]
public static ulong ToUInt64(string value) { return default(ulong); }
[System.CLSCompliantAttribute(false)]
public static ulong ToUInt64(string value, System.IFormatProvider provider) { return default(ulong); }
[System.CLSCompliantAttribute(false)]
public static ulong ToUInt64(string value, int fromBase) { return default(ulong); }
[System.CLSCompliantAttribute(false)]
public static ulong ToUInt64(ushort value) { return default(ulong); }
[System.CLSCompliantAttribute(false)]
public static ulong ToUInt64(uint value) { return default(ulong); }
[System.CLSCompliantAttribute(false)]
public static ulong ToUInt64(ulong value) { return default(ulong); }
}
public static partial class Environment
{
public static int CurrentManagedThreadId { get { return default(int); } }
public static bool HasShutdownStarted { get { return default(bool); } }
public static string MachineName { get { return default(string); } }
public static string NewLine { get { return default(string); } }
public static int ProcessorCount { get { return default(int); } }
public static string StackTrace { get { return default(string); } }
public static int TickCount { get { return default(int); } }
public static string ExpandEnvironmentVariables(string name) { return default(string); }
public static void Exit(int exitCode) {}
[System.Security.SecurityCriticalAttribute]
public static void FailFast(string message) { }
[System.Security.SecurityCriticalAttribute]
public static void FailFast(string message, System.Exception exception) { }
public static string GetEnvironmentVariable(string variable) { return default(string); }
public static System.Collections.IDictionary GetEnvironmentVariables() { return default(System.Collections.IDictionary); }
public static void SetEnvironmentVariable(string variable, string value) { }
public static string[] GetCommandLineArgs() { return default(string[]); }
}
public static partial class Math
{
public static decimal Abs(decimal value) { return default(decimal); }
public static double Abs(double value) { return default(double); }
public static short Abs(short value) { return default(short); }
public static int Abs(int value) { return default(int); }
public static long Abs(long value) { return default(long); }
[System.CLSCompliantAttribute(false)]
public static sbyte Abs(sbyte value) { return default(sbyte); }
public static float Abs(float value) { return default(float); }
public static double Acos(double d) { return default(double); }
public static double Asin(double d) { return default(double); }
public static double Atan(double d) { return default(double); }
public static double Atan2(double y, double x) { return default(double); }
public static decimal Ceiling(decimal d) { return default(decimal); }
public static double Ceiling(double a) { return default(double); }
public static double Cos(double d) { return default(double); }
public static double Cosh(double value) { return default(double); }
public static double Exp(double d) { return default(double); }
public static decimal Floor(decimal d) { return default(decimal); }
public static double Floor(double d) { return default(double); }
public static double IEEERemainder(double x, double y) { return default(double); }
public static double Log(double d) { return default(double); }
public static double Log(double a, double newBase) { return default(double); }
public static double Log10(double d) { return default(double); }
public static byte Max(byte val1, byte val2) { return default(byte); }
public static decimal Max(decimal val1, decimal val2) { return default(decimal); }
public static double Max(double val1, double val2) { return default(double); }
public static short Max(short val1, short val2) { return default(short); }
public static int Max(int val1, int val2) { return default(int); }
public static long Max(long val1, long val2) { return default(long); }
[System.CLSCompliantAttribute(false)]
public static sbyte Max(sbyte val1, sbyte val2) { return default(sbyte); }
public static float Max(float val1, float val2) { return default(float); }
[System.CLSCompliantAttribute(false)]
public static ushort Max(ushort val1, ushort val2) { return default(ushort); }
[System.CLSCompliantAttribute(false)]
public static uint Max(uint val1, uint val2) { return default(uint); }
[System.CLSCompliantAttribute(false)]
public static ulong Max(ulong val1, ulong val2) { return default(ulong); }
public static byte Min(byte val1, byte val2) { return default(byte); }
public static decimal Min(decimal val1, decimal val2) { return default(decimal); }
public static double Min(double val1, double val2) { return default(double); }
public static short Min(short val1, short val2) { return default(short); }
public static int Min(int val1, int val2) { return default(int); }
public static long Min(long val1, long val2) { return default(long); }
[System.CLSCompliantAttribute(false)]
public static sbyte Min(sbyte val1, sbyte val2) { return default(sbyte); }
public static float Min(float val1, float val2) { return default(float); }
[System.CLSCompliantAttribute(false)]
public static ushort Min(ushort val1, ushort val2) { return default(ushort); }
[System.CLSCompliantAttribute(false)]
public static uint Min(uint val1, uint val2) { return default(uint); }
[System.CLSCompliantAttribute(false)]
public static ulong Min(ulong val1, ulong val2) { return default(ulong); }
public static double Pow(double x, double y) { return default(double); }
public static decimal Round(decimal d) { return default(decimal); }
public static decimal Round(decimal d, int decimals) { return default(decimal); }
public static decimal Round(decimal d, int decimals, System.MidpointRounding mode) { return default(decimal); }
public static decimal Round(decimal d, System.MidpointRounding mode) { return default(decimal); }
public static double Round(double a) { return default(double); }
public static double Round(double value, int digits) { return default(double); }
public static double Round(double value, int digits, System.MidpointRounding mode) { return default(double); }
public static double Round(double value, System.MidpointRounding mode) { return default(double); }
public static int Sign(decimal value) { return default(int); }
public static int Sign(double value) { return default(int); }
public static int Sign(short value) { return default(int); }
public static int Sign(int value) { return default(int); }
public static int Sign(long value) { return default(int); }
[System.CLSCompliantAttribute(false)]
public static int Sign(sbyte value) { return default(int); }
public static int Sign(float value) { return default(int); }
public static double Sin(double a) { return default(double); }
public static double Sinh(double value) { return default(double); }
public static double Sqrt(double d) { return default(double); }
public static double Tan(double a) { return default(double); }
public static double Tanh(double value) { return default(double); }
public static decimal Truncate(decimal d) { return default(decimal); }
public static double Truncate(double d) { return default(double); }
}
public enum MidpointRounding
{
AwayFromZero = 1,
ToEven = 0,
}
public partial class Progress<T> : System.IProgress<T>
{
public Progress() { }
public Progress(System.Action<T> handler) { }
public event System.EventHandler<T> ProgressChanged { add { } remove { } }
protected virtual void OnReport(T value) { }
void System.IProgress<T>.Report(T value) { }
}
public partial class Random
{
public Random() { }
public Random(int Seed) { }
public virtual int Next() { return default(int); }
public virtual int Next(int maxValue) { return default(int); }
public virtual int Next(int minValue, int maxValue) { return default(int); }
public virtual void NextBytes(byte[] buffer) { }
public virtual double NextDouble() { return default(double); }
protected virtual double Sample() { return default(double); }
}
public abstract partial class StringComparer : System.Collections.Generic.IComparer<string>, System.Collections.Generic.IEqualityComparer<string>, System.Collections.IComparer, System.Collections.IEqualityComparer
{
protected StringComparer() { }
public static System.StringComparer CurrentCulture { get { return default(System.StringComparer); } }
public static System.StringComparer CurrentCultureIgnoreCase { get { return default(System.StringComparer); } }
public static System.StringComparer Ordinal { get { return default(System.StringComparer); } }
public static System.StringComparer OrdinalIgnoreCase { get { return default(System.StringComparer); } }
public abstract int Compare(string x, string y);
public abstract bool Equals(string x, string y);
public abstract int GetHashCode(string obj);
int System.Collections.IComparer.Compare(object x, object y) { return default(int); }
bool System.Collections.IEqualityComparer.Equals(object x, object y) { return default(bool); }
int System.Collections.IEqualityComparer.GetHashCode(object obj) { return default(int); }
}
public partial class UriBuilder
{
public UriBuilder() { }
public UriBuilder(string uri) { }
public UriBuilder(string schemeName, string hostName) { }
public UriBuilder(string scheme, string host, int portNumber) { }
public UriBuilder(string scheme, string host, int port, string pathValue) { }
public UriBuilder(string scheme, string host, int port, string path, string extraValue) { }
public UriBuilder(System.Uri uri) { }
public string Fragment { get { return default(string); } set { } }
public string Host { get { return default(string); } set { } }
public string Password { get { return default(string); } set { } }
public string Path { get { return default(string); } set { } }
public int Port { get { return default(int); } set { } }
public string Query { get { return default(string); } set { } }
public string Scheme { get { return default(string); } set { } }
public System.Uri Uri { get { return default(System.Uri); } }
public string UserName { get { return default(string); } set { } }
public override bool Equals(object rparam) { return default(bool); }
public override int GetHashCode() { return default(int); }
public override string ToString() { return default(string); }
}
}
namespace System.Diagnostics
{
public partial class Stopwatch
{
public static readonly long Frequency;
public static readonly bool IsHighResolution;
public Stopwatch() { }
public System.TimeSpan Elapsed { get { return default(System.TimeSpan); } }
public long ElapsedMilliseconds { get { return default(long); } }
public long ElapsedTicks { get { return default(long); } }
public bool IsRunning { get { return default(bool); } }
public static long GetTimestamp() { return default(long); }
public void Reset() { }
public void Restart() { }
public void Start() { }
public static System.Diagnostics.Stopwatch StartNew() { return default(System.Diagnostics.Stopwatch); }
public void Stop() { }
}
}
namespace System.IO
{
public static partial class Path
{
public static readonly char AltDirectorySeparatorChar;
public static readonly char DirectorySeparatorChar;
public static readonly char PathSeparator;
public static readonly char VolumeSeparatorChar;
public static string ChangeExtension(string path, string extension) { return default(string); }
public static string Combine(string path1, string path2) { return default(string); }
public static string Combine(string path1, string path2, string path3) { return default(string); }
public static string Combine(params string[] paths) { return default(string); }
public static string GetDirectoryName(string path) { return default(string); }
public static string GetExtension(string path) { return default(string); }
public static string GetFileName(string path) { return default(string); }
public static string GetFileNameWithoutExtension(string path) { return default(string); }
public static string GetFullPath(string path) { return default(string); }
public static char[] GetInvalidFileNameChars() { return default(char[]); }
public static char[] GetInvalidPathChars() { return default(char[]); }
public static string GetPathRoot(string path) { return default(string); }
public static string GetRandomFileName() { return default(string); }
public static string GetTempFileName() { return default(string); }
public static string GetTempPath() { return default(string); }
public static bool HasExtension(string path) { return default(bool); }
public static bool IsPathRooted(string path) { return default(bool); }
}
}
namespace System.Net
{
public static partial class WebUtility
{
public static string HtmlDecode(string value) { return default(string); }
public static string HtmlEncode(string value) { return default(string); }
public static string UrlDecode(string encodedValue) { return default(string); }
public static byte[] UrlDecodeToBytes(byte[] encodedValue, int offset, int count) { return default(byte[]); }
public static string UrlEncode(string value) { return default(string); }
public static byte[] UrlEncodeToBytes(byte[] value, int offset, int count) { return default(byte[]); }
}
}
namespace System.Runtime.Versioning
{
public sealed partial class FrameworkName : System.IEquatable<System.Runtime.Versioning.FrameworkName>
{
public FrameworkName(string frameworkName) { }
public FrameworkName(string identifier, System.Version version) { }
public FrameworkName(string identifier, System.Version version, string profile) { }
public string FullName { get { return default(string); } }
public string Identifier { get { return default(string); } }
public string Profile { get { return default(string); } }
public System.Version Version { get { return default(System.Version); } }
public override bool Equals(object obj) { return default(bool); }
public bool Equals(System.Runtime.Versioning.FrameworkName other) { return default(bool); }
public override int GetHashCode() { return default(int); }
public static bool operator ==(System.Runtime.Versioning.FrameworkName left, System.Runtime.Versioning.FrameworkName right) { return default(bool); }
public static bool operator !=(System.Runtime.Versioning.FrameworkName left, System.Runtime.Versioning.FrameworkName right) { return default(bool); }
public override string ToString() { return default(string); }
}
}
| |
#region license
// Copyright (c) 2009 Rodrigo B. de Oliveira (rbo@acm.org)
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
// * Neither the name of Rodrigo B. de Oliveira nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#endregion
//
// DO NOT EDIT THIS FILE!
//
// This file was generated automatically by astgen.boo.
//
namespace Boo.Lang.Compiler.Ast
{
using System.Collections;
using System.Runtime.Serialization;
[System.Serializable]
public partial class EnumDefinition : TypeDefinition
{
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
new public EnumDefinition CloneNode()
{
return (EnumDefinition)Clone();
}
/// <summary>
/// <see cref="Node.CleanClone"/>
/// </summary>
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
new public EnumDefinition CleanClone()
{
return (EnumDefinition)base.CleanClone();
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
override public NodeType NodeType
{
get { return NodeType.EnumDefinition; }
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
override public void Accept(IAstVisitor visitor)
{
visitor.OnEnumDefinition(this);
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
override public bool Matches(Node node)
{
if (node == null) return false;
if (NodeType != node.NodeType) return false;
var other = ( EnumDefinition)node;
if (_modifiers != other._modifiers) return NoMatch("EnumDefinition._modifiers");
if (_name != other._name) return NoMatch("EnumDefinition._name");
if (!Node.AllMatch(_attributes, other._attributes)) return NoMatch("EnumDefinition._attributes");
if (!Node.AllMatch(_members, other._members)) return NoMatch("EnumDefinition._members");
if (!Node.AllMatch(_baseTypes, other._baseTypes)) return NoMatch("EnumDefinition._baseTypes");
if (!Node.AllMatch(_genericParameters, other._genericParameters)) return NoMatch("EnumDefinition._genericParameters");
return true;
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
override public bool Replace(Node existing, Node newNode)
{
if (base.Replace(existing, newNode))
{
return true;
}
if (_attributes != null)
{
Attribute item = existing as Attribute;
if (null != item)
{
Attribute newItem = (Attribute)newNode;
if (_attributes.Replace(item, newItem))
{
return true;
}
}
}
if (_members != null)
{
TypeMember item = existing as TypeMember;
if (null != item)
{
TypeMember newItem = (TypeMember)newNode;
if (_members.Replace(item, newItem))
{
return true;
}
}
}
if (_baseTypes != null)
{
TypeReference item = existing as TypeReference;
if (null != item)
{
TypeReference newItem = (TypeReference)newNode;
if (_baseTypes.Replace(item, newItem))
{
return true;
}
}
}
if (_genericParameters != null)
{
GenericParameterDeclaration item = existing as GenericParameterDeclaration;
if (null != item)
{
GenericParameterDeclaration newItem = (GenericParameterDeclaration)newNode;
if (_genericParameters.Replace(item, newItem))
{
return true;
}
}
}
return false;
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
override public object Clone()
{
EnumDefinition clone = (EnumDefinition)FormatterServices.GetUninitializedObject(typeof(EnumDefinition));
clone._lexicalInfo = _lexicalInfo;
clone._endSourceLocation = _endSourceLocation;
clone._documentation = _documentation;
clone._entity = _entity;
if (_annotations != null) clone._annotations = (Hashtable)_annotations.Clone();
clone._modifiers = _modifiers;
clone._name = _name;
if (null != _attributes)
{
clone._attributes = _attributes.Clone() as AttributeCollection;
clone._attributes.InitializeParent(clone);
}
if (null != _members)
{
clone._members = _members.Clone() as TypeMemberCollection;
clone._members.InitializeParent(clone);
}
if (null != _baseTypes)
{
clone._baseTypes = _baseTypes.Clone() as TypeReferenceCollection;
clone._baseTypes.InitializeParent(clone);
}
if (null != _genericParameters)
{
clone._genericParameters = _genericParameters.Clone() as GenericParameterDeclarationCollection;
clone._genericParameters.InitializeParent(clone);
}
return clone;
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
override internal void ClearTypeSystemBindings()
{
_annotations = null;
_entity = null;
if (null != _attributes)
{
_attributes.ClearTypeSystemBindings();
}
if (null != _members)
{
_members.ClearTypeSystemBindings();
}
if (null != _baseTypes)
{
_baseTypes.ClearTypeSystemBindings();
}
if (null != _genericParameters)
{
_genericParameters.ClearTypeSystemBindings();
}
}
}
}
| |
namespace Be.HexEditor
{
partial class FormHexEditor
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(FormHexEditor));
this.menuStrip = new Be.HexEditor.Core.MenuStripEx();
this.fileToolStripMenuItem = new Be.HexEditor.Core.ToolStripMenuItemEx();
this.openToolStripMenuItem = new Be.HexEditor.Core.ToolStripMenuItemEx();
this.toolStripSeparator = new System.Windows.Forms.ToolStripSeparator();
this.saveToolStripMenuItem = new Be.HexEditor.Core.ToolStripMenuItemEx();
this.toolStripSeparator2 = new System.Windows.Forms.ToolStripSeparator();
this.recentFilesToolStripMenuItem = new Be.HexEditor.Core.ToolStripMenuItemEx();
this.toolStripSeparator1 = new System.Windows.Forms.ToolStripSeparator();
this.exitToolStripMenuItem = new Be.HexEditor.Core.ToolStripMenuItemEx();
this.editToolStripMenuItem = new Be.HexEditor.Core.ToolStripMenuItemEx();
this.cutToolStripMenuItem = new Be.HexEditor.Core.ToolStripMenuItemEx();
this.copyToolStripMenuItem = new Be.HexEditor.Core.ToolStripMenuItemEx();
this.pasteToolStripMenuItem = new Be.HexEditor.Core.ToolStripMenuItemEx();
this.toolStripSeparator3 = new System.Windows.Forms.ToolStripSeparator();
this.copyHexStringToolStripMenuItem = new Be.HexEditor.Core.ToolStripMenuItemEx();
this.pasteHexToolStripMenuItem = new Be.HexEditor.Core.ToolStripMenuItemEx();
this.toolStripSeparator4 = new System.Windows.Forms.ToolStripSeparator();
this.findToolStripMenuItem = new Be.HexEditor.Core.ToolStripMenuItemEx();
this.findNextToolStripMenuItem = new Be.HexEditor.Core.ToolStripMenuItemEx();
this.goToToolStripMenuItem = new Be.HexEditor.Core.ToolStripMenuItemEx();
this.toolStripSeparator5 = new System.Windows.Forms.ToolStripSeparator();
this.selectAllToolStripMenuItem = new Be.HexEditor.Core.ToolStripMenuItemEx();
this.viewToolStripMenuItem = new Be.HexEditor.Core.ToolStripMenuItemEx();
this.encodingToolStripMenuItem = new Be.HexEditor.Core.ToolStripMenuItemEx();
this.bitsToolStripMenuItem = new Be.HexEditor.Core.ToolStripMenuItemEx();
this.toolsToolStripMenuItem = new Be.HexEditor.Core.ToolStripMenuItemEx();
this.optionsToolStripMenuItem = new Be.HexEditor.Core.ToolStripMenuItemEx();
this.helpToolStripMenuItem = new Be.HexEditor.Core.ToolStripMenuItemEx();
this.aboutToolStripMenuItem = new Be.HexEditor.Core.ToolStripMenuItemEx();
this.toolStrip = new Be.HexEditor.Core.ToolStripEx();
this.openToolStripButton = new Be.HexEditor.Core.ToolStripButtonEx();
this.saveToolStripButton = new Be.HexEditor.Core.ToolStripButtonEx();
this.toolStripSeparator6 = new System.Windows.Forms.ToolStripSeparator();
this.cutToolStripButton = new Be.HexEditor.Core.ToolStripButtonEx();
this.copyToolStripSplitButton = new Be.HexEditor.Core.ToolStripSplitButtonEx();
this.copyToolStripMenuItem1 = new Be.HexEditor.Core.ToolStripMenuItemEx();
this.copyHexToolStripMenuItem1 = new Be.HexEditor.Core.ToolStripMenuItemEx();
this.pasteToolStripSplitButton = new Be.HexEditor.Core.ToolStripSplitButtonEx();
this.pasteToolStripMenuItem1 = new Be.HexEditor.Core.ToolStripMenuItemEx();
this.pasteHexToolStripMenuItem1 = new Be.HexEditor.Core.ToolStripMenuItemEx();
this.encodingToolStripComboBox = new System.Windows.Forms.ToolStripComboBox();
this.statusStrip = new System.Windows.Forms.StatusStrip();
this.toolStripStatusLabel = new System.Windows.Forms.ToolStripStatusLabel();
this.fileSizeToolStripStatusLabel = new System.Windows.Forms.ToolStripStatusLabel();
this.bitToolStripStatusLabel = new System.Windows.Forms.ToolStripStatusLabel();
this.openFileDialog = new System.Windows.Forms.OpenFileDialog();
this.bodyPanel = new System.Windows.Forms.Panel();
this.hexBox = new Be.Windows.Forms.HexBox();
this.bitControl1 = new Be.HexEditor.BitControl();
this.RecentFileHandler = new Be.HexEditor.RecentFileHandler(this.components);
this.menuStrip.SuspendLayout();
this.toolStrip.SuspendLayout();
this.statusStrip.SuspendLayout();
this.bodyPanel.SuspendLayout();
this.SuspendLayout();
//
// menuStrip
//
this.menuStrip.BackColor = System.Drawing.SystemColors.Control;
this.menuStrip.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.fileToolStripMenuItem,
this.editToolStripMenuItem,
this.viewToolStripMenuItem,
this.toolsToolStripMenuItem,
this.helpToolStripMenuItem});
resources.ApplyResources(this.menuStrip, "menuStrip");
this.menuStrip.Name = "menuStrip";
this.menuStrip.ItemClicked += new System.Windows.Forms.ToolStripItemClickedEventHandler(this.menuStrip_ItemClicked);
//
// fileToolStripMenuItem
//
this.fileToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.openToolStripMenuItem,
this.toolStripSeparator,
this.saveToolStripMenuItem,
this.toolStripSeparator2,
this.recentFilesToolStripMenuItem,
this.toolStripSeparator1,
this.exitToolStripMenuItem});
this.fileToolStripMenuItem.Name = "fileToolStripMenuItem";
resources.ApplyResources(this.fileToolStripMenuItem, "fileToolStripMenuItem");
//
// openToolStripMenuItem
//
this.openToolStripMenuItem.Image = global::Be.HexEditor.ScalingImages.FolderOpen_16;
this.openToolStripMenuItem.Image16 = global::Be.HexEditor.ScalingImages.FolderOpen_16;
this.openToolStripMenuItem.Image24 = global::Be.HexEditor.ScalingImages.FolderOpen_24;
this.openToolStripMenuItem.Image32 = global::Be.HexEditor.ScalingImages.FolderOpen_32;
resources.ApplyResources(this.openToolStripMenuItem, "openToolStripMenuItem");
this.openToolStripMenuItem.Name = "openToolStripMenuItem";
this.openToolStripMenuItem.Click += new System.EventHandler(this.open_Click);
//
// toolStripSeparator
//
this.toolStripSeparator.Name = "toolStripSeparator";
resources.ApplyResources(this.toolStripSeparator, "toolStripSeparator");
//
// saveToolStripMenuItem
//
this.saveToolStripMenuItem.Image = global::Be.HexEditor.ScalingImages.save16;
this.saveToolStripMenuItem.Image16 = global::Be.HexEditor.ScalingImages.save16;
this.saveToolStripMenuItem.Image24 = global::Be.HexEditor.ScalingImages.Save24;
this.saveToolStripMenuItem.Image32 = global::Be.HexEditor.ScalingImages.Save32;
resources.ApplyResources(this.saveToolStripMenuItem, "saveToolStripMenuItem");
this.saveToolStripMenuItem.Name = "saveToolStripMenuItem";
this.saveToolStripMenuItem.Click += new System.EventHandler(this.save_Click);
//
// toolStripSeparator2
//
this.toolStripSeparator2.Name = "toolStripSeparator2";
resources.ApplyResources(this.toolStripSeparator2, "toolStripSeparator2");
//
// recentFilesToolStripMenuItem
//
resources.ApplyResources(this.recentFilesToolStripMenuItem, "recentFilesToolStripMenuItem");
this.recentFilesToolStripMenuItem.Name = "recentFilesToolStripMenuItem";
this.recentFilesToolStripMenuItem.DropDownItemClicked += new System.Windows.Forms.ToolStripItemClickedEventHandler(this.recentFiles_DropDownItemClicked);
//
// toolStripSeparator1
//
this.toolStripSeparator1.Name = "toolStripSeparator1";
resources.ApplyResources(this.toolStripSeparator1, "toolStripSeparator1");
//
// exitToolStripMenuItem
//
this.exitToolStripMenuItem.Name = "exitToolStripMenuItem";
resources.ApplyResources(this.exitToolStripMenuItem, "exitToolStripMenuItem");
this.exitToolStripMenuItem.Click += new System.EventHandler(this.exit_Click);
//
// editToolStripMenuItem
//
this.editToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.cutToolStripMenuItem,
this.copyToolStripMenuItem,
this.pasteToolStripMenuItem,
this.toolStripSeparator3,
this.copyHexStringToolStripMenuItem,
this.pasteHexToolStripMenuItem,
this.toolStripSeparator4,
this.findToolStripMenuItem,
this.findNextToolStripMenuItem,
this.goToToolStripMenuItem,
this.toolStripSeparator5,
this.selectAllToolStripMenuItem});
this.editToolStripMenuItem.Name = "editToolStripMenuItem";
resources.ApplyResources(this.editToolStripMenuItem, "editToolStripMenuItem");
//
// cutToolStripMenuItem
//
this.cutToolStripMenuItem.Image = global::Be.HexEditor.ScalingImages.Cut16;
this.cutToolStripMenuItem.Image16 = global::Be.HexEditor.ScalingImages.Copy16;
this.cutToolStripMenuItem.Image24 = global::Be.HexEditor.ScalingImages.Copy24;
this.cutToolStripMenuItem.Image32 = global::Be.HexEditor.ScalingImages.Copy32;
resources.ApplyResources(this.cutToolStripMenuItem, "cutToolStripMenuItem");
this.cutToolStripMenuItem.Name = "cutToolStripMenuItem";
this.cutToolStripMenuItem.Click += new System.EventHandler(this.cut_Click);
//
// copyToolStripMenuItem
//
this.copyToolStripMenuItem.Image = global::Be.HexEditor.ScalingImages.Copy16;
this.copyToolStripMenuItem.Image16 = global::Be.HexEditor.ScalingImages.Copy16;
this.copyToolStripMenuItem.Image24 = global::Be.HexEditor.ScalingImages.Copy24;
this.copyToolStripMenuItem.Image32 = global::Be.HexEditor.ScalingImages.Copy32;
resources.ApplyResources(this.copyToolStripMenuItem, "copyToolStripMenuItem");
this.copyToolStripMenuItem.Name = "copyToolStripMenuItem";
this.copyToolStripMenuItem.Click += new System.EventHandler(this.copy_Click);
//
// pasteToolStripMenuItem
//
this.pasteToolStripMenuItem.Image = global::Be.HexEditor.ScalingImages.Paste16;
this.pasteToolStripMenuItem.Image16 = global::Be.HexEditor.ScalingImages.Paste16;
this.pasteToolStripMenuItem.Image24 = global::Be.HexEditor.ScalingImages.Paste24;
this.pasteToolStripMenuItem.Image32 = global::Be.HexEditor.ScalingImages.Paste32;
resources.ApplyResources(this.pasteToolStripMenuItem, "pasteToolStripMenuItem");
this.pasteToolStripMenuItem.Name = "pasteToolStripMenuItem";
this.pasteToolStripMenuItem.Click += new System.EventHandler(this.paste_Click);
//
// toolStripSeparator3
//
this.toolStripSeparator3.Name = "toolStripSeparator3";
resources.ApplyResources(this.toolStripSeparator3, "toolStripSeparator3");
//
// copyHexStringToolStripMenuItem
//
this.copyHexStringToolStripMenuItem.Name = "copyHexStringToolStripMenuItem";
resources.ApplyResources(this.copyHexStringToolStripMenuItem, "copyHexStringToolStripMenuItem");
this.copyHexStringToolStripMenuItem.Click += new System.EventHandler(this.copyHex_Click);
//
// pasteHexToolStripMenuItem
//
this.pasteHexToolStripMenuItem.Name = "pasteHexToolStripMenuItem";
resources.ApplyResources(this.pasteHexToolStripMenuItem, "pasteHexToolStripMenuItem");
this.pasteHexToolStripMenuItem.Click += new System.EventHandler(this.pasteHex_Click);
//
// toolStripSeparator4
//
this.toolStripSeparator4.Name = "toolStripSeparator4";
resources.ApplyResources(this.toolStripSeparator4, "toolStripSeparator4");
//
// findToolStripMenuItem
//
this.findToolStripMenuItem.Image = global::Be.HexEditor.ScalingImages.Find16;
this.findToolStripMenuItem.Image16 = global::Be.HexEditor.ScalingImages.Find16;
this.findToolStripMenuItem.Image24 = global::Be.HexEditor.ScalingImages.Find24;
this.findToolStripMenuItem.Image32 = global::Be.HexEditor.ScalingImages.Find32;
this.findToolStripMenuItem.Name = "findToolStripMenuItem";
resources.ApplyResources(this.findToolStripMenuItem, "findToolStripMenuItem");
this.findToolStripMenuItem.Click += new System.EventHandler(this.find_Click);
//
// findNextToolStripMenuItem
//
this.findNextToolStripMenuItem.Image = global::Be.HexEditor.ScalingImages.FindNext16;
this.findNextToolStripMenuItem.Image16 = global::Be.HexEditor.ScalingImages.FindNext16;
this.findNextToolStripMenuItem.Image24 = global::Be.HexEditor.ScalingImages.FindNext24;
this.findNextToolStripMenuItem.Image32 = global::Be.HexEditor.ScalingImages.FindNext32;
this.findNextToolStripMenuItem.Name = "findNextToolStripMenuItem";
resources.ApplyResources(this.findNextToolStripMenuItem, "findNextToolStripMenuItem");
this.findNextToolStripMenuItem.Click += new System.EventHandler(this.findNext_Click);
//
// goToToolStripMenuItem
//
this.goToToolStripMenuItem.Name = "goToToolStripMenuItem";
resources.ApplyResources(this.goToToolStripMenuItem, "goToToolStripMenuItem");
this.goToToolStripMenuItem.Click += new System.EventHandler(this.goTo_Click);
//
// toolStripSeparator5
//
this.toolStripSeparator5.Name = "toolStripSeparator5";
resources.ApplyResources(this.toolStripSeparator5, "toolStripSeparator5");
//
// selectAllToolStripMenuItem
//
this.selectAllToolStripMenuItem.Name = "selectAllToolStripMenuItem";
resources.ApplyResources(this.selectAllToolStripMenuItem, "selectAllToolStripMenuItem");
this.selectAllToolStripMenuItem.Click += new System.EventHandler(this.selectAllToolStripMenuItem_Click);
//
// viewToolStripMenuItem
//
this.viewToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.encodingToolStripMenuItem,
this.bitsToolStripMenuItem});
this.viewToolStripMenuItem.Name = "viewToolStripMenuItem";
resources.ApplyResources(this.viewToolStripMenuItem, "viewToolStripMenuItem");
//
// encodingToolStripMenuItem
//
this.encodingToolStripMenuItem.Name = "encodingToolStripMenuItem";
resources.ApplyResources(this.encodingToolStripMenuItem, "encodingToolStripMenuItem");
//
// bitsToolStripMenuItem
//
this.bitsToolStripMenuItem.CheckOnClick = true;
this.bitsToolStripMenuItem.Name = "bitsToolStripMenuItem";
resources.ApplyResources(this.bitsToolStripMenuItem, "bitsToolStripMenuItem");
this.bitsToolStripMenuItem.CheckedChanged += new System.EventHandler(this.bitsToolStripMenuItem_CheckedChanged);
//
// toolsToolStripMenuItem
//
this.toolsToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.optionsToolStripMenuItem});
this.toolsToolStripMenuItem.Name = "toolsToolStripMenuItem";
resources.ApplyResources(this.toolsToolStripMenuItem, "toolsToolStripMenuItem");
//
// optionsToolStripMenuItem
//
this.optionsToolStripMenuItem.Name = "optionsToolStripMenuItem";
resources.ApplyResources(this.optionsToolStripMenuItem, "optionsToolStripMenuItem");
this.optionsToolStripMenuItem.Click += new System.EventHandler(this.options_Click);
//
// helpToolStripMenuItem
//
this.helpToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.aboutToolStripMenuItem});
this.helpToolStripMenuItem.Name = "helpToolStripMenuItem";
resources.ApplyResources(this.helpToolStripMenuItem, "helpToolStripMenuItem");
//
// aboutToolStripMenuItem
//
this.aboutToolStripMenuItem.Name = "aboutToolStripMenuItem";
resources.ApplyResources(this.aboutToolStripMenuItem, "aboutToolStripMenuItem");
this.aboutToolStripMenuItem.Click += new System.EventHandler(this.about_Click);
//
// toolStrip
//
resources.ApplyResources(this.toolStrip, "toolStrip");
this.toolStrip.BackColor = System.Drawing.SystemColors.Control;
this.toolStrip.GripStyle = System.Windows.Forms.ToolStripGripStyle.Hidden;
this.toolStrip.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.openToolStripButton,
this.saveToolStripButton,
this.toolStripSeparator6,
this.cutToolStripButton,
this.copyToolStripSplitButton,
this.pasteToolStripSplitButton,
this.encodingToolStripComboBox});
this.toolStrip.Name = "toolStrip";
//
// openToolStripButton
//
this.openToolStripButton.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this.openToolStripButton.Image = global::Be.HexEditor.images.openHS;
this.openToolStripButton.Image16 = global::Be.HexEditor.ScalingImages.FolderOpen_16;
this.openToolStripButton.Image24 = global::Be.HexEditor.ScalingImages.FolderOpen_24;
this.openToolStripButton.Image32 = global::Be.HexEditor.ScalingImages.FolderOpen_32;
resources.ApplyResources(this.openToolStripButton, "openToolStripButton");
this.openToolStripButton.Name = "openToolStripButton";
this.openToolStripButton.Click += new System.EventHandler(this.open_Click);
//
// saveToolStripButton
//
this.saveToolStripButton.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this.saveToolStripButton.Image = global::Be.HexEditor.images.saveHS;
this.saveToolStripButton.Image16 = global::Be.HexEditor.ScalingImages.save16;
this.saveToolStripButton.Image24 = global::Be.HexEditor.ScalingImages.Save24;
this.saveToolStripButton.Image32 = global::Be.HexEditor.ScalingImages.Save32;
resources.ApplyResources(this.saveToolStripButton, "saveToolStripButton");
this.saveToolStripButton.Name = "saveToolStripButton";
this.saveToolStripButton.Click += new System.EventHandler(this.save_Click);
//
// toolStripSeparator6
//
this.toolStripSeparator6.Name = "toolStripSeparator6";
resources.ApplyResources(this.toolStripSeparator6, "toolStripSeparator6");
//
// cutToolStripButton
//
this.cutToolStripButton.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this.cutToolStripButton.Image = global::Be.HexEditor.images.CutHS;
this.cutToolStripButton.Image16 = global::Be.HexEditor.ScalingImages.Cut16;
this.cutToolStripButton.Image24 = global::Be.HexEditor.ScalingImages.Copy24;
this.cutToolStripButton.Image32 = global::Be.HexEditor.ScalingImages.Copy32;
resources.ApplyResources(this.cutToolStripButton, "cutToolStripButton");
this.cutToolStripButton.Name = "cutToolStripButton";
this.cutToolStripButton.Click += new System.EventHandler(this.cut_Click);
//
// copyToolStripSplitButton
//
this.copyToolStripSplitButton.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this.copyToolStripSplitButton.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.copyToolStripMenuItem1,
this.copyHexToolStripMenuItem1});
this.copyToolStripSplitButton.ForeColor = System.Drawing.SystemColors.ControlText;
this.copyToolStripSplitButton.Image = global::Be.HexEditor.ScalingImages.Copy16;
this.copyToolStripSplitButton.Image16 = global::Be.HexEditor.ScalingImages.Copy16;
this.copyToolStripSplitButton.Image24 = global::Be.HexEditor.ScalingImages.Copy24;
this.copyToolStripSplitButton.Image32 = global::Be.HexEditor.ScalingImages.Copy32;
resources.ApplyResources(this.copyToolStripSplitButton, "copyToolStripSplitButton");
this.copyToolStripSplitButton.Name = "copyToolStripSplitButton";
this.copyToolStripSplitButton.ButtonClick += new System.EventHandler(this.copy_Click);
//
// copyToolStripMenuItem1
//
this.copyToolStripMenuItem1.Image = global::Be.HexEditor.images.CopyHS;
this.copyToolStripMenuItem1.Name = "copyToolStripMenuItem1";
resources.ApplyResources(this.copyToolStripMenuItem1, "copyToolStripMenuItem1");
this.copyToolStripMenuItem1.Click += new System.EventHandler(this.copy_Click);
//
// copyHexToolStripMenuItem1
//
this.copyHexToolStripMenuItem1.Image = global::Be.HexEditor.images.CopyHS;
this.copyHexToolStripMenuItem1.Name = "copyHexToolStripMenuItem1";
resources.ApplyResources(this.copyHexToolStripMenuItem1, "copyHexToolStripMenuItem1");
this.copyHexToolStripMenuItem1.Click += new System.EventHandler(this.copyHex_Click);
//
// pasteToolStripSplitButton
//
this.pasteToolStripSplitButton.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this.pasteToolStripSplitButton.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.pasteToolStripMenuItem1,
this.pasteHexToolStripMenuItem1});
this.pasteToolStripSplitButton.Image = global::Be.HexEditor.ScalingImages.Paste16;
this.pasteToolStripSplitButton.Image16 = global::Be.HexEditor.ScalingImages.Paste16;
this.pasteToolStripSplitButton.Image24 = global::Be.HexEditor.ScalingImages.Paste24;
this.pasteToolStripSplitButton.Image32 = global::Be.HexEditor.ScalingImages.Paste32;
resources.ApplyResources(this.pasteToolStripSplitButton, "pasteToolStripSplitButton");
this.pasteToolStripSplitButton.Name = "pasteToolStripSplitButton";
this.pasteToolStripSplitButton.ButtonClick += new System.EventHandler(this.paste_Click);
//
// pasteToolStripMenuItem1
//
this.pasteToolStripMenuItem1.Name = "pasteToolStripMenuItem1";
resources.ApplyResources(this.pasteToolStripMenuItem1, "pasteToolStripMenuItem1");
this.pasteToolStripMenuItem1.Click += new System.EventHandler(this.paste_Click);
//
// pasteHexToolStripMenuItem1
//
this.pasteHexToolStripMenuItem1.Name = "pasteHexToolStripMenuItem1";
resources.ApplyResources(this.pasteHexToolStripMenuItem1, "pasteHexToolStripMenuItem1");
this.pasteHexToolStripMenuItem1.Click += new System.EventHandler(this.pasteHex_Click);
//
// encodingToolStripComboBox
//
this.encodingToolStripComboBox.BackColor = System.Drawing.SystemColors.Control;
this.encodingToolStripComboBox.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.encodingToolStripComboBox.DropDownWidth = 180;
resources.ApplyResources(this.encodingToolStripComboBox, "encodingToolStripComboBox");
this.encodingToolStripComboBox.Name = "encodingToolStripComboBox";
this.encodingToolStripComboBox.SelectedIndexChanged += new System.EventHandler(this.toolStripEncoding_SelectedIndexChanged);
//
// statusStrip
//
this.statusStrip.BackColor = System.Drawing.SystemColors.Control;
this.statusStrip.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.toolStripStatusLabel,
this.fileSizeToolStripStatusLabel,
this.bitToolStripStatusLabel});
resources.ApplyResources(this.statusStrip, "statusStrip");
this.statusStrip.Name = "statusStrip";
this.statusStrip.RenderMode = System.Windows.Forms.ToolStripRenderMode.ManagerRenderMode;
this.statusStrip.SizingGrip = false;
//
// toolStripStatusLabel
//
this.toolStripStatusLabel.Margin = new System.Windows.Forms.Padding(5, 3, 0, 2);
this.toolStripStatusLabel.Name = "toolStripStatusLabel";
this.toolStripStatusLabel.Padding = new System.Windows.Forms.Padding(7, 0, 0, 0);
resources.ApplyResources(this.toolStripStatusLabel, "toolStripStatusLabel");
//
// fileSizeToolStripStatusLabel
//
this.fileSizeToolStripStatusLabel.Name = "fileSizeToolStripStatusLabel";
this.fileSizeToolStripStatusLabel.Padding = new System.Windows.Forms.Padding(4, 0, 4, 0);
resources.ApplyResources(this.fileSizeToolStripStatusLabel, "fileSizeToolStripStatusLabel");
//
// bitToolStripStatusLabel
//
this.bitToolStripStatusLabel.Name = "bitToolStripStatusLabel";
resources.ApplyResources(this.bitToolStripStatusLabel, "bitToolStripStatusLabel");
//
// bodyPanel
//
resources.ApplyResources(this.bodyPanel, "bodyPanel");
this.bodyPanel.Controls.Add(this.hexBox);
this.bodyPanel.Controls.Add(this.bitControl1);
this.bodyPanel.Name = "bodyPanel";
//
// hexBox
//
this.hexBox.AllowDrop = true;
resources.ApplyResources(this.hexBox, "hexBox");
this.hexBox.BorderStyle = System.Windows.Forms.BorderStyle.None;
//
//
//
this.hexBox.BuiltInContextMenu.CopyMenuItemImage = global::Be.HexEditor.images.CopyHS;
this.hexBox.BuiltInContextMenu.CopyMenuItemText = resources.GetString("hexBox.BuiltInContextMenu.CopyMenuItemText");
this.hexBox.BuiltInContextMenu.CutMenuItemImage = global::Be.HexEditor.images.CutHS;
this.hexBox.BuiltInContextMenu.CutMenuItemText = resources.GetString("hexBox.BuiltInContextMenu.CutMenuItemText");
this.hexBox.BuiltInContextMenu.PasteMenuItemImage = global::Be.HexEditor.images.PasteHS;
this.hexBox.BuiltInContextMenu.PasteMenuItemText = resources.GetString("hexBox.BuiltInContextMenu.PasteMenuItemText");
this.hexBox.BuiltInContextMenu.SelectAllMenuItemText = resources.GetString("hexBox.BuiltInContextMenu.SelectAllMenuItemText");
this.hexBox.ColumnInfoVisible = true;
this.hexBox.HexCasing = Be.Windows.Forms.HexCasing.Lower;
this.hexBox.InfoForeColor = System.Drawing.Color.Gray;
this.hexBox.LineInfoVisible = true;
this.hexBox.Name = "hexBox";
this.hexBox.ShadowSelectionColor = System.Drawing.Color.FromArgb(((int)(((byte)(100)))), ((int)(((byte)(60)))), ((int)(((byte)(188)))), ((int)(((byte)(255)))));
this.hexBox.StringViewVisible = true;
this.hexBox.UseFixedBytesPerLine = true;
this.hexBox.VScrollBarVisible = true;
this.hexBox.SelectionStartChanged += new System.EventHandler(this.hexBox_SelectionStartChanged);
this.hexBox.SelectionLengthChanged += new System.EventHandler(this.hexBox_SelectionLengthChanged);
this.hexBox.CurrentLineChanged += new System.EventHandler(this.Position_Changed);
this.hexBox.CurrentPositionInLineChanged += new System.EventHandler(this.Position_Changed);
this.hexBox.Copied += new System.EventHandler(this.hexBox_Copied);
this.hexBox.CopiedHex += new System.EventHandler(this.hexBox_CopiedHex);
this.hexBox.RequiredWidthChanged += new System.EventHandler(this.hexBox_RequiredWidthChanged);
this.hexBox.DragDrop += new System.Windows.Forms.DragEventHandler(this.hexBox_DragDrop);
this.hexBox.DragEnter += new System.Windows.Forms.DragEventHandler(this.hexBox_DragEnter);
//
// bitControl1
//
resources.ApplyResources(this.bitControl1, "bitControl1");
this.bitControl1.Name = "bitControl1";
this.bitControl1.BitChanged += new System.EventHandler(this.bitControl1_BitChanged);
//
// RecentFileHandler
//
this.RecentFileHandler.RecentFileToolStripItem = this.recentFilesToolStripMenuItem;
//
// FormHexEditor
//
resources.ApplyResources(this, "$this");
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Dpi;
this.BackColor = System.Drawing.SystemColors.Control;
this.Controls.Add(this.bodyPanel);
this.Controls.Add(this.statusStrip);
this.Controls.Add(this.toolStrip);
this.Controls.Add(this.menuStrip);
this.MainMenuStrip = this.menuStrip;
this.Name = "FormHexEditor";
this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.FormHexEditor_FormClosing);
this.menuStrip.ResumeLayout(false);
this.menuStrip.PerformLayout();
this.toolStrip.ResumeLayout(false);
this.toolStrip.PerformLayout();
this.statusStrip.ResumeLayout(false);
this.statusStrip.PerformLayout();
this.bodyPanel.ResumeLayout(false);
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private Core.MenuStripEx menuStrip;
private Core.ToolStripMenuItemEx fileToolStripMenuItem;
private Core.ToolStripMenuItemEx openToolStripMenuItem;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator;
private Core.ToolStripMenuItemEx saveToolStripMenuItem;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator2;
private Core.ToolStripMenuItemEx exitToolStripMenuItem;
private Core.ToolStripMenuItemEx editToolStripMenuItem;
private Core.ToolStripMenuItemEx cutToolStripMenuItem;
private Core.ToolStripMenuItemEx copyToolStripMenuItem;
private Core.ToolStripMenuItemEx pasteToolStripMenuItem;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator4;
private Core.ToolStripMenuItemEx findToolStripMenuItem;
private Core.ToolStripMenuItemEx toolsToolStripMenuItem;
private Core.ToolStripMenuItemEx optionsToolStripMenuItem;
private Core.ToolStripMenuItemEx helpToolStripMenuItem;
private Core.ToolStripMenuItemEx aboutToolStripMenuItem;
private Core.ToolStripEx toolStrip;
private Core.ToolStripButtonEx openToolStripButton;
private Core.ToolStripButtonEx saveToolStripButton;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator6;
private Core.ToolStripButtonEx cutToolStripButton;
private Be.Windows.Forms.HexBox hexBox;
private System.Windows.Forms.StatusStrip statusStrip;
private Core.ToolStripMenuItemEx findNextToolStripMenuItem;
private Core.ToolStripMenuItemEx goToToolStripMenuItem;
private System.Windows.Forms.OpenFileDialog openFileDialog;
private System.Windows.Forms.ToolStripStatusLabel toolStripStatusLabel;
private Core.ToolStripMenuItemEx recentFilesToolStripMenuItem;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator1;
private System.Windows.Forms.ToolStripStatusLabel fileSizeToolStripStatusLabel;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator3;
private Core.ToolStripMenuItemEx copyHexStringToolStripMenuItem;
private Core.ToolStripMenuItemEx pasteHexToolStripMenuItem;
private Core.ToolStripSplitButtonEx copyToolStripSplitButton;
private Core.ToolStripMenuItemEx copyToolStripMenuItem1;
private Core.ToolStripMenuItemEx copyHexToolStripMenuItem1;
private Core.ToolStripSplitButtonEx pasteToolStripSplitButton;
private Core.ToolStripMenuItemEx pasteToolStripMenuItem1;
private Core.ToolStripMenuItemEx pasteHexToolStripMenuItem1;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator5;
private Core.ToolStripMenuItemEx selectAllToolStripMenuItem;
public RecentFileHandler RecentFileHandler;
private System.Windows.Forms.ToolStripStatusLabel bitToolStripStatusLabel;
private System.Windows.Forms.ToolStripComboBox encodingToolStripComboBox;
private Core.ToolStripMenuItemEx viewToolStripMenuItem;
private Core.ToolStripMenuItemEx encodingToolStripMenuItem;
private Core.ToolStripMenuItemEx bitsToolStripMenuItem;
private BitControl bitControl1;
private System.Windows.Forms.Panel bodyPanel;
}
}
| |
// ------------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information.
// ------------------------------------------------------------------------------
// **NOTE** This file was generated by a tool and any changes will be overwritten.
namespace Microsoft.Graph
{
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Threading;
using System.Linq.Expressions;
/// <summary>
/// The type WorkbookWorksheetsCollectionRequest.
/// </summary>
public partial class WorkbookWorksheetsCollectionRequest : BaseRequest, IWorkbookWorksheetsCollectionRequest
{
/// <summary>
/// Constructs a new WorkbookWorksheetsCollectionRequest.
/// </summary>
/// <param name="requestUrl">The URL for the built request.</param>
/// <param name="client">The <see cref="IBaseClient"/> for handling requests.</param>
/// <param name="options">Query and header option name value pairs for the request.</param>
public WorkbookWorksheetsCollectionRequest(
string requestUrl,
IBaseClient client,
IEnumerable<Option> options)
: base(requestUrl, client, options)
{
}
/// <summary>
/// Adds the specified WorkbookWorksheet to the collection via POST.
/// </summary>
/// <param name="workbookWorksheet">The WorkbookWorksheet to add.</param>
/// <returns>The created WorkbookWorksheet.</returns>
public System.Threading.Tasks.Task<WorkbookWorksheet> AddAsync(WorkbookWorksheet workbookWorksheet)
{
return this.AddAsync(workbookWorksheet, CancellationToken.None);
}
/// <summary>
/// Adds the specified WorkbookWorksheet to the collection via POST.
/// </summary>
/// <param name="workbookWorksheet">The WorkbookWorksheet to add.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param>
/// <returns>The created WorkbookWorksheet.</returns>
public System.Threading.Tasks.Task<WorkbookWorksheet> AddAsync(WorkbookWorksheet workbookWorksheet, CancellationToken cancellationToken)
{
this.ContentType = "application/json";
this.Method = "POST";
return this.SendAsync<WorkbookWorksheet>(workbookWorksheet, cancellationToken);
}
/// <summary>
/// Gets the collection page.
/// </summary>
/// <returns>The collection page.</returns>
public System.Threading.Tasks.Task<IWorkbookWorksheetsCollectionPage> GetAsync()
{
return this.GetAsync(CancellationToken.None);
}
/// <summary>
/// Gets the collection page.
/// </summary>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param>
/// <returns>The collection page.</returns>
public async System.Threading.Tasks.Task<IWorkbookWorksheetsCollectionPage> GetAsync(CancellationToken cancellationToken)
{
this.Method = "GET";
var response = await this.SendAsync<WorkbookWorksheetsCollectionResponse>(null, cancellationToken).ConfigureAwait(false);
if (response != null && response.Value != null && response.Value.CurrentPage != null)
{
if (response.AdditionalData != null)
{
object nextPageLink;
response.AdditionalData.TryGetValue("@odata.nextLink", out nextPageLink);
var nextPageLinkString = nextPageLink as string;
if (!string.IsNullOrEmpty(nextPageLinkString))
{
response.Value.InitializeNextPageRequest(
this.Client,
nextPageLinkString);
}
// Copy the additional data collection to the page itself so that information is not lost
response.Value.AdditionalData = response.AdditionalData;
}
return response.Value;
}
return null;
}
/// <summary>
/// Adds the specified expand value to the request.
/// </summary>
/// <param name="value">The expand value.</param>
/// <returns>The request object to send.</returns>
public IWorkbookWorksheetsCollectionRequest Expand(string value)
{
this.QueryOptions.Add(new QueryOption("$expand", value));
return this;
}
/// <summary>
/// Adds the specified expand value to the request.
/// </summary>
/// <param name="expandExpression">The expression from which to calculate the expand value.</param>
/// <returns>The request object to send.</returns>
public IWorkbookWorksheetsCollectionRequest Expand(Expression<Func<WorkbookWorksheet, object>> expandExpression)
{
if (expandExpression == null)
{
throw new ArgumentNullException(nameof(expandExpression));
}
string error;
string value = ExpressionExtractHelper.ExtractMembers(expandExpression, out error);
if (value == null)
{
throw new ArgumentException(error, nameof(expandExpression));
}
else
{
this.QueryOptions.Add(new QueryOption("$expand", value));
}
return this;
}
/// <summary>
/// Adds the specified select value to the request.
/// </summary>
/// <param name="value">The select value.</param>
/// <returns>The request object to send.</returns>
public IWorkbookWorksheetsCollectionRequest Select(string value)
{
this.QueryOptions.Add(new QueryOption("$select", value));
return this;
}
/// <summary>
/// Adds the specified select value to the request.
/// </summary>
/// <param name="selectExpression">The expression from which to calculate the select value.</param>
/// <returns>The request object to send.</returns>
public IWorkbookWorksheetsCollectionRequest Select(Expression<Func<WorkbookWorksheet, object>> selectExpression)
{
if (selectExpression == null)
{
throw new ArgumentNullException(nameof(selectExpression));
}
string error;
string value = ExpressionExtractHelper.ExtractMembers(selectExpression, out error);
if (value == null)
{
throw new ArgumentException(error, nameof(selectExpression));
}
else
{
this.QueryOptions.Add(new QueryOption("$select", value));
}
return this;
}
/// <summary>
/// Adds the specified top value to the request.
/// </summary>
/// <param name="value">The top value.</param>
/// <returns>The request object to send.</returns>
public IWorkbookWorksheetsCollectionRequest Top(int value)
{
this.QueryOptions.Add(new QueryOption("$top", value.ToString()));
return this;
}
/// <summary>
/// Adds the specified filter value to the request.
/// </summary>
/// <param name="value">The filter value.</param>
/// <returns>The request object to send.</returns>
public IWorkbookWorksheetsCollectionRequest Filter(string value)
{
this.QueryOptions.Add(new QueryOption("$filter", value));
return this;
}
/// <summary>
/// Adds the specified skip value to the request.
/// </summary>
/// <param name="value">The skip value.</param>
/// <returns>The request object to send.</returns>
public IWorkbookWorksheetsCollectionRequest Skip(int value)
{
this.QueryOptions.Add(new QueryOption("$skip", value.ToString()));
return this;
}
/// <summary>
/// Adds the specified orderby value to the request.
/// </summary>
/// <param name="value">The orderby value.</param>
/// <returns>The request object to send.</returns>
public IWorkbookWorksheetsCollectionRequest OrderBy(string value)
{
this.QueryOptions.Add(new QueryOption("$orderby", value));
return this;
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
// This program uses code hyperlinks available as part of the HyperAddin Visual Studio plug-in.
// It is available from http://www.codeplex.com/hyperAddin
#define FEATURE_MANAGED_ETW
#if !ES_BUILD_STANDALONE
#define FEATURE_ACTIVITYSAMPLING
#endif
#if ES_BUILD_STANDALONE
#define FEATURE_MANAGED_ETW_CHANNELS
// #define FEATURE_ADVANCED_MANAGED_ETW_CHANNELS
#endif
#if ES_BUILD_STANDALONE
using Environment = Microsoft.Diagnostics.Tracing.Internal.Environment;
#endif
using System;
using System.Runtime.InteropServices;
using System.Security;
using System.Collections.ObjectModel;
#if !ES_BUILD_AGAINST_DOTNET_V35
using Contract = System.Diagnostics.Contracts.Contract;
using System.Collections.Generic;
using System.Text;
#else
using Contract = Microsoft.Diagnostics.Contracts.Internal.Contract;
using System.Collections.Generic;
using System.Text;
#endif
#if ES_BUILD_STANDALONE
namespace Microsoft.Diagnostics.Tracing
#else
namespace System.Diagnostics.Tracing
#endif
{
public partial class EventSource
{
private byte[] providerMetadata;
/// <summary>
/// Construct an EventSource with a given name for non-contract based events (e.g. those using the Write() API).
/// </summary>
/// <param name="eventSourceName">
/// The name of the event source. Must not be null.
/// </param>
public EventSource(
string eventSourceName)
: this(eventSourceName, EventSourceSettings.EtwSelfDescribingEventFormat)
{ }
/// <summary>
/// Construct an EventSource with a given name for non-contract based events (e.g. those using the Write() API).
/// </summary>
/// <param name="eventSourceName">
/// The name of the event source. Must not be null.
/// </param>
/// <param name="config">
/// Configuration options for the EventSource as a whole.
/// </param>
public EventSource(
string eventSourceName,
EventSourceSettings config)
: this(eventSourceName, config, null) { }
/// <summary>
/// Construct an EventSource with a given name for non-contract based events (e.g. those using the Write() API).
///
/// Also specify a list of key-value pairs called traits (you must pass an even number of strings).
/// The first string is the key and the second is the value. These are not interpreted by EventSource
/// itself but may be interprated the listeners. Can be fetched with GetTrait(string).
/// </summary>
/// <param name="eventSourceName">
/// The name of the event source. Must not be null.
/// </param>
/// <param name="config">
/// Configuration options for the EventSource as a whole.
/// </param>
/// <param name="traits">A collection of key-value strings (must be an even number).</param>
public EventSource(
string eventSourceName,
EventSourceSettings config,
params string[] traits)
: this(
eventSourceName == null ? new Guid() : GenerateGuidFromName(eventSourceName.ToUpperInvariant()),
eventSourceName,
config, traits)
{
if (eventSourceName == null)
{
throw new ArgumentNullException("eventSourceName");
}
Contract.EndContractBlock();
}
/// <summary>
/// Writes an event with no fields and default options.
/// (Native API: EventWriteTransfer)
/// </summary>
/// <param name="eventName">The name of the event. Must not be null.</param>
[SecuritySafeCritical]
public unsafe void Write(string eventName)
{
if (eventName == null)
{
throw new ArgumentNullException("eventName");
}
Contract.EndContractBlock();
if (!this.IsEnabled())
{
return;
}
var options = new EventSourceOptions();
var data = new EmptyStruct();
this.WriteImpl(eventName, ref options, ref data, null, null);
}
/// <summary>
/// Writes an event with no fields.
/// (Native API: EventWriteTransfer)
/// </summary>
/// <param name="eventName">The name of the event. Must not be null.</param>
/// <param name="options">
/// Options for the event, such as the level, keywords, and opcode. Unset
/// options will be set to default values.
/// </param>
[SecuritySafeCritical]
public unsafe void Write(string eventName, EventSourceOptions options)
{
if (eventName == null)
{
throw new ArgumentNullException("eventName");
}
Contract.EndContractBlock();
if (!this.IsEnabled())
{
return;
}
var data = new EmptyStruct();
this.WriteImpl(eventName, ref options, ref data, null, null);
}
/// <summary>
/// Writes an event.
/// (Native API: EventWriteTransfer)
/// </summary>
/// <typeparam name="T">
/// The type that defines the event and its payload. This must be an
/// anonymous type or a type with an [EventData] attribute.
/// </typeparam>
/// <param name="eventName">
/// The name for the event. If null, the event name is automatically
/// determined based on T, either from the Name property of T's EventData
/// attribute or from typeof(T).Name.
/// </param>
/// <param name="data">
/// The object containing the event payload data. The type T must be
/// an anonymous type or a type with an [EventData] attribute. The
/// public instance properties of data will be written recursively to
/// create the fields of the event.
/// </param>
[SecuritySafeCritical]
public unsafe void Write<T>(
string eventName,
T data)
{
if (!this.IsEnabled())
{
return;
}
var options = new EventSourceOptions();
this.WriteImpl(eventName, ref options, ref data, null, null);
}
/// <summary>
/// Writes an event.
/// (Native API: EventWriteTransfer)
/// </summary>
/// <typeparam name="T">
/// The type that defines the event and its payload. This must be an
/// anonymous type or a type with an [EventData] attribute.
/// </typeparam>
/// <param name="eventName">
/// The name for the event. If null, the event name is automatically
/// determined based on T, either from the Name property of T's EventData
/// attribute or from typeof(T).Name.
/// </param>
/// <param name="options">
/// Options for the event, such as the level, keywords, and opcode. Unset
/// options will be set to default values.
/// </param>
/// <param name="data">
/// The object containing the event payload data. The type T must be
/// an anonymous type or a type with an [EventData] attribute. The
/// public instance properties of data will be written recursively to
/// create the fields of the event.
/// </param>
[SecuritySafeCritical]
public unsafe void Write<T>(
string eventName,
EventSourceOptions options,
T data)
{
if (!this.IsEnabled())
{
return;
}
this.WriteImpl(eventName, ref options, ref data, null, null);
}
/// <summary>
/// Writes an event.
/// This overload is for use with extension methods that wish to efficiently
/// forward the options or data parameter without performing an extra copy.
/// (Native API: EventWriteTransfer)
/// </summary>
/// <typeparam name="T">
/// The type that defines the event and its payload. This must be an
/// anonymous type or a type with an [EventData] attribute.
/// </typeparam>
/// <param name="eventName">
/// The name for the event. If null, the event name is automatically
/// determined based on T, either from the Name property of T's EventData
/// attribute or from typeof(T).Name.
/// </param>
/// <param name="options">
/// Options for the event, such as the level, keywords, and opcode. Unset
/// options will be set to default values.
/// </param>
/// <param name="data">
/// The object containing the event payload data. The type T must be
/// an anonymous type or a type with an [EventData] attribute. The
/// public instance properties of data will be written recursively to
/// create the fields of the event.
/// </param>
[SecuritySafeCritical]
public unsafe void Write<T>(
string eventName,
ref EventSourceOptions options,
ref T data)
{
if (!this.IsEnabled())
{
return;
}
this.WriteImpl(eventName, ref options, ref data, null, null);
}
/// <summary>
/// Writes an event.
/// This overload is meant for clients that need to manipuate the activityId
/// and related ActivityId for the event.
/// </summary>
/// <typeparam name="T">
/// The type that defines the event and its payload. This must be an
/// anonymous type or a type with an [EventData] attribute.
/// </typeparam>
/// <param name="eventName">
/// The name for the event. If null, the event name is automatically
/// determined based on T, either from the Name property of T's EventData
/// attribute or from typeof(T).Name.
/// </param>
/// <param name="options">
/// Options for the event, such as the level, keywords, and opcode. Unset
/// options will be set to default values.
/// </param>
/// <param name="activityId">
/// The GUID of the activity associated with this event.
/// </param>
/// <param name="relatedActivityId">
/// The GUID of another activity that is related to this activity, or Guid.Empty
/// if there is no related activity. Most commonly, the Start operation of a
/// new activity specifies a parent activity as its related activity.
/// </param>
/// <param name="data">
/// The object containing the event payload data. The type T must be
/// an anonymous type or a type with an [EventData] attribute. The
/// public instance properties of data will be written recursively to
/// create the fields of the event.
/// </param>
[SecuritySafeCritical]
public unsafe void Write<T>(
string eventName,
ref EventSourceOptions options,
ref Guid activityId,
ref Guid relatedActivityId,
ref T data)
{
if (!this.IsEnabled())
{
return;
}
fixed (Guid* pActivity = &activityId, pRelated = &relatedActivityId)
{
this.WriteImpl(
eventName,
ref options,
ref data,
pActivity,
relatedActivityId == Guid.Empty ? null : pRelated);
}
}
/// <summary>
/// Writes an extended event, where the values of the event are the
/// combined properties of any number of values. This method is
/// intended for use in advanced logging scenarios that support a
/// dynamic set of event context providers.
/// This method does a quick check on whether this event is enabled.
/// </summary>
/// <param name="eventName">
/// The name for the event. If null, the name from eventTypes is used.
/// (Note that providing the event name via the name parameter is slightly
/// less efficient than using the name from eventTypes.)
/// </param>
/// <param name="options">
/// Optional overrides for the event, such as the level, keyword, opcode,
/// activityId, and relatedActivityId. Any settings not specified by options
/// are obtained from eventTypes.
/// </param>
/// <param name="eventTypes">
/// Information about the event and the types of the values in the event.
/// Must not be null. Note that the eventTypes object should be created once and
/// saved. It should not be recreated for each event.
/// </param>
/// <param name="activityID">
/// A pointer to the activity ID GUID to log
/// </param>
/// <param name="childActivityID">
/// A pointer to the child activity ID to log (can be null) </param>
/// <param name="values">
/// The values to include in the event. Must not be null. The number and types of
/// the values must match the number and types of the fields described by the
/// eventTypes parameter.
/// </param>
[SecuritySafeCritical]
private unsafe void WriteMultiMerge(
string eventName,
ref EventSourceOptions options,
TraceLoggingEventTypes eventTypes,
Guid* activityID,
Guid* childActivityID,
params object[] values)
{
if (!this.IsEnabled())
{
return;
}
byte level = (options.valuesSet & EventSourceOptions.levelSet) != 0
? options.level
: eventTypes.level;
EventKeywords keywords = (options.valuesSet & EventSourceOptions.keywordsSet) != 0
? options.keywords
: eventTypes.keywords;
if (this.IsEnabled((EventLevel)level, keywords))
{
WriteMultiMergeInner(eventName, ref options, eventTypes, activityID, childActivityID, values);
}
}
/// <summary>
/// Writes an extended event, where the values of the event are the
/// combined properties of any number of values. This method is
/// intended for use in advanced logging scenarios that support a
/// dynamic set of event context providers.
/// Attention: This API does not check whether the event is enabled or not.
/// Please use WriteMultiMerge to avoid spending CPU cycles for events that are
/// not enabled.
/// </summary>
/// <param name="eventName">
/// The name for the event. If null, the name from eventTypes is used.
/// (Note that providing the event name via the name parameter is slightly
/// less efficient than using the name from eventTypes.)
/// </param>
/// <param name="options">
/// Optional overrides for the event, such as the level, keyword, opcode,
/// activityId, and relatedActivityId. Any settings not specified by options
/// are obtained from eventTypes.
/// </param>
/// <param name="eventTypes">
/// Information about the event and the types of the values in the event.
/// Must not be null. Note that the eventTypes object should be created once and
/// saved. It should not be recreated for each event.
/// </param>
/// <param name="activityID">
/// A pointer to the activity ID GUID to log
/// </param>
/// <param name="childActivityID">
/// A pointer to the child activity ID to log (can be null)
/// </param>
/// <param name="values">
/// The values to include in the event. Must not be null. The number and types of
/// the values must match the number and types of the fields described by the
/// eventTypes parameter.
/// </param>
[SecuritySafeCritical]
private unsafe void WriteMultiMergeInner(
string eventName,
ref EventSourceOptions options,
TraceLoggingEventTypes eventTypes,
Guid* activityID,
Guid* childActivityID,
params object[] values)
{
int identity = 0;
byte level = (options.valuesSet & EventSourceOptions.levelSet) != 0
? options.level
: eventTypes.level;
byte opcode = (options.valuesSet & EventSourceOptions.opcodeSet) != 0
? options.opcode
: eventTypes.opcode;
EventTags tags = (options.valuesSet & EventSourceOptions.tagsSet) != 0
? options.tags
: eventTypes.Tags;
EventKeywords keywords = (options.valuesSet & EventSourceOptions.keywordsSet) != 0
? options.keywords
: eventTypes.keywords;
var nameInfo = eventTypes.GetNameInfo(eventName ?? eventTypes.Name, tags);
if (nameInfo == null)
{
return;
}
identity = nameInfo.identity;
EventDescriptor descriptor = new EventDescriptor(identity, level, opcode, (long)keywords);
var pinCount = eventTypes.pinCount;
var scratch = stackalloc byte[eventTypes.scratchSize];
var descriptors = stackalloc EventData[eventTypes.dataCount + 3];
var pins = stackalloc GCHandle[pinCount];
fixed (byte*
pMetadata0 = this.providerMetadata,
pMetadata1 = nameInfo.nameMetadata,
pMetadata2 = eventTypes.typeMetadata)
{
descriptors[0].SetMetadata(pMetadata0, this.providerMetadata.Length, 2);
descriptors[1].SetMetadata(pMetadata1, nameInfo.nameMetadata.Length, 1);
descriptors[2].SetMetadata(pMetadata2, eventTypes.typeMetadata.Length, 1);
#if !ES_BUILD_PCL
System.Runtime.CompilerServices.RuntimeHelpers.PrepareConstrainedRegions();
#endif
try
{
DataCollector.ThreadInstance.Enable(
scratch,
eventTypes.scratchSize,
descriptors + 3,
eventTypes.dataCount,
pins,
pinCount);
for (int i = 0; i < eventTypes.typeInfos.Length; i++)
{
eventTypes.typeInfos[i].WriteObjectData(TraceLoggingDataCollector.Instance, values[i]);
}
this.WriteEventRaw(
ref descriptor,
activityID,
childActivityID,
(int)(DataCollector.ThreadInstance.Finish() - descriptors),
(IntPtr)descriptors);
}
finally
{
this.WriteCleanup(pins, pinCount);
}
}
}
/// <summary>
/// Writes an extended event, where the values of the event have already
/// been serialized in "data".
/// </summary>
/// <param name="eventName">
/// The name for the event. If null, the name from eventTypes is used.
/// (Note that providing the event name via the name parameter is slightly
/// less efficient than using the name from eventTypes.)
/// </param>
/// <param name="options">
/// Optional overrides for the event, such as the level, keyword, opcode,
/// activityId, and relatedActivityId. Any settings not specified by options
/// are obtained from eventTypes.
/// </param>
/// <param name="eventTypes">
/// Information about the event and the types of the values in the event.
/// Must not be null. Note that the eventTypes object should be created once and
/// saved. It should not be recreated for each event.
/// </param>
/// <param name="activityID">
/// A pointer to the activity ID GUID to log
/// </param>
/// <param name="childActivityID">
/// A pointer to the child activity ID to log (can be null)
/// </param>
/// <param name="data">
/// The previously serialized values to include in the event. Must not be null.
/// The number and types of the values must match the number and types of the
/// fields described by the eventTypes parameter.
/// </param>
[SecuritySafeCritical]
internal unsafe void WriteMultiMerge(
string eventName,
ref EventSourceOptions options,
TraceLoggingEventTypes eventTypes,
Guid* activityID,
Guid* childActivityID,
EventData* data)
{
if (!this.IsEnabled())
{
return;
}
fixed (EventSourceOptions* pOptions = &options)
{
EventDescriptor descriptor;
var nameInfo = this.UpdateDescriptor(eventName, eventTypes, ref options, out descriptor);
if (nameInfo == null)
{
return;
}
// We make a descriptor for each EventData, and because we morph strings to counted strings
// we may have 2 for each arg, so we allocate enough for this.
var descriptors = stackalloc EventData[eventTypes.dataCount + eventTypes.typeInfos.Length * 2 + 3];
fixed (byte*
pMetadata0 = this.providerMetadata,
pMetadata1 = nameInfo.nameMetadata,
pMetadata2 = eventTypes.typeMetadata)
{
descriptors[0].SetMetadata(pMetadata0, this.providerMetadata.Length, 2);
descriptors[1].SetMetadata(pMetadata1, nameInfo.nameMetadata.Length, 1);
descriptors[2].SetMetadata(pMetadata2, eventTypes.typeMetadata.Length, 1);
int numDescrs = 3;
for (int i = 0; i < eventTypes.typeInfos.Length; i++)
{
// Until M3, we need to morph strings to a counted representation
// When TDH supports null terminated strings, we can remove this.
if (eventTypes.typeInfos[i].DataType == typeof(string))
{
// Write out the size of the string
descriptors[numDescrs].m_Ptr = (long)&descriptors[numDescrs + 1].m_Size;
descriptors[numDescrs].m_Size = 2;
numDescrs++;
descriptors[numDescrs].m_Ptr = data[i].m_Ptr;
descriptors[numDescrs].m_Size = data[i].m_Size - 2; // Remove the null terminator
numDescrs++;
}
else
{
descriptors[numDescrs].m_Ptr = data[i].m_Ptr;
descriptors[numDescrs].m_Size = data[i].m_Size;
// old conventions for bool is 4 bytes, but meta-data assumes 1.
if (data[i].m_Size == 4 && eventTypes.typeInfos[i].DataType == typeof(bool))
descriptors[numDescrs].m_Size = 1;
numDescrs++;
}
}
this.WriteEventRaw(
ref descriptor,
activityID,
childActivityID,
numDescrs,
(IntPtr)descriptors);
}
}
}
[SecuritySafeCritical]
private unsafe void WriteImpl<T>(
string eventName,
ref EventSourceOptions options,
ref T data,
Guid* pActivityId,
Guid* pRelatedActivityId)
{
try
{
var eventTypes = SimpleEventTypes<T>.Instance;
fixed (EventSourceOptions* pOptions = &options)
{
EventDescriptor descriptor;
options.Opcode = options.IsOpcodeSet ? options.Opcode : GetOpcodeWithDefault(options.Opcode, eventName);
var nameInfo = this.UpdateDescriptor(eventName, eventTypes, ref options, out descriptor);
if (nameInfo == null)
{
return;
}
var pinCount = eventTypes.pinCount;
var scratch = stackalloc byte[eventTypes.scratchSize];
var descriptors = stackalloc EventData[eventTypes.dataCount + 3];
var pins = stackalloc GCHandle[pinCount];
fixed (byte*
pMetadata0 = this.providerMetadata,
pMetadata1 = nameInfo.nameMetadata,
pMetadata2 = eventTypes.typeMetadata)
{
descriptors[0].SetMetadata(pMetadata0, this.providerMetadata.Length, 2);
descriptors[1].SetMetadata(pMetadata1, nameInfo.nameMetadata.Length, 1);
descriptors[2].SetMetadata(pMetadata2, eventTypes.typeMetadata.Length, 1);
#if !ES_BUILD_PCL
System.Runtime.CompilerServices.RuntimeHelpers.PrepareConstrainedRegions();
#endif
EventOpcode opcode = (EventOpcode)descriptor.Opcode;
Guid activityId = Guid.Empty;
Guid relatedActivityId = Guid.Empty;
if (pActivityId == null && pRelatedActivityId == null &&
((options.ActivityOptions & EventActivityOptions.Disable) == 0))
{
if (opcode == EventOpcode.Start)
{
m_activityTracker.OnStart(m_name, eventName, 0, ref activityId, ref relatedActivityId, options.ActivityOptions);
}
else if (opcode == EventOpcode.Stop)
{
m_activityTracker.OnStop(m_name, eventName, 0, ref activityId);
}
if (activityId != Guid.Empty)
pActivityId = &activityId;
if (relatedActivityId != Guid.Empty)
pRelatedActivityId = &relatedActivityId;
}
try
{
DataCollector.ThreadInstance.Enable(
scratch,
eventTypes.scratchSize,
descriptors + 3,
eventTypes.dataCount,
pins,
pinCount);
eventTypes.typeInfo.WriteData(TraceLoggingDataCollector.Instance, ref data);
this.WriteEventRaw(
ref descriptor,
pActivityId,
pRelatedActivityId,
(int)(DataCollector.ThreadInstance.Finish() - descriptors),
(IntPtr)descriptors);
// TODO enable filtering for listeners.
if (m_Dispatchers != null)
{
var eventData = (EventPayload)(eventTypes.typeInfo.GetData(data));
WriteToAllListeners(eventName, ref descriptor, nameInfo.tags, pActivityId, eventData);
}
}
catch(Exception ex)
{
if (ex is EventSourceException)
throw;
else
ThrowEventSourceException(ex);
}
finally
{
this.WriteCleanup(pins, pinCount);
}
}
}
}
catch (Exception ex)
{
if (ex is EventSourceException)
throw;
else
ThrowEventSourceException(ex);
}
}
[SecurityCritical]
private unsafe void WriteToAllListeners(string eventName, ref EventDescriptor eventDescriptor, EventTags tags, Guid* pActivityId, EventPayload payload)
{
EventWrittenEventArgs eventCallbackArgs = new EventWrittenEventArgs(this);
eventCallbackArgs.EventName = eventName;
eventCallbackArgs.m_level = (EventLevel) eventDescriptor.Level;
eventCallbackArgs.m_keywords = (EventKeywords) eventDescriptor.Keywords;
eventCallbackArgs.m_opcode = (EventOpcode) eventDescriptor.Opcode;
eventCallbackArgs.m_tags = tags;
// Self described events do not have an id attached. We mark it internally with -1.
eventCallbackArgs.EventId = -1;
if (pActivityId != null)
eventCallbackArgs.RelatedActivityId = *pActivityId;
if (payload != null)
{
eventCallbackArgs.Payload = new ReadOnlyCollection<object>((IList<object>)payload.Values);
eventCallbackArgs.PayloadNames = new ReadOnlyCollection<string>((IList<string>)payload.Keys);
}
DispatchToAllListeners(-1, pActivityId, eventCallbackArgs);
}
#if !ES_BUILD_PCL
[System.Runtime.ConstrainedExecution.ReliabilityContract(
System.Runtime.ConstrainedExecution.Consistency.WillNotCorruptState,
System.Runtime.ConstrainedExecution.Cer.Success)]
#endif
[SecurityCritical]
[NonEvent]
private unsafe void WriteCleanup(GCHandle* pPins, int cPins)
{
DataCollector.ThreadInstance.Disable();
for (int i = 0; i != cPins; i++)
{
if (IntPtr.Zero != (IntPtr)pPins[i])
{
pPins[i].Free();
}
}
}
private void InitializeProviderMetadata()
{
if (m_traits != null)
{
List<byte> traitMetaData = new List<byte>(100);
for (int i = 0; i < m_traits.Length - 1; i += 2)
{
if (m_traits[i].StartsWith("ETW_"))
{
string etwTrait = m_traits[i].Substring(4);
byte traitNum;
if (!byte.TryParse(etwTrait, out traitNum))
{
if (etwTrait == "GROUP")
traitNum = 1;
else
throw new ArgumentException(Environment.GetResourceString("UnknownEtwTrait", etwTrait), "traits");
}
string value = m_traits[i + 1];
int lenPos = traitMetaData.Count;
traitMetaData.Add(0); // Emit size (to be filled in later)
traitMetaData.Add(0);
traitMetaData.Add(traitNum); // Emit Trait number
var valueLen = AddValueToMetaData(traitMetaData, value) + 3; // Emit the value bytes +3 accounts for 3 bytes we emited above.
traitMetaData[lenPos] = unchecked((byte)valueLen); // Fill in size
traitMetaData[lenPos + 1] = unchecked((byte)(valueLen >> 8));
}
}
providerMetadata = Statics.MetadataForString(this.Name, 0, traitMetaData.Count, 0);
int startPos = providerMetadata.Length-traitMetaData.Count;
foreach (var b in traitMetaData)
providerMetadata[startPos++] = b;
}
else
providerMetadata = Statics.MetadataForString(this.Name, 0, 0, 0);
}
private static int AddValueToMetaData(List<byte> metaData, string value)
{
if (value.Length == 0)
return 0;
int startPos = metaData.Count;
char firstChar = value[0];
if (firstChar == '@')
metaData.AddRange(Encoding.UTF8.GetBytes(value.Substring(1)));
else if (firstChar == '{')
metaData.AddRange(new Guid(value).ToByteArray());
else if (firstChar == '#')
{
for (int i = 1; i < value.Length; i++)
{
if (value[i] != ' ') // Skip spaces between bytes.
{
if (!(i + 1 < value.Length))
throw new ArgumentException(Environment.GetResourceString("EvenHexDigits"), "traits");
metaData.Add((byte)(HexDigit(value[i]) * 16 + HexDigit(value[i + 1])));
i++;
}
}
}
else if ('A' <= firstChar || ' ' == firstChar) // Is it alphabetic or space (excludes digits and most punctuation).
metaData.AddRange(Encoding.UTF8.GetBytes(value));
else
throw new ArgumentException(Environment.GetResourceString("IllegalValue", value), "traits");
return metaData.Count - startPos;
}
/// <summary>
/// Returns a value 0-15 if 'c' is a hexadecimal digit. If it throws an argument exception.
/// </summary>
private static int HexDigit(char c)
{
if ('0' <= c && c <= '9')
return (c - '0');
if ('a' <= c)
c = unchecked((char) (c - ('a' - 'A'))); // Convert to lower case
if ('A' <= c && c <= 'F')
return (c - 'A' + 10);
throw new ArgumentException(Environment.GetResourceString("BadHexDigit", c), "traits");
}
private NameInfo UpdateDescriptor(
string name,
TraceLoggingEventTypes eventInfo,
ref EventSourceOptions options,
out EventDescriptor descriptor)
{
NameInfo nameInfo = null;
int identity = 0;
byte level = (options.valuesSet & EventSourceOptions.levelSet) != 0
? options.level
: eventInfo.level;
byte opcode = (options.valuesSet & EventSourceOptions.opcodeSet) != 0
? options.opcode
: eventInfo.opcode;
EventTags tags = (options.valuesSet & EventSourceOptions.tagsSet) != 0
? options.tags
: eventInfo.Tags;
EventKeywords keywords = (options.valuesSet & EventSourceOptions.keywordsSet) != 0
? options.keywords
: eventInfo.keywords;
if (this.IsEnabled((EventLevel)level, keywords))
{
nameInfo = eventInfo.GetNameInfo(name ?? eventInfo.Name, tags);
identity = nameInfo.identity;
}
descriptor = new EventDescriptor(identity, level, opcode, (long)keywords);
return nameInfo;
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.