I am getting null pointer exception in asp.net application - c#

I am debugging an asp.net application. It works flawlessly in test environment, however, I am getting null reference exception in real server. I am using ninject. The problem arose from ninject I suppose.Here is the problematic code fragment:
public partial class PersonelAylikRapor : MasterClass
{
protected void btnSorgula_Click(object sender, EventArgs e)
{
//other codes ommited for brevity
DateTime baslangicTarihi = DateTime.MinValue;
//arac is null here.
baslangicTarihi = this.arac.CevirDateTimea("01." + ddlAy.SelectedValue + "." + ddlYil.SelectedValue);
}
}
the variable arac should have been solved in MasterClass, since it is the father class, so I do not check null reference issue.
MasterClass is the place that I set the ninject kernel. Here is the content of the MasterClass:
public class MasterClass : System.Web.UI.Page
{
IKernel ninjectKernel = null;
private bool cekirdekKurulduMu = false;
public IPersonelIsKurali personelik = null;
public IAraclarTaha arac = null;
public ITurnikePersonelIsKurali turnikepersonelik = null;
public IPersonelBirimlerIsKurali personelbirimlerik = null;
public ITurnikeIslemlerIsKurali turnikeIsKurali = null;
public IPersonelIliskilendir personelilisiklendirik = null;
public IBirimlerIsKurali birimlerik = null;
public IPersonelIzinIsKurali personelizinik = null;
public IServisIsKurali servisIsKurali = null;
public FonksiyonSonuc fs = null;
public List<PersonelKunye> listpersonelkunye = null;
public List<uint> listgorebilecegipersonelid = null;
public MasterClass()
{
}
protected override void OnPreInit(EventArgs e)
{
try
{
base.OnPreInit(e);
if (this.cekirdekKurulduMu == false)
{
this.cekirdekKurulduMu = true;
this.ninjectKernel = new StandardKernel();
this.ninjectCekirdegiKur(this.ninjectKernel);
this.DegiskenlereAta();
}
}
catch (Exception ex)
{
IAraclarTaha arac = new AraclarTaha();
FonksiyonSonuc fs = new FonksiyonSonuc(true);
fs = arac.HatayiVeritabaninaYaz(ex, OrmanSuTypes.Enums.HataCiddiyetiEnum.OLUMCUL);
if (fs.fonksiyonBasariDurumu == false)
{
throw ex;
}
}
}
private void ninjectCekirdegiKur(IKernel ninjectKernel)
{
this.ninjectKernel = new StandardKernel();
this.ninjectKernel.Bind<IPersonelBirimlerIsKurali>().To<PersonelBirimlerIsKurali>();
this.ninjectKernel.Bind<IPersonelIzinIsKurali>().To<PersonelIzinIsKurali>();
this.ninjectKernel.Bind<IPersonelIsKurali>().To<PersonelIsKurali>();
this.ninjectKernel.Bind<IAraclarTaha>().To<AraclarTaha>().WithConstructorArgument("debugMode", Araclar.DebugModdaMi());
this.ninjectKernel.Bind<ITurnikeIslemlerIsKurali>().To<TurnikeIslemlerIsKurali>();
this.ninjectKernel.Bind<IBirimlerIsKurali>().To<BirimlerIsKurali>();
this.ninjectKernel.Bind<IPersonelIliskilendir>().To<PersonelIiskilendirIsKurali>();
this.ninjectKernel.Bind<ITurnikePersonelIsKurali>().To<TurnikePersonelIsKurali>();
this.ninjectKernel.Bind<IServisIsKurali>().To<ServisIsKurali>();
}
public void DegiskenlereAta()
{
if (this.arac == null)
{
this.arac = this.ninjectKernel.Get<IAraclarTaha>();
}
if (this.personelik == null)
{
this.personelik = this.ninjectKernel.Get<IPersonelIsKurali>();
}
if (this.turnikepersonelik == null)
{
this.turnikepersonelik = this.ninjectKernel.Get<ITurnikePersonelIsKurali>();
}
if (this.personelbirimlerik == null)
{
this.personelbirimlerik = this.ninjectKernel.Get<IPersonelBirimlerIsKurali>();
}
if (this.turnikeIsKurali == null)
{
this.turnikeIsKurali = this.ninjectKernel.Get<ITurnikeIslemlerIsKurali>();
}
if (this.personelilisiklendirik == null)
{
this.personelilisiklendirik = this.ninjectKernel.Get<IPersonelIliskilendir>();
}
if (this.birimlerik == null)
{
this.birimlerik = this.ninjectKernel.Get<IBirimlerIsKurali>();
}
if (this.personelizinik == null)
{
this.personelizinik = this.ninjectKernel.Get<IPersonelIzinIsKurali>();
}
if (this.fs == null)
{
this.fs = new FonksiyonSonuc(true);
}
if (this.servisIsKurali == null)
{
this.servisIsKurali = this.ninjectKernel.Get<IServisIsKurali>();
}
}
}
What is wrong with it? Thanks in advance.
Edit-1: Here is the visual explanatory of the error:

I have just solve that problem. You can not set your ninject kernel in such manner. Implementing ninject kernel in asp.net web forms are expressed here:
How can I implement Ninject or DI on asp.net Web Forms?

Related

How can I develop Azure Telemetry base APM?

Actually, I am trying to write an open-source project called Telemetrium. It is a baby step but I got stuck with something: I will explain the situation in 2 parts
Without Telemetrium
With Telemetrium
Without Telemetrium:
Files :
Function1.cs
Startup.cs
TelemetryInitializer.cs
Everything is working good like below:
TelemetryInitializer.cs:
public class TelemetryInitializer : ITelemetryInitializer
{
private readonly IHttpContextAccessor _httpContextAccessor;
public TelemetryInitializer(IHttpContextAccessor httpContextAccessor)
{
if (httpContextAccessor == null) throw new System.ArgumentNullException(nameof(httpContextAccessor));
_httpContextAccessor = httpContextAccessor;
}
public async void Initialize(ITelemetry telemetry)
{
if (telemetry is DependencyTelemetry)
{
var dependencyTelemetry = telemetry as DependencyTelemetry;
if (dependencyTelemetry.Success == true)
dependencyTelemetry = dependencyTelemetry.ActivityToTelemetry(System.Diagnostics.Activity.Current) as DependencyTelemetry;
dependencyTelemetry.Success = true;
}
var requestTelemetry = telemetry as RequestTelemetry;
if (requestTelemetry == null) return;
var context = _httpContextAccessor.HttpContext;
if (context == null) return;
try
{
if (context.Request != null)
{
requestTelemetry = requestTelemetry.ActivityToTelemetry(System.Diagnostics.Activity.Current) as RequestTelemetry;
context.Request.EnableBuffering();
context.Request.Body.Position = 0;
requestTelemetry.Properties[$"Request"] = await new StreamReader(context.Request.Body).ReadToEndAsync();
foreach (var headerName in context.Request.Headers)
{
var header = context.Request.Headers[headerName.Key];
requestTelemetry.Properties[$"Request-{headerName.Key}"] = header;
}
}
if (context.Response != null && (context.Response.Body.CanRead && context.Response.Body.CanSeek))
{
requestTelemetry.Properties[$"Response"] = await new StreamReader(context.Response.Body).ReadToEndAsync();
foreach (var headerName in context.Response.Headers)
{
var header = context.Response.Headers[headerName.Key];
requestTelemetry.Properties[$"Response-{headerName.Key}"] = header;
}
}
}
catch (ObjectDisposedException ex)
{
Console.WriteLine($"obj accessed after dispose!: {ex.Message}");
Debug.WriteLine($"obj accessed after dispose!: {ex.Message}");
requestTelemetry.Success = false;
}
requestTelemetry.Success = true;
}
}
public static class Extensions
{
public static ITelemetry ActivityToTelemetry(this OperationTelemetry telemetry, Activity activity)
{
if (telemetry == null)
throw new ArgumentNullException(nameof(telemetry));
if (activity.Tags.Count() > 0)
foreach (var tag in activity.Tags)
telemetry.Properties[tag.Key] = tag.Value;
telemetry.Properties["Id"] = activity.Id;
telemetry.Properties["ParentId"] = activity.ParentId;
telemetry.Properties["RootId"] = activity.RootId;
return telemetry;
}
}
But I decided to make some changes for Telemetrium:
What I did:
I added Attributes
I developed reflection based Extension
This is Telemetrium.cs:
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
public class TelemetriumAttribute : Attribute
{
private TelemetryEnum TelemetryType;
private string MethodName;
public TelemetriumAttribute(TelemetryEnum TelemetryType, string MethodName)
{
this.TelemetryType = TelemetryType;
this.MethodName = MethodName;
}
public void RUN()
{
if (TelemetryType == TelemetryEnum.RequestTelemtry)
{
var req = Telemetrium.telemetryClient.StartOperation<RequestTelemetry>(this.MethodName);
}
else if (TelemetryType == TelemetryEnum.DependencyTelemetry)
{
var dep = Telemetrium.telemetryClient.StartOperation<DependencyTelemetry>(this.MethodName);
}
}
}
public enum TelemetryEnum
{
RequestTelemtry, DependencyTelemetry
}
public static class Telemetrium
{
public static TelemetryClient telemetryClient { get; set; }
static public void StartTelemetrium(this Function1 This)
{
Type objType = typeof(Function1);
try
{
MethodInfo[] info = objType.GetMethods(BindingFlags.NonPublic | BindingFlags.Instance);
var methods = objType.GetMethods(BindingFlags.NonPublic | BindingFlags.Instance).Where(m => m.GetCustomAttributes(typeof(TelemetriumAttribute), false).Length > 0).ToArray();
var customAttributes = objType.GetMethods(BindingFlags.NonPublic | BindingFlags.Instance).Where(m => m.GetCustomAttributes(typeof(TelemetriumAttribute), false).Length > 0)
.Select(q => q.GetCustomAttributes(typeof(TelemetriumAttribute), false)).ToArray();
if (customAttributes.Length > 0 && customAttributes[0] != null)
{
foreach (var customAttribute in customAttributes)
{
foreach (var item in customAttribute)
{
TelemetriumAttribute _customAttribute = item as TelemetriumAttribute;
_customAttribute.RUN();
}
}
}
}
// catch ArgumentNullException here
catch (ArgumentNullException e)
{
Console.Write("name is null.");
Console.Write("Exception Thrown: ");
Console.Write("{0}", e.GetType(), e.Message);
}
}
}
By using Telemtrium I want to Convert method1 in Function1.cs from
private void method1()
{
using (var dep1 = Telemetrium.telemetryClient.StartOperation<DependencyTelemetry>("method1"))
{
int a = 2;
int b = 2;
int v = a * b;
dep2.Telemetry.Success = true;
}
}
TO
[Telemetrium(TelemetryEnum.DependencyTelemetry, "method1")]
private void method1()
{
//using (var dep1 = telemetryClient.StartOperation<DependencyTelemetry>("method1"))
//{
int a = 2;
int b = 2;
int v = a * b;
//dep1.Telemetry.Success = true;
//}
}
As a Result:
I don`t want to use like that
using (var getDetailsOperation = Telemetrium.telemetryClient.StartOperation("GetProductDetails"))
When any function in azure it should be automatically can in RUN method.
also when submethods run, using (var dep2 = Telemetrium.telemetryClient.StartOperation("method2")) should be created automatically. But How?

Loading XML document loads the same group twice

Some classes to start, I'm writing them all so you can reproduce my problem:
public class PermissionObject
{
public string permissionName;
public string permissionObject;
public bool permissionGranted;
public PermissionObject()
{
permissionName = "";
permissionObject = "";
permissionGranted = true;
}
public PermissionObject(string name, string obj, bool granted)
{
permissionName = name;
permissionObject = obj;
permissionGranted = granted;
}
}
public class Config
{
public string cmsDataPath = "";
public string cmsIP = "";
public List<UserClass> usersCMS = new List<UserClass>();
static public string pathToConfig = #"E:\testconpcms.xml";
public string cardServerAddress = "";
public void Save()
{
XmlSerializer serializer = new XmlSerializer(typeof(Config));
using (Stream fileStream = new FileStream(pathToConfig, FileMode.Create))
{
serializer.Serialize(fileStream, this);
}
}
public static Config Load()
{
if (File.Exists(pathToConfig))
{
XmlSerializer serializer = new XmlSerializer(typeof(Config));
try
{
using (Stream fileStream = new FileStream(pathToConfig, FileMode.Open))
{
return (Config)serializer.Deserialize(fileStream);
}
}
catch (Exception ex)
{
return new Config();
}
}
else
{
return null;
}
}
}
public class UserClass
{
public string Name;
public string Login;
public string Password;
public PCMS2 PermissionsList; // OR new PCMS1, as I will explain in a bit
public UserClass()
{
this.Name = "Admin";
this.Login = "61-64-6D-69-6E";
this.Password = "61-64-6D-69-6E";
this.PermissionsList = new PCMS2(); // OR new PCMS1, as I will explain in a bit
}
}
The problematic bit: consider two implementations of PCMS class, PCMS1 and PCMS2:
public class PCMS1
{
public PermissionObject p1, p2;
public PCMS1()
{
p1 = new PermissionObject("ImportConfigCMS", "tsmiImportCMSConfigFile", true);
p2 = new PermissionObject("ExportConfigCMS", "tsmiExportCMSConfigFile", true);
}
}
public class PCMS2
{
public List<PermissionObject> listOfPermissions = new List<PermissionObject>();
public PCMS2()
{
listOfPermissions.Add(new PermissionObject("ImportConfigCMS", "tsmiImportCMSConfigFile", true));
listOfPermissions.Add(new PermissionObject("ExportConfigCMS", "tsmiExportCMSConfigFile", true));
}
}
And finally main class:
public partial class Form1 : Form
{
private Config Con;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
Con = Config.Load();
if (Con == null)
{
Con = new Config();
Con.cmsDataPath = #"E:\testconpcms.xml";
Con.Save();
}
if (Con.usersCMS.Count == 0)
{
UserClass adminDefault = new UserClass();
Con.usersCMS.Add(adminDefault);
Con.Save();
}
}
}
Now, using either PCMS1 or PCMS2, the config file generates properly - one user with 2 permissions.
However, when config file is present, calling Con = Config.Load() in the main class gives different results.
Using PCMS1, the Con object is as expected - 1 user with 2 permissions.
However, using PCMS2, the Con object is 1 user with 4 (four) permissions. It doubles that field (it's basically p1, p2, p1, p2). Put a BP to see Con after Load().
I guess the list (PCMS2) implementation is doing something wonky during load which I'm not aware of, but I can't seem to find the issue.
You creates your permission objects in constructor of PMCS2 you do it in the constructor of PMCS1 too, but there you do have two properties that will be overwritten by serializer.
In case of of PMCS2 your constructor adds two items to List and than serializer adds the items it has deserilized to the same list.
I don't know exactly your usecase but i would suggest to move init of the permissions to separated method:
public class PCMS1
{
public PermissionObject p1, p2;
public void Init()
{
p1 = new PermissionObject("ImportConfigCMS", "tsmiImportCMSConfigFile", true);
p2 = new PermissionObject("ExportConfigCMS", "tsmiExportCMSConfigFile", true);
}
}
public class PCMS2
{
public List<PermissionObject> listOfPermissions = new List<PermissionObject>();
public void Init()
{
listOfPermissions.Add(new PermissionObject("ImportConfigCMS", "tsmiImportCMSConfigFile", true));
listOfPermissions.Add(new PermissionObject("ExportConfigCMS", "tsmiExportCMSConfigFile", true));
}
}
after that you could call it, if you want to get initial settings:
if (Con.usersCMS.Count == 0)
{
UserClass adminDefault = new UserClass();
adminDefault.PermissionsList.Init();
Con.usersCMS.Add(adminDefault);
Con.Save();
}

Load serialized data in multiple applications C#

Scenario:
I have a program which uses a simple class to generate game data. Using the said program, I write the data out using serialization and BinaryFormatter to a file to be used by a second program. Reading the data from this initial program works without issue.
Problem:
It's probably down to my ignorance to how serialized files are handled, but I cannot then load this data into a second program, the actual game itself.
saveGame code (in program 1):
static List<GameData> gameData;
static GameData currentData;
private void saveGame(Sudoku sdk) {
BinaryFormatter bf = new BinaryFormatter();
FileStream file = null;
try {
if(!File.Exists(gameDataFile[currentDifficulty])) {
file = File.Open(gameDataFile[currentDifficulty], FileMode.CreateNew);
} else {
file = File.Open(gameDataFile[currentDifficulty], FileMode.Append);
}
currentData = setGameData(sdk);
bf.Serialize(file, currentData);
savePuzzleLog();
} catch(Exception e) {
Debug.LogException("saveGame", e);
}
if(file != null) {
file.Close();
}
}
loadGameData: (in program 2)
public static List<GameData> gameData;
public bool loadGameData() {
if(gameData == null) {
gameData = new List<GameData>();
} else {
gameData.Clear();
}
bool loadData = true;
bool OK = false;
if(File.Exists(gameDataFile[currentDifficulty])) {
BinaryFormatter bf = new BinaryFormatter();
FileStream file = File.Open(gameDataFile[currentDifficulty], FileMode.Open);
while(loadData) {
try {
GameData gd = new GameData();
gd = (GameData)bf.Deserialize(file);
gameData.Add(gd);
OK = true;
if(file.Position == file.Length) {
loadData = false;
}
} catch(Exception e) {
Debug.LogException(e);
loadData = false;
OK = false;
}
}
if(file != null) {
file.Close();
}
} else {
Debug.LogWarning(gameDataFile[currentDifficulty] + " does not exist!");
}
return OK;
}
GameData Class: (1st program)
[Serializable]
class GameData {
private int gameID;
private List<int> contentArray;
private int difficultyValue;
public GameData(List<int> data = null) {
id = -1;
difficulty = -1;
if(content != null) {
content.Clear();
} else {
content = new List<int>();
}
if(data != null) {
foreach(int i in data) {
content.Add(i);
}
}
}
public int id {
get {
return this.gameID;
}
set {
this.gameID = value;
}
}
public int difficulty {
get {
return this.difficultyValue;
}
set {
this.difficultyValue = value;
}
}
public List<int> content {
get {
return this.contentArray;
}
set {
this.contentArray = value;
}
}
}
GameData Class: (2nd program) The only difference is declaring as public
[Serializable]
public class GameData {
private int gameID;
private List<int> contentArray;
private int difficultyValue;
public GameData(List<int> data = null) {
id = -1;
difficulty = -1;
if(content != null) {
content.Clear();
} else {
content = new List<int>();
}
if(data != null) {
foreach(int i in data) {
content.Add(i);
}
}
}
public int id {
get {
return this.gameID;
}
set {
this.gameID = value;
}
}
public int difficulty {
get {
return this.difficultyValue;
}
set {
this.difficultyValue = value;
}
}
public List<int> content {
get {
return this.contentArray;
}
set {
this.contentArray = value;
}
}
}
What my question is, is how do I save the data out in one program and be able to load it using a different program without getting serialization errors or do I need to use an alternate save/load method and/or class structure?
When I had to do it i made it this way :
An independant dll (assembly) containing the class holding the data (for you the GameData class), and utility methods to save/load from a file.
Your two other projects must then reference this dll (assembly) and you should be able to (de)serialize correctly.
What I think the issue is in your case is that the BinaryFormatter does not only save the data in the file, but also the complete Type of the serialized object.
When you try to deserialize in another similar object, even if the structure is the same, the full name of the class is not (because the assembly name is not).
OK, I've sorted it using the advice given. Instead of using BinaryFormatter I have used BinaryWriter and BinaryReader as follows...
In program 1 (the creator):
private byte[] setByteData(Sudoku sdk) {
List<int> clues = sdk.puzzleListData();
byte[] bd = new byte[puzzleSize];
SudokuSolver solver = new SudokuSolver();
List<int> solution = solver.Solve(sdk.Copy(), false, currentDifficulty).puzzleListData();
for(int i = 0; i < puzzleSize; i++) {
bd[i] = Convert.ToByte(solution[i] + (clues[i] == 0 ? 0xF0 : 0));
}
return bd;
}
private GameData setGameData(Sudoku sdk) {
List<int> clues = sdk.puzzleListData();
GameData gd = new GameData();
gd.id = puzzleList.Items.Count;
gd.difficulty = currentDifficulty;
SudokuSolver solver = new SudokuSolver();
List<int> solution = solver.Solve(sdk.Copy(), false, currentDifficulty).puzzleListData();
for(int i = 0; i < puzzleSize; i++) {
gd.content.Add(solution[i] + (clues[i] == 0 ? 0xF0 : 0));
}
return gd;
}
private List<int> getByteData(byte[] data) {
List<int> retVal = new List<int>();
foreach(byte i in data) {
if(i > 9) {
retVal.Add(i - 0xF0);
} else {
retVal.Add(0);
}
}
return retVal;
}
private string getGameData(List<int> data) {
string retVal = "";
foreach(int i in data) {
if(i > 9) {
retVal += (i - 0xF0).ToString();
} else {
retVal += i.ToString();
}
}
return retVal;
}
private void saveGame(Sudoku sdk) {
FileStream file = null;
BinaryWriter bw = null;
try {
if(!File.Exists(gameDataFile[currentDifficulty])) {
file = File.Open(gameDataFile[currentDifficulty], FileMode.CreateNew);
} else {
file = File.Open(gameDataFile[currentDifficulty], FileMode.Append);
}
bw = new BinaryWriter(file);
currentData = setGameData(sdk);
byte[] bd = setByteData(sdk);
bw.Write(currentData.id);
bw.Write(currentData.difficulty);
bw.Write(bd);
savePuzzleLog();
} catch(Exception e) {
Debug.LogException("saveGame", e);
}
if(file != null) {
if(bw != null) {
bw.Flush();
bw.Close();
}
file.Close();
}
}
In program 2: (the actual game)
public bool loadGameData() {
if(gameData == null) {
gameData = new List<GameData>();
} else {
gameData.Clear();
}
bool loadData = true;
bool OK = false;
if(File.Exists(gameDataFile[currentDifficulty])) {
FileStream file = File.Open(gameDataFile[currentDifficulty], FileMode.Open);
BinaryReader br = new BinaryReader(file);
while(loadData) {
try {
GameData gd = new GameData();
gd.id = br.ReadInt32();
gd.difficulty = br.ReadInt32();
gd.content = getByteData(br.ReadBytes(puzzleSize));
gameData.Add(gd);
OK = true;
if(file.Position == file.Length) {
loadData = false;
}
} catch(Exception e) {
Debug.LogException(e);
loadData = false;
OK = false;
}
}
if(file != null) {
file.Close();
}
} else {
Debug.LogWarning(gameDataFile[currentDifficulty] + " does not exist!");
}
return OK;
}
The class structure is the same as before but using this method has resolved my issue and I can now create the data files using my creator and load the data comfortably using the actual game.
Thanks all for your assistance and advice to help me get this sorted.

SharpDXException on setting Shader inputLayout

This didnt used to throw this exception but now it does
if (shader.ShaderInput == null) shader.ShaderInput = new InputLayout(OneEngineInstance.EngineInstance.Device, ShaderSignature.GetInputSignature(shader.CompilationResult), new[] { new InputElement("POSITION", 0, Format.R32G32B32_Float, 0, 0), new InputElement("COLOR", 0, Format.R32G32B32_Float, 16, 0) });
The only useful information it gives me is
An unhandled exception of type 'SharpDX.SharpDXException' occurred in SharpDX.dll
Additional information: HRESULT: [0x80070057], Module: [General], ApiCode: [E_INVALIDARG/Invalid Arguments], Message: The parameter is incorrect.
Im not sure why this is doing this and im still pretty new to SharpDX
AssetsLoader.cs
using System;
using System.IO;
using SharpDX;
using SharpDX.DXGI;
using SharpDX.Direct3D;
using SharpDX.Direct3D11;
using SharpDX.D3DCompiler;
using SharpDX.XAudio2;
using SharpDX.Multimedia;
using OneEngine.DataTypes;
using OneEngine.Core;
namespace OneEngine.Assets
{
public static class AssetsLoader
{
public static void LoadImage(Image image)
{
image.Texture = Texture2D.FromFile<Texture2D>(OneEngineInstance.EngineInstance.Device, image.FilePath);
image.ShaderResourceView = new ShaderResourceView(OneEngineInstance.EngineInstance.Device, image.Texture);
image.Sampler = new SamplerState(OneEngineInstance.EngineInstance.Device, new SamplerStateDescription()
{
// TODO > Make Simplifier classes for these values and adapt to engine settings
Filter = Filter.MinMagMipLinear,
AddressU = TextureAddressMode.Wrap,
AddressV = TextureAddressMode.Wrap,
AddressW = TextureAddressMode.Wrap,
BorderColor = Color.Black,
ComparisonFunction = Comparison.Never,
MaximumAnisotropy = 16,
MipLodBias = 0,
MinimumLod = 0,
MaximumLod = 16
});
}
public static void LoadShader(Shader shader)
{
for (int i = 0; i < shader.ShaderTypes.Length; i++)
{
switch (shader.ShaderTypes[i])
{
case EShaderType.VERTEX:
shader.CompilationResult = ShaderBytecode.CompileFromFile(shader.FilePath, "VS", "vs_5_0");
shader.VertexShader = new VertexShader(OneEngineInstance.EngineInstance.Device, shader.CompilationResult);
break;
case EShaderType.PIXEL:
shader.CompilationResult = ShaderBytecode.CompileFromFile(shader.FilePath, "PS", "ps_5_0");
shader.PixelShader = new PixelShader(OneEngineInstance.EngineInstance.Device, shader.CompilationResult);
break;
case EShaderType.GEOMETRY:
shader.CompilationResult = ShaderBytecode.CompileFromFile(shader.FilePath, "GS", "gs_5_0");
shader.GeometryShader = new GeometryShader(OneEngineInstance.EngineInstance.Device, shader.CompilationResult);
break;
case EShaderType.COMPUTE:
shader.CompilationResult = ShaderBytecode.CompileFromFile(shader.FilePath, "CS", "cs_5_0");
shader.ComputeShader = new ComputeShader(OneEngineInstance.EngineInstance.Device, shader.CompilationResult);
break;
case EShaderType.DOMAIN:
shader.CompilationResult = ShaderBytecode.CompileFromFile(shader.FilePath, "DS", "ds_5_0");
shader.DomainShader = new DomainShader(OneEngineInstance.EngineInstance.Device, shader.CompilationResult);
break;
case EShaderType.HULL:
shader.CompilationResult = ShaderBytecode.CompileFromFile(shader.FilePath, "HS", "hs_5_0");
shader.HullShader = new HullShader(OneEngineInstance.EngineInstance.Device, shader.CompilationResult);
break;
}
}
if (shader.ShaderInput == null) shader.ShaderInput = new InputLayout(OneEngineInstance.EngineInstance.Device, ShaderSignature.GetInputSignature(shader.CompilationResult), new[] { new InputElement("POSITION", 0, Format.R32G32B32_Float, 0, 0), new InputElement("COLOR", 0, Format.R32G32B32_Float, 16, 0) });
}
public static void LoadAudio(Audio audio)
{
audio.Stream = new SoundStream(File.OpenRead(audio.FilePath));
audio.Format = audio.Stream.Format;
audio.Buffer = new AudioBuffer
{
Stream = audio.Stream.ToDataStream(), AudioBytes = (int)audio.Stream.Length, Flags = BufferFlags.EndOfStream
};
audio.Stream.Close();
audio.Voice = new SourceVoice(AudioCore.XAudio, audio.Format, true);
if (audio.IsLoopable) audio.Buffer.LoopCount = audio.LoopTimes;
}
public static void LoadVideo()
{
}
public static void LoadFont()
{
}
public static void LoadLanguage()
{
}
}
public enum EShaderType
{
VERTEX, PIXEL, GEOMETRY, COMPUTE, DOMAIN, HULL
}
}
Shader.cs
using System;
using SharpDX.Direct3D;
using SharpDX.Direct3D11;
using SharpDX.D3DCompiler;
using OneEngine.Assets;
namespace OneEngine.DataTypes
{
public sealed class Shader
{
private String filePath;
private EShaderType[] shaderTypes;
private CompilationResult shaderByteCode;
private VertexShader vs;
private PixelShader ps;
private GeometryShader gs;
private ComputeShader cs;
private DomainShader ds;
private HullShader hs;
private InputLayout shaderInput;
private InputElement[] inputElements;
public Shader(String shaderFilePath, EShaderType[] types, InputElement[] elemets)
{
this.filePath = shaderFilePath;
this.shaderTypes = types;
this.inputElements = elemets;
}
public void RemoveFromMemory()
{
if (shaderByteCode != null) shaderByteCode.Dispose();
if (vs != null) vs.Dispose();
if (ps != null) ps.Dispose();
if (gs != null) gs.Dispose();
if (cs != null) cs.Dispose();
if (ds != null) ds.Dispose();
if (hs != null) hs.Dispose();
}
public String FilePath
{
get { return filePath; }
}
public EShaderType[] ShaderTypes
{
get { return shaderTypes; }
set { shaderTypes = value; }
}
public CompilationResult CompilationResult
{
get { return shaderByteCode; }
set { shaderByteCode = value; }
}
public VertexShader VertexShader
{
get { return vs; }
set { vs = value; }
}
public PixelShader PixelShader
{
get { return ps; }
set { ps = value; }
}
public GeometryShader GeometryShader
{
get { return gs; }
set { gs = value; }
}
public ComputeShader ComputeShader
{
get { return cs; }
set { cs = value; }
}
public DomainShader DomainShader
{
get { return ds; }
set { ds = value; }
}
public HullShader HullShader
{
get { return hs; }
set { hs = value; }
}
public InputLayout ShaderInput
{
set { shaderInput = value; }
get { return shaderInput; }
}
public InputElement[] ShaderInputElements
{
get { return inputElements; }
}
}
}
If you need anything else, the project is open source https://github.com/TheNanonNetwork/OneGames
Try creating your Graphics Device with DeviceCreationFlags.Debug and if the input layout is failing to create properly, then it'll tell you why.
Also, are you sure your Color attribute is supposed to be at an offset of 16 bytes given that the attribute before it is only 12 bytes in size?

How can I extend the OOTB Content Editor Web Part in Sharepoint 2010?

I need a webpart that has a plaintext field for a title, an image for a thumbnail and a HTML content-editable block, so I thought the best way to do this would be to try and extend the existing Content Editor Web Part. Unfortunately, the CEWP is marked as sealed so I can't subclass it. I've reflected and tried to recreate the functionality in my own custom webpart (see the end of the question for code), but the content of my custom version of the CEWP is not persisted.
Does anyone know how I can:
safely subclass the ContentEditableWebPart, or
include a rich text block (including the RTE Ribbon) in a custom web part, or
host multiple web parts in one "wrapper" web part?
Thanks in advance!
code follows below (stuff that was stopping it compiling that was copied from reflector has been commented out/altered/removed)
using System;
using System.ComponentModel;
using System.Security.Permissions;
using System.Web;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml;
using System.Xml.Serialization;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Security;
using Microsoft.SharePoint.Utilities;
using Microsoft.SharePoint.WebControls;
using Microsoft.SharePoint.WebPartPages;
namespace Public.Webparts
{
[ToolboxItemAttribute(false)]
[XmlRoot(Namespace="Webparts/ProductItem")]
public class ProductItemWebPart :System.Web.UI.WebControls.WebParts.WebPart
{
// Fields
private string _content;
private bool _contentHasToken;
private string _contentLink;
private string _partContent;
private string _partStorage;
private HtmlGenericControl editableRegion = new HtmlGenericControl();
private HtmlGenericControl emptyPanel = new HtmlGenericControl();
private const string EmptyPanelHtmlV4 = "<A href=\"#\" title=\"{0}\" style=\"padding:8px 0px\" class=\"ms-toolbar ms-selectorlink\" >{0}</A>";
internal const string InputContentClientId = "content";
// Methods
[AspNetHostingPermission(SecurityAction.LinkDemand, Level=AspNetHostingPermissionLevel.Minimal)]
public ProductItemWebPart()
{
//base.PreRender += new EventHandler(this.OnPreRender);
if (this.Title.Length == 0)
{
this.Title = "Product Item Webpart";
}
if (this.Description.Length == 0)
{
this.Description = "This web part contains a title, content and image for a product item.";
}
}
private string GetContent()
{
if (this._partContent != null)
{
return SPHttpUtility.NoEncode(ReplaceTokens(this._partContent));
}
return "";
}
protected internal string ReplaceTokens(string input)
{
string str = string.Empty;
if (this.WebPartManager != null)
{
return SPWebPartManager.ReplaceTokens(HttpContext.Current, SPContext.Current.Web, this, input);
}
if (input != null)
{
str = input;
}
return str;
}
private string getEmptyPanelHtml()
{
return "<A href=\"#\" title=\"Click to enter content.\" style=\"padding:8px 0px\" class=\"ms-toolbar ms-selectorlink\" >Click to enter content.</A>";
}
//private void HttpAsyncCallback(object state)
//{
// ULS.SendTraceTag(0x38393969, ULSCat.msoulscat_WSS_WebParts, ULSTraceLevel.Medium, "ASYNC: Http Callback: UniqueID={0}", new object[] { this.UniqueID.ToString() });
// if ((HttpStatusCode.OK != base.GetHttpWebResponse(this._contentLink, out this._partContent)) && (this._content == null))
// {
// this._partContent = "<p class=\"UserGeneric\">" + SPHttpUtility.HtmlEncode(WebPartPageResource.GetString("CannotRetrieveContent", new object[] { WebPartPageResource.GetString("ContentLinkLiteral") })) + "</p>";
// }
//}
private bool inEditMode()
{
SPWebPartManager currentWebPartManager = (SPWebPartManager) WebPartManager.GetCurrentWebPartManager(this.Page);
return (((currentWebPartManager != null) && !base.IsStandalone) && currentWebPartManager.GetDisplayMode().AllowPageDesign);
}
//[SharePointPermission(SecurityAction.Demand, ObjectModel=true)]
//public override string LoadResource(string id)
//{
// string str = WebPartPageResource.GetString(id);
// if (str != null)
// {
// return str;
// }
// return id;
//}
[SharePointPermission(SecurityAction.Demand, ObjectModel=true)]
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
if (this.ShowContentEditable())
{
SPRibbon current = SPRibbon.GetCurrent(this.Page);
if (current != null)
{
current.MakeTabAvailable("Ribbon.EditingTools.CPEditTab");
current.MakeTabAvailable("Ribbon.Image.Image");
current.MakeTabAvailable("Ribbon.EditingTools.CPInsert");
current.MakeTabAvailable("Ribbon.Link.Link");
current.MakeTabAvailable("Ribbon.Table.Layout");
current.MakeTabAvailable("Ribbon.Table.Design");
//if (!(this.Page is WikiEditPage))
//{
// current.TrimRTEWikiControls();
//}
}
}
}
[SharePointPermission(SecurityAction.Demand, ObjectModel=true)]
protected override void OnLoad(EventArgs e)
{
this.Controls.Add(this.editableRegion);
this.Controls.Add(this.emptyPanel);
this.editableRegion.Visible = false;
this.emptyPanel.Visible = false;
base.OnLoad(e);
string str = this.Page.Request.Form[this.ClientID + "content"];
if ((str != null) && (this._content != str))
{
this._content = str;
try
{
SPWebPartManager currentWebPartManager = (SPWebPartManager) WebPartManager.GetCurrentWebPartManager(this.Page);
Guid storageKey = currentWebPartManager.GetStorageKey(this);
currentWebPartManager.SaveChanges(storageKey);
}
catch (Exception exception)
{
Label child = new Label();
child.Text = exception.Message;
this.Controls.Add(child);
}
}
if (this.ShowContentEditable())
{
string str2;
//if (this.ContentHasToken)
//{
// str2 = ReplaceTokens(this._content);
//}
//else
//{
// str2 = this._content;
//}
str2 = this._content;
this.Page.ClientScript.RegisterHiddenField(this.ClientID + "content", str2);
this.editableRegion.Visible = true;
this.emptyPanel.Visible = true;
this.emptyPanel.TagName = "DIV";
this.emptyPanel.Style.Add(HtmlTextWriterStyle.Cursor, "hand");
this.emptyPanel.Controls.Add(new LiteralControl(this.getEmptyPanelHtml()));
this.emptyPanel.Style.Add(HtmlTextWriterStyle.TextAlign, "center");
base.Attributes["RteRedirect"] = this.editableRegion.ClientID;
ScriptLink.RegisterScriptAfterUI(this.Page, "SP.UI.Rte.js", false);
ScriptLink.RegisterScriptAfterUI(this.Page, "SP.js", false);
ScriptLink.RegisterScriptAfterUI(this.Page, "SP.Runtime.js", false);
this.editableRegion.TagName = "DIV";
this.editableRegion.InnerHtml = str2;
this.editableRegion.Attributes["class"] = "ms-rtestate-write ms-rtestate-field";
this.editableRegion.Attributes["contentEditable"] = "true";
this.editableRegion.Attributes["InputFieldId"] = this.ClientID + "content";
this.editableRegion.Attributes["EmptyPanelId"] = this.emptyPanel.ClientID;
this.editableRegion.Attributes["ContentEditor"] = "True";
this.editableRegion.Attributes["AllowScripts"] = "True";
this.editableRegion.Attributes["AllowWebParts"] = "False";
string script = "RTE.RichTextEditor.transferContentsToInputField('" + SPHttpUtility.EcmaScriptStringLiteralEncode(this.editableRegion.ClientID) + "');";
this.Page.ClientScript.RegisterOnSubmitStatement(base.GetType(), "transfer" + this.editableRegion.ClientID, script);
if (string.IsNullOrEmpty(this._content))
{
this.emptyPanel.Style["display"] = "";
this.editableRegion.Style["display"] = "none";
}
else
{
this.emptyPanel.Style["display"] = "none";
this.editableRegion.Style["display"] = "";
}
}
}
//private void OnPreRender(object sender, EventArgs e)
//{
// Uri fullURLPath = base.GetFullURLPath(this._contentLink);
// if ((fullURLPath != null) && !base.TryToGetFileFromDatabase(fullURLPath, out this._partContent))
// {
// ULS.SendTraceTag(0x38393968, ULSCat.msoulscat_WSS_WebParts, ULSTraceLevel.Medium, "ASYNC: Begin Fetch: UniqueID={0}", new object[] { this.UniqueID.ToString() });
// base.RegisterWorkItemCallback(new WaitCallback(this.HttpAsyncCallback), null);
// }
//}
[SharePointPermission(SecurityAction.Demand, ObjectModel=true)]
//protected override void RenderWebPart(HtmlTextWriter writer)
protected override void Render(HtmlTextWriter writer)
{
//if (this.ShowContentEditable() && base.WebPartManager.IsAllowedToScript(this))
if (this.ShowContentEditable())
{
base.Render(writer);
}
else
{
writer.Write(this.GetContent());
}
}
//[SharePointPermission(SecurityAction.Demand, ObjectModel=true)]
//protected internal override bool RequiresWebPartClientScript()
//{
// return true;
//}
//public bool ShouldSerializeContent()
//{
// if (!base.SerializeAll)
// {
// return (this.WebPartDefault._content != this._content);
// }
// return true;
//}
//public bool ShouldSerializeContentHasToken()
//{
// return ((this.WebPartDefault._contentHasToken != this._contentHasToken) && !base.SerializeAll);
//}
//public bool ShouldSerializeContentLink()
//{
// if (!base.SerializeAll)
// {
// return (this.WebPartDefault._contentLink != this._contentLink);
// }
// return true;
//}
public bool ShouldSerializePartStorage()
{
//if (!base.SerializeAll)
//{
//return (this.WebPartDefault._partStorage != this._partStorage);
//}
return true;
}
internal bool ShowContentEditable()
{
return (((SPContext.Current.Web.UIVersion > 3) && (this._partContent == null)) && this.inEditMode());
}
//[XmlElement("ContentHasToken", IsNullable=false), Browsable(false), WebPartStorage(Storage.Shared)]
//public bool ContentHasToken
//{
// get
// {
// return this._contentHasToken;
// }
// set
// {
// this._contentHasToken = value;
// }
//}
//private string EncodedInvalidContentError
//{
// get
// {
// string str2;
// string str = "<a id=\"" + this.ID + "HelpLink\" href=\"javascript:HelpWindowUrl('" + SPHttpUtility.NoEncode("sts/html/dpvwpabt.htm") + "');\">" + SPHttpUtility.HtmlEncode(WebPartPageResource.GetString("InvalidContentErrorHelpLink")) + "</a>";
// if ((this.Context != null) && Utility.BrowserIsIE(this.Context.Request.Browser))
// {
// str2 = "InvalidContentError";
// }
// else
// {
// str2 = "InvalidContentErrorDL";
// }
// return ("<p><div class=\"UserGeneric\">" + string.Format(CultureInfo.InvariantCulture, SPHttpUtility.HtmlEncodeAllowSimpleTextFormatting(WebPartPageResource.GetString(str2)), new object[] { str }) + "</div></p>");
// }
//}
[Resources("PartStorageLiteral", "Advanced", "PartStorage"), WebPartStorage(Storage.Personal), XmlElement("PartStorage", IsNullable=false)]
public string PartStorage
{
get
{
//return Utility.GetMemberString(this._partStorage);
return this._partStorage ?? String.Empty;
}
set
{
//Utility.SetMemberString(ref this._partStorage, value);
if (value != null && value.Length > 0)
{
this._partStorage = value;
}
else
{
this._partStorage = null;
}
}
}
//internal ContentEditorWebPart WebPartDefault
//{
// get
// {
// return (ContentEditorWebPart) base.WebPartDefault;
// }
//}
}
}
Think this may solve your problem - you were on the right track when you got Reflector out :)
http://zootfroot.blogspot.com/2010/09/develop-custom-editable-visual-web-part.html
You can use ControlAdapter, as described in this article: http://blog.mastykarz.nl/inconvenient-content-editor-web-part/
Why not create a "Visual Web Part" and use a rich text editor (like Telerik or others)? I think trying to reverse engineer the code for CEWP is probably overkill and probably against SharePoint's license.

Categories