├── .gitattributes ├── .gitignore ├── LICENSE ├── README.md ├── W2Open Code Project.sln ├── W2Open.API ├── App_Start │ ├── BundleConfig.cs │ ├── FilterConfig.cs │ ├── IdentityConfig.cs │ ├── RouteConfig.cs │ ├── Startup.Auth.cs │ └── WebApiConfig.cs ├── Areas │ └── HelpPage │ │ ├── ApiDescriptionExtensions.cs │ │ ├── App_Start │ │ └── HelpPageConfig.cs │ │ ├── Controllers │ │ └── HelpController.cs │ │ ├── HelpPage.css │ │ ├── HelpPageAreaRegistration.cs │ │ ├── HelpPageConfigurationExtensions.cs │ │ ├── ModelDescriptions │ │ ├── CollectionModelDescription.cs │ │ ├── ComplexTypeModelDescription.cs │ │ ├── DictionaryModelDescription.cs │ │ ├── EnumTypeModelDescription.cs │ │ ├── EnumValueDescription.cs │ │ ├── IModelDocumentationProvider.cs │ │ ├── KeyValuePairModelDescription.cs │ │ ├── ModelDescription.cs │ │ ├── ModelDescriptionGenerator.cs │ │ ├── ModelNameAttribute.cs │ │ ├── ModelNameHelper.cs │ │ ├── ParameterAnnotation.cs │ │ ├── ParameterDescription.cs │ │ └── SimpleTypeModelDescription.cs │ │ ├── Models │ │ └── HelpPageApiModel.cs │ │ ├── SampleGeneration │ │ ├── HelpPageSampleGenerator.cs │ │ ├── HelpPageSampleKey.cs │ │ ├── ImageSample.cs │ │ ├── InvalidSample.cs │ │ ├── ObjectGenerator.cs │ │ ├── SampleDirection.cs │ │ └── TextSample.cs │ │ ├── Views │ │ ├── Help │ │ │ ├── Api.cshtml │ │ │ ├── DisplayTemplates │ │ │ │ ├── ApiGroup.cshtml │ │ │ │ ├── CollectionModelDescription.cshtml │ │ │ │ ├── ComplexTypeModelDescription.cshtml │ │ │ │ ├── DictionaryModelDescription.cshtml │ │ │ │ ├── EnumTypeModelDescription.cshtml │ │ │ │ ├── HelpPageApiModel.cshtml │ │ │ │ ├── ImageSample.cshtml │ │ │ │ ├── InvalidSample.cshtml │ │ │ │ ├── KeyValuePairModelDescription.cshtml │ │ │ │ ├── ModelDescriptionLink.cshtml │ │ │ │ ├── Parameters.cshtml │ │ │ │ ├── Samples.cshtml │ │ │ │ ├── SimpleTypeModelDescription.cshtml │ │ │ │ └── TextSample.cshtml │ │ │ ├── Index.cshtml │ │ │ └── ResourceModel.cshtml │ │ ├── Shared │ │ │ └── _Layout.cshtml │ │ ├── Web.config │ │ └── _ViewStart.cshtml │ │ └── XmlDocumentationProvider.cs ├── Content │ ├── Site.css │ ├── bootstrap-theme.css │ ├── bootstrap-theme.css.map │ ├── bootstrap-theme.min.css │ ├── bootstrap-theme.min.css.map │ ├── bootstrap.css │ ├── bootstrap.css.map │ ├── bootstrap.min.css │ └── bootstrap.min.css.map ├── Controllers │ ├── AccountController.cs │ ├── HomeController.cs │ └── ValuesController.cs ├── Global.asax ├── Global.asax.cs ├── Models │ ├── AccountBindingModels.cs │ ├── AccountViewModels.cs │ └── IdentityModels.cs ├── Properties │ └── AssemblyInfo.cs ├── Providers │ └── ApplicationOAuthProvider.cs ├── Results │ └── ChallengeResult.cs ├── Scripts │ ├── bootstrap.js │ ├── bootstrap.min.js │ ├── jquery-3.3.1.intellisense.js │ ├── jquery-3.3.1.js │ ├── jquery-3.3.1.min.js │ ├── jquery-3.3.1.min.map │ ├── jquery-3.3.1.slim.js │ ├── jquery-3.3.1.slim.min.js │ ├── jquery-3.3.1.slim.min.map │ ├── jquery.validate-vsdoc.js │ ├── jquery.validate.js │ ├── jquery.validate.min.js │ ├── jquery.validate.unobtrusive.js │ ├── jquery.validate.unobtrusive.min.js │ └── modernizr-2.8.3.js ├── Startup.cs ├── Views │ ├── Home │ │ └── Index.cshtml │ ├── Shared │ │ ├── Error.cshtml │ │ └── _Layout.cshtml │ ├── Web.config │ └── _ViewStart.cshtml ├── W2Open.API.csproj ├── Web.Debug.config ├── Web.Release.config ├── Web.config ├── favicon.ico ├── fonts │ ├── glyphicons-halflings-regular.eot │ ├── glyphicons-halflings-regular.svg │ ├── glyphicons-halflings-regular.ttf │ ├── glyphicons-halflings-regular.woff │ └── glyphicons-halflings-regular.woff2 └── packages.config ├── W2Open.Common ├── Defines.cs ├── GameBasics.cs ├── GameStructure │ ├── Enuns.cs │ ├── MPacketHeader.cs │ └── Structs.cs ├── ProjectBasics.cs ├── Properties │ └── AssemblyInfo.cs ├── Utility │ ├── CCompoundBuffer.cs │ ├── ConfigServer.cs │ ├── Functions.cs │ ├── MYSQL.cs │ ├── PacketSecurity.cs │ ├── W2GenericExtensionMethods.cs │ ├── W2Log.cs │ ├── W2Marshal.cs │ └── W2Random.cs ├── W2Open.Common.csproj └── packages.config ├── W2Open.DataServer ├── PersistencyBasics.cs ├── Properties │ └── AssemblyInfo.cs └── W2Open.DataServer.csproj ├── W2Open.GameState.Plugin ├── DefaultPlayerRequestHandler │ ├── PacketControl │ │ └── PacketsFunctions.cs │ └── ProcessClientMessage.cs ├── IGameStatePlugin.cs ├── PluginController.cs ├── Properties │ └── AssemblyInfo.cs ├── W2Open.GameState.Plugin.csproj └── packages.config ├── W2Open.GameState ├── CGameStateController.cs ├── CPlayer.cs ├── ERequestResult.cs ├── ProcessSecTimer │ ├── ProcessImportItem.cs │ ├── ProcessImportUser.cs │ ├── ProcessUpdateUser.cs │ └── SecTimer.cs ├── Properties │ └── AssemblyInfo.cs ├── W2Open.GameState.csproj └── packages.config ├── W2Open.Server ├── App.config ├── MainForm.cs ├── MainForm.designer.cs ├── MainForm.resx ├── ProcessSecTimer │ └── MainSecTimer.cs ├── Program.cs ├── Properties │ ├── AssemblyInfo.cs │ ├── Resources.Designer.cs │ ├── Resources.resx │ ├── Settings.Designer.cs │ └── Settings.settings ├── W2Open.Server.csproj ├── icon1.ico └── packages.config └── config.json /.gitattributes: -------------------------------------------------------------------------------- 1 | ############################################################################### 2 | # Set default behavior to automatically normalize line endings. 3 | ############################################################################### 4 | * text=auto 5 | 6 | ############################################################################### 7 | # Set default behavior for command prompt diff. 8 | # 9 | # This is need for earlier builds of msysgit that does not have it on by 10 | # default for csharp files. 11 | # Note: This is only used by command line 12 | ############################################################################### 13 | #*.cs diff=csharp 14 | 15 | ############################################################################### 16 | # Set the merge driver for project and solution files 17 | # 18 | # Merging from the command prompt will add diff markers to the files if there 19 | # are conflicts (Merging from VS is not affected by the settings below, in VS 20 | # the diff markers are never inserted). Diff markers may cause the following 21 | # file extensions to fail to load in VS. An alternative would be to treat 22 | # these files as binary and thus will always conflict and require user 23 | # intervention with every merge. To do so, just uncomment the entries below 24 | ############################################################################### 25 | #*.sln merge=binary 26 | #*.csproj merge=binary 27 | #*.vbproj merge=binary 28 | #*.vcxproj merge=binary 29 | #*.vcproj merge=binary 30 | #*.dbproj merge=binary 31 | #*.fsproj merge=binary 32 | #*.lsproj merge=binary 33 | #*.wixproj merge=binary 34 | #*.modelproj merge=binary 35 | #*.sqlproj merge=binary 36 | #*.wwaproj merge=binary 37 | 38 | ############################################################################### 39 | # behavior for image files 40 | # 41 | # image files are treated as binary by default. 42 | ############################################################################### 43 | #*.jpg binary 44 | #*.png binary 45 | #*.gif binary 46 | 47 | ############################################################################### 48 | # diff behavior for common document formats 49 | # 50 | # Convert binary document formats to text before diffing them. This feature 51 | # is only available from the command line. Turn it on by uncommenting the 52 | # entries below. 53 | ############################################################################### 54 | #*.doc diff=astextplain 55 | #*.DOC diff=astextplain 56 | #*.docx diff=astextplain 57 | #*.DOCX diff=astextplain 58 | #*.dot diff=astextplain 59 | #*.DOT diff=astextplain 60 | #*.pdf diff=astextplain 61 | #*.PDF diff=astextplain 62 | #*.rtf diff=astextplain 63 | #*.RTF diff=astextplain 64 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | ## Ignore Visual Studio temporary files, build results, and 2 | ## files generated by popular Visual Studio add-ons. 3 | 4 | # User-specific files 5 | *.suo 6 | *.user 7 | *.userosscache 8 | *.sln.docstates 9 | 10 | # User-specific files (MonoDevelop/Xamarin Studio) 11 | *.userprefs 12 | 13 | # Build results 14 | [Dd]ebug/ 15 | [Dd]ebugPublic/ 16 | [Rr]elease/ 17 | [Rr]eleases/ 18 | [Xx]64/ 19 | [Xx]86/ 20 | [Bb]uild/ 21 | bld/ 22 | [Bb]in/ 23 | [Oo]bj/ 24 | 25 | # Visual Studio 2015 cache/options directory 26 | .vs/ 27 | # Uncomment if you have tasks that create the project's static files in wwwroot 28 | #wwwroot/ 29 | 30 | # MSTest test Results 31 | [Tt]est[Rr]esult*/ 32 | [Bb]uild[Ll]og.* 33 | 34 | # NUNIT 35 | *.VisualState.xml 36 | TestResult.xml 37 | 38 | # Build Results of an ATL Project 39 | [Dd]ebugPS/ 40 | [Rr]eleasePS/ 41 | dlldata.c 42 | 43 | # DNX 44 | project.lock.json 45 | artifacts/ 46 | 47 | *_i.c 48 | *_p.c 49 | *_i.h 50 | *.ilk 51 | *.meta 52 | *.obj 53 | *.pch 54 | *.pdb 55 | *.pgc 56 | *.pgd 57 | *.rsp 58 | *.sbr 59 | *.tlb 60 | *.tli 61 | *.tlh 62 | *.tmp 63 | *.tmp_proj 64 | *.log 65 | *.vspscc 66 | *.vssscc 67 | .builds 68 | *.pidb 69 | *.svclog 70 | *.scc 71 | 72 | # Chutzpah Test files 73 | _Chutzpah* 74 | 75 | # Visual C++ cache files 76 | ipch/ 77 | *.aps 78 | *.ncb 79 | *.opendb 80 | *.opensdf 81 | *.sdf 82 | *.cachefile 83 | *.VC.db 84 | 85 | # Visual Studio profiler 86 | *.psess 87 | *.vsp 88 | *.vspx 89 | *.sap 90 | 91 | # TFS 2012 Local Workspace 92 | $tf/ 93 | 94 | # Guidance Automation Toolkit 95 | *.gpState 96 | 97 | # ReSharper is a .NET coding add-in 98 | _ReSharper*/ 99 | *.[Rr]e[Ss]harper 100 | *.DotSettings.user 101 | 102 | # JustCode is a .NET coding add-in 103 | .JustCode 104 | 105 | # TeamCity is a build add-in 106 | _TeamCity* 107 | 108 | # DotCover is a Code Coverage Tool 109 | *.dotCover 110 | 111 | # NCrunch 112 | _NCrunch_* 113 | .*crunch*.local.xml 114 | nCrunchTemp_* 115 | 116 | # MightyMoose 117 | *.mm.* 118 | AutoTest.Net/ 119 | 120 | # Web workbench (sass) 121 | .sass-cache/ 122 | 123 | # Installshield output folder 124 | [Ee]xpress/ 125 | 126 | # DocProject is a documentation generator add-in 127 | DocProject/buildhelp/ 128 | DocProject/Help/*.HxT 129 | DocProject/Help/*.HxC 130 | DocProject/Help/*.hhc 131 | DocProject/Help/*.hhk 132 | DocProject/Help/*.hhp 133 | DocProject/Help/Html2 134 | DocProject/Help/html 135 | 136 | # Click-Once directory 137 | publish/ 138 | 139 | # Publish Web Output 140 | *.[Pp]ublish.xml 141 | *.azurePubxml 142 | 143 | # TODO: Un-comment the next line if you do not want to checkin 144 | # your web deploy settings because they may include unencrypted 145 | # passwords 146 | #*.pubxml 147 | *.publishproj 148 | 149 | # NuGet Packages 150 | *.nupkg 151 | # The packages folder can be ignored because of Package Restore 152 | **/packages/* 153 | # except build/, which is used as an MSBuild target. 154 | !**/packages/build/ 155 | # Uncomment if necessary however generally it will be regenerated when needed 156 | #!**/packages/repositories.config 157 | # NuGet v3's project.json files produces more ignoreable files 158 | *.nuget.props 159 | *.nuget.targets 160 | 161 | # Microsoft Azure Build Output 162 | csx/ 163 | *.build.csdef 164 | 165 | # Microsoft Azure Emulator 166 | ecf/ 167 | rcf/ 168 | 169 | # Microsoft Azure ApplicationInsights config file 170 | ApplicationInsights.config 171 | 172 | # Windows Store app package directory 173 | AppPackages/ 174 | BundleArtifacts/ 175 | 176 | # Visual Studio cache files 177 | # files ending in .cache can be ignored 178 | *.[Cc]ache 179 | # but keep track of directories ending in .cache 180 | !*.[Cc]ache/ 181 | 182 | # Others 183 | ClientBin/ 184 | [Ss]tyle[Cc]op.* 185 | ~$* 186 | *~ 187 | *.dbmdl 188 | *.dbproj.schemaview 189 | *.pfx 190 | *.publishsettings 191 | node_modules/ 192 | orleans.codegen.cs 193 | 194 | # RIA/Silverlight projects 195 | Generated_Code/ 196 | 197 | # Backup & report files from converting an old project file 198 | # to a newer Visual Studio version. Backup files are not needed, 199 | # because we have git ;-) 200 | _UpgradeReport_Files/ 201 | Backup*/ 202 | UpgradeLog*.XML 203 | UpgradeLog*.htm 204 | 205 | # SQL Server files 206 | *.mdf 207 | *.ldf 208 | 209 | # Business Intelligence projects 210 | *.rdl.data 211 | *.bim.layout 212 | *.bim_*.settings 213 | 214 | # Microsoft Fakes 215 | FakesAssemblies/ 216 | 217 | # GhostDoc plugin setting file 218 | *.GhostDoc.xml 219 | 220 | # Node.js Tools for Visual Studio 221 | .ntvs_analysis.dat 222 | 223 | # Visual Studio 6 build log 224 | *.plg 225 | 226 | # Visual Studio 6 workspace options file 227 | *.opt 228 | 229 | # Visual Studio LightSwitch build output 230 | **/*.HTMLClient/GeneratedArtifacts 231 | **/*.DesktopClient/GeneratedArtifacts 232 | **/*.DesktopClient/ModelManifest.xml 233 | **/*.Server/GeneratedArtifacts 234 | **/*.Server/ModelManifest.xml 235 | _Pvt_Extensions 236 | 237 | # LightSwitch generated files 238 | GeneratedArtifacts/ 239 | ModelManifest.xml 240 | 241 | # Paket dependency manager 242 | .paket/paket.exe 243 | 244 | # FAKE - F# Make 245 | .fake/ -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ![W2OpenProject Logo](http://was547.com/osi.png) 2 | 3 | 4 | # W2Open - C# W2 Server Emulator # 5 | 6 | W2Open is a free C# W2 Server Emulator which is completely written in C# and compiled with Roslyn. 7 | 8 | W2Open currently it's developed by indie community on the internet. 9 | 10 | For more details, take a look at the source or the [online documentation (Soon)](#). 11 | 12 | Feel free to download or clone the source code: 13 | 14 | https://github.com/andresantacruz/W2Open-Code-Project.git 15 | 16 | ### Why W2Open Project? ### 17 | - **Secure and powerful** 18 | - **Designed for newbies and professionals** 19 | - **Tons of features** 20 | - **Chance to develop your own emulator** 21 | - **Licensed under the GNU-GPL** 22 | 23 | ### Supported Features ### 24 | 25 | Currently the following features are implemented: 26 | 27 | - **Soon** 28 | 29 | Required Resources: 30 | - [Roslyn](https://github.com/dotnet/roslyn): C# Compiler._ 31 | - ... 32 | 33 | 34 | #### As long as this document is in development, see [W2Open Discussion](http://forum.brasilwyd.com/index.php?/topic/68-w2open-project-apresenta%C3%A7%C3%A3o/) for more details. #### 35 | -------------------------------------------------------------------------------- /W2Open Code Project.sln: -------------------------------------------------------------------------------- 1 |  2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio Version 16 4 | VisualStudioVersion = 16.0.29411.108 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "W2Open.Common", "W2Open.Common\W2Open.Common.csproj", "{9E37305B-BADD-49E4-842A-FC45B8CE0B95}" 7 | EndProject 8 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "W2Open.DataServer", "W2Open.DataServer\W2Open.DataServer.csproj", "{5CA9998D-9362-417A-89FD-C7603C59BB46}" 9 | EndProject 10 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "W2Open.Server", "W2Open.Server\W2Open.Server.csproj", "{C1E44D36-A1FB-478F-8F8D-D3E3CD16750B}" 11 | EndProject 12 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "W2Open.GameState", "W2Open.GameState\W2Open.GameState.csproj", "{7F6663C7-A2BF-4637-B018-70CFE7C39DC4}" 13 | EndProject 14 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "W2Open.GameState.Plugin", "W2Open.GameState.Plugin\W2Open.GameState.Plugin.csproj", "{756C8536-C282-47F2-843F-C3334B5F619D}" 15 | EndProject 16 | Global 17 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 18 | Debug|Any CPU = Debug|Any CPU 19 | Release|Any CPU = Release|Any CPU 20 | EndGlobalSection 21 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 22 | {9E37305B-BADD-49E4-842A-FC45B8CE0B95}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 23 | {9E37305B-BADD-49E4-842A-FC45B8CE0B95}.Debug|Any CPU.Build.0 = Debug|Any CPU 24 | {9E37305B-BADD-49E4-842A-FC45B8CE0B95}.Release|Any CPU.ActiveCfg = Release|Any CPU 25 | {9E37305B-BADD-49E4-842A-FC45B8CE0B95}.Release|Any CPU.Build.0 = Release|Any CPU 26 | {5CA9998D-9362-417A-89FD-C7603C59BB46}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 27 | {5CA9998D-9362-417A-89FD-C7603C59BB46}.Debug|Any CPU.Build.0 = Debug|Any CPU 28 | {5CA9998D-9362-417A-89FD-C7603C59BB46}.Release|Any CPU.ActiveCfg = Release|Any CPU 29 | {5CA9998D-9362-417A-89FD-C7603C59BB46}.Release|Any CPU.Build.0 = Release|Any CPU 30 | {C1E44D36-A1FB-478F-8F8D-D3E3CD16750B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 31 | {C1E44D36-A1FB-478F-8F8D-D3E3CD16750B}.Debug|Any CPU.Build.0 = Debug|Any CPU 32 | {C1E44D36-A1FB-478F-8F8D-D3E3CD16750B}.Release|Any CPU.ActiveCfg = Release|Any CPU 33 | {C1E44D36-A1FB-478F-8F8D-D3E3CD16750B}.Release|Any CPU.Build.0 = Release|Any CPU 34 | {7F6663C7-A2BF-4637-B018-70CFE7C39DC4}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 35 | {7F6663C7-A2BF-4637-B018-70CFE7C39DC4}.Debug|Any CPU.Build.0 = Debug|Any CPU 36 | {7F6663C7-A2BF-4637-B018-70CFE7C39DC4}.Release|Any CPU.ActiveCfg = Release|Any CPU 37 | {7F6663C7-A2BF-4637-B018-70CFE7C39DC4}.Release|Any CPU.Build.0 = Release|Any CPU 38 | {756C8536-C282-47F2-843F-C3334B5F619D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 39 | {756C8536-C282-47F2-843F-C3334B5F619D}.Debug|Any CPU.Build.0 = Debug|Any CPU 40 | {756C8536-C282-47F2-843F-C3334B5F619D}.Release|Any CPU.ActiveCfg = Release|Any CPU 41 | {756C8536-C282-47F2-843F-C3334B5F619D}.Release|Any CPU.Build.0 = Release|Any CPU 42 | EndGlobalSection 43 | GlobalSection(SolutionProperties) = preSolution 44 | HideSolutionNode = FALSE 45 | EndGlobalSection 46 | GlobalSection(ExtensibilityGlobals) = postSolution 47 | SolutionGuid = {7FD52D53-0B33-4920-AAC2-61BA6BEE7E57} 48 | EndGlobalSection 49 | EndGlobal 50 | -------------------------------------------------------------------------------- /W2Open.API/App_Start/BundleConfig.cs: -------------------------------------------------------------------------------- 1 | using System.Web; 2 | using System.Web.Optimization; 3 | 4 | namespace W2Open.API 5 | { 6 | public class BundleConfig 7 | { 8 | // Para obter mais informações sobre o agrupamento, visite https://go.microsoft.com/fwlink/?LinkId=301862 9 | public static void RegisterBundles(BundleCollection bundles) 10 | { 11 | bundles.Add(new ScriptBundle("~/bundles/jquery").Include( 12 | "~/Scripts/jquery-{version}.js")); 13 | 14 | // Use a versão em desenvolvimento do Modernizr para desenvolver e aprender com ela. Após isso, quando você estiver 15 | // pronto para a produção, utilize a ferramenta de build em https://modernizr.com para escolher somente os testes que precisa. 16 | bundles.Add(new ScriptBundle("~/bundles/modernizr").Include( 17 | "~/Scripts/modernizr-*")); 18 | 19 | bundles.Add(new ScriptBundle("~/bundles/bootstrap").Include( 20 | "~/Scripts/bootstrap.js")); 21 | 22 | bundles.Add(new StyleBundle("~/Content/css").Include( 23 | "~/Content/bootstrap.css", 24 | "~/Content/site.css")); 25 | } 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /W2Open.API/App_Start/FilterConfig.cs: -------------------------------------------------------------------------------- 1 | using System.Web; 2 | using System.Web.Mvc; 3 | 4 | namespace W2Open.API 5 | { 6 | public class FilterConfig 7 | { 8 | public static void RegisterGlobalFilters(GlobalFilterCollection filters) 9 | { 10 | filters.Add(new HandleErrorAttribute()); 11 | } 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /W2Open.API/App_Start/IdentityConfig.cs: -------------------------------------------------------------------------------- 1 | using System.Threading.Tasks; 2 | using Microsoft.AspNet.Identity; 3 | using Microsoft.AspNet.Identity.EntityFramework; 4 | using Microsoft.AspNet.Identity.Owin; 5 | using Microsoft.Owin; 6 | using W2Open.API.Models; 7 | 8 | namespace W2Open.API 9 | { 10 | // Configure o gerenciador de usuários do aplicativo usado nesse aplicativo. O UserManager está definido no ASP.NET Identity e é usado pelo aplicativo. 11 | 12 | public class ApplicationUserManager : UserManager 13 | { 14 | public ApplicationUserManager(IUserStore store) 15 | : base(store) 16 | { 17 | } 18 | 19 | public static ApplicationUserManager Create(IdentityFactoryOptions options, IOwinContext context) 20 | { 21 | var manager = new ApplicationUserManager(new UserStore(context.Get())); 22 | // Configurar a lógica de validação para nomes de usuário 23 | manager.UserValidator = new UserValidator(manager) 24 | { 25 | AllowOnlyAlphanumericUserNames = false, 26 | RequireUniqueEmail = true 27 | }; 28 | // Configurar a lógica de validação para senhas 29 | manager.PasswordValidator = new PasswordValidator 30 | { 31 | RequiredLength = 6, 32 | RequireNonLetterOrDigit = true, 33 | RequireDigit = true, 34 | RequireLowercase = true, 35 | RequireUppercase = true, 36 | }; 37 | var dataProtectionProvider = options.DataProtectionProvider; 38 | if (dataProtectionProvider != null) 39 | { 40 | manager.UserTokenProvider = new DataProtectorTokenProvider(dataProtectionProvider.Create("ASP.NET Identity")); 41 | } 42 | return manager; 43 | } 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /W2Open.API/App_Start/RouteConfig.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Web; 5 | using System.Web.Mvc; 6 | using System.Web.Routing; 7 | 8 | namespace W2Open.API 9 | { 10 | public class RouteConfig 11 | { 12 | public static void RegisterRoutes(RouteCollection routes) 13 | { 14 | routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); 15 | 16 | routes.MapRoute( 17 | name: "Default", 18 | url: "{controller}/{action}/{id}", 19 | defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional } 20 | ); 21 | } 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /W2Open.API/App_Start/Startup.Auth.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using Microsoft.AspNet.Identity; 5 | using Microsoft.AspNet.Identity.EntityFramework; 6 | using Microsoft.Owin; 7 | using Microsoft.Owin.Security.Cookies; 8 | using Microsoft.Owin.Security.Google; 9 | using Microsoft.Owin.Security.OAuth; 10 | using Owin; 11 | using W2Open.API.Providers; 12 | using W2Open.API.Models; 13 | 14 | namespace W2Open.API 15 | { 16 | public partial class Startup 17 | { 18 | public static OAuthAuthorizationServerOptions OAuthOptions { get; private set; } 19 | 20 | public static string PublicClientId { get; private set; } 21 | 22 | // Para obter mais informações sobre a autenticação de configuração, visite https://go.microsoft.com/fwlink/?LinkId=301864 23 | public void ConfigureAuth(IAppBuilder app) 24 | { 25 | // Configure o contexto do banco de dados e o gerenciador de usuários para usar uma instância por solicitação 26 | app.CreatePerOwinContext(ApplicationDbContext.Create); 27 | app.CreatePerOwinContext(ApplicationUserManager.Create); 28 | 29 | // Habilite o aplicativo para usar um cookie que armazena informações do usuário conectado 30 | // e um cookie que armazena informações temporárias sobre um usuário que faz login em um provedor de login de terceiros 31 | app.UseCookieAuthentication(new CookieAuthenticationOptions()); 32 | app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie); 33 | 34 | // Configure o aplicativo para fluxo com base em OAuth 35 | PublicClientId = "self"; 36 | OAuthOptions = new OAuthAuthorizationServerOptions 37 | { 38 | TokenEndpointPath = new PathString("/Token"), 39 | Provider = new ApplicationOAuthProvider(PublicClientId), 40 | AuthorizeEndpointPath = new PathString("/api/Account/ExternalLogin"), 41 | AccessTokenExpireTimeSpan = TimeSpan.FromDays(14), 42 | // Em modo de produção, defina AllowInsecureHttp = false 43 | AllowInsecureHttp = true 44 | }; 45 | 46 | // Habilite o aplicativo para usar tokens portadores na autenticação de usuários 47 | app.UseOAuthBearerTokens(OAuthOptions); 48 | 49 | // Remova comentários das linhas a seguir para habilitar o login com provedores de login de terceiros 50 | //app.UseMicrosoftAccountAuthentication( 51 | // clientId: "", 52 | // clientSecret: ""); 53 | 54 | //app.UseTwitterAuthentication( 55 | // consumerKey: "", 56 | // consumerSecret: ""); 57 | 58 | //app.UseFacebookAuthentication( 59 | // appId: "", 60 | // appSecret: ""); 61 | 62 | //app.UseGoogleAuthentication(new GoogleOAuth2AuthenticationOptions() 63 | //{ 64 | // ClientId = "", 65 | // ClientSecret = "" 66 | //}); 67 | } 68 | } 69 | } 70 | -------------------------------------------------------------------------------- /W2Open.API/App_Start/WebApiConfig.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Net.Http; 5 | using System.Web.Http; 6 | using Microsoft.Owin.Security.OAuth; 7 | using Newtonsoft.Json.Serialization; 8 | 9 | namespace W2Open.API 10 | { 11 | public static class WebApiConfig 12 | { 13 | public static void Register(HttpConfiguration config) 14 | { 15 | // Configuração e serviços de API Web 16 | // Configure a API Web para usar somente a autenticação de token de portador. 17 | config.SuppressDefaultHostAuthentication(); 18 | config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType)); 19 | 20 | // Rotas de API Web 21 | config.MapHttpAttributeRoutes(); 22 | 23 | config.Routes.MapHttpRoute( 24 | name: "DefaultApi", 25 | routeTemplate: "api/{controller}/{id}", 26 | defaults: new { id = RouteParameter.Optional } 27 | ); 28 | } 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /W2Open.API/Areas/HelpPage/ApiDescriptionExtensions.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Text; 3 | using System.Web; 4 | using System.Web.Http.Description; 5 | 6 | namespace W2Open.API.Areas.HelpPage 7 | { 8 | public static class ApiDescriptionExtensions 9 | { 10 | /// 11 | /// Generates an URI-friendly ID for the . E.g. "Get-Values-id_name" instead of "GetValues/{id}?name={name}" 12 | /// 13 | /// The . 14 | /// The ID as a string. 15 | public static string GetFriendlyId(this ApiDescription description) 16 | { 17 | string path = description.RelativePath; 18 | string[] urlParts = path.Split('?'); 19 | string localPath = urlParts[0]; 20 | string queryKeyString = null; 21 | if (urlParts.Length > 1) 22 | { 23 | string query = urlParts[1]; 24 | string[] queryKeys = HttpUtility.ParseQueryString(query).AllKeys; 25 | queryKeyString = String.Join("_", queryKeys); 26 | } 27 | 28 | StringBuilder friendlyPath = new StringBuilder(); 29 | friendlyPath.AppendFormat("{0}-{1}", 30 | description.HttpMethod.Method, 31 | localPath.Replace("/", "-").Replace("{", String.Empty).Replace("}", String.Empty)); 32 | if (queryKeyString != null) 33 | { 34 | friendlyPath.AppendFormat("_{0}", queryKeyString.Replace('.', '-')); 35 | } 36 | return friendlyPath.ToString(); 37 | } 38 | } 39 | } -------------------------------------------------------------------------------- /W2Open.API/Areas/HelpPage/App_Start/HelpPageConfig.cs: -------------------------------------------------------------------------------- 1 | // Uncomment the following to provide samples for PageResult. Must also add the Microsoft.AspNet.WebApi.OData 2 | // package to your project. 3 | ////#define Handle_PageResultOfT 4 | 5 | using System; 6 | using System.Collections; 7 | using System.Collections.Generic; 8 | using System.Diagnostics; 9 | using System.Diagnostics.CodeAnalysis; 10 | using System.Linq; 11 | using System.Net.Http.Headers; 12 | using System.Reflection; 13 | using System.Web; 14 | using System.Web.Http; 15 | #if Handle_PageResultOfT 16 | using System.Web.Http.OData; 17 | #endif 18 | 19 | namespace W2Open.API.Areas.HelpPage 20 | { 21 | /// 22 | /// Use this class to customize the Help Page. 23 | /// For example you can set a custom to supply the documentation 24 | /// or you can provide the samples for the requests/responses. 25 | /// 26 | public static class HelpPageConfig 27 | { 28 | [SuppressMessage("Microsoft.Globalization", "CA1303:Do not pass literals as localized parameters", 29 | MessageId = "W2Open.API.Areas.HelpPage.TextSample.#ctor(System.String)", 30 | Justification = "End users may choose to merge this string with existing localized resources.")] 31 | [SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly", 32 | MessageId = "bsonspec", 33 | Justification = "Part of a URI.")] 34 | public static void Register(HttpConfiguration config) 35 | { 36 | //// Uncomment the following to use the documentation from XML documentation file. 37 | //config.SetDocumentationProvider(new XmlDocumentationProvider(HttpContext.Current.Server.MapPath("~/App_Data/XmlDocument.xml"))); 38 | 39 | //// Uncomment the following to use "sample string" as the sample for all actions that have string as the body parameter or return type. 40 | //// Also, the string arrays will be used for IEnumerable. The sample objects will be serialized into different media type 41 | //// formats by the available formatters. 42 | //config.SetSampleObjects(new Dictionary 43 | //{ 44 | // {typeof(string), "sample string"}, 45 | // {typeof(IEnumerable), new string[]{"sample 1", "sample 2"}} 46 | //}); 47 | 48 | // Extend the following to provide factories for types not handled automatically (those lacking parameterless 49 | // constructors) or for which you prefer to use non-default property values. Line below provides a fallback 50 | // since automatic handling will fail and GeneratePageResult handles only a single type. 51 | #if Handle_PageResultOfT 52 | config.GetHelpPageSampleGenerator().SampleObjectFactories.Add(GeneratePageResult); 53 | #endif 54 | 55 | // Extend the following to use a preset object directly as the sample for all actions that support a media 56 | // type, regardless of the body parameter or return type. The lines below avoid display of binary content. 57 | // The BsonMediaTypeFormatter (if available) is not used to serialize the TextSample object. 58 | config.SetSampleForMediaType( 59 | new TextSample("Binary JSON content. See http://bsonspec.org for details."), 60 | new MediaTypeHeaderValue("application/bson")); 61 | 62 | //// Uncomment the following to use "[0]=foo&[1]=bar" directly as the sample for all actions that support form URL encoded format 63 | //// and have IEnumerable as the body parameter or return type. 64 | //config.SetSampleForType("[0]=foo&[1]=bar", new MediaTypeHeaderValue("application/x-www-form-urlencoded"), typeof(IEnumerable)); 65 | 66 | //// Uncomment the following to use "1234" directly as the request sample for media type "text/plain" on the controller named "Values" 67 | //// and action named "Put". 68 | //config.SetSampleRequest("1234", new MediaTypeHeaderValue("text/plain"), "Values", "Put"); 69 | 70 | //// Uncomment the following to use the image on "../images/aspNetHome.png" directly as the response sample for media type "image/png" 71 | //// on the controller named "Values" and action named "Get" with parameter "id". 72 | //config.SetSampleResponse(new ImageSample("../images/aspNetHome.png"), new MediaTypeHeaderValue("image/png"), "Values", "Get", "id"); 73 | 74 | //// Uncomment the following to correct the sample request when the action expects an HttpRequestMessage with ObjectContent. 75 | //// The sample will be generated as if the controller named "Values" and action named "Get" were having string as the body parameter. 76 | //config.SetActualRequestType(typeof(string), "Values", "Get"); 77 | 78 | //// Uncomment the following to correct the sample response when the action returns an HttpResponseMessage with ObjectContent. 79 | //// The sample will be generated as if the controller named "Values" and action named "Post" were returning a string. 80 | //config.SetActualResponseType(typeof(string), "Values", "Post"); 81 | } 82 | 83 | #if Handle_PageResultOfT 84 | private static object GeneratePageResult(HelpPageSampleGenerator sampleGenerator, Type type) 85 | { 86 | if (type.IsGenericType) 87 | { 88 | Type openGenericType = type.GetGenericTypeDefinition(); 89 | if (openGenericType == typeof(PageResult<>)) 90 | { 91 | // Get the T in PageResult 92 | Type[] typeParameters = type.GetGenericArguments(); 93 | Debug.Assert(typeParameters.Length == 1); 94 | 95 | // Create an enumeration to pass as the first parameter to the PageResult constuctor 96 | Type itemsType = typeof(List<>).MakeGenericType(typeParameters); 97 | object items = sampleGenerator.GetSampleObject(itemsType); 98 | 99 | // Fill in the other information needed to invoke the PageResult constuctor 100 | Type[] parameterTypes = new Type[] { itemsType, typeof(Uri), typeof(long?), }; 101 | object[] parameters = new object[] { items, null, (long)ObjectGenerator.DefaultCollectionSize, }; 102 | 103 | // Call PageResult(IEnumerable items, Uri nextPageLink, long? count) constructor 104 | ConstructorInfo constructor = type.GetConstructor(parameterTypes); 105 | return constructor.Invoke(parameters); 106 | } 107 | } 108 | 109 | return null; 110 | } 111 | #endif 112 | } 113 | } -------------------------------------------------------------------------------- /W2Open.API/Areas/HelpPage/Controllers/HelpController.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Web.Http; 3 | using System.Web.Mvc; 4 | using W2Open.API.Areas.HelpPage.ModelDescriptions; 5 | using W2Open.API.Areas.HelpPage.Models; 6 | 7 | namespace W2Open.API.Areas.HelpPage.Controllers 8 | { 9 | /// 10 | /// The controller that will handle requests for the help page. 11 | /// 12 | public class HelpController : Controller 13 | { 14 | private const string ErrorViewName = "Error"; 15 | 16 | public HelpController() 17 | : this(GlobalConfiguration.Configuration) 18 | { 19 | } 20 | 21 | public HelpController(HttpConfiguration config) 22 | { 23 | Configuration = config; 24 | } 25 | 26 | public HttpConfiguration Configuration { get; private set; } 27 | 28 | public ActionResult Index() 29 | { 30 | ViewBag.DocumentationProvider = Configuration.Services.GetDocumentationProvider(); 31 | return View(Configuration.Services.GetApiExplorer().ApiDescriptions); 32 | } 33 | 34 | public ActionResult Api(string apiId) 35 | { 36 | if (!String.IsNullOrEmpty(apiId)) 37 | { 38 | HelpPageApiModel apiModel = Configuration.GetHelpPageApiModel(apiId); 39 | if (apiModel != null) 40 | { 41 | return View(apiModel); 42 | } 43 | } 44 | 45 | return View(ErrorViewName); 46 | } 47 | 48 | public ActionResult ResourceModel(string modelName) 49 | { 50 | if (!String.IsNullOrEmpty(modelName)) 51 | { 52 | ModelDescriptionGenerator modelDescriptionGenerator = Configuration.GetModelDescriptionGenerator(); 53 | ModelDescription modelDescription; 54 | if (modelDescriptionGenerator.GeneratedModels.TryGetValue(modelName, out modelDescription)) 55 | { 56 | return View(modelDescription); 57 | } 58 | } 59 | 60 | return View(ErrorViewName); 61 | } 62 | } 63 | } -------------------------------------------------------------------------------- /W2Open.API/Areas/HelpPage/HelpPage.css: -------------------------------------------------------------------------------- 1 | .help-page h1, 2 | .help-page .h1, 3 | .help-page h2, 4 | .help-page .h2, 5 | .help-page h3, 6 | .help-page .h3, 7 | #body.help-page, 8 | .help-page-table th, 9 | .help-page-table pre, 10 | .help-page-table p { 11 | font-family: "Segoe UI Light", Frutiger, "Frutiger Linotype", "Dejavu Sans", "Helvetica Neue", Arial, sans-serif; 12 | } 13 | 14 | .help-page pre.wrapped { 15 | white-space: -moz-pre-wrap; 16 | white-space: -pre-wrap; 17 | white-space: -o-pre-wrap; 18 | white-space: pre-wrap; 19 | } 20 | 21 | .help-page .warning-message-container { 22 | margin-top: 20px; 23 | padding: 0 10px; 24 | color: #525252; 25 | background: #EFDCA9; 26 | border: 1px solid #CCCCCC; 27 | } 28 | 29 | .help-page-table { 30 | width: 100%; 31 | border-collapse: collapse; 32 | text-align: left; 33 | margin: 0px 0px 20px 0px; 34 | border-top: 1px solid #D4D4D4; 35 | } 36 | 37 | .help-page-table th { 38 | text-align: left; 39 | font-weight: bold; 40 | border-bottom: 1px solid #D4D4D4; 41 | padding: 5px 6px 5px 6px; 42 | } 43 | 44 | .help-page-table td { 45 | border-bottom: 1px solid #D4D4D4; 46 | padding: 10px 8px 10px 8px; 47 | vertical-align: top; 48 | } 49 | 50 | .help-page-table pre, 51 | .help-page-table p { 52 | margin: 0px; 53 | padding: 0px; 54 | font-family: inherit; 55 | font-size: 100%; 56 | } 57 | 58 | .help-page-table tbody tr:hover td { 59 | background-color: #F3F3F3; 60 | } 61 | 62 | .help-page a:hover { 63 | background-color: transparent; 64 | } 65 | 66 | .help-page .sample-header { 67 | border: 2px solid #D4D4D4; 68 | background: #00497E; 69 | color: #FFFFFF; 70 | padding: 8px 15px; 71 | border-bottom: none; 72 | display: inline-block; 73 | margin: 10px 0px 0px 0px; 74 | } 75 | 76 | .help-page .sample-content { 77 | display: block; 78 | border-width: 0; 79 | padding: 15px 20px; 80 | background: #FFFFFF; 81 | border: 2px solid #D4D4D4; 82 | margin: 0px 0px 10px 0px; 83 | } 84 | 85 | .help-page .api-name { 86 | width: 40%; 87 | } 88 | 89 | .help-page .api-documentation { 90 | width: 60%; 91 | } 92 | 93 | .help-page .parameter-name { 94 | width: 20%; 95 | } 96 | 97 | .help-page .parameter-documentation { 98 | width: 40%; 99 | } 100 | 101 | .help-page .parameter-type { 102 | width: 20%; 103 | } 104 | 105 | .help-page .parameter-annotations { 106 | width: 20%; 107 | } 108 | 109 | .help-page h1, 110 | .help-page .h1 { 111 | font-size: 36px; 112 | line-height: normal; 113 | } 114 | 115 | .help-page h2, 116 | .help-page .h2 { 117 | font-size: 24px; 118 | } 119 | 120 | .help-page h3, 121 | .help-page .h3 { 122 | font-size: 20px; 123 | } 124 | 125 | #body.help-page { 126 | font-size: 14px; 127 | line-height: 143%; 128 | color: #333; 129 | } 130 | 131 | .help-page a { 132 | color: #0000EE; 133 | text-decoration: none; 134 | } 135 | -------------------------------------------------------------------------------- /W2Open.API/Areas/HelpPage/HelpPageAreaRegistration.cs: -------------------------------------------------------------------------------- 1 | using System.Web.Http; 2 | using System.Web.Mvc; 3 | 4 | namespace W2Open.API.Areas.HelpPage 5 | { 6 | public class HelpPageAreaRegistration : AreaRegistration 7 | { 8 | public override string AreaName 9 | { 10 | get 11 | { 12 | return "HelpPage"; 13 | } 14 | } 15 | 16 | public override void RegisterArea(AreaRegistrationContext context) 17 | { 18 | context.MapRoute( 19 | "HelpPage_Default", 20 | "Help/{action}/{apiId}", 21 | new { controller = "Help", action = "Index", apiId = UrlParameter.Optional }); 22 | 23 | HelpPageConfig.Register(GlobalConfiguration.Configuration); 24 | } 25 | } 26 | } -------------------------------------------------------------------------------- /W2Open.API/Areas/HelpPage/ModelDescriptions/CollectionModelDescription.cs: -------------------------------------------------------------------------------- 1 | namespace W2Open.API.Areas.HelpPage.ModelDescriptions 2 | { 3 | public class CollectionModelDescription : ModelDescription 4 | { 5 | public ModelDescription ElementDescription { get; set; } 6 | } 7 | } -------------------------------------------------------------------------------- /W2Open.API/Areas/HelpPage/ModelDescriptions/ComplexTypeModelDescription.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.ObjectModel; 2 | 3 | namespace W2Open.API.Areas.HelpPage.ModelDescriptions 4 | { 5 | public class ComplexTypeModelDescription : ModelDescription 6 | { 7 | public ComplexTypeModelDescription() 8 | { 9 | Properties = new Collection(); 10 | } 11 | 12 | public Collection Properties { get; private set; } 13 | } 14 | } -------------------------------------------------------------------------------- /W2Open.API/Areas/HelpPage/ModelDescriptions/DictionaryModelDescription.cs: -------------------------------------------------------------------------------- 1 | namespace W2Open.API.Areas.HelpPage.ModelDescriptions 2 | { 3 | public class DictionaryModelDescription : KeyValuePairModelDescription 4 | { 5 | } 6 | } -------------------------------------------------------------------------------- /W2Open.API/Areas/HelpPage/ModelDescriptions/EnumTypeModelDescription.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using System.Collections.ObjectModel; 3 | 4 | namespace W2Open.API.Areas.HelpPage.ModelDescriptions 5 | { 6 | public class EnumTypeModelDescription : ModelDescription 7 | { 8 | public EnumTypeModelDescription() 9 | { 10 | Values = new Collection(); 11 | } 12 | 13 | public Collection Values { get; private set; } 14 | } 15 | } -------------------------------------------------------------------------------- /W2Open.API/Areas/HelpPage/ModelDescriptions/EnumValueDescription.cs: -------------------------------------------------------------------------------- 1 | namespace W2Open.API.Areas.HelpPage.ModelDescriptions 2 | { 3 | public class EnumValueDescription 4 | { 5 | public string Documentation { get; set; } 6 | 7 | public string Name { get; set; } 8 | 9 | public string Value { get; set; } 10 | } 11 | } -------------------------------------------------------------------------------- /W2Open.API/Areas/HelpPage/ModelDescriptions/IModelDocumentationProvider.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Reflection; 3 | 4 | namespace W2Open.API.Areas.HelpPage.ModelDescriptions 5 | { 6 | public interface IModelDocumentationProvider 7 | { 8 | string GetDocumentation(MemberInfo member); 9 | 10 | string GetDocumentation(Type type); 11 | } 12 | } -------------------------------------------------------------------------------- /W2Open.API/Areas/HelpPage/ModelDescriptions/KeyValuePairModelDescription.cs: -------------------------------------------------------------------------------- 1 | namespace W2Open.API.Areas.HelpPage.ModelDescriptions 2 | { 3 | public class KeyValuePairModelDescription : ModelDescription 4 | { 5 | public ModelDescription KeyModelDescription { get; set; } 6 | 7 | public ModelDescription ValueModelDescription { get; set; } 8 | } 9 | } -------------------------------------------------------------------------------- /W2Open.API/Areas/HelpPage/ModelDescriptions/ModelDescription.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace W2Open.API.Areas.HelpPage.ModelDescriptions 4 | { 5 | /// 6 | /// Describes a type model. 7 | /// 8 | public abstract class ModelDescription 9 | { 10 | public string Documentation { get; set; } 11 | 12 | public Type ModelType { get; set; } 13 | 14 | public string Name { get; set; } 15 | } 16 | } -------------------------------------------------------------------------------- /W2Open.API/Areas/HelpPage/ModelDescriptions/ModelNameAttribute.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace W2Open.API.Areas.HelpPage.ModelDescriptions 4 | { 5 | /// 6 | /// Use this attribute to change the name of the generated for a type. 7 | /// 8 | [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Enum, AllowMultiple = false, Inherited = false)] 9 | public sealed class ModelNameAttribute : Attribute 10 | { 11 | public ModelNameAttribute(string name) 12 | { 13 | Name = name; 14 | } 15 | 16 | public string Name { get; private set; } 17 | } 18 | } -------------------------------------------------------------------------------- /W2Open.API/Areas/HelpPage/ModelDescriptions/ModelNameHelper.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Globalization; 3 | using System.Linq; 4 | using System.Reflection; 5 | 6 | namespace W2Open.API.Areas.HelpPage.ModelDescriptions 7 | { 8 | internal static class ModelNameHelper 9 | { 10 | // Modify this to provide custom model name mapping. 11 | public static string GetModelName(Type type) 12 | { 13 | ModelNameAttribute modelNameAttribute = type.GetCustomAttribute(); 14 | if (modelNameAttribute != null && !String.IsNullOrEmpty(modelNameAttribute.Name)) 15 | { 16 | return modelNameAttribute.Name; 17 | } 18 | 19 | string modelName = type.Name; 20 | if (type.IsGenericType) 21 | { 22 | // Format the generic type name to something like: GenericOfAgurment1AndArgument2 23 | Type genericType = type.GetGenericTypeDefinition(); 24 | Type[] genericArguments = type.GetGenericArguments(); 25 | string genericTypeName = genericType.Name; 26 | 27 | // Trim the generic parameter counts from the name 28 | genericTypeName = genericTypeName.Substring(0, genericTypeName.IndexOf('`')); 29 | string[] argumentTypeNames = genericArguments.Select(t => GetModelName(t)).ToArray(); 30 | modelName = String.Format(CultureInfo.InvariantCulture, "{0}Of{1}", genericTypeName, String.Join("And", argumentTypeNames)); 31 | } 32 | 33 | return modelName; 34 | } 35 | } 36 | } -------------------------------------------------------------------------------- /W2Open.API/Areas/HelpPage/ModelDescriptions/ParameterAnnotation.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace W2Open.API.Areas.HelpPage.ModelDescriptions 4 | { 5 | public class ParameterAnnotation 6 | { 7 | public Attribute AnnotationAttribute { get; set; } 8 | 9 | public string Documentation { get; set; } 10 | } 11 | } -------------------------------------------------------------------------------- /W2Open.API/Areas/HelpPage/ModelDescriptions/ParameterDescription.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using System.Collections.ObjectModel; 3 | 4 | namespace W2Open.API.Areas.HelpPage.ModelDescriptions 5 | { 6 | public class ParameterDescription 7 | { 8 | public ParameterDescription() 9 | { 10 | Annotations = new Collection(); 11 | } 12 | 13 | public Collection Annotations { get; private set; } 14 | 15 | public string Documentation { get; set; } 16 | 17 | public string Name { get; set; } 18 | 19 | public ModelDescription TypeDescription { get; set; } 20 | } 21 | } -------------------------------------------------------------------------------- /W2Open.API/Areas/HelpPage/ModelDescriptions/SimpleTypeModelDescription.cs: -------------------------------------------------------------------------------- 1 | namespace W2Open.API.Areas.HelpPage.ModelDescriptions 2 | { 3 | public class SimpleTypeModelDescription : ModelDescription 4 | { 5 | } 6 | } -------------------------------------------------------------------------------- /W2Open.API/Areas/HelpPage/Models/HelpPageApiModel.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using System.Collections.ObjectModel; 3 | using System.Net.Http.Headers; 4 | using System.Web.Http.Description; 5 | using W2Open.API.Areas.HelpPage.ModelDescriptions; 6 | 7 | namespace W2Open.API.Areas.HelpPage.Models 8 | { 9 | /// 10 | /// The model that represents an API displayed on the help page. 11 | /// 12 | public class HelpPageApiModel 13 | { 14 | /// 15 | /// Initializes a new instance of the class. 16 | /// 17 | public HelpPageApiModel() 18 | { 19 | UriParameters = new Collection(); 20 | SampleRequests = new Dictionary(); 21 | SampleResponses = new Dictionary(); 22 | ErrorMessages = new Collection(); 23 | } 24 | 25 | /// 26 | /// Gets or sets the that describes the API. 27 | /// 28 | public ApiDescription ApiDescription { get; set; } 29 | 30 | /// 31 | /// Gets or sets the collection that describes the URI parameters for the API. 32 | /// 33 | public Collection UriParameters { get; private set; } 34 | 35 | /// 36 | /// Gets or sets the documentation for the request. 37 | /// 38 | public string RequestDocumentation { get; set; } 39 | 40 | /// 41 | /// Gets or sets the that describes the request body. 42 | /// 43 | public ModelDescription RequestModelDescription { get; set; } 44 | 45 | /// 46 | /// Gets the request body parameter descriptions. 47 | /// 48 | public IList RequestBodyParameters 49 | { 50 | get 51 | { 52 | return GetParameterDescriptions(RequestModelDescription); 53 | } 54 | } 55 | 56 | /// 57 | /// Gets or sets the that describes the resource. 58 | /// 59 | public ModelDescription ResourceDescription { get; set; } 60 | 61 | /// 62 | /// Gets the resource property descriptions. 63 | /// 64 | public IList ResourceProperties 65 | { 66 | get 67 | { 68 | return GetParameterDescriptions(ResourceDescription); 69 | } 70 | } 71 | 72 | /// 73 | /// Gets the sample requests associated with the API. 74 | /// 75 | public IDictionary SampleRequests { get; private set; } 76 | 77 | /// 78 | /// Gets the sample responses associated with the API. 79 | /// 80 | public IDictionary SampleResponses { get; private set; } 81 | 82 | /// 83 | /// Gets the error messages associated with this model. 84 | /// 85 | public Collection ErrorMessages { get; private set; } 86 | 87 | private static IList GetParameterDescriptions(ModelDescription modelDescription) 88 | { 89 | ComplexTypeModelDescription complexTypeModelDescription = modelDescription as ComplexTypeModelDescription; 90 | if (complexTypeModelDescription != null) 91 | { 92 | return complexTypeModelDescription.Properties; 93 | } 94 | 95 | CollectionModelDescription collectionModelDescription = modelDescription as CollectionModelDescription; 96 | if (collectionModelDescription != null) 97 | { 98 | complexTypeModelDescription = collectionModelDescription.ElementDescription as ComplexTypeModelDescription; 99 | if (complexTypeModelDescription != null) 100 | { 101 | return complexTypeModelDescription.Properties; 102 | } 103 | } 104 | 105 | return null; 106 | } 107 | } 108 | } -------------------------------------------------------------------------------- /W2Open.API/Areas/HelpPage/SampleGeneration/HelpPageSampleKey.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.ComponentModel; 4 | using System.Net.Http.Headers; 5 | 6 | namespace W2Open.API.Areas.HelpPage 7 | { 8 | /// 9 | /// This is used to identify the place where the sample should be applied. 10 | /// 11 | public class HelpPageSampleKey 12 | { 13 | /// 14 | /// Creates a new based on media type. 15 | /// 16 | /// The media type. 17 | public HelpPageSampleKey(MediaTypeHeaderValue mediaType) 18 | { 19 | if (mediaType == null) 20 | { 21 | throw new ArgumentNullException("mediaType"); 22 | } 23 | 24 | ActionName = String.Empty; 25 | ControllerName = String.Empty; 26 | MediaType = mediaType; 27 | ParameterNames = new HashSet(StringComparer.OrdinalIgnoreCase); 28 | } 29 | 30 | /// 31 | /// Creates a new based on media type and CLR type. 32 | /// 33 | /// The media type. 34 | /// The CLR type. 35 | public HelpPageSampleKey(MediaTypeHeaderValue mediaType, Type type) 36 | : this(mediaType) 37 | { 38 | if (type == null) 39 | { 40 | throw new ArgumentNullException("type"); 41 | } 42 | 43 | ParameterType = type; 44 | } 45 | 46 | /// 47 | /// Creates a new based on , controller name, action name and parameter names. 48 | /// 49 | /// The . 50 | /// Name of the controller. 51 | /// Name of the action. 52 | /// The parameter names. 53 | public HelpPageSampleKey(SampleDirection sampleDirection, string controllerName, string actionName, IEnumerable parameterNames) 54 | { 55 | if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection)) 56 | { 57 | throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection)); 58 | } 59 | if (controllerName == null) 60 | { 61 | throw new ArgumentNullException("controllerName"); 62 | } 63 | if (actionName == null) 64 | { 65 | throw new ArgumentNullException("actionName"); 66 | } 67 | if (parameterNames == null) 68 | { 69 | throw new ArgumentNullException("parameterNames"); 70 | } 71 | 72 | ControllerName = controllerName; 73 | ActionName = actionName; 74 | ParameterNames = new HashSet(parameterNames, StringComparer.OrdinalIgnoreCase); 75 | SampleDirection = sampleDirection; 76 | } 77 | 78 | /// 79 | /// Creates a new based on media type, , controller name, action name and parameter names. 80 | /// 81 | /// The media type. 82 | /// The . 83 | /// Name of the controller. 84 | /// Name of the action. 85 | /// The parameter names. 86 | public HelpPageSampleKey(MediaTypeHeaderValue mediaType, SampleDirection sampleDirection, string controllerName, string actionName, IEnumerable parameterNames) 87 | : this(sampleDirection, controllerName, actionName, parameterNames) 88 | { 89 | if (mediaType == null) 90 | { 91 | throw new ArgumentNullException("mediaType"); 92 | } 93 | 94 | MediaType = mediaType; 95 | } 96 | 97 | /// 98 | /// Gets the name of the controller. 99 | /// 100 | /// 101 | /// The name of the controller. 102 | /// 103 | public string ControllerName { get; private set; } 104 | 105 | /// 106 | /// Gets the name of the action. 107 | /// 108 | /// 109 | /// The name of the action. 110 | /// 111 | public string ActionName { get; private set; } 112 | 113 | /// 114 | /// Gets the media type. 115 | /// 116 | /// 117 | /// The media type. 118 | /// 119 | public MediaTypeHeaderValue MediaType { get; private set; } 120 | 121 | /// 122 | /// Gets the parameter names. 123 | /// 124 | public HashSet ParameterNames { get; private set; } 125 | 126 | public Type ParameterType { get; private set; } 127 | 128 | /// 129 | /// Gets the . 130 | /// 131 | public SampleDirection? SampleDirection { get; private set; } 132 | 133 | public override bool Equals(object obj) 134 | { 135 | HelpPageSampleKey otherKey = obj as HelpPageSampleKey; 136 | if (otherKey == null) 137 | { 138 | return false; 139 | } 140 | 141 | return String.Equals(ControllerName, otherKey.ControllerName, StringComparison.OrdinalIgnoreCase) && 142 | String.Equals(ActionName, otherKey.ActionName, StringComparison.OrdinalIgnoreCase) && 143 | (MediaType == otherKey.MediaType || (MediaType != null && MediaType.Equals(otherKey.MediaType))) && 144 | ParameterType == otherKey.ParameterType && 145 | SampleDirection == otherKey.SampleDirection && 146 | ParameterNames.SetEquals(otherKey.ParameterNames); 147 | } 148 | 149 | public override int GetHashCode() 150 | { 151 | int hashCode = ControllerName.ToUpperInvariant().GetHashCode() ^ ActionName.ToUpperInvariant().GetHashCode(); 152 | if (MediaType != null) 153 | { 154 | hashCode ^= MediaType.GetHashCode(); 155 | } 156 | if (SampleDirection != null) 157 | { 158 | hashCode ^= SampleDirection.GetHashCode(); 159 | } 160 | if (ParameterType != null) 161 | { 162 | hashCode ^= ParameterType.GetHashCode(); 163 | } 164 | foreach (string parameterName in ParameterNames) 165 | { 166 | hashCode ^= parameterName.ToUpperInvariant().GetHashCode(); 167 | } 168 | 169 | return hashCode; 170 | } 171 | } 172 | } 173 | -------------------------------------------------------------------------------- /W2Open.API/Areas/HelpPage/SampleGeneration/ImageSample.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace W2Open.API.Areas.HelpPage 4 | { 5 | /// 6 | /// This represents an image sample on the help page. There's a display template named ImageSample associated with this class. 7 | /// 8 | public class ImageSample 9 | { 10 | /// 11 | /// Initializes a new instance of the class. 12 | /// 13 | /// The URL of an image. 14 | public ImageSample(string src) 15 | { 16 | if (src == null) 17 | { 18 | throw new ArgumentNullException("src"); 19 | } 20 | Src = src; 21 | } 22 | 23 | public string Src { get; private set; } 24 | 25 | public override bool Equals(object obj) 26 | { 27 | ImageSample other = obj as ImageSample; 28 | return other != null && Src == other.Src; 29 | } 30 | 31 | public override int GetHashCode() 32 | { 33 | return Src.GetHashCode(); 34 | } 35 | 36 | public override string ToString() 37 | { 38 | return Src; 39 | } 40 | } 41 | } -------------------------------------------------------------------------------- /W2Open.API/Areas/HelpPage/SampleGeneration/InvalidSample.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace W2Open.API.Areas.HelpPage 4 | { 5 | /// 6 | /// This represents an invalid sample on the help page. There's a display template named InvalidSample associated with this class. 7 | /// 8 | public class InvalidSample 9 | { 10 | public InvalidSample(string errorMessage) 11 | { 12 | if (errorMessage == null) 13 | { 14 | throw new ArgumentNullException("errorMessage"); 15 | } 16 | ErrorMessage = errorMessage; 17 | } 18 | 19 | public string ErrorMessage { get; private set; } 20 | 21 | public override bool Equals(object obj) 22 | { 23 | InvalidSample other = obj as InvalidSample; 24 | return other != null && ErrorMessage == other.ErrorMessage; 25 | } 26 | 27 | public override int GetHashCode() 28 | { 29 | return ErrorMessage.GetHashCode(); 30 | } 31 | 32 | public override string ToString() 33 | { 34 | return ErrorMessage; 35 | } 36 | } 37 | } -------------------------------------------------------------------------------- /W2Open.API/Areas/HelpPage/SampleGeneration/SampleDirection.cs: -------------------------------------------------------------------------------- 1 | namespace W2Open.API.Areas.HelpPage 2 | { 3 | /// 4 | /// Indicates whether the sample is used for request or response 5 | /// 6 | public enum SampleDirection 7 | { 8 | Request = 0, 9 | Response 10 | } 11 | } -------------------------------------------------------------------------------- /W2Open.API/Areas/HelpPage/SampleGeneration/TextSample.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace W2Open.API.Areas.HelpPage 4 | { 5 | /// 6 | /// This represents a preformatted text sample on the help page. There's a display template named TextSample associated with this class. 7 | /// 8 | public class TextSample 9 | { 10 | public TextSample(string text) 11 | { 12 | if (text == null) 13 | { 14 | throw new ArgumentNullException("text"); 15 | } 16 | Text = text; 17 | } 18 | 19 | public string Text { get; private set; } 20 | 21 | public override bool Equals(object obj) 22 | { 23 | TextSample other = obj as TextSample; 24 | return other != null && Text == other.Text; 25 | } 26 | 27 | public override int GetHashCode() 28 | { 29 | return Text.GetHashCode(); 30 | } 31 | 32 | public override string ToString() 33 | { 34 | return Text; 35 | } 36 | } 37 | } -------------------------------------------------------------------------------- /W2Open.API/Areas/HelpPage/Views/Help/Api.cshtml: -------------------------------------------------------------------------------- 1 | @using System.Web.Http 2 | @using W2Open.API.Areas.HelpPage.Models 3 | @model HelpPageApiModel 4 | 5 | @{ 6 | var description = Model.ApiDescription; 7 | ViewBag.Title = description.HttpMethod.Method + " " + description.RelativePath; 8 | } 9 | 10 | 11 |
12 | 19 |
20 | @Html.DisplayForModel() 21 |
22 |
23 | -------------------------------------------------------------------------------- /W2Open.API/Areas/HelpPage/Views/Help/DisplayTemplates/ApiGroup.cshtml: -------------------------------------------------------------------------------- 1 | @using System.Web.Http 2 | @using System.Web.Http.Controllers 3 | @using System.Web.Http.Description 4 | @using W2Open.API.Areas.HelpPage 5 | @using W2Open.API.Areas.HelpPage.Models 6 | @model IGrouping 7 | 8 | @{ 9 | var controllerDocumentation = ViewBag.DocumentationProvider != null ? 10 | ViewBag.DocumentationProvider.GetDocumentation(Model.Key) : 11 | null; 12 | } 13 | 14 |

@Model.Key.ControllerName

15 | @if (!String.IsNullOrEmpty(controllerDocumentation)) 16 | { 17 |

@controllerDocumentation

18 | } 19 | 20 | 21 | 22 | 23 | 24 | @foreach (var api in Model) 25 | { 26 | 27 | 28 | 38 | 39 | } 40 | 41 |
APIDescription
@api.HttpMethod.Method @api.RelativePath 29 | @if (api.Documentation != null) 30 | { 31 |

@api.Documentation

32 | } 33 | else 34 | { 35 |

No documentation available.

36 | } 37 |
-------------------------------------------------------------------------------- /W2Open.API/Areas/HelpPage/Views/Help/DisplayTemplates/CollectionModelDescription.cshtml: -------------------------------------------------------------------------------- 1 | @using W2Open.API.Areas.HelpPage.ModelDescriptions 2 | @model CollectionModelDescription 3 | @if (Model.ElementDescription is ComplexTypeModelDescription) 4 | { 5 | @Html.DisplayFor(m => m.ElementDescription) 6 | } -------------------------------------------------------------------------------- /W2Open.API/Areas/HelpPage/Views/Help/DisplayTemplates/ComplexTypeModelDescription.cshtml: -------------------------------------------------------------------------------- 1 | @using W2Open.API.Areas.HelpPage.ModelDescriptions 2 | @model ComplexTypeModelDescription 3 | @Html.DisplayFor(m => m.Properties, "Parameters") -------------------------------------------------------------------------------- /W2Open.API/Areas/HelpPage/Views/Help/DisplayTemplates/DictionaryModelDescription.cshtml: -------------------------------------------------------------------------------- 1 | @using W2Open.API.Areas.HelpPage.ModelDescriptions 2 | @model DictionaryModelDescription 3 | Dictionary of @Html.DisplayFor(m => Model.KeyModelDescription.ModelType, "ModelDescriptionLink", new { modelDescription = Model.KeyModelDescription }) [key] 4 | and @Html.DisplayFor(m => Model.ValueModelDescription.ModelType, "ModelDescriptionLink", new { modelDescription = Model.ValueModelDescription }) [value] -------------------------------------------------------------------------------- /W2Open.API/Areas/HelpPage/Views/Help/DisplayTemplates/EnumTypeModelDescription.cshtml: -------------------------------------------------------------------------------- 1 | @using W2Open.API.Areas.HelpPage.ModelDescriptions 2 | @model EnumTypeModelDescription 3 | 4 |

Possible enumeration values:

5 | 6 | 7 | 8 | 9 | 10 | 11 | @foreach (EnumValueDescription value in Model.Values) 12 | { 13 | 14 | 15 | 18 | 21 | 22 | } 23 | 24 |
NameValueDescription
@value.Name 16 |

@value.Value

17 |
19 |

@value.Documentation

20 |
-------------------------------------------------------------------------------- /W2Open.API/Areas/HelpPage/Views/Help/DisplayTemplates/HelpPageApiModel.cshtml: -------------------------------------------------------------------------------- 1 | @using System.Web.Http 2 | @using System.Web.Http.Description 3 | @using W2Open.API.Areas.HelpPage.Models 4 | @using W2Open.API.Areas.HelpPage.ModelDescriptions 5 | @model HelpPageApiModel 6 | 7 | @{ 8 | ApiDescription description = Model.ApiDescription; 9 | } 10 |

@description.HttpMethod.Method @description.RelativePath

11 |
12 |

@description.Documentation

13 | 14 |

Request Information

15 | 16 |

URI Parameters

17 | @Html.DisplayFor(m => m.UriParameters, "Parameters") 18 | 19 |

Body Parameters

20 | 21 |

@Model.RequestDocumentation

22 | 23 | @if (Model.RequestModelDescription != null) 24 | { 25 | @Html.DisplayFor(m => m.RequestModelDescription.ModelType, "ModelDescriptionLink", new { modelDescription = Model.RequestModelDescription }) 26 | if (Model.RequestBodyParameters != null) 27 | { 28 | @Html.DisplayFor(m => m.RequestBodyParameters, "Parameters") 29 | } 30 | } 31 | else 32 | { 33 |

None.

34 | } 35 | 36 | @if (Model.SampleRequests.Count > 0) 37 | { 38 |

Request Formats

39 | @Html.DisplayFor(m => m.SampleRequests, "Samples") 40 | } 41 | 42 |

Response Information

43 | 44 |

Resource Description

45 | 46 |

@description.ResponseDescription.Documentation

47 | 48 | @if (Model.ResourceDescription != null) 49 | { 50 | @Html.DisplayFor(m => m.ResourceDescription.ModelType, "ModelDescriptionLink", new { modelDescription = Model.ResourceDescription }) 51 | if (Model.ResourceProperties != null) 52 | { 53 | @Html.DisplayFor(m => m.ResourceProperties, "Parameters") 54 | } 55 | } 56 | else 57 | { 58 |

None.

59 | } 60 | 61 | @if (Model.SampleResponses.Count > 0) 62 | { 63 |

Response Formats

64 | @Html.DisplayFor(m => m.SampleResponses, "Samples") 65 | } 66 | 67 |
-------------------------------------------------------------------------------- /W2Open.API/Areas/HelpPage/Views/Help/DisplayTemplates/ImageSample.cshtml: -------------------------------------------------------------------------------- 1 | @using W2Open.API.Areas.HelpPage 2 | @model ImageSample 3 | 4 | -------------------------------------------------------------------------------- /W2Open.API/Areas/HelpPage/Views/Help/DisplayTemplates/InvalidSample.cshtml: -------------------------------------------------------------------------------- 1 | @using W2Open.API.Areas.HelpPage 2 | @model InvalidSample 3 | 4 | @if (HttpContext.Current.IsDebuggingEnabled) 5 | { 6 |
7 |

@Model.ErrorMessage

8 |
9 | } 10 | else 11 | { 12 |

Sample not available.

13 | } -------------------------------------------------------------------------------- /W2Open.API/Areas/HelpPage/Views/Help/DisplayTemplates/KeyValuePairModelDescription.cshtml: -------------------------------------------------------------------------------- 1 | @using W2Open.API.Areas.HelpPage.ModelDescriptions 2 | @model KeyValuePairModelDescription 3 | Pair of @Html.DisplayFor(m => Model.KeyModelDescription.ModelType, "ModelDescriptionLink", new { modelDescription = Model.KeyModelDescription }) [key] 4 | and @Html.DisplayFor(m => Model.ValueModelDescription.ModelType, "ModelDescriptionLink", new { modelDescription = Model.ValueModelDescription }) [value] -------------------------------------------------------------------------------- /W2Open.API/Areas/HelpPage/Views/Help/DisplayTemplates/ModelDescriptionLink.cshtml: -------------------------------------------------------------------------------- 1 | @using W2Open.API.Areas.HelpPage.ModelDescriptions 2 | @model Type 3 | @{ 4 | ModelDescription modelDescription = ViewBag.modelDescription; 5 | if (modelDescription is ComplexTypeModelDescription || modelDescription is EnumTypeModelDescription) 6 | { 7 | if (Model == typeof(Object)) 8 | { 9 | @:Object 10 | } 11 | else 12 | { 13 | @Html.ActionLink(modelDescription.Name, "ResourceModel", "Help", new { modelName = modelDescription.Name }, null) 14 | } 15 | } 16 | else if (modelDescription is CollectionModelDescription) 17 | { 18 | var collectionDescription = modelDescription as CollectionModelDescription; 19 | var elementDescription = collectionDescription.ElementDescription; 20 | @:Collection of @Html.DisplayFor(m => elementDescription.ModelType, "ModelDescriptionLink", new { modelDescription = elementDescription }) 21 | } 22 | else 23 | { 24 | @Html.DisplayFor(m => modelDescription) 25 | } 26 | } -------------------------------------------------------------------------------- /W2Open.API/Areas/HelpPage/Views/Help/DisplayTemplates/Parameters.cshtml: -------------------------------------------------------------------------------- 1 | @using System.Collections.Generic 2 | @using System.Collections.ObjectModel 3 | @using System.Web.Http.Description 4 | @using System.Threading 5 | @using W2Open.API.Areas.HelpPage.ModelDescriptions 6 | @model IList 7 | 8 | @if (Model.Count > 0) 9 | { 10 | 11 | 12 | 13 | 14 | 15 | @foreach (ParameterDescription parameter in Model) 16 | { 17 | ModelDescription modelDescription = parameter.TypeDescription; 18 | 19 | 20 | 23 | 26 | 39 | 40 | } 41 | 42 |
NameDescriptionTypeAdditional information
@parameter.Name 21 |

@parameter.Documentation

22 |
24 | @Html.DisplayFor(m => modelDescription.ModelType, "ModelDescriptionLink", new { modelDescription = modelDescription }) 25 | 27 | @if (parameter.Annotations.Count > 0) 28 | { 29 | foreach (var annotation in parameter.Annotations) 30 | { 31 |

@annotation.Documentation

32 | } 33 | } 34 | else 35 | { 36 |

None.

37 | } 38 |
43 | } 44 | else 45 | { 46 |

None.

47 | } 48 | 49 | -------------------------------------------------------------------------------- /W2Open.API/Areas/HelpPage/Views/Help/DisplayTemplates/Samples.cshtml: -------------------------------------------------------------------------------- 1 | @using System.Net.Http.Headers 2 | @model Dictionary 3 | 4 | @{ 5 | // Group the samples into a single tab if they are the same. 6 | Dictionary samples = Model.GroupBy(pair => pair.Value).ToDictionary( 7 | pair => String.Join(", ", pair.Select(m => m.Key.ToString()).ToArray()), 8 | pair => pair.Key); 9 | var mediaTypes = samples.Keys; 10 | } 11 |
12 | @foreach (var mediaType in mediaTypes) 13 | { 14 |

@mediaType

15 |
16 | Sample: 17 | @{ 18 | var sample = samples[mediaType]; 19 | if (sample == null) 20 | { 21 |

Sample not available.

22 | } 23 | else 24 | { 25 | @Html.DisplayFor(s => sample); 26 | } 27 | } 28 |
29 | } 30 |
-------------------------------------------------------------------------------- /W2Open.API/Areas/HelpPage/Views/Help/DisplayTemplates/SimpleTypeModelDescription.cshtml: -------------------------------------------------------------------------------- 1 | @using W2Open.API.Areas.HelpPage.ModelDescriptions 2 | @model SimpleTypeModelDescription 3 | @Model.Documentation -------------------------------------------------------------------------------- /W2Open.API/Areas/HelpPage/Views/Help/DisplayTemplates/TextSample.cshtml: -------------------------------------------------------------------------------- 1 | @using W2Open.API.Areas.HelpPage 2 | @model TextSample 3 | 4 |
5 | @Model.Text
6 | 
-------------------------------------------------------------------------------- /W2Open.API/Areas/HelpPage/Views/Help/Index.cshtml: -------------------------------------------------------------------------------- 1 | @using System.Web.Http 2 | @using System.Web.Http.Controllers 3 | @using System.Web.Http.Description 4 | @using System.Collections.ObjectModel 5 | @using W2Open.API.Areas.HelpPage.Models 6 | @model Collection 7 | 8 | @{ 9 | ViewBag.Title = "ASP.NET Web API Help Page"; 10 | 11 | // Group APIs by controller 12 | ILookup apiGroups = Model.ToLookup(api => api.ActionDescriptor.ControllerDescriptor); 13 | } 14 | 15 | 16 |
17 |
18 |
19 |

@ViewBag.Title

20 |
21 |
22 |
23 |
24 | 32 |
33 | @foreach (var group in apiGroups) 34 | { 35 | @Html.DisplayFor(m => group, "ApiGroup") 36 | } 37 |
38 |
39 | -------------------------------------------------------------------------------- /W2Open.API/Areas/HelpPage/Views/Help/ResourceModel.cshtml: -------------------------------------------------------------------------------- 1 | @using System.Web.Http 2 | @using W2Open.API.Areas.HelpPage.ModelDescriptions 3 | @model ModelDescription 4 | 5 | 6 |
7 | 14 |

@Model.Name

15 |

@Model.Documentation

16 |
17 | @Html.DisplayFor(m => Model) 18 |
19 |
20 | -------------------------------------------------------------------------------- /W2Open.API/Areas/HelpPage/Views/Shared/_Layout.cshtml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | @ViewBag.Title 7 | @RenderSection("scripts", required: false) 8 | 9 | 10 | @RenderBody() 11 | 12 | -------------------------------------------------------------------------------- /W2Open.API/Areas/HelpPage/Views/Web.config: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | 6 |
7 |
8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | -------------------------------------------------------------------------------- /W2Open.API/Areas/HelpPage/Views/_ViewStart.cshtml: -------------------------------------------------------------------------------- 1 | @{ 2 | // Change the Layout path below to blend the look and feel of the help page with your existing web pages 3 | Layout = "~/Views/Shared/_Layout.cshtml"; 4 | } -------------------------------------------------------------------------------- /W2Open.API/Areas/HelpPage/XmlDocumentationProvider.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Globalization; 3 | using System.Linq; 4 | using System.Reflection; 5 | using System.Web.Http.Controllers; 6 | using System.Web.Http.Description; 7 | using System.Xml.XPath; 8 | using W2Open.API.Areas.HelpPage.ModelDescriptions; 9 | 10 | namespace W2Open.API.Areas.HelpPage 11 | { 12 | /// 13 | /// A custom that reads the API documentation from an XML documentation file. 14 | /// 15 | public class XmlDocumentationProvider : IDocumentationProvider, IModelDocumentationProvider 16 | { 17 | private XPathNavigator _documentNavigator; 18 | private const string TypeExpression = "/doc/members/member[@name='T:{0}']"; 19 | private const string MethodExpression = "/doc/members/member[@name='M:{0}']"; 20 | private const string PropertyExpression = "/doc/members/member[@name='P:{0}']"; 21 | private const string FieldExpression = "/doc/members/member[@name='F:{0}']"; 22 | private const string ParameterExpression = "param[@name='{0}']"; 23 | 24 | /// 25 | /// Initializes a new instance of the class. 26 | /// 27 | /// The physical path to XML document. 28 | public XmlDocumentationProvider(string documentPath) 29 | { 30 | if (documentPath == null) 31 | { 32 | throw new ArgumentNullException("documentPath"); 33 | } 34 | XPathDocument xpath = new XPathDocument(documentPath); 35 | _documentNavigator = xpath.CreateNavigator(); 36 | } 37 | 38 | public string GetDocumentation(HttpControllerDescriptor controllerDescriptor) 39 | { 40 | XPathNavigator typeNode = GetTypeNode(controllerDescriptor.ControllerType); 41 | return GetTagValue(typeNode, "summary"); 42 | } 43 | 44 | public virtual string GetDocumentation(HttpActionDescriptor actionDescriptor) 45 | { 46 | XPathNavigator methodNode = GetMethodNode(actionDescriptor); 47 | return GetTagValue(methodNode, "summary"); 48 | } 49 | 50 | public virtual string GetDocumentation(HttpParameterDescriptor parameterDescriptor) 51 | { 52 | ReflectedHttpParameterDescriptor reflectedParameterDescriptor = parameterDescriptor as ReflectedHttpParameterDescriptor; 53 | if (reflectedParameterDescriptor != null) 54 | { 55 | XPathNavigator methodNode = GetMethodNode(reflectedParameterDescriptor.ActionDescriptor); 56 | if (methodNode != null) 57 | { 58 | string parameterName = reflectedParameterDescriptor.ParameterInfo.Name; 59 | XPathNavigator parameterNode = methodNode.SelectSingleNode(String.Format(CultureInfo.InvariantCulture, ParameterExpression, parameterName)); 60 | if (parameterNode != null) 61 | { 62 | return parameterNode.Value.Trim(); 63 | } 64 | } 65 | } 66 | 67 | return null; 68 | } 69 | 70 | public string GetResponseDocumentation(HttpActionDescriptor actionDescriptor) 71 | { 72 | XPathNavigator methodNode = GetMethodNode(actionDescriptor); 73 | return GetTagValue(methodNode, "returns"); 74 | } 75 | 76 | public string GetDocumentation(MemberInfo member) 77 | { 78 | string memberName = String.Format(CultureInfo.InvariantCulture, "{0}.{1}", GetTypeName(member.DeclaringType), member.Name); 79 | string expression = member.MemberType == MemberTypes.Field ? FieldExpression : PropertyExpression; 80 | string selectExpression = String.Format(CultureInfo.InvariantCulture, expression, memberName); 81 | XPathNavigator propertyNode = _documentNavigator.SelectSingleNode(selectExpression); 82 | return GetTagValue(propertyNode, "summary"); 83 | } 84 | 85 | public string GetDocumentation(Type type) 86 | { 87 | XPathNavigator typeNode = GetTypeNode(type); 88 | return GetTagValue(typeNode, "summary"); 89 | } 90 | 91 | private XPathNavigator GetMethodNode(HttpActionDescriptor actionDescriptor) 92 | { 93 | ReflectedHttpActionDescriptor reflectedActionDescriptor = actionDescriptor as ReflectedHttpActionDescriptor; 94 | if (reflectedActionDescriptor != null) 95 | { 96 | string selectExpression = String.Format(CultureInfo.InvariantCulture, MethodExpression, GetMemberName(reflectedActionDescriptor.MethodInfo)); 97 | return _documentNavigator.SelectSingleNode(selectExpression); 98 | } 99 | 100 | return null; 101 | } 102 | 103 | private static string GetMemberName(MethodInfo method) 104 | { 105 | string name = String.Format(CultureInfo.InvariantCulture, "{0}.{1}", GetTypeName(method.DeclaringType), method.Name); 106 | ParameterInfo[] parameters = method.GetParameters(); 107 | if (parameters.Length != 0) 108 | { 109 | string[] parameterTypeNames = parameters.Select(param => GetTypeName(param.ParameterType)).ToArray(); 110 | name += String.Format(CultureInfo.InvariantCulture, "({0})", String.Join(",", parameterTypeNames)); 111 | } 112 | 113 | return name; 114 | } 115 | 116 | private static string GetTagValue(XPathNavigator parentNode, string tagName) 117 | { 118 | if (parentNode != null) 119 | { 120 | XPathNavigator node = parentNode.SelectSingleNode(tagName); 121 | if (node != null) 122 | { 123 | return node.Value.Trim(); 124 | } 125 | } 126 | 127 | return null; 128 | } 129 | 130 | private XPathNavigator GetTypeNode(Type type) 131 | { 132 | string controllerTypeName = GetTypeName(type); 133 | string selectExpression = String.Format(CultureInfo.InvariantCulture, TypeExpression, controllerTypeName); 134 | return _documentNavigator.SelectSingleNode(selectExpression); 135 | } 136 | 137 | private static string GetTypeName(Type type) 138 | { 139 | string name = type.FullName; 140 | if (type.IsGenericType) 141 | { 142 | // Format the generic type name to something like: Generic{System.Int32,System.String} 143 | Type genericType = type.GetGenericTypeDefinition(); 144 | Type[] genericArguments = type.GetGenericArguments(); 145 | string genericTypeName = genericType.FullName; 146 | 147 | // Trim the generic parameter counts from the name 148 | genericTypeName = genericTypeName.Substring(0, genericTypeName.IndexOf('`')); 149 | string[] argumentTypeNames = genericArguments.Select(t => GetTypeName(t)).ToArray(); 150 | name = String.Format(CultureInfo.InvariantCulture, "{0}{{{1}}}", genericTypeName, String.Join(",", argumentTypeNames)); 151 | } 152 | if (type.IsNested) 153 | { 154 | // Changing the nested type name from OuterType+InnerType to OuterType.InnerType to match the XML documentation syntax. 155 | name = name.Replace("+", "."); 156 | } 157 | 158 | return name; 159 | } 160 | } 161 | } 162 | -------------------------------------------------------------------------------- /W2Open.API/Content/Site.css: -------------------------------------------------------------------------------- 1 | body { 2 | padding-top: 50px; 3 | padding-bottom: 20px; 4 | } 5 | 6 | /* Set padding to keep content from hitting the edges */ 7 | .body-content { 8 | padding-left: 15px; 9 | padding-right: 15px; 10 | } 11 | 12 | /* Set width on the form input elements since they're 100% wide by default */ 13 | input, 14 | select, 15 | textarea { 16 | max-width: 280px; 17 | } 18 | -------------------------------------------------------------------------------- /W2Open.API/Controllers/HomeController.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Web; 5 | using System.Web.Mvc; 6 | 7 | namespace W2Open.API.Controllers 8 | { 9 | public class HomeController : Controller 10 | { 11 | public ActionResult Index() 12 | { 13 | ViewBag.Title = "Home Page"; 14 | 15 | return View(); 16 | } 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /W2Open.API/Controllers/ValuesController.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Net; 5 | using System.Net.Http; 6 | using System.Web.Http; 7 | 8 | namespace W2Open.API.Controllers 9 | { 10 | [Authorize] 11 | public class ValuesController : ApiController 12 | { 13 | // GET api/values 14 | public IEnumerable Get() 15 | { 16 | return new string[] { "value1", "value2" }; 17 | } 18 | 19 | // GET api/values/5 20 | public string Get(int id) 21 | { 22 | return "value"; 23 | } 24 | 25 | // POST api/values 26 | public void Post([FromBody]string value) 27 | { 28 | } 29 | 30 | // PUT api/values/5 31 | public void Put(int id, [FromBody]string value) 32 | { 33 | } 34 | 35 | // DELETE api/values/5 36 | public void Delete(int id) 37 | { 38 | } 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /W2Open.API/Global.asax: -------------------------------------------------------------------------------- 1 | <%@ Application Codebehind="Global.asax.cs" Inherits="W2Open.API.WebApiApplication" Language="C#" %> 2 | -------------------------------------------------------------------------------- /W2Open.API/Global.asax.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Web; 5 | using System.Web.Http; 6 | using System.Web.Mvc; 7 | using System.Web.Optimization; 8 | using System.Web.Routing; 9 | 10 | namespace W2Open.API 11 | { 12 | public class WebApiApplication : System.Web.HttpApplication 13 | { 14 | protected void Application_Start() 15 | { 16 | AreaRegistration.RegisterAllAreas(); 17 | GlobalConfiguration.Configure(WebApiConfig.Register); 18 | FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); 19 | RouteConfig.RegisterRoutes(RouteTable.Routes); 20 | BundleConfig.RegisterBundles(BundleTable.Bundles); 21 | } 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /W2Open.API/Models/AccountBindingModels.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.ComponentModel.DataAnnotations; 3 | using Newtonsoft.Json; 4 | 5 | namespace W2Open.API.Models 6 | { 7 | // Modelos usados como parâmetros para as ações AccountController. 8 | 9 | public class AddExternalLoginBindingModel 10 | { 11 | [Required] 12 | [Display(Name = "Token de acesso externo")] 13 | public string ExternalAccessToken { get; set; } 14 | } 15 | 16 | public class ChangePasswordBindingModel 17 | { 18 | [Required] 19 | [DataType(DataType.Password)] 20 | [Display(Name = "Senha atual")] 21 | public string OldPassword { get; set; } 22 | 23 | [Required] 24 | [StringLength(100, ErrorMessage = "O {0} deve ter pelo menos {2} caracteres.", MinimumLength = 6)] 25 | [DataType(DataType.Password)] 26 | [Display(Name = "Nova senha")] 27 | public string NewPassword { get; set; } 28 | 29 | [DataType(DataType.Password)] 30 | [Display(Name = "Confirmar nova senha")] 31 | [Compare("NewPassword", ErrorMessage = "A nova senha e a senha de confirmação não coincidem.")] 32 | public string ConfirmPassword { get; set; } 33 | } 34 | 35 | public class RegisterBindingModel 36 | { 37 | [Required] 38 | [Display(Name = "Email")] 39 | public string Email { get; set; } 40 | 41 | [Required] 42 | [StringLength(100, ErrorMessage = "O {0} deve ter pelo menos {2} caracteres.", MinimumLength = 6)] 43 | [DataType(DataType.Password)] 44 | [Display(Name = "Senha")] 45 | public string Password { get; set; } 46 | 47 | [DataType(DataType.Password)] 48 | [Display(Name = "Confirmar senha")] 49 | [Compare("Password", ErrorMessage = "A senha e a senha de confirmação não coincidem.")] 50 | public string ConfirmPassword { get; set; } 51 | } 52 | 53 | public class RegisterExternalBindingModel 54 | { 55 | [Required] 56 | [Display(Name = "Email")] 57 | public string Email { get; set; } 58 | } 59 | 60 | public class RemoveLoginBindingModel 61 | { 62 | [Required] 63 | [Display(Name = "Provedor de logon")] 64 | public string LoginProvider { get; set; } 65 | 66 | [Required] 67 | [Display(Name = "Chave do Provedor")] 68 | public string ProviderKey { get; set; } 69 | } 70 | 71 | public class SetPasswordBindingModel 72 | { 73 | [Required] 74 | [StringLength(100, ErrorMessage = "O {0} deve ter pelo menos {2} caracteres.", MinimumLength = 6)] 75 | [DataType(DataType.Password)] 76 | [Display(Name = "Nova senha")] 77 | public string NewPassword { get; set; } 78 | 79 | [DataType(DataType.Password)] 80 | [Display(Name = "Confirmar nova senha")] 81 | [Compare("NewPassword", ErrorMessage = "A nova senha e a senha de confirmação não coincidem.")] 82 | public string ConfirmPassword { get; set; } 83 | } 84 | } 85 | -------------------------------------------------------------------------------- /W2Open.API/Models/AccountViewModels.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | 4 | namespace W2Open.API.Models 5 | { 6 | // Modelos retornados por ações AccountController. 7 | 8 | public class ExternalLoginViewModel 9 | { 10 | public string Name { get; set; } 11 | 12 | public string Url { get; set; } 13 | 14 | public string State { get; set; } 15 | } 16 | 17 | public class ManageInfoViewModel 18 | { 19 | public string LocalLoginProvider { get; set; } 20 | 21 | public string Email { get; set; } 22 | 23 | public IEnumerable Logins { get; set; } 24 | 25 | public IEnumerable ExternalLoginProviders { get; set; } 26 | } 27 | 28 | public class UserInfoViewModel 29 | { 30 | public string Email { get; set; } 31 | 32 | public bool HasRegistered { get; set; } 33 | 34 | public string LoginProvider { get; set; } 35 | } 36 | 37 | public class UserLoginInfoViewModel 38 | { 39 | public string LoginProvider { get; set; } 40 | 41 | public string ProviderKey { get; set; } 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /W2Open.API/Models/IdentityModels.cs: -------------------------------------------------------------------------------- 1 | using System.Security.Claims; 2 | using System.Threading.Tasks; 3 | using Microsoft.AspNet.Identity; 4 | using Microsoft.AspNet.Identity.EntityFramework; 5 | using Microsoft.AspNet.Identity.Owin; 6 | 7 | namespace W2Open.API.Models 8 | { 9 | // É possível adicionar dados do perfil do usuário adicionando mais propriedades na sua classe ApplicationUser, visite https://go.microsoft.com/fwlink/?LinkID=317594 para obter mais informações. 10 | public class ApplicationUser : IdentityUser 11 | { 12 | public async Task GenerateUserIdentityAsync(UserManager manager, string authenticationType) 13 | { 14 | // authenticationType deve corresponder a um definido em CookieAuthenticationOptions.AuthenticationType 15 | var userIdentity = await manager.CreateIdentityAsync(this, authenticationType); 16 | // Adicione declarações de usuários aqui 17 | return userIdentity; 18 | } 19 | } 20 | 21 | public class ApplicationDbContext : IdentityDbContext 22 | { 23 | public ApplicationDbContext() 24 | : base("DefaultConnection", throwIfV1Schema: false) 25 | { 26 | } 27 | 28 | public static ApplicationDbContext Create() 29 | { 30 | return new ApplicationDbContext(); 31 | } 32 | } 33 | } -------------------------------------------------------------------------------- /W2Open.API/Properties/AssemblyInfo.cs: -------------------------------------------------------------------------------- 1 | using System.Reflection; 2 | using System.Runtime.CompilerServices; 3 | using System.Runtime.InteropServices; 4 | 5 | // As informações gerais sobre um assembly são controladas através do seguinte 6 | // conjunto de atributos a seguir. Altere esses valores de atributo para modificar as informações 7 | // associadas a um assembly. 8 | [assembly: AssemblyTitle("W2Open.API")] 9 | [assembly: AssemblyDescription("")] 10 | [assembly: AssemblyConfiguration("")] 11 | [assembly: AssemblyCompany("")] 12 | [assembly: AssemblyProduct("W2Open.API")] 13 | [assembly: AssemblyCopyright("Copyright © 2018")] 14 | [assembly: AssemblyTrademark("")] 15 | [assembly: AssemblyCulture("")] 16 | 17 | // Definir ComVisible como falso torna não visíveis os tipos neste assembly 18 | // para componentes COM. Caso precise acessar um tipo neste assembly a partir de 19 | // COM, defina o atributo ComVisible como true nesse tipo. 20 | [assembly: ComVisible(false)] 21 | 22 | // A GUID a seguir será referente à ID do typelib se este projeto for exposto ao COM 23 | [assembly: Guid("37825f9e-d549-4a6a-af46-e9f15d30787c")] 24 | 25 | // As informações de versão de um assembly consistem nos seguintes quatro valores: 26 | // 27 | // Versão Principal 28 | // Versão Secundária 29 | // Número da Versão 30 | // Revisão 31 | // 32 | // É possível especificar todos os valores ou definir como padrão os números de revisão e de versão 33 | // usando o '*' como mostrado abaixo: 34 | [assembly: AssemblyVersion("1.0.0.0")] 35 | [assembly: AssemblyFileVersion("1.0.0.0")] 36 | -------------------------------------------------------------------------------- /W2Open.API/Providers/ApplicationOAuthProvider.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Security.Claims; 5 | using System.Threading.Tasks; 6 | using Microsoft.AspNet.Identity; 7 | using Microsoft.AspNet.Identity.EntityFramework; 8 | using Microsoft.AspNet.Identity.Owin; 9 | using Microsoft.Owin.Security; 10 | using Microsoft.Owin.Security.Cookies; 11 | using Microsoft.Owin.Security.OAuth; 12 | using W2Open.API.Models; 13 | 14 | namespace W2Open.API.Providers 15 | { 16 | public class ApplicationOAuthProvider : OAuthAuthorizationServerProvider 17 | { 18 | private readonly string _publicClientId; 19 | 20 | public ApplicationOAuthProvider(string publicClientId) 21 | { 22 | if (publicClientId == null) 23 | { 24 | throw new ArgumentNullException("publicClientId"); 25 | } 26 | 27 | _publicClientId = publicClientId; 28 | } 29 | 30 | public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context) 31 | { 32 | var userManager = context.OwinContext.GetUserManager(); 33 | 34 | ApplicationUser user = await userManager.FindAsync(context.UserName, context.Password); 35 | 36 | if (user == null) 37 | { 38 | context.SetError("invalid_grant", "Nome de usuário ou senha incorreto."); 39 | return; 40 | } 41 | 42 | ClaimsIdentity oAuthIdentity = await user.GenerateUserIdentityAsync(userManager, 43 | OAuthDefaults.AuthenticationType); 44 | ClaimsIdentity cookiesIdentity = await user.GenerateUserIdentityAsync(userManager, 45 | CookieAuthenticationDefaults.AuthenticationType); 46 | 47 | AuthenticationProperties properties = CreateProperties(user.UserName); 48 | AuthenticationTicket ticket = new AuthenticationTicket(oAuthIdentity, properties); 49 | context.Validated(ticket); 50 | context.Request.Context.Authentication.SignIn(cookiesIdentity); 51 | } 52 | 53 | public override Task TokenEndpoint(OAuthTokenEndpointContext context) 54 | { 55 | foreach (KeyValuePair property in context.Properties.Dictionary) 56 | { 57 | context.AdditionalResponseParameters.Add(property.Key, property.Value); 58 | } 59 | 60 | return Task.FromResult(null); 61 | } 62 | 63 | public override Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context) 64 | { 65 | // As credenciais de senha do proprietário do recurso não fornecem um ID de cliente. 66 | if (context.ClientId == null) 67 | { 68 | context.Validated(); 69 | } 70 | 71 | return Task.FromResult(null); 72 | } 73 | 74 | public override Task ValidateClientRedirectUri(OAuthValidateClientRedirectUriContext context) 75 | { 76 | if (context.ClientId == _publicClientId) 77 | { 78 | Uri expectedRootUri = new Uri(context.Request.Uri, "/"); 79 | 80 | if (expectedRootUri.AbsoluteUri == context.RedirectUri) 81 | { 82 | context.Validated(); 83 | } 84 | } 85 | 86 | return Task.FromResult(null); 87 | } 88 | 89 | public static AuthenticationProperties CreateProperties(string userName) 90 | { 91 | IDictionary data = new Dictionary 92 | { 93 | { "userName", userName } 94 | }; 95 | return new AuthenticationProperties(data); 96 | } 97 | } 98 | } -------------------------------------------------------------------------------- /W2Open.API/Results/ChallengeResult.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Net; 5 | using System.Net.Http; 6 | using System.Threading; 7 | using System.Threading.Tasks; 8 | using System.Web.Http; 9 | 10 | namespace W2Open.API.Results 11 | { 12 | public class ChallengeResult : IHttpActionResult 13 | { 14 | public ChallengeResult(string loginProvider, ApiController controller) 15 | { 16 | LoginProvider = loginProvider; 17 | Request = controller.Request; 18 | } 19 | 20 | public string LoginProvider { get; set; } 21 | public HttpRequestMessage Request { get; set; } 22 | 23 | public Task ExecuteAsync(CancellationToken cancellationToken) 24 | { 25 | Request.GetOwinContext().Authentication.Challenge(LoginProvider); 26 | 27 | HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.Unauthorized); 28 | response.RequestMessage = Request; 29 | return Task.FromResult(response); 30 | } 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /W2Open.API/Scripts/jquery.validate.unobtrusive.min.js: -------------------------------------------------------------------------------- 1 | /* NUGET: BEGIN LICENSE TEXT 2 | * 3 | * Microsoft grants you the right to use these script files for the sole 4 | * purpose of either: (i) interacting through your browser with the Microsoft 5 | * website or online service, subject to the applicable licensing or use 6 | * terms; or (ii) using the files as included with a Microsoft product subject 7 | * to that product's license terms. Microsoft reserves all other rights to the 8 | * files not expressly granted by Microsoft, whether by implication, estoppel 9 | * or otherwise. Insofar as a script file is dual licensed under GPL, 10 | * Microsoft neither took the code under GPL nor distributes it thereunder but 11 | * under the terms set out in this paragraph. All notices and licenses 12 | * below are for informational purposes only. 13 | * 14 | * NUGET: END LICENSE TEXT */ 15 | /* NUGET: BEGIN LICENSE TEXT 16 | * 17 | * Microsoft grants you the right to use these script files for the sole 18 | * purpose of either: (i) interacting through your browser with the Microsoft 19 | * website or online service, subject to the applicable licensing or use 20 | * terms; or (ii) using the files as included with a Microsoft product subject 21 | * to that product's license terms. Microsoft reserves all other rights to the 22 | * files not expressly granted by Microsoft, whether by implication, estoppel 23 | * or otherwise. Insofar as a script file is dual licensed under GPL, 24 | * Microsoft neither took the code under GPL nor distributes it thereunder but 25 | * under the terms set out in this paragraph. All notices and licenses 26 | * below are for informational purposes only. 27 | * 28 | * NUGET: END LICENSE TEXT */ 29 | /* 30 | ** Unobtrusive validation support library for jQuery and jQuery Validate 31 | ** Copyright (C) Microsoft Corporation. All rights reserved. 32 | */ 33 | (function(a){var d=a.validator,b,e="unobtrusiveValidation";function c(a,b,c){a.rules[b]=c;if(a.message)a.messages[b]=a.message}function j(a){return a.replace(/^\s+|\s+$/g,"").split(/\s*,\s*/g)}function f(a){return a.replace(/([!"#$%&'()*+,./:;<=>?@\[\\\]^`{|}~])/g,"\\$1")}function h(a){return a.substr(0,a.lastIndexOf(".")+1)}function g(a,b){if(a.indexOf("*.")===0)a=a.replace("*.",b);return a}function m(c,e){var b=a(this).find("[data-valmsg-for='"+f(e[0].name)+"']"),d=b.attr("data-valmsg-replace"),g=d?a.parseJSON(d)!==false:null;b.removeClass("field-validation-valid").addClass("field-validation-error");c.data("unobtrusiveContainer",b);if(g){b.empty();c.removeClass("input-validation-error").appendTo(b)}else c.hide()}function l(e,d){var c=a(this).find("[data-valmsg-summary=true]"),b=c.find("ul");if(b&&b.length&&d.errorList.length){b.empty();c.addClass("validation-summary-errors").removeClass("validation-summary-valid");a.each(d.errorList,function(){a("
  • ").html(this.message).appendTo(b)})}}function k(d){var b=d.data("unobtrusiveContainer"),c=b.attr("data-valmsg-replace"),e=c?a.parseJSON(c):null;if(b){b.addClass("field-validation-valid").removeClass("field-validation-error");d.removeData("unobtrusiveContainer");e&&b.empty()}}function n(){var b=a(this),c="__jquery_unobtrusive_validation_form_reset";if(b.data(c))return;b.data(c,true);try{b.data("validator").resetForm()}finally{b.removeData(c)}b.find(".validation-summary-errors").addClass("validation-summary-valid").removeClass("validation-summary-errors");b.find(".field-validation-error").addClass("field-validation-valid").removeClass("field-validation-error").removeData("unobtrusiveContainer").find(">*").removeData("unobtrusiveContainer")}function i(b){var c=a(b),f=c.data(e),i=a.proxy(n,b),g=d.unobtrusive.options||{},h=function(e,d){var c=g[e];c&&a.isFunction(c)&&c.apply(b,d)};if(!f){f={options:{errorClass:g.errorClass||"input-validation-error",errorElement:g.errorElement||"span",errorPlacement:function(){m.apply(b,arguments);h("errorPlacement",arguments)},invalidHandler:function(){l.apply(b,arguments);h("invalidHandler",arguments)},messages:{},rules:{},success:function(){k.apply(b,arguments);h("success",arguments)}},attachValidation:function(){c.off("reset."+e,i).on("reset."+e,i).validate(this.options)},validate:function(){c.validate();return c.valid()}};c.data(e,f)}return f}d.unobtrusive={adapters:[],parseElement:function(b,h){var d=a(b),f=d.parents("form")[0],c,e,g;if(!f)return;c=i(f);c.options.rules[b.name]=e={};c.options.messages[b.name]=g={};a.each(this.adapters,function(){var c="data-val-"+this.name,i=d.attr(c),h={};if(i!==undefined){c+="-";a.each(this.params,function(){h[this]=d.attr(c+this)});this.adapt({element:b,form:f,message:i,params:h,rules:e,messages:g})}});a.extend(e,{__dummy__:true});!h&&c.attachValidation()},parse:function(c){var b=a(c),e=b.parents().addBack().filter("form").add(b.find("form")).has("[data-val=true]");b.find("[data-val=true]").each(function(){d.unobtrusive.parseElement(this,true)});e.each(function(){var a=i(this);a&&a.attachValidation()})}};b=d.unobtrusive.adapters;b.add=function(c,a,b){if(!b){b=a;a=[]}this.push({name:c,params:a,adapt:b});return this};b.addBool=function(a,b){return this.add(a,function(d){c(d,b||a,true)})};b.addMinMax=function(e,g,f,a,d,b){return this.add(e,[d||"min",b||"max"],function(b){var e=b.params.min,d=b.params.max;if(e&&d)c(b,a,[e,d]);else if(e)c(b,g,e);else d&&c(b,f,d)})};b.addSingleVal=function(a,b,d){return this.add(a,[b||"val"],function(e){c(e,d||a,e.params[b])})};d.addMethod("__dummy__",function(){return true});d.addMethod("regex",function(b,c,d){var a;if(this.optional(c))return true;a=(new RegExp(d)).exec(b);return a&&a.index===0&&a[0].length===b.length});d.addMethod("nonalphamin",function(c,d,b){var a;if(b){a=c.match(/\W/g);a=a&&a.length>=b}return a});if(d.methods.extension){b.addSingleVal("accept","mimtype");b.addSingleVal("extension","extension")}else b.addSingleVal("extension","extension","accept");b.addSingleVal("regex","pattern");b.addBool("creditcard").addBool("date").addBool("digits").addBool("email").addBool("number").addBool("url");b.addMinMax("length","minlength","maxlength","rangelength").addMinMax("range","min","max","range");b.addMinMax("minlength","minlength").addMinMax("maxlength","minlength","maxlength");b.add("equalto",["other"],function(b){var i=h(b.element.name),j=b.params.other,d=g(j,i),e=a(b.form).find(":input").filter("[name='"+f(d)+"']")[0];c(b,"equalTo",e)});b.add("required",function(a){(a.element.tagName.toUpperCase()!=="INPUT"||a.element.type.toUpperCase()!=="CHECKBOX")&&c(a,"required",true)});b.add("remote",["url","type","additionalfields"],function(b){var d={url:b.params.url,type:b.params.type||"GET",data:{}},e=h(b.element.name);a.each(j(b.params.additionalfields||b.element.name),function(i,h){var c=g(h,e);d.data[c]=function(){var d=a(b.form).find(":input").filter("[name='"+f(c)+"']");return d.is(":checkbox")?d.filter(":checked").val()||d.filter(":hidden").val()||"":d.is(":radio")?d.filter(":checked").val()||"":d.val()}});c(b,"remote",d)});b.add("password",["min","nonalphamin","regex"],function(a){a.params.min&&c(a,"minlength",a.params.min);a.params.nonalphamin&&c(a,"nonalphamin",a.params.nonalphamin);a.params.regex&&c(a,"regex",a.params.regex)});a(function(){d.unobtrusive.parse(document)})})(jQuery); -------------------------------------------------------------------------------- /W2Open.API/Startup.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using Microsoft.Owin; 5 | using Owin; 6 | 7 | [assembly: OwinStartup(typeof(W2Open.API.Startup))] 8 | 9 | namespace W2Open.API 10 | { 11 | public partial class Startup 12 | { 13 | public void Configuration(IAppBuilder app) 14 | { 15 | ConfigureAuth(app); 16 | } 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /W2Open.API/Views/Home/Index.cshtml: -------------------------------------------------------------------------------- 1 | 
    2 |

    ASP.NET

    3 |

    ASP.NET is a free web framework for building great Web sites and Web applications using HTML, CSS, and JavaScript.

    4 |

    Learn more »

    5 |
    6 |
    7 |
    8 |

    Getting started

    9 |

    ASP.NET Web API is a framework that makes it easy to build HTTP services that reach 10 | a broad range of clients, including browsers and mobile devices. ASP.NET Web API 11 | is an ideal platform for building RESTful applications on the .NET Framework.

    12 |

    Learn more »

    13 |
    14 |
    15 |

    Get more libraries

    16 |

    NuGet is a free Visual Studio extension that makes it easy to add, remove, and update libraries and tools in Visual Studio projects.

    17 |

    Learn more »

    18 |
    19 |
    20 |

    Web Hosting

    21 |

    You can easily find a web hosting company that offers the right mix of features and price for your applications.

    22 |

    Learn more »

    23 |
    24 |
    25 | -------------------------------------------------------------------------------- /W2Open.API/Views/Shared/Error.cshtml: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | 6 | Erro 7 | 8 | 9 |
    10 |

    Erro.

    11 |

    Ocorreu um erro ao processar sua solicitação.

    12 |
    13 | 14 | 15 | -------------------------------------------------------------------------------- /W2Open.API/Views/Shared/_Layout.cshtml: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | 6 | 7 | @ViewBag.Title 8 | @Styles.Render("~/Content/css") 9 | @Scripts.Render("~/bundles/modernizr") 10 | 11 | 12 | 13 | 31 |
    32 | @RenderBody() 33 |
    34 |
    35 |

    © @DateTime.Now.Year - Meu Aplicativo ASP.NET

    36 |
    37 |
    38 | 39 | @Scripts.Render("~/bundles/jquery") 40 | @Scripts.Render("~/bundles/bootstrap") 41 | @RenderSection("scripts", required: false) 42 | 43 | 44 | -------------------------------------------------------------------------------- /W2Open.API/Views/Web.config: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | 6 |
    7 |
    8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | -------------------------------------------------------------------------------- /W2Open.API/Views/_ViewStart.cshtml: -------------------------------------------------------------------------------- 1 | @{ 2 | Layout = "~/Views/Shared/_Layout.cshtml"; 3 | } 4 | -------------------------------------------------------------------------------- /W2Open.API/Web.Debug.config: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | 6 | 17 | 18 | 29 | 30 | 31 | -------------------------------------------------------------------------------- /W2Open.API/Web.Release.config: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | 6 | 17 | 18 | 19 | 30 | 31 | 32 | -------------------------------------------------------------------------------- /W2Open.API/Web.config: -------------------------------------------------------------------------------- 1 | 2 | 6 | 7 | 8 | 9 |
    12 | 13 | 14 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 33 | 34 | 36 | 37 | 38 | 39 | 40 | 41 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | 77 | 78 | 79 | 80 | 81 | 82 | 83 | 84 | 85 | 86 | 87 | 88 | 89 | 90 | 91 | 92 | 93 | 94 | 95 | 96 | 97 | 98 | 99 | 100 | 101 | 102 | 103 | 104 | 105 | 106 | 107 | 108 | 109 | 110 | 113 | 116 | 117 | 118 | -------------------------------------------------------------------------------- /W2Open.API/favicon.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/seitbnao/W2-DataBase/84c55a71764cb61c47982574f42750737edc226e/W2Open.API/favicon.ico -------------------------------------------------------------------------------- /W2Open.API/fonts/glyphicons-halflings-regular.eot: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/seitbnao/W2-DataBase/84c55a71764cb61c47982574f42750737edc226e/W2Open.API/fonts/glyphicons-halflings-regular.eot -------------------------------------------------------------------------------- /W2Open.API/fonts/glyphicons-halflings-regular.ttf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/seitbnao/W2-DataBase/84c55a71764cb61c47982574f42750737edc226e/W2Open.API/fonts/glyphicons-halflings-regular.ttf -------------------------------------------------------------------------------- /W2Open.API/fonts/glyphicons-halflings-regular.woff: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/seitbnao/W2-DataBase/84c55a71764cb61c47982574f42750737edc226e/W2Open.API/fonts/glyphicons-halflings-regular.woff -------------------------------------------------------------------------------- /W2Open.API/fonts/glyphicons-halflings-regular.woff2: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/seitbnao/W2-DataBase/84c55a71764cb61c47982574f42750737edc226e/W2Open.API/fonts/glyphicons-halflings-regular.woff2 -------------------------------------------------------------------------------- /W2Open.API/packages.config: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | -------------------------------------------------------------------------------- /W2Open.Common/Defines.cs: -------------------------------------------------------------------------------- 1 | namespace W2Open.Common 2 | { 3 | /// 4 | /// Contains the basic definitions related to the server's network connection. 5 | /// 6 | public static class BaseDef 7 | { 8 | 9 | 10 | /// 11 | /// Max packet length in bytes. 12 | /// 13 | public const int MAXL_PACKET = 128000; 14 | 15 | /// 16 | /// Code used in the game network protocol to initiate the connection. Every GameServer must send this 4-byte value as the first packet. 17 | /// 18 | public const int INIT_CODE = 0x1F11F311; 19 | 20 | /// 21 | /// Max simultaneous connected amount of GameServers. 22 | /// 23 | /// 24 | 25 | 26 | 27 | 28 | public const int MAX_CHANNEL = 10; 29 | public const int MAX_GUILDZONE = 5; 30 | public const int MAX_MAXUSER = 1000; 31 | public const int MAX_GUILD = 5000; 32 | public const int MAX_ITEMLIST = 5000; 33 | public const int FLAG_GAME2CLIENT = 0x0100; 34 | public const int FLAG_CLIENT2GAME = 0x0200; 35 | 36 | public const int FLAG_DB2GAME = 0x0400; 37 | public const int FLAG_GAME2DB = 0x0800; 38 | 39 | public const int FLAG_DB2NP = 0x1000; 40 | public const int FLAG_NP2DB = 0x2000; 41 | 42 | public const int FLAG_NEW = 0x4000; 43 | //0xDC3 44 | public const ushort _MSG_DBCapsuleInfo = (60 | FLAG_DB2GAME | FLAG_GAME2DB); 45 | public const ushort _MSG_DBPutInCapsule = (61 | FLAG_DB2GAME | FLAG_GAME2DB); 46 | public const ushort _MSG_DBOutCapsule = (62 | FLAG_DB2GAME | FLAG_GAME2DB); 47 | public const ushort _MSG_CNFDBCapsuleInfo = (31 | FLAG_DB2GAME | FLAG_GAME2DB | FLAG_GAME2CLIENT); 48 | public const ushort _MSG_DBCNFCapsuleSucess = (18 | FLAG_DB2GAME); 49 | public const ushort _MSG_DBClientMessage = (19 | FLAG_DB2GAME); 50 | public const ushort _MSG_DBCNFArchCharacterSucess = (14 | FLAG_DB2GAME); 51 | public const ushort _MSG_DBCNFArchCharacterFail = (15 | FLAG_DB2GAME); 52 | public const ushort _MSG_DBCNFCapsuleCharacterFail = (16 | FLAG_DB2GAME); 53 | public const ushort _MSG_DBCNFCapsuleCharacterFail2 = (17 | FLAG_DB2GAME); 54 | public const ushort _MSG_DBDeleteCharacter = (9 | FLAG_GAME2DB); 55 | public const ushort _MSG_DBUpdateSapphire = (10 | FLAG_GAME2DB); 56 | public const ushort _MSG_DBCNFAccountLogOut = (11 | FLAG_DB2GAME); 57 | public const ushort _MSG_MessageDBRecord = (12 | FLAG_GAME2DB); 58 | public const ushort _MSG_DBSavingQuit = (10 | FLAG_DB2GAME); 59 | public const ushort _MSG_DBCNFCharacterLogin = (23 | FLAG_DB2GAME); 60 | public const ushort _MSG_DBCNFNewCharacter = (24 | FLAG_DB2GAME); 61 | public const ushort _MSG_DBCreateArchCharacter = (31 | FLAG_GAME2DB); 62 | public const ushort _MSG_DBCNFDeleteCharacter = (25 | FLAG_DB2GAME); 63 | public const ushort _MSG_DBNewAccountFail = (26 | FLAG_DB2GAME); 64 | public const ushort _MSG_DBCharacterLoginFail = (28 | FLAG_DB2GAME); 65 | public const ushort _MSG_DBNewCharacterFail = (29 | FLAG_DB2GAME); 66 | public const ushort _MSG_DBDeleteCharacterFail = (30 | FLAG_DB2GAME); 67 | public const ushort _MSG_DBAlreadyPlaying = (31 | FLAG_DB2GAME); 68 | public const ushort _MSG_DBStillPlaying = (32 | FLAG_DB2GAME); 69 | public const ushort _MSG_DBAccountLoginFail_Account = (33 | FLAG_DB2GAME); 70 | public const ushort _MSG_DBAccountLoginFail_Pass = (34 | FLAG_DB2GAME); 71 | public const ushort _MSG_DBSetIndex = (35 | FLAG_DB2GAME); 72 | public const ushort _MSG_DBAccountLoginFail_Block = (36 | FLAG_DB2GAME); 73 | public const ushort _MSG_DBAccountLoginFail_Disable = (37 | FLAG_DB2GAME); 74 | public const ushort _MSG_DBOnlyOncePerDay = (38 | FLAG_DB2GAME); 75 | public const ushort _MSG_DBMessagePanel = (1 | FLAG_DB2GAME); 76 | public const ushort _MSG_DBMessageBoxOk = (2 | FLAG_DB2GAME); 77 | public const ushort _MSG_DBAccountLogin = (3 | FLAG_GAME2DB); 78 | public const ushort _MSG_DBCharacterLogin = (4 | FLAG_GAME2DB); 79 | public const ushort _MSG_DBNoNeedSave = (5 | FLAG_GAME2DB); 80 | public const ushort _MLoginSuccessfulPacket = 0x416; 81 | public const ushort _MSG_DBSaveMob = (7 | FLAG_GAME2DB); 82 | public const ushort _MSG_SavingQuit = (6 | FLAG_GAME2DB); 83 | public const ushort _MSG_TransperCharacter = (169 | FLAG_GAME2CLIENT | FLAG_CLIENT2GAME | FLAG_DB2GAME); 84 | public const ushort _MSG_ReqTransper = (170 | FLAG_GAME2CLIENT | FLAG_CLIENT2GAME | FLAG_DB2GAME | FLAG_GAME2DB); 85 | public const ushort _MSG_War = (14 | FLAG_CLIENT2GAME | FLAG_DB2GAME | FLAG_GAME2DB); 86 | public const ushort _MSG_DBCreateCharacter = (2 | FLAG_GAME2DB); 87 | public const ushort _MSG_DBSendItem = (15 | FLAG_GAME2DB | FLAG_DB2GAME); // 0xC0F 88 | public const ushort _MSG_GuildAlly = (18 | FLAG_CLIENT2GAME | FLAG_DB2GAME | FLAG_GAME2DB); 89 | public const ushort _MSG_GuildInfo = (19 | FLAG_CLIENT2GAME | FLAG_DB2GAME | FLAG_GAME2DB); 90 | public const ushort _MSG_CNFCharacterLogin = 0x417; 91 | public const ushort _MSG_DBItemDayLog = (21 | FLAG_GAME2DB); 92 | public const ushort _MSG_GuildReport = (39 | FLAG_DB2GAME); 93 | } 94 | } -------------------------------------------------------------------------------- /W2Open.Common/GameBasics.cs: -------------------------------------------------------------------------------- 1 | namespace W2Open.Common 2 | { 3 | /// 4 | /// All the basic definitions related directly to the game content. 5 | /// 6 | public static class GameBasics 7 | { 8 | #region Persistent Related 9 | public const int MAXL_ACC_MOB = 4; 10 | public const int MAXL_CARGO_ITEM = 128; 11 | public const int MAXL_AFFECT = 32; 12 | public const int MAXL_ITEM_EFFECT = 3; 13 | public const int MAXL_EQUIP = 16; 14 | public const int MAXL_INVENTORY = 64; 15 | #endregion 16 | 17 | /// 18 | /// The highest move speed a mob can get in the game. 19 | /// 20 | public const byte MAX_MOB_SPEED = 6; 21 | 22 | public const short MAX_NumericERRORS = 3; 23 | } 24 | } -------------------------------------------------------------------------------- /W2Open.Common/GameStructure/Enuns.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Runtime.InteropServices; 3 | 4 | namespace W2Open.Common.GameStructure 5 | { 6 | /// 7 | /// The character class in the game 8 | /// 9 | public enum ECharClass : byte 10 | { 11 | /// 12 | /// Trans Knight. 13 | /// 14 | TK = 0, 15 | /// 16 | /// Foema. 17 | /// 18 | FM = 1, 19 | /// 20 | /// Beast Master. 21 | /// 22 | BM = 2, 23 | /// 24 | /// Huntress. 25 | /// 26 | HT = 3 27 | } 28 | 29 | public enum ClassType : short 30 | { 31 | Arch = 1, 32 | Mortal = 2, 33 | Celestial = 3, 34 | CelestialCS = 4, 35 | SubCelestial = 5 36 | }; 37 | } -------------------------------------------------------------------------------- /W2Open.Common/GameStructure/MPacketHeader.cs: -------------------------------------------------------------------------------- 1 | using System.Runtime.InteropServices; 2 | 3 | namespace W2Open.Common.GameStructure 4 | { 5 | /// 6 | /// All the packet structures must implement this interface. 7 | /// 8 | public interface DBSRVPackets 9 | { 10 | MSG_HEADER Header { get; set; } 11 | } 12 | 13 | /// 14 | /// Header present in all the valid game packets. 15 | /// 16 | [StructLayout(LayoutKind.Sequential, Pack = Defines.DEFAULT_PACK)] 17 | public struct MSG_HEADER 18 | { 19 | public ushort Size; // 1 20 | 21 | public byte Key; // 2 22 | public byte CheckSum; // 3 23 | 24 | public ushort PacketID; 25 | public ushort ClientId; 26 | 27 | public uint TimeStamp; 28 | } 29 | 30 | [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi, Pack = Defines.DEFAULT_PACK)] 31 | public struct _MSG_SIGNAL : DBSRVPackets 32 | { 33 | public MSG_HEADER Header { get; set; } 34 | 35 | } 36 | 37 | [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi, Pack = Defines.DEFAULT_PACK)] 38 | public struct _MSG_SIGNALPARM : DBSRVPackets 39 | { 40 | public MSG_HEADER Header { get; set; } 41 | public int parm; 42 | } 43 | 44 | [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi, Pack = Defines.DEFAULT_PACK)] 45 | public struct _MSG_SIGNALPARM2 : DBSRVPackets 46 | { 47 | public MSG_HEADER Header { get; set; } 48 | public int parm; 49 | public int parm2; 50 | } 51 | 52 | [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi, Pack = Defines.DEFAULT_PACK)] 53 | public struct _MSG_SIGNALPARM3 : DBSRVPackets 54 | { 55 | public MSG_HEADER Header { get; set; } 56 | public int parm; 57 | public int parm1; 58 | public int parm2; 59 | } 60 | 61 | [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi, Pack = Defines.DEFAULT_PACK)] 62 | public struct MPingPacket : DBSRVPackets 63 | { 64 | public const ushort PacketID = 0x3A0; 65 | 66 | public MSG_HEADER Header { get; set; } 67 | } 68 | } -------------------------------------------------------------------------------- /W2Open.Common/ProjectBasics.cs: -------------------------------------------------------------------------------- 1 | namespace W2Open.Common 2 | { 3 | /// 4 | /// Contains all the basic definitions related to the project. 5 | /// Mostly, lower level definitions about the patterns used in the code. 6 | /// 7 | public static class Defines 8 | { 9 | /// 10 | /// Memory pack layout used to correctly Marshals the raw data into structures. 11 | /// This is the memory pack alignment used in the game's client, so we have to respect that. 12 | /// 13 | public const int DEFAULT_PACK = 1; 14 | } 15 | } -------------------------------------------------------------------------------- /W2Open.Common/Properties/AssemblyInfo.cs: -------------------------------------------------------------------------------- 1 | using System.Reflection; 2 | using System.Runtime.CompilerServices; 3 | using System.Runtime.InteropServices; 4 | 5 | // General Information about an assembly is controlled through the following 6 | // set of attributes. Change these attribute values to modify the information 7 | // associated with an assembly. 8 | [assembly: AssemblyTitle("W2Open.Common")] 9 | [assembly: AssemblyDescription("")] 10 | [assembly: AssemblyConfiguration("")] 11 | [assembly: AssemblyCompany("")] 12 | [assembly: AssemblyProduct("W2Open.Common")] 13 | [assembly: AssemblyCopyright("Copyright © 2016")] 14 | [assembly: AssemblyTrademark("")] 15 | [assembly: AssemblyCulture("")] 16 | 17 | // Setting ComVisible to false makes the types in this assembly not visible 18 | // to COM components. If you need to access a type in this assembly from 19 | // COM, set the ComVisible attribute to true on that type. 20 | [assembly: ComVisible(false)] 21 | 22 | // The following GUID is for the ID of the typelib if this project is exposed to COM 23 | [assembly: Guid("9e37305b-badd-49e4-842a-fc45b8ce0b95")] 24 | 25 | // Version information for an assembly consists of the following four values: 26 | // 27 | // Major Version 28 | // Minor Version 29 | // Build Number 30 | // Revision 31 | // 32 | // You can specify all the values or you can default the Build and Revision Numbers 33 | // by using the '*' as shown below: 34 | // [assembly: AssemblyVersion("1.0.*")] 35 | [assembly: AssemblyVersion("1.0.0.0")] 36 | [assembly: AssemblyFileVersion("1.0.0.0")] 37 | -------------------------------------------------------------------------------- /W2Open.Common/Utility/CCompoundBuffer.cs: -------------------------------------------------------------------------------- 1 | namespace W2Open.Common.Utility 2 | { 3 | /// 4 | /// The implementation of a compounded raw byte buffer. 5 | /// This object encapsulates the process of reading and writing to a byte buffer when this activity is will be done many times. 6 | /// After instantiating a CCoumpoundBuffer, you read or write in the byte buffer via the Read/Write methods. 7 | /// 8 | public class CCompoundBuffer 9 | { 10 | /// 11 | /// The raw packet buffer. 12 | /// 13 | public byte[] RawBuffer { get; set; } 14 | 15 | /// 16 | /// This variable must be called only in his property! 17 | /// 18 | private int m_Offset; 19 | /// 20 | /// The actual offset to the valid data in the buffer. 21 | /// 22 | public int Offset 23 | { 24 | get { return m_Offset; } 25 | 26 | set 27 | { 28 | if (value < 0) 29 | m_Offset = 0; 30 | else if (value >= RawBuffer.Length) 31 | m_Offset = RawBuffer.Length - 1; 32 | else 33 | m_Offset = value; 34 | } 35 | } 36 | 37 | public CCompoundBuffer(int bufferLength, int initialOffset = 0) 38 | { 39 | RawBuffer = new byte[bufferLength]; 40 | Offset = initialOffset; 41 | } 42 | 43 | public unsafe short ReadNextShort(int adtOffset = 0) 44 | { 45 | fixed (byte* b = RawBuffer) 46 | { 47 | return *(short*)&b[(Offset + adtOffset).Clamp(0, RawBuffer.Length)]; 48 | } 49 | } 50 | 51 | public ushort ReadNextUShort(int adtOffset = 0) 52 | { 53 | return (ushort)ReadNextShort(adtOffset); 54 | } 55 | 56 | public unsafe int ReadNextInt(int adtOffset = 0) 57 | { 58 | fixed (byte* b = RawBuffer) 59 | { 60 | return *(int*)&b[(Offset + adtOffset).Clamp(0, RawBuffer.Length)]; 61 | } 62 | } 63 | } 64 | 65 | 66 | 67 | } -------------------------------------------------------------------------------- /W2Open.Common/Utility/ConfigServer.cs: -------------------------------------------------------------------------------- 1 | using Newtonsoft.Json; 2 | using System; 3 | using System.Collections.Generic; 4 | using System.IO; 5 | using System.Linq; 6 | using System.Text; 7 | using System.Threading.Tasks; 8 | using W2Open.Common.GameStructure; 9 | 10 | namespace W2Open.Common.Utility 11 | { 12 | //"Server=localhost;Database=w2pp;Uid=root;Pwd=;" 13 | public class ConfigServer 14 | { 15 | public string ServerName; 16 | public string IPAddrs; 17 | public int Port; 18 | public string MYSQL_Server; 19 | public string MYSQL_DataBase; 20 | public string MYSQL_User; 21 | public string MYSQL_Pass; 22 | public int[,] ChargedGuildList; 23 | public int Sapphire; 24 | public int LastCapsule; 25 | public int ItemCount; 26 | 27 | 28 | public ConfigServer() 29 | { 30 | ServerName = "WYD"; 31 | IPAddrs = "25.19.43.5"; 32 | Port = 7514; 33 | MYSQL_Server = "localhost"; 34 | MYSQL_DataBase = "w2pp"; 35 | MYSQL_User = "root"; 36 | MYSQL_Pass = ""; 37 | ChargedGuildList = new int[BaseDef.MAX_CHANNEL, BaseDef.MAX_GUILDZONE]; 38 | Sapphire = 8; 39 | LastCapsule = 1; 40 | ItemCount = 0; 41 | } 42 | 43 | public static void ReadConfigFile(ConfigServer Config) 44 | { 45 | if (!File.Exists("config.json")) 46 | { 47 | Config = new ConfigServer(); 48 | 49 | 50 | using (StreamWriter file = File.CreateText("config.json")) 51 | { 52 | string indented = JsonConvert.SerializeObject(Config, Formatting.Indented); 53 | file.Write(indented); 54 | } 55 | } 56 | using (StreamReader r = new StreamReader("config.json")) 57 | { 58 | string json = r.ReadToEnd(); 59 | Config = JsonConvert.DeserializeObject(json); 60 | } 61 | } 62 | 63 | 64 | 65 | 66 | 67 | public static void saveConfig(ConfigServer Config) 68 | { 69 | try 70 | { 71 | using (StreamWriter file = File.CreateText("config.json")) 72 | { 73 | string indented = JsonConvert.SerializeObject(Config, Formatting.Indented); 74 | file.Write(indented); 75 | } 76 | } 77 | catch (Exception e) 78 | { 79 | W2Log.Write("Erro ao salvar config.json " + e.Message); 80 | return; 81 | } 82 | } 83 | 84 | 85 | 86 | 87 | 88 | 89 | 90 | 91 | 92 | 93 | 94 | 95 | 96 | 97 | 98 | } 99 | } 100 | -------------------------------------------------------------------------------- /W2Open.Common/Utility/W2GenericExtensionMethods.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace W2Open.Common.Utility 4 | { 5 | /// 6 | /// Extension methods to generic types. 7 | /// 8 | public static class W2GenericExtensionMethods 9 | { 10 | public static T Clamp(this T val, T min, T max) where T : IComparable 11 | { 12 | if (val.CompareTo(min) < 0) 13 | return min; 14 | else if (val.CompareTo(max) > 0) 15 | return max; 16 | else 17 | return val; 18 | } 19 | } 20 | } -------------------------------------------------------------------------------- /W2Open.Common/Utility/W2Log.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace W2Open.Common.Utility 4 | { 5 | public enum ELogType 6 | { 7 | CRITICAL_ERROR = 0, 8 | /// 9 | /// Represents a game event related log. 10 | /// 11 | GAME_EVENT, 12 | /// 13 | /// Represents a network related log. 14 | /// 15 | NETWORK, 16 | 17 | UPDATE_EVENT, 18 | SHOW_ONLY, 19 | } 20 | 21 | /// 22 | /// Responsible for all kind of work related to logging events. 23 | /// Events: 24 | /// 25 | /// 26 | public static class W2Log 27 | { 28 | /// 29 | /// Fired when someone writes any log. 30 | /// 31 | public static event Action DidLog; 32 | 33 | /// 34 | /// Logs a text. 35 | /// 36 | /// Text to be logged 37 | /// Type of the log. 38 | public static void Write(String txt, ELogType logType) 39 | { 40 | // TODO: log the text in the hard disk file. 41 | 42 | DidLog?.Invoke(txt, logType); 43 | } 44 | 45 | public static void Write(string v) 46 | { 47 | Write(v, ELogType.GAME_EVENT); 48 | } 49 | public static void Show(string v) 50 | { 51 | Write(v, ELogType.SHOW_ONLY); 52 | } 53 | public static void SendUpdate() 54 | { 55 | Write("", ELogType.UPDATE_EVENT); 56 | } 57 | } 58 | } -------------------------------------------------------------------------------- /W2Open.Common/Utility/W2Marshal.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Reflection.Emit; 3 | using System.Runtime.InteropServices; 4 | using W2Open.Common.GameStructure; 5 | 6 | namespace W2Open.Common.Utility 7 | { 8 | /// 9 | /// A wrapper encapsulating some core methods used to marshals raw data buffers into structures. 10 | /// 11 | public static class W2Marshal 12 | { 13 | 14 | [DllImport("msvcrt.dll", EntryPoint = "memset", CallingConvention = CallingConvention.Cdecl, SetLastError = false)] 15 | public static extern IntPtr Memset(IntPtr dest, int c, int count); 16 | /// 17 | /// Marshals a raw buffer to a given marshalable struct. 18 | /// 19 | /// 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | public static unsafe T GetStructure(byte[] buffer, int offset = 0) where T : struct 28 | { 29 | fixed (byte* bufferPin = &buffer[offset]) 30 | { 31 | return GetStructure(bufferPin); 32 | } 33 | } 34 | 35 | public static unsafe T GetStructure(CCompoundBuffer buffer) where T : struct 36 | { 37 | return GetStructure(buffer.RawBuffer, buffer.Offset); 38 | } 39 | 40 | public static unsafe T GetStructure(byte* buffer) where T : struct 41 | { 42 | return (T)Marshal.PtrToStructure(new IntPtr(buffer), typeof(T)); 43 | } 44 | 45 | /// 46 | /// Marshals a given T instance into a raw buffer. 47 | /// 48 | public static unsafe byte[] GetBytes(T obj) where T : struct 49 | { 50 | byte[] rawBuffer = new byte[Marshal.SizeOf(obj)]; 51 | 52 | fixed (byte* rawBufferPin = rawBuffer) 53 | { 54 | Marshal.StructureToPtr(obj, new IntPtr(rawBufferPin), false); 55 | } 56 | 57 | return rawBuffer; 58 | } 59 | public static bool IsNull(this T source) where T : struct 60 | { 61 | return source.Equals(default(T)); 62 | } 63 | /// 64 | /// Crates a read-to-use marshaled instance of T 65 | /// 66 | /// Type to be marshaled as zero-initialized instance. 67 | /// A zero-initialized instance of T. 68 | public static unsafe T CreateEmpty() where T : struct 69 | { 70 | int typeSize = Marshal.SizeOf(typeof(T)); 71 | 72 | byte* rawBuffer = stackalloc byte[typeSize]; 73 | 74 | for (int i = 0; i < typeSize; i++) 75 | rawBuffer[i] = 0; 76 | 77 | T zeroInited = (T)Marshal.PtrToStructure(new IntPtr(rawBuffer), typeof(T)); 78 | 79 | return zeroInited; 80 | } 81 | 82 | /// 83 | /// Creates a empty ready-to-use copy of a given implementation of DBSRVPackets. 84 | /// 85 | public static T CreatePacket(ushort opcode) where T : struct, DBSRVPackets 86 | { 87 | MSG_HEADER validHeader = new MSG_HEADER(); 88 | T packet = W2Marshal.CreateEmpty(); 89 | 90 | // Set the default values to the packet header. 91 | validHeader.Size = (ushort)Marshal.SizeOf(packet); 92 | validHeader.PacketID = opcode; 93 | validHeader.Key = (byte)W2Random.Instance.Next(127); 94 | validHeader.TimeStamp = (uint)Environment.TickCount; 95 | 96 | packet.Header = validHeader; 97 | 98 | return packet; 99 | } 100 | public static T CreatePacket(ushort opcode,ushort id) where T : struct, DBSRVPackets 101 | { 102 | MSG_HEADER validHeader = new MSG_HEADER(); 103 | T packet = W2Marshal.CreateEmpty(); 104 | 105 | // Set the default values to the packet header. 106 | validHeader.Size = (ushort)Marshal.SizeOf(packet); 107 | validHeader.PacketID = opcode; 108 | validHeader.ClientId = id; 109 | validHeader.Key = (byte)W2Random.Instance.Next(127); 110 | validHeader.TimeStamp = (uint)Environment.TickCount; 111 | 112 | packet.Header = validHeader; 113 | 114 | return packet; 115 | } 116 | 117 | public static D ReinterpretCast(S SPacket) where D : struct, DBSRVPackets 118 | { 119 | byte[] rawBuffer = new byte[Marshal.SizeOf(SPacket)]; 120 | unsafe 121 | { 122 | fixed (byte* rawBufferPin = rawBuffer) 123 | { 124 | Marshal.StructureToPtr(SPacket, new IntPtr(rawBufferPin), false); 125 | } 126 | } 127 | D sm = GetStructure(rawBuffer); 128 | return sm; 129 | } 130 | 131 | 132 | 133 | 134 | public static T memset(T Struct) where T : struct 135 | { 136 | byte[] rawData = W2Marshal.GetBytes(Struct); 137 | GCHandle gch = GCHandle.Alloc(rawData, GCHandleType.Pinned); 138 | Memset(gch.AddrOfPinnedObject(), 0, rawData.Length); 139 | var pinnedRawData = GCHandle.Alloc(rawData, GCHandleType.Pinned); 140 | try 141 | { 142 | var pinnedRawDataPtr = pinnedRawData.AddrOfPinnedObject(); 143 | return (T)Marshal.PtrToStructure(pinnedRawDataPtr, typeof(T)); 144 | } 145 | finally 146 | { 147 | pinnedRawData.Free(); 148 | } 149 | } 150 | } 151 | } -------------------------------------------------------------------------------- /W2Open.Common/Utility/W2Random.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace W2Open.Common.Utility 4 | { 5 | /// 6 | /// Encapsulates a singleton System.Random class implementation. 7 | /// 8 | public class W2Random : Random 9 | { 10 | private static W2Random m_Instance; 11 | 12 | public static W2Random Instance 13 | { 14 | get 15 | { 16 | if (m_Instance == null) 17 | m_Instance = new W2Random(); 18 | 19 | return m_Instance; 20 | } 21 | } 22 | 23 | private W2Random() { } 24 | } 25 | } -------------------------------------------------------------------------------- /W2Open.Common/W2Open.Common.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | Debug 6 | AnyCPU 7 | {9E37305B-BADD-49E4-842A-FC45B8CE0B95} 8 | Library 9 | Properties 10 | W2Open.Common 11 | W2Open.Common 12 | v4.6.1 13 | 512 14 | 15 | 16 | 17 | true 18 | full 19 | false 20 | ..\..\..\..\..\..\..\Servidor WYD2\Release\DBSRV\run\ 21 | DEBUG;TRACE 22 | prompt 23 | 4 24 | true 25 | 7.3 26 | 27 | 28 | pdbonly 29 | true 30 | ..\..\W2Open Server\ 31 | TRACE 32 | prompt 33 | 4 34 | true 35 | 7.3 36 | 37 | 38 | 39 | ..\packages\Google.Protobuf.3.5.1\lib\net45\Google.Protobuf.dll 40 | 41 | 42 | ..\packages\MySql.Data.8.0.11\lib\net452\MySql.Data.dll 43 | 44 | 45 | ..\packages\Newtonsoft.Json.11.0.2\lib\net45\Newtonsoft.Json.dll 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | 77 | 78 | 79 | 80 | 81 | 82 | 83 | 84 | 85 | 86 | 93 | -------------------------------------------------------------------------------- /W2Open.Common/packages.config: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /W2Open.DataServer/PersistencyBasics.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace W2Open.DataServer 4 | { 5 | internal static class PersistencyBasics 6 | { 7 | internal const String DB_ROOT_PATH = "./DataBase"; 8 | } 9 | } -------------------------------------------------------------------------------- /W2Open.DataServer/Properties/AssemblyInfo.cs: -------------------------------------------------------------------------------- 1 | using System.Reflection; 2 | using System.Runtime.CompilerServices; 3 | using System.Runtime.InteropServices; 4 | 5 | // General Information about an assembly is controlled through the following 6 | // set of attributes. Change these attribute values to modify the information 7 | // associated with an assembly. 8 | [assembly: AssemblyTitle("W2Open.DataServer")] 9 | [assembly: AssemblyDescription("")] 10 | [assembly: AssemblyConfiguration("")] 11 | [assembly: AssemblyCompany("")] 12 | [assembly: AssemblyProduct("W2Open.DataServer")] 13 | [assembly: AssemblyCopyright("Copyright © 2016")] 14 | [assembly: AssemblyTrademark("")] 15 | [assembly: AssemblyCulture("")] 16 | 17 | // Setting ComVisible to false makes the types in this assembly not visible 18 | // to COM components. If you need to access a type in this assembly from 19 | // COM, set the ComVisible attribute to true on that type. 20 | [assembly: ComVisible(false)] 21 | 22 | // The following GUID is for the ID of the typelib if this project is exposed to COM 23 | [assembly: Guid("5ca9998d-9362-417a-89fd-c7603c59bb46")] 24 | 25 | // Version information for an assembly consists of the following four values: 26 | // 27 | // Major Version 28 | // Minor Version 29 | // Build Number 30 | // Revision 31 | // 32 | // You can specify all the values or you can default the Build and Revision Numbers 33 | // by using the '*' as shown below: 34 | // [assembly: AssemblyVersion("1.0.*")] 35 | [assembly: AssemblyVersion("1.0.0.0")] 36 | [assembly: AssemblyFileVersion("1.0.0.0")] 37 | -------------------------------------------------------------------------------- /W2Open.DataServer/W2Open.DataServer.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | Debug 6 | AnyCPU 7 | {5CA9998D-9362-417A-89FD-C7603C59BB46} 8 | Library 9 | Properties 10 | W2Open.DataServer 11 | W2Open.DataServer 12 | v4.6.1 13 | 512 14 | 15 | 16 | 17 | true 18 | full 19 | false 20 | ..\..\..\..\..\..\..\Servidor WYD2\Release\DBSRV\run\ 21 | DEBUG;TRACE 22 | prompt 23 | 4 24 | true 25 | 26 | 27 | pdbonly 28 | true 29 | ..\..\W2Open Server\ 30 | TRACE 31 | prompt 32 | 4 33 | true 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | {9e37305b-badd-49e4-842a-fc45b8ce0b95} 52 | W2Open.Common 53 | 54 | 55 | 56 | 63 | -------------------------------------------------------------------------------- /W2Open.GameState.Plugin/DefaultPlayerRequestHandler/ProcessClientMessage.cs: -------------------------------------------------------------------------------- 1 | using System.Threading.Tasks; 2 | using W2Open.Common; 3 | using W2Open.Common.GameStructure; 4 | using W2Open.Common.Utility; 5 | using W2Open.GameState.Plugin.DefaultPlayerRequestHandler.PacketControl; 6 | 7 | 8 | namespace W2Open.GameState.Plugin.DefaultPlayerRequestHandler 9 | { 10 | public class ProcessClientMessage : IGameStatePlugin 11 | { 12 | public void Install() 13 | { 14 | DBController.OnProcessPacket += ProcessPacketControl; 15 | } 16 | 17 | private DBResult ProcessPacketControl(DBController gs, pServer GameServer) 18 | { 19 | 20 | MSG_HEADER packet = W2Marshal.GetStructure(GameServer.RecvPacket.RawBuffer); 21 | 22 | 23 | if (0 == (packet.PacketID & BaseDef.FLAG_GAME2DB) || (packet.ClientId < 0) || (packet.ClientId >= 1000)) 24 | { 25 | 26 | W2Log.Write($"err,ProcessDBMessage packet Type:({packet.PacketID}) ID:{packet.ClientId} Size:{packet.Size}"); 27 | return DBResult.PACKET_NOT_HANDLED; 28 | } 29 | 30 | 31 | 32 | switch (packet.PacketID) 33 | { 34 | 35 | case BaseDef._MSG_GuildInfo: 36 | return Packet.Exec_MSG_GuildInfo(gs, GameServer); 37 | 38 | case BaseDef._MSG_War: 39 | return Packet.Exec_MSG_War(gs, GameServer); 40 | 41 | case BaseDef._MSG_GuildAlly: 42 | return Packet.Exec_MSG_GuildAlly(gs, GameServer); 43 | 44 | case _MSG_GuildZoneReport.PacketID: 45 | return Packet.Exec_MSG_GuildZoneReport(gs, GameServer); 46 | 47 | case BaseDef._MSG_DBAccountLogin: 48 | return Packet.Exec_MSG_DBAccountLogin(gs, GameServer); 49 | 50 | case _MSG_DBCharacterLogin2.Opcode: 51 | return Packet.Exec_MSG_DBCharacterLogin2(gs, GameServer); 52 | 53 | case BaseDef._MSG_DBSaveMob: 54 | return Packet.Exec_MSG_DBSaveMob(gs, GameServer); 55 | 56 | case BaseDef._MSG_SavingQuit: 57 | return Packet.Exec_MSG_SavingQuit(gs, GameServer); 58 | 59 | case BaseDef._MSG_DBSendItem: 60 | return Packet.Exec_MSG_DBSendItem(gs, GameServer); 61 | 62 | case BaseDef._MSG_DBCreateCharacter: 63 | return Packet.Exec_MSG_DBCreateCharacter(gs, GameServer); 64 | 65 | case BaseDef._MSG_DBDeleteCharacter: 66 | return Packet.Exec_MSG_DBCNFDeleteCharacter(gs, GameServer); 67 | 68 | case BaseDef._MSG_DBNoNeedSave: 69 | return Packet.Exec_MSG_DBNoNeedSave(gs, GameServer); 70 | 71 | case BaseDef._MSG_DBUpdateSapphire: 72 | return Packet.Exec_MSG_DBUpdateSapphire(gs, GameServer); 73 | 74 | case BaseDef._MSG_MessageDBRecord: 75 | return Packet.Exec_MSG_MessageDBRecord(gs, GameServer); 76 | 77 | case BaseDef._MSG_DBCreateArchCharacter: 78 | return Packet.Exec_MSG_DBCreateArchCharacter(gs, GameServer); 79 | 80 | case BaseDef._MSG_DBCapsuleInfo: 81 | return Packet.Exec_MSG_DBCapsuleInfo(gs, GameServer); 82 | 83 | case BaseDef._MSG_DBPutInCapsule: 84 | return Packet.Exec_MSG_DBPutInCapsule(gs, GameServer); 85 | 86 | case BaseDef._MSG_DBOutCapsule: 87 | return Packet.Exec_MSG_DBOutCapsule(gs, GameServer); 88 | 89 | case BaseDef._MSG_DBItemDayLog: 90 | return Packet.Exec_MSG_DBItemDayLog(gs, GameServer); 91 | 92 | 93 | default: return DBResult.PACKET_NOT_HANDLED; 94 | } 95 | } 96 | private async Task seTimerPacketControl(DBController gs, pServer GameServer) 97 | { 98 | 99 | while (true) 100 | { 101 | ProcessPacketControl(gs, GameServer); 102 | 103 | await Task.Delay(500); 104 | } 105 | } 106 | } 107 | } -------------------------------------------------------------------------------- /W2Open.GameState.Plugin/IGameStatePlugin.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Threading.Tasks; 6 | 7 | namespace W2Open.GameState.Plugin 8 | { 9 | public interface IGameStatePlugin 10 | { 11 | void Install(); 12 | } 13 | } -------------------------------------------------------------------------------- /W2Open.GameState.Plugin/PluginController.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Reflection; 5 | using W2Open.GameState.Plugin.DefaultPlayerRequestHandler; 6 | 7 | 8 | namespace W2Open.GameState.Plugin 9 | { 10 | public static class PluginController 11 | { 12 | public static List ActivatedPlugins; 13 | 14 | static PluginController() 15 | { 16 | ActivatedPlugins = new List(); 17 | } 18 | 19 | /// 20 | /// Automatically iterate in all created plugins and call their Install method. 21 | /// 22 | public static void InstallPlugins() 23 | { 24 | String pluginInterfaceName = typeof(IGameStatePlugin).Name; 25 | 26 | IEnumerable pluginTypes = Assembly.GetExecutingAssembly().GetTypes().Where(t => typeof(IGameStatePlugin).IsAssignableFrom(t) && t.Name != pluginInterfaceName); 27 | 28 | Queue defaultPlugins = new Queue(); 29 | Queue otherPlugins = new Queue(); 30 | 31 | String defaultPlayerRequestPluginNS = typeof(ProcessClientMessage).Namespace; 32 | 33 | 34 | // Read all types in this assembly and enqueue them into default or other plugin queues. 35 | foreach (Type thisPlugin in pluginTypes) 36 | { 37 | IGameStatePlugin pluginObj = (IGameStatePlugin)Activator.CreateInstance(thisPlugin); 38 | 39 | if (pluginObj == null) 40 | continue; 41 | 42 | if (thisPlugin.Namespace == defaultPlayerRequestPluginNS) 43 | { 44 | defaultPlugins.Enqueue(pluginObj); 45 | } 46 | else 47 | { 48 | otherPlugins.Enqueue(pluginObj); 49 | } 50 | } 51 | 52 | // Install the default plugins firstly. 53 | foreach (IGameStatePlugin thisPlugin in defaultPlugins) 54 | { 55 | thisPlugin.Install(); 56 | ActivatedPlugins.Add(thisPlugin); 57 | } 58 | 59 | // Then install the other plugins. 60 | foreach (IGameStatePlugin thisPlugin in otherPlugins) 61 | { 62 | thisPlugin.Install(); 63 | ActivatedPlugins.Add(thisPlugin); 64 | } 65 | } 66 | } 67 | } -------------------------------------------------------------------------------- /W2Open.GameState.Plugin/Properties/AssemblyInfo.cs: -------------------------------------------------------------------------------- 1 | using System.Reflection; 2 | using System.Runtime.CompilerServices; 3 | using System.Runtime.InteropServices; 4 | 5 | // General Information about an assembly is controlled through the following 6 | // set of attributes. Change these attribute values to modify the information 7 | // associated with an assembly. 8 | [assembly: AssemblyTitle("W2Open.GameState.Plugin")] 9 | [assembly: AssemblyDescription("")] 10 | [assembly: AssemblyConfiguration("")] 11 | [assembly: AssemblyCompany("")] 12 | [assembly: AssemblyProduct("W2Open.GameState.Plugin")] 13 | [assembly: AssemblyCopyright("Copyright © 2016")] 14 | [assembly: AssemblyTrademark("")] 15 | [assembly: AssemblyCulture("")] 16 | 17 | // Setting ComVisible to false makes the types in this assembly not visible 18 | // to COM components. If you need to access a type in this assembly from 19 | // COM, set the ComVisible attribute to true on that type. 20 | [assembly: ComVisible(false)] 21 | 22 | // The following GUID is for the ID of the typelib if this project is exposed to COM 23 | [assembly: Guid("756c8536-c282-47f2-843f-c3334b5f619d")] 24 | 25 | // Version information for an assembly consists of the following four values: 26 | // 27 | // Major Version 28 | // Minor Version 29 | // Build Number 30 | // Revision 31 | // 32 | // You can specify all the values or you can default the Build and Revision Numbers 33 | // by using the '*' as shown below: 34 | // [assembly: AssemblyVersion("1.0.*")] 35 | [assembly: AssemblyVersion("1.0.0.0")] 36 | [assembly: AssemblyFileVersion("1.0.0.0")] 37 | -------------------------------------------------------------------------------- /W2Open.GameState.Plugin/W2Open.GameState.Plugin.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | Debug 6 | AnyCPU 7 | {756C8536-C282-47F2-843F-C3334B5F619D} 8 | Library 9 | Properties 10 | W2Open.GameState.Plugin 11 | W2Open.GameState.Plugin 12 | v4.6.1 13 | 512 14 | 15 | 16 | 17 | true 18 | full 19 | false 20 | ..\..\..\..\..\..\..\Servidor WYD2\Release\DBSRV\run\ 21 | DEBUG;TRACE 22 | prompt 23 | 4 24 | true 25 | latest 26 | 27 | 28 | pdbonly 29 | true 30 | ..\..\W2Open Server\ 31 | TRACE 32 | prompt 33 | 4 34 | true 35 | latest 36 | 37 | 38 | 39 | ..\packages\Newtonsoft.Json.11.0.2\lib\net45\Newtonsoft.Json.dll 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | {9e37305b-badd-49e4-842a-fc45b8ce0b95} 61 | W2Open.Common 62 | 63 | 64 | {5ca9998d-9362-417a-89fd-c7603c59bb46} 65 | W2Open.DataServer 66 | 67 | 68 | {7f6663c7-a2bf-4637-b018-70cfe7c39dc4} 69 | W2Open.GameState 70 | 71 | 72 | 73 | 74 | 75 | 76 | 77 | 78 | 79 | 86 | -------------------------------------------------------------------------------- /W2Open.GameState.Plugin/packages.config: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | -------------------------------------------------------------------------------- /W2Open.GameState/ERequestResult.cs: -------------------------------------------------------------------------------- 1 | namespace W2Open.GameState 2 | { 3 | public enum DBResult 4 | { 5 | NO_ERROR, 6 | CHECKSUM_FAIL, 7 | PACKET_NOT_HANDLED, 8 | /// 9 | /// This error is caused when the GameServer's state is not the right to receive the given packet. 10 | /// This is CRITICAL and should result in a forced disconnection. 11 | /// 12 | PLAYER_INCONSISTENT_STATE, 13 | /// 14 | /// Some unknown error occour. Treat this as a CRITICAL error! The best approach is disconnect the GameServer. 15 | /// 16 | UNKNOWN, 17 | 18 | SUCCESS, 19 | 20 | WAIT, 21 | } 22 | } -------------------------------------------------------------------------------- /W2Open.GameState/ProcessSecTimer/ProcessImportItem.cs: -------------------------------------------------------------------------------- 1 | using Newtonsoft.Json; 2 | using System; 3 | using System.Collections.Generic; 4 | using System.IO; 5 | using System.Linq; 6 | using System.Text; 7 | using System.Threading.Tasks; 8 | using W2Open.Common; 9 | using W2Open.Common.GameStructure; 10 | using W2Open.Common.Utility; 11 | 12 | namespace W2Open.GameState.ProcessSecTimer 13 | { 14 | public class ProcessImportItem 15 | { 16 | 17 | public static int getEmptyCargo(STRUCT_ACCOUNTFILE Account) 18 | { 19 | for (int i = 0; i < 120; i++) 20 | { 21 | 22 | if (Account.Cargo.Items[i].Index == 0) 23 | return i; 24 | } 25 | return -1; 26 | } 27 | 28 | 29 | static public void Start(DBController gs) 30 | { 31 | 32 | foreach (string file in Directory.EnumerateFiles("./npc/")) 33 | { 34 | using (StreamReader sr = new StreamReader(file)) 35 | { 36 | 37 | try 38 | { 39 | STRUCT_MOB CurrentMob = Functions.ReadAccount(file); 40 | string indented = JsonConvert.SerializeObject(CurrentMob, Formatting.Indented); 41 | 42 | int update = gs.MySQL.nQuery(string.Format("INSERT INTO `mobs_json` (`nome`, `conteudo`) VALUES ('{0}', '{1}') ON DUPLICATE KEY UPDATE `nome` = '{2}' ",CurrentMob.Name, indented, CurrentMob.Name)); 43 | if (update != 0) 44 | W2Log.Write(string.Format("Sucess update drops: {0}", file)); 45 | 46 | 47 | } 48 | catch (Exception e) 49 | { 50 | return; 51 | } 52 | } 53 | } 54 | } 55 | 56 | 57 | 58 | 59 | } 60 | } 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | //static public void Start(DBController gs) 77 | //{ 78 | // bool Importend = false; 79 | 80 | // foreach (string file in Directory.EnumerateFiles("./DataBase/ImportInfo/", "*.item")) 81 | // { 82 | // using (StreamReader sr = new StreamReader(file)) 83 | // { 84 | // string line; 85 | // while ((line = sr.ReadLine()) != null) 86 | // { 87 | // //*%d %s %d %d %d %d %d %d %d ", &id_pedido, accountname, &Index, &Eff1, &Val1, &Eff2, &Val2, &Eff3, &Val3) 88 | // string[] data = line.Split(' '); 89 | 90 | 91 | // int Idx = gs.GetIndex(data[1]); 92 | // // W2Log.Write(String.Format($"Data: {data[1]} AccountIDX: {gs.AccountList[Idx].Account.Info.AccountName} IDX: {Idx}"), ELogType.CRITICAL_ERROR); 93 | // if (gs.AccountList[Idx].State != EServerStatus.INGAME) 94 | // return; 95 | 96 | // int IdPedido = int.Parse(data[0].Replace('*', ' ')); 97 | // if (Idx != 0) 98 | // { 99 | // int EmptyCargo = gs.AccountList[Idx].Account.getEmptyCargo(); 100 | // if (EmptyCargo == -1) 101 | // { 102 | // W2Log.Write(String.Format($"can't importitem: {data[1]} no empty slot"), ELogType.CRITICAL_ERROR); 103 | // return; 104 | // } 105 | 106 | // short itemID = short.Parse(data[2]); 107 | // if (itemID < 1 || itemID >= BaseDef.MAX_ITEMLIST) 108 | // { 109 | // if (EmptyCargo == -1) 110 | // { 111 | // W2Log.Write(String.Format($"can't importitem: {data[1]} no valid item index"), ELogType.CRITICAL_ERROR); 112 | // return; 113 | // } 114 | // } 115 | 116 | 117 | 118 | // if (Idx > 0 && Idx < BaseDef.MAX_MAXUSER && gs.AccountList[Idx].Slot >= 0 && gs.AccountList[Idx].Slot <= 3 && IdPedido != 0) 119 | // { 120 | 121 | // gs.AccountList[Idx].Account.Cargo.Items[EmptyCargo].Index = itemID; 122 | // gs.AccountList[Idx].Account.Cargo.Items[EmptyCargo].Effects[0].Code = byte.Parse(data[3]); 123 | // gs.AccountList[Idx].Account.Cargo.Items[EmptyCargo].Effects[0].Value = byte.Parse(data[4]); 124 | // gs.AccountList[Idx].Account.Cargo.Items[EmptyCargo].Effects[1].Code = byte.Parse(data[5]); 125 | // gs.AccountList[Idx].Account.Cargo.Items[EmptyCargo].Effects[1].Value = byte.Parse(data[6]); 126 | // gs.AccountList[Idx].Account.Cargo.Items[EmptyCargo].Effects[2].Code = byte.Parse(data[7]); 127 | // gs.AccountList[Idx].Account.Cargo.Items[EmptyCargo].Effects[2].Value = byte.Parse(data[8]); 128 | 129 | // MSG_DBSendItem sm = W2Marshal.CreatePacket(BaseDef._MSG_DBSendItem, (ushort)Idx); 130 | 131 | // sm.id_pedido = IdPedido; 132 | // sm.Account = gs.AccountList[Idx].Account.Info.AccountName; 133 | // sm.Items = gs.AccountList[Idx].Account.Cargo.Items[EmptyCargo]; 134 | // gs.Server.SendPacket(sm); 135 | // Importend = true; 136 | // W2Log.Write(String.Format($"importitem: {data[2]},{data[3]},{data[4]},{data[5]},{data[6]},{data[7]},{data[8]} to {data[1]} slot {EmptyCargo}"), ELogType.CRITICAL_ERROR); 137 | // } 138 | // else 139 | // Importend = false; 140 | // } 141 | // } 142 | // if (Importend) 143 | // { 144 | // sr.Close(); 145 | // File.Delete(file); 146 | // Importend = false; 147 | // return; 148 | // } 149 | // } 150 | // } 151 | //} 152 | -------------------------------------------------------------------------------- /W2Open.GameState/ProcessSecTimer/ProcessImportUser.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.IO; 4 | using System.Linq; 5 | using System.Text; 6 | using System.Threading.Tasks; 7 | using W2Open.Common.GameStructure; 8 | using W2Open.Common.Utility; 9 | 10 | namespace W2Open.GameState.ProcessSecTimer 11 | { 12 | public class ProcessImportUser 13 | { 14 | 15 | 16 | 17 | 18 | 19 | static public void Start( ) 20 | { 21 | bool Importend = false; 22 | 23 | foreach (string file in Directory.EnumerateFiles("./DataBase/ImportInfo/", "*.user")) 24 | { 25 | using (StreamReader sr = new StreamReader(file)) 26 | { 27 | string line; 28 | int countLine = 0; 29 | string Login = string.Empty, Senha = string.Empty, Nome = string.Empty, Email = string.Empty, IP = string.Empty; 30 | while ((line = sr.ReadLine()) != null) 31 | { 32 | line.Trim().Trim(' '); 33 | 34 | if (countLine == 0) 35 | Login = line; 36 | if (countLine == 1) 37 | Senha = line; 38 | if (countLine == 2) 39 | Nome = line; 40 | if (countLine == 3) 41 | Email = line; 42 | if (countLine == 4) 43 | IP = line; 44 | countLine++; 45 | } 46 | if (!string.IsNullOrEmpty(Login) && !string.IsNullOrEmpty(Senha) && !string.IsNullOrEmpty(Nome) && !string.IsNullOrEmpty(Email) && !string.IsNullOrEmpty(IP)) 47 | { 48 | if(!File.Exists(Functions.getCorrectPath(Login) + ".json")) 49 | Importend = Functions.CreateEmptyAccount(Login, Senha, IP, Email, Nome); 50 | } 51 | if (Importend) 52 | { 53 | sr.Close(); 54 | File.Delete(file); 55 | Importend = false; 56 | W2Log.Write(String.Format($"sucess import user: {Login} - {Email}"), ELogType.CRITICAL_ERROR); 57 | return; 58 | } 59 | else 60 | W2Log.Write(String.Format($"can't import user: {Login}"), ELogType.CRITICAL_ERROR); 61 | } 62 | } 63 | } 64 | } 65 | } 66 | -------------------------------------------------------------------------------- /W2Open.GameState/ProcessSecTimer/ProcessUpdateUser.cs: -------------------------------------------------------------------------------- 1 | using Newtonsoft.Json; 2 | using System; 3 | using System.Collections.Generic; 4 | using System.IO; 5 | using System.Linq; 6 | using System.Text; 7 | using System.Threading.Tasks; 8 | using W2Open.Common.GameStructure; 9 | using W2Open.Common.Utility; 10 | 11 | namespace W2Open.GameState.ProcessSecTimer 12 | { 13 | public class ProcessUpdateUser 14 | { 15 | 16 | static public bool UpdateUser(DBController gs, string Login, string Senha) 17 | { 18 | 19 | STRUCT_ACCOUNTFILE target = new STRUCT_ACCOUNTFILE(); 20 | 21 | if (!gs.ReadAccount(Login, out target)) 22 | { 23 | W2Log.Write(String.Format("fail to read account file {0}", Login), ELogType.GAME_EVENT); 24 | return false; 25 | } 26 | 27 | if (0 != String.Compare(target.Info.AccountName, Login)) 28 | { 29 | W2Log.Write(String.Format("fail to read account file {0}/{1}", Login, target.Info.AccountName), ELogType.GAME_EVENT); 30 | return false; 31 | } 32 | // W2Log.Write(String.Format("pass teste file {0}/{1}", target.Info.AccountPass, Senha), ELogType.GAME_EVENT); 33 | target.Info.AccountPass = Senha; 34 | 35 | try 36 | { 37 | string CorrectPatch = Functions.getCorrectPath(target.Info.AccountName); 38 | using (StreamWriter file = File.CreateText(CorrectPatch + ".json")) 39 | { 40 | string indented = JsonConvert.SerializeObject(target, Formatting.Indented); 41 | file.Write(indented); 42 | } 43 | 44 | W2Log.Write(String.Format("save account sucess: {0}", target.Info.AccountName), ELogType.GAME_EVENT); 45 | return true; 46 | } 47 | catch (Exception e) 48 | { 49 | W2Log.Write(String.Format("save account fail: {0}/{1}", target.Info.AccountName, e.Message), ELogType.GAME_EVENT); 50 | return false; 51 | } 52 | } 53 | 54 | 55 | static public void Start(DBController gs) 56 | { 57 | bool Importend = false; 58 | 59 | foreach (string file in Directory.EnumerateFiles("./DataBase/ImportInfo/", "*.update")) 60 | { 61 | using (StreamReader sr = new StreamReader(file)) 62 | { 63 | string line; 64 | int countLine = 0; 65 | string Login = string.Empty, Senha = string.Empty; 66 | while ((line = sr.ReadLine()) != null) 67 | { 68 | 69 | if (countLine == 0) 70 | Login = line; 71 | if (countLine == 1) 72 | Senha = line; 73 | 74 | countLine++; 75 | if (!string.IsNullOrEmpty(Login) && !string.IsNullOrEmpty(Senha)) 76 | break; 77 | } 78 | 79 | if (File.Exists(Functions.getCorrectPath(Login) + ".json")) 80 | { 81 | STRUCT_ACCOUNTFILE target = new STRUCT_ACCOUNTFILE(); 82 | 83 | if (!gs.ReadAccount(Login, out target)) 84 | { 85 | W2Log.Write(String.Format("fail to read account file {0}", Login), ELogType.GAME_EVENT); 86 | Importend = false; 87 | } 88 | 89 | if (0 != String.Compare(target.Info.AccountName, Login)) 90 | { 91 | W2Log.Write(String.Format("fail to read account file {0}/{1}", Login, target.Info.AccountName), ELogType.GAME_EVENT); 92 | Importend = false; 93 | } 94 | // W2Log.Write(String.Format("pass teste file {0}/{1}", target.Info.AccountPass, Senha), ELogType.GAME_EVENT); 95 | target.Info.AccountPass = Senha; 96 | 97 | try 98 | { 99 | string CorrectPatch = Functions.getCorrectPath(target.Info.AccountName); 100 | using (StreamWriter pfile = File.CreateText(CorrectPatch + ".json")) 101 | { 102 | string indented = JsonConvert.SerializeObject(target, Formatting.Indented); 103 | pfile.Write(indented); 104 | } 105 | 106 | W2Log.Write(String.Format("save account sucess: {0}", target.Info.AccountName), ELogType.GAME_EVENT); 107 | Importend = true; 108 | } 109 | catch (Exception e) 110 | { 111 | W2Log.Write(String.Format("save account fail: {0}/{1}", target.Info.AccountName, e.Message), ELogType.GAME_EVENT); 112 | Importend = false; 113 | } 114 | } 115 | if (Importend) 116 | { 117 | sr.Close(); 118 | File.Delete(file); 119 | Importend = false; 120 | W2Log.Write(String.Format($"sucess update user: {Login}"), ELogType.CRITICAL_ERROR); 121 | return; 122 | } 123 | 124 | 125 | } 126 | } 127 | } 128 | } 129 | } 130 | -------------------------------------------------------------------------------- /W2Open.GameState/ProcessSecTimer/SecTimer.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using W2Open.Common; 3 | using W2Open.Common.Utility; 4 | namespace W2Open.GameState.ProcessSecTimer 5 | { 6 | public class SecTimer 7 | { 8 | public static int Sec = 1; 9 | 10 | 11 | public static void Start(DBController gs,pServer Server) 12 | { 13 | if(Sec % 15 == 0)//15 segundos 14 | { 15 | // ProcessImportItem.Start(gs); 16 | 17 | W2Log.SendUpdate(); 18 | } 19 | if (Sec % 5 == 0)//5 segundos 20 | { 21 | ProcessImportItem.Start(gs); 22 | 23 | } 24 | 25 | 26 | if (Sec++ > 1000) 27 | Sec = 0; 28 | } 29 | 30 | 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /W2Open.GameState/Properties/AssemblyInfo.cs: -------------------------------------------------------------------------------- 1 | using System.Reflection; 2 | using System.Runtime.CompilerServices; 3 | using System.Runtime.InteropServices; 4 | 5 | // General Information about an assembly is controlled through the following 6 | // set of attributes. Change these attribute values to modify the information 7 | // associated with an assembly. 8 | [assembly: AssemblyTitle("W2Open.GameState")] 9 | [assembly: AssemblyDescription("")] 10 | [assembly: AssemblyConfiguration("")] 11 | [assembly: AssemblyCompany("")] 12 | [assembly: AssemblyProduct("W2Open.GameState")] 13 | [assembly: AssemblyCopyright("Copyright © 2016")] 14 | [assembly: AssemblyTrademark("")] 15 | [assembly: AssemblyCulture("")] 16 | 17 | // Setting ComVisible to false makes the types in this assembly not visible 18 | // to COM components. If you need to access a type in this assembly from 19 | // COM, set the ComVisible attribute to true on that type. 20 | [assembly: ComVisible(false)] 21 | 22 | // The following GUID is for the ID of the typelib if this project is exposed to COM 23 | [assembly: Guid("7f6663c7-a2bf-4637-b018-70cfe7c39dc4")] 24 | 25 | // Version information for an assembly consists of the following four values: 26 | // 27 | // Major Version 28 | // Minor Version 29 | // Build Number 30 | // Revision 31 | // 32 | // You can specify all the values or you can default the Build and Revision Numbers 33 | // by using the '*' as shown below: 34 | // [assembly: AssemblyVersion("1.0.*")] 35 | [assembly: AssemblyVersion("1.0.0.0")] 36 | [assembly: AssemblyFileVersion("1.0.0.0")] 37 | -------------------------------------------------------------------------------- /W2Open.GameState/W2Open.GameState.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | Debug 6 | AnyCPU 7 | {7F6663C7-A2BF-4637-B018-70CFE7C39DC4} 8 | Library 9 | Properties 10 | W2Open.GameState 11 | W2Open.GameState 12 | v4.6.1 13 | 512 14 | 15 | 16 | 17 | true 18 | full 19 | false 20 | ..\..\..\..\..\..\..\Servidor WYD2\Release\DBSRV\run\ 21 | DEBUG;TRACE 22 | prompt 23 | 4 24 | true 25 | 26 | 27 | pdbonly 28 | true 29 | ..\..\W2Open Server\ 30 | TRACE 31 | prompt 32 | 4 33 | true 34 | 35 | 36 | 37 | ..\packages\Newtonsoft.Json.11.0.2\lib\net45\Newtonsoft.Json.dll 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | {9e37305b-badd-49e4-842a-fc45b8ce0b95} 65 | W2Open.Common 66 | 67 | 68 | {5ca9998d-9362-417a-89fd-c7603c59bb46} 69 | W2Open.DataServer 70 | 71 | 72 | 73 | 80 | -------------------------------------------------------------------------------- /W2Open.GameState/packages.config: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | -------------------------------------------------------------------------------- /W2Open.Server/App.config: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | -------------------------------------------------------------------------------- /W2Open.Server/ProcessSecTimer/MainSecTimer.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Threading.Tasks; 6 | using W2Open.Common.Utility; 7 | 8 | namespace W2Open.Server.ProcessSecTimer 9 | { 10 | public class MainSecTimer 11 | { 12 | public static async Task MainTask() 13 | { 14 | while (true) 15 | { 16 | 17 | await Task.Delay(1000); 18 | } 19 | } 20 | 21 | 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /W2Open.Server/Program.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Windows.Forms; 3 | 4 | namespace W2Open.Server 5 | { 6 | static class Program 7 | { 8 | /// 9 | /// The main entry point for the application. 10 | /// 11 | [STAThread] 12 | static void Main() 13 | { 14 | Application.EnableVisualStyles(); 15 | Application.SetCompatibleTextRenderingDefault(false); 16 | Application.Run(new MainForm()); 17 | } 18 | } 19 | } -------------------------------------------------------------------------------- /W2Open.Server/Properties/AssemblyInfo.cs: -------------------------------------------------------------------------------- 1 | using System.Reflection; 2 | using System.Runtime.CompilerServices; 3 | using System.Runtime.InteropServices; 4 | 5 | // General Information about an assembly is controlled through the following 6 | // set of attributes. Change these attribute values to modify the information 7 | // associated with an assembly. 8 | [assembly: AssemblyTitle("W2Open.Server")] 9 | [assembly: AssemblyDescription("")] 10 | [assembly: AssemblyConfiguration("")] 11 | [assembly: AssemblyCompany("")] 12 | [assembly: AssemblyProduct("W2Open.Server")] 13 | [assembly: AssemblyCopyright("Copyright © 2016")] 14 | [assembly: AssemblyTrademark("")] 15 | [assembly: AssemblyCulture("")] 16 | 17 | // Setting ComVisible to false makes the types in this assembly not visible 18 | // to COM components. If you need to access a type in this assembly from 19 | // COM, set the ComVisible attribute to true on that type. 20 | [assembly: ComVisible(false)] 21 | 22 | // The following GUID is for the ID of the typelib if this project is exposed to COM 23 | [assembly: Guid("c1e44d36-a1fb-478f-8f8d-d3e3cd16750b")] 24 | 25 | // Version information for an assembly consists of the following four values: 26 | // 27 | // Major Version 28 | // Minor Version 29 | // Build Number 30 | // Revision 31 | // 32 | // You can specify all the values or you can default the Build and Revision Numbers 33 | // by using the '*' as shown below: 34 | // [assembly: AssemblyVersion("1.0.*")] 35 | [assembly: AssemblyVersion("1.0.0.0")] 36 | [assembly: AssemblyFileVersion("1.0.0.0")] 37 | -------------------------------------------------------------------------------- /W2Open.Server/Properties/Resources.Designer.cs: -------------------------------------------------------------------------------- 1 | //------------------------------------------------------------------------------ 2 | // 3 | // This code was generated by a tool. 4 | // Runtime Version:4.0.30319.42000 5 | // 6 | // Changes to this file may cause incorrect behavior and will be lost if 7 | // the code is regenerated. 8 | // 9 | //------------------------------------------------------------------------------ 10 | 11 | namespace W2Open.Server.Properties { 12 | using System; 13 | 14 | 15 | /// 16 | /// A strongly-typed resource class, for looking up localized strings, etc. 17 | /// 18 | // This class was auto-generated by the StronglyTypedResourceBuilder 19 | // class via a tool like ResGen or Visual Studio. 20 | // To add or remove a member, edit your .ResX file then rerun ResGen 21 | // with the /str option, or rebuild your VS project. 22 | [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")] 23 | [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] 24 | [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] 25 | internal class Resources { 26 | 27 | private static global::System.Resources.ResourceManager resourceMan; 28 | 29 | private static global::System.Globalization.CultureInfo resourceCulture; 30 | 31 | [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] 32 | internal Resources() { 33 | } 34 | 35 | /// 36 | /// Returns the cached ResourceManager instance used by this class. 37 | /// 38 | [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] 39 | internal static global::System.Resources.ResourceManager ResourceManager { 40 | get { 41 | if (object.ReferenceEquals(resourceMan, null)) { 42 | global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("W2Open.Server.Properties.Resources", typeof(Resources).Assembly); 43 | resourceMan = temp; 44 | } 45 | return resourceMan; 46 | } 47 | } 48 | 49 | /// 50 | /// Overrides the current thread's CurrentUICulture property for all 51 | /// resource lookups using this strongly typed resource class. 52 | /// 53 | [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] 54 | internal static global::System.Globalization.CultureInfo Culture { 55 | get { 56 | return resourceCulture; 57 | } 58 | set { 59 | resourceCulture = value; 60 | } 61 | } 62 | } 63 | } 64 | -------------------------------------------------------------------------------- /W2Open.Server/Properties/Resources.resx: -------------------------------------------------------------------------------- 1 |  2 | 3 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | 77 | 78 | 79 | 80 | 81 | 82 | 83 | 84 | 85 | 86 | 87 | 88 | 89 | 90 | 91 | 92 | 93 | 94 | 95 | 96 | 97 | 98 | 99 | 100 | 101 | 102 | 103 | 104 | 105 | 106 | text/microsoft-resx 107 | 108 | 109 | 2.0 110 | 111 | 112 | System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 113 | 114 | 115 | System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 116 | 117 | -------------------------------------------------------------------------------- /W2Open.Server/Properties/Settings.Designer.cs: -------------------------------------------------------------------------------- 1 | //------------------------------------------------------------------------------ 2 | // 3 | // This code was generated by a tool. 4 | // Runtime Version:4.0.30319.42000 5 | // 6 | // Changes to this file may cause incorrect behavior and will be lost if 7 | // the code is regenerated. 8 | // 9 | //------------------------------------------------------------------------------ 10 | 11 | namespace W2Open.Server.Properties { 12 | 13 | 14 | [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] 15 | [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "14.0.0.0")] 16 | internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase { 17 | 18 | private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings()))); 19 | 20 | public static Settings Default { 21 | get { 22 | return defaultInstance; 23 | } 24 | } 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /W2Open.Server/Properties/Settings.settings: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /W2Open.Server/W2Open.Server.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | Debug 6 | AnyCPU 7 | {C1E44D36-A1FB-478F-8F8D-D3E3CD16750B} 8 | WinExe 9 | Properties 10 | W2Open.Server 11 | W2Open.Server 12 | v4.6.1 13 | 512 14 | true 15 | 16 | publish\ 17 | true 18 | Disk 19 | false 20 | Foreground 21 | 7 22 | Days 23 | false 24 | false 25 | true 26 | 0 27 | 1.0.0.%2a 28 | false 29 | false 30 | true 31 | 32 | 33 | AnyCPU 34 | true 35 | full 36 | false 37 | ..\..\..\..\..\..\..\Servidor WYD2\Release\DBSRV\run\ 38 | DEBUG;TRACE 39 | prompt 40 | 4 41 | true 42 | 43 | 44 | AnyCPU 45 | pdbonly 46 | true 47 | ..\..\W2Open Server\ 48 | TRACE 49 | prompt 50 | 4 51 | true 52 | 53 | 54 | icon1.ico 55 | 56 | 57 | 58 | ..\packages\Newtonsoft.Json.11.0.2\lib\net45\Newtonsoft.Json.dll 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | Form 75 | 76 | 77 | MainForm.cs 78 | 79 | 80 | 81 | 82 | 83 | MainForm.cs 84 | 85 | 86 | ResXFileCodeGenerator 87 | Resources.Designer.cs 88 | Designer 89 | 90 | 91 | True 92 | Resources.resx 93 | True 94 | 95 | 96 | 97 | SettingsSingleFileGenerator 98 | Settings.Designer.cs 99 | 100 | 101 | True 102 | Settings.settings 103 | True 104 | 105 | 106 | 107 | 108 | 109 | 110 | 111 | {9e37305b-badd-49e4-842a-fc45b8ce0b95} 112 | W2Open.Common 113 | 114 | 115 | {756c8536-c282-47f2-843f-c3334b5f619d} 116 | W2Open.GameState.Plugin 117 | 118 | 119 | {7f6663c7-a2bf-4637-b018-70cfe7c39dc4} 120 | W2Open.GameState 121 | 122 | 123 | 124 | 125 | 126 | 127 | 128 | False 129 | Microsoft .NET Framework 4.6.1 %28x86 e x64%29 130 | true 131 | 132 | 133 | False 134 | .NET Framework 3.5 SP1 135 | false 136 | 137 | 138 | 139 | 146 | -------------------------------------------------------------------------------- /W2Open.Server/icon1.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/seitbnao/W2-DataBase/84c55a71764cb61c47982574f42750737edc226e/W2Open.Server/icon1.ico -------------------------------------------------------------------------------- /W2Open.Server/packages.config: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | -------------------------------------------------------------------------------- /config.json: -------------------------------------------------------------------------------- 1 | { 2 | "ServerName": "WYD", 3 | "IPAddrs": "127.0.0.1", 4 | "Port": 7514, 5 | "MYSQL_Server": "localhost", 6 | "MYSQL_DataBase": "wyd2pp", 7 | "MYSQL_User": "root", 8 | "MYSQL_Pass": "", 9 | "ChargedGuildList": { 10 | "Guild": [ 11 | 0, 12 | 0, 13 | 0, 14 | 0, 15 | 0 16 | ] 17 | }, 18 | "Sapphire": 8, 19 | "LastCapsule": 1 20 | } --------------------------------------------------------------------------------