Topics:
Higher Calling Functions
Lazy Code
Asynch and Parallel
static void Main(string[] args)
{
var elapsed = Measure(() =>
{
var numbers = new[]{3, 5, 7, 9, 11, 13};
foreach(var prime in numbers.Find(IsPrime).Take(2))
{
Console.WriteLine(prime);
}
});
Console.WriteLine(elapsed);
//Parallel
Parallel.Invoke(new Action[]
{
() => FindLargePrimes(3,100),
() => FindLargePrimes(101,200)
});
//Task
var task = new Task<IEnumerable<int>>(
() => FindLargePrimes(3,100)
);
var task2 = task.ContinueWith((antecedent) =>
{
foreach(var number in antecedent.Result)
{
Console.WriteLine(number);
}
});
task.Start();
Console.WriteLine("Doing other work");
task2.Wait();
}
private static IEnumerable<int> Find(this IEnumerable<int> values, Func<int, bool> test)
{
foreach(var number in values)
{
if(test(number))
{
yield return number;
}
}
}
private static bool IsPrime(int number) [...]
private TimeSpan Measure(Action action)
{
var watch = new StopWatch();
watch.start();
action();
return watch.Elapsed;
}
Reference: Scott Allen's C# Fundamentals - Part 2
Wednesday, March 20, 2013
Thursday, March 14, 2013
Dynamic C#
using System.Dynamic;
public class Employee
{
public string FirstName {get; set;}
public void Speak()
{
Console.WriteLine("Hi, my name is {0}", FirstName);
}
}
class Program
{
static void Main(string[] args)
{
//old method
object o = GetASpeaker();
o.GetType().GetMethod("Speak").Invoke(0, null);
//dynamic object
dynamic o = GetASpeaker();
o.Speak();
//loading 3rd-party assembly and dynamic object
Type dogType = Assembly.Load("Dogs").GetType("Dog");
dynamic dog = Activator.CreateInstance(dogType);
dog.Speak();
//excel automation and dynamic object
Type excelType = Type.GetTypeFromProgId("Excel.Application");
dynamic excel = Activator.CreateInstance(excelType);
excel.Visible = true;
excel.Workbooks.Add();
dynamic sheet = excel.ActiveSheet;
Process[] processes = Process.GetProcesses();
for(int i = 0; i < processes.Length; i++)
{
sheet.Cells[i+1, "A"] = processes[i].ProcessName;
sheet.Cells[i+1, "B"] = processes[i].Threads.Count;
}
//expandoobject
dynamic expando = new ExpandoObject();
//or, dynamic expando = new ExpandoObject() as IDictionary<string, object>;
expando.Name = "The";
//or, expando["Name"] = "The"
expando.Speak = new Action(() => Console.WriteLine(expando.Name));
foreach(var member in expando)
{
Console.WriteLine(member.Key);
}
expando.Speak();
//implements dynamicobject interface
dynamic doc = new DynamicXml("Employees.xml");
foreach(var employee in doc.Employees)
{
Console.WriteLine(employee.FirstName);
}
//C# and IronRuby interaction
// running .rb file with passed c# object
var engine = IronRuby.Ruby.CreateEngine();
var scope = engine.CreateScope();
scope.SetVariable("employee", new Employee { FirstName = "The C#"});
engine.ExecuteFile("Program.rb", scope);
// instantiates classes from .rb file in c# code
dynamic ruby = engine.Runtime.Globals;
dynamic person = ruby.Person.@new();
person.firstName = "The Ruby";
person.speak();
}
private static object GetASpeaker()
{
return new Employee { FirstName = "Scott" };
}
}
internal class DynamicXml : System.Dynamic.DynamicObject, System.Collections.IEnumerable
{
private dynamic _xml;
public DynamicXml(string fileName)
{
_xml = XDocument.Load(fileName);
}
public DynamicXml(dynamic xml)
{
_xml = xml;
}
public override bool TryGetMember(GetMemberBinder binder, out object results)
{
var xml = _xml.Element(binder.Name);
if(xml != null)
{
result = new DynamicXml(xml);
return true;
}
result = null;
return false;
}
public IEnumerator GetEnumerator()
{
foreach(var child in _xml.Elements())
{
yield return new DynamicXml(child);
}
}
}
Program.rb
class Person
attr_accessor :firstName
def speak
puts @firstName
end
end
employee.Speak
Reference: Scott Allen's C# Fundamentals Part 2
public class Employee
{
public string FirstName {get; set;}
public void Speak()
{
Console.WriteLine("Hi, my name is {0}", FirstName);
}
}
class Program
{
static void Main(string[] args)
{
//old method
object o = GetASpeaker();
o.GetType().GetMethod("Speak").Invoke(0, null);
//dynamic object
dynamic o = GetASpeaker();
o.Speak();
//loading 3rd-party assembly and dynamic object
Type dogType = Assembly.Load("Dogs").GetType("Dog");
dynamic dog = Activator.CreateInstance(dogType);
dog.Speak();
//excel automation and dynamic object
Type excelType = Type.GetTypeFromProgId("Excel.Application");
dynamic excel = Activator.CreateInstance(excelType);
excel.Visible = true;
excel.Workbooks.Add();
dynamic sheet = excel.ActiveSheet;
Process[] processes = Process.GetProcesses();
for(int i = 0; i < processes.Length; i++)
{
sheet.Cells[i+1, "A"] = processes[i].ProcessName;
sheet.Cells[i+1, "B"] = processes[i].Threads.Count;
}
//expandoobject
dynamic expando = new ExpandoObject();
//or, dynamic expando = new ExpandoObject() as IDictionary<string, object>;
expando.Name = "The";
//or, expando["Name"] = "The"
expando.Speak = new Action(() => Console.WriteLine(expando.Name));
foreach(var member in expando)
{
Console.WriteLine(member.Key);
}
expando.Speak();
//implements dynamicobject interface
dynamic doc = new DynamicXml("Employees.xml");
foreach(var employee in doc.Employees)
{
Console.WriteLine(employee.FirstName);
}
//C# and IronRuby interaction
// running .rb file with passed c# object
var engine = IronRuby.Ruby.CreateEngine();
var scope = engine.CreateScope();
scope.SetVariable("employee", new Employee { FirstName = "The C#"});
engine.ExecuteFile("Program.rb", scope);
// instantiates classes from .rb file in c# code
dynamic ruby = engine.Runtime.Globals;
dynamic person = ruby.Person.@new();
person.firstName = "The Ruby";
person.speak();
}
private static object GetASpeaker()
{
return new Employee { FirstName = "Scott" };
}
}
internal class DynamicXml : System.Dynamic.DynamicObject, System.Collections.IEnumerable
{
private dynamic _xml;
public DynamicXml(string fileName)
{
_xml = XDocument.Load(fileName);
}
public DynamicXml(dynamic xml)
{
_xml = xml;
}
public override bool TryGetMember(GetMemberBinder binder, out object results)
{
var xml = _xml.Element(binder.Name);
if(xml != null)
{
result = new DynamicXml(xml);
return true;
}
result = null;
return false;
}
public IEnumerator GetEnumerator()
{
foreach(var child in _xml.Elements())
{
yield return new DynamicXml(child);
}
}
}
Program.rb
class Person
attr_accessor :firstName
def speak
puts @firstName
end
end
employee.Speak
Reference: Scott Allen's C# Fundamentals Part 2
Tuesday, March 12, 2013
C# Delegate, Func, Action, and Extension Method
IEnumerable<string> cities = new[]{"Falls Church", "Annandale", "Reston"};
//delegate 1
IEnumerable<string> query = cities.Filter(StringThatStartWithA);
//delegate 2
IEnumerable<string> query2 = cities.Filter(delegate(string item)
{
return item.StartsWith("A");
});
//expression method
IEnumerable<string> query3 = cities.Filter((item) => item.StartsWith("A"));
static bool StringThatStartWithA(string s)
{
return s.StartWith("A");
}
public static IEnumerable<T> Filter<T> (this IEnumerable<T> input, FilterDelegate<T> predicate)
{
foreach(var item in input)
{
if(predicate(item))
{
yield return item;
}
}
}
//or, FilterDelegate<T> predicate can be replaced by Func<T, bool> predicate
//Func returns a value while Action does not
//ex:
//Func<int, int> square = x => x*x;
//Func<int, int, int> add = (x,y) => x+y;
//Action<int> write = x => Console.WriteLine(x);
//write(square(add(1,3)));
public delegate bool FilterDelegate<T>(T item);
//delegate 1
IEnumerable<string> query = cities.Filter(StringThatStartWithA);
//delegate 2
IEnumerable<string> query2 = cities.Filter(delegate(string item)
{
return item.StartsWith("A");
});
//expression method
IEnumerable<string> query3 = cities.Filter((item) => item.StartsWith("A"));
static bool StringThatStartWithA(string s)
{
return s.StartWith("A");
}
public static IEnumerable<T> Filter<T> (this IEnumerable<T> input, FilterDelegate<T> predicate)
{
foreach(var item in input)
{
if(predicate(item))
{
yield return item;
}
}
}
//or, FilterDelegate<T> predicate can be replaced by Func<T, bool> predicate
//Func returns a value while Action does not
//ex:
//Func<int, int> square = x => x*x;
//Func<int, int, int> add = (x,y) => x+y;
//Action<int> write = x => Console.WriteLine(x);
//write(square(add(1,3)));
public delegate bool FilterDelegate<T>(T item);
Ninject Basics
using Ninject;
class Program
{
static void Main(string[] args)
{
var kernel = new StandardKernel();
//or, passes in an instance of a class that implements NinjectModule interface
//var kernel = new StandardKernel(new MyModule());
//manages object lifetime using .InScope(), .InSingletonScope(), InThreadScope(), InTransientScope()
//.InSingletonScope: shopper and shopper2 are the same object
kernel.Bind<ICreditCard>().To<MasterCard>().InSingletonScope();
//or, gives binding a name if there are multiple bindings to ICreditCard
//kernel.Bind<ICreditCard>().To<MasterCard>().Named("MasterCard");
//kernel.Get<ICreditCard>("MasterCard");
//or, bind to method
/*
kernel.Bind<ICreditCard>().ToMethod(context =>
{
Console.WriteLine("Creating new card");
return new MasterCard();
});
*/
//could rebind ICreditCard to Visa after MasterCard
//kernel.Rebind<ICreditCard>().To<Visa>();
//no need to bind Shopper class to itself, Ninject takes care of bindings automatically
var shopper = kernel.Get<Shopper>();
shopper.Charge();
Console.WriteLine(shopper.ChargesForCurrentCard);
var shopper2 = kernel.Get<Shopper>();
shopper2.Charge();
Console.WriteLine(shopper2.ChargesForCurrentCard);
Console.Read();
}
}
public class MyModule : NinjectModule
{
public override void Load()
{
Kernel.Bind<ICreditCard>().To<MasterCard>();
}
}
Reference: John Sonmez's IoC Course on Pluralsight
class Program
{
static void Main(string[] args)
{
var kernel = new StandardKernel();
//or, passes in an instance of a class that implements NinjectModule interface
//var kernel = new StandardKernel(new MyModule());
//manages object lifetime using .InScope(), .InSingletonScope(), InThreadScope(), InTransientScope()
//.InSingletonScope: shopper and shopper2 are the same object
kernel.Bind<ICreditCard>().To<MasterCard>().InSingletonScope();
//or, gives binding a name if there are multiple bindings to ICreditCard
//kernel.Bind<ICreditCard>().To<MasterCard>().Named("MasterCard");
//kernel.Get<ICreditCard>("MasterCard");
//or, bind to method
/*
kernel.Bind<ICreditCard>().ToMethod(context =>
{
Console.WriteLine("Creating new card");
return new MasterCard();
});
*/
//could rebind ICreditCard to Visa after MasterCard
//kernel.Rebind<ICreditCard>().To<Visa>();
//no need to bind Shopper class to itself, Ninject takes care of bindings automatically
var shopper = kernel.Get<Shopper>();
shopper.Charge();
Console.WriteLine(shopper.ChargesForCurrentCard);
var shopper2 = kernel.Get<Shopper>();
shopper2.Charge();
Console.WriteLine(shopper2.ChargesForCurrentCard);
Console.Read();
}
}
public class MyModule : NinjectModule
{
public override void Load()
{
Kernel.Bind<ICreditCard>().To<MasterCard>();
}
}
Reference: John Sonmez's IoC Course on Pluralsight
Monday, March 11, 2013
Getting TeamCity Build Number with MSBuild
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Version>$(BUILD_NUMBER)</Version>
<SourceXMLFile>..\src\UNNAMED.Web\web.config</SourceXMLFile>
<DestXMLFile>..\src\UNNAMED.Web\web.config</DestXMLFile>
</PropertyGroup>
<ItemGroup>
<XmlConfigUpdates Include="ConfigUpdates-WebConfig">
<XPath>/configuration/appSettings/add[@key='BuildNumber']/@value</XPath>
<NewValue>$(Version)</NewValue>
</XmlConfigUpdates>
<BuildArtifacts Include=".\buildartifacts\"/>
<SolutionFile Include="..\src\UNNAMED.sln"/>
</ItemGroup>
<Target Name="UpdateWebConfig">
<Message Text="Updating Web.config"/>
<Copy SourceFiles="$(SourceXMLFile)" DestinationFiles="$(DestXMLFile)"/>
<XmlPoke XmlInputPath="$(DestXMLFile)" Query="%(XmlConfigUpdates.XPath)" Value="%(XmlConfigUpdates.NewValue)"/>
</Target>
<Target Name="Clean">
<RemoveDir Directories="@(BuildArtifacts)"/>
</Target>
<Target Name="Init" DependsOnTargets="Clean">
<MakeDir Directories="@(BuildArtifacts)"/>
</Target>
<Target Name="Compile" DependsOnTargets="Init; UpdateWebConfig">
<MSBuild Projects="@(SolutionFile)" Properties="OutDir=%(BuildArtifacts.FullPath);Configuration=$(Configuration)"/>
</Target>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Version>$(BUILD_NUMBER)</Version>
<SourceXMLFile>..\src\UNNAMED.Web\web.config</SourceXMLFile>
<DestXMLFile>..\src\UNNAMED.Web\web.config</DestXMLFile>
</PropertyGroup>
<ItemGroup>
<XmlConfigUpdates Include="ConfigUpdates-WebConfig">
<XPath>/configuration/appSettings/add[@key='BuildNumber']/@value</XPath>
<NewValue>$(Version)</NewValue>
</XmlConfigUpdates>
<BuildArtifacts Include=".\buildartifacts\"/>
<SolutionFile Include="..\src\UNNAMED.sln"/>
</ItemGroup>
<Target Name="UpdateWebConfig">
<Message Text="Updating Web.config"/>
<Copy SourceFiles="$(SourceXMLFile)" DestinationFiles="$(DestXMLFile)"/>
<XmlPoke XmlInputPath="$(DestXMLFile)" Query="%(XmlConfigUpdates.XPath)" Value="%(XmlConfigUpdates.NewValue)"/>
</Target>
<Target Name="Clean">
<RemoveDir Directories="@(BuildArtifacts)"/>
</Target>
<Target Name="Init" DependsOnTargets="Clean">
<MakeDir Directories="@(BuildArtifacts)"/>
</Target>
<Target Name="Compile" DependsOnTargets="Init; UpdateWebConfig">
<MSBuild Projects="@(SolutionFile)" Properties="OutDir=%(BuildArtifacts.FullPath);Configuration=$(Configuration)"/>
</Target>
Programming IoC Container
class Program
{
static void Main(string[] args){
Resolver resolver = new Resolver();
resolver.Register<Shopper, Shopper>();
resolver.Register<ICreditCard, MasterCard>();
var shoper = resolver.Resolve<Shopper>();
shopper.Charge();
Console.Read();
}
}
public class Resolver
{
private Dictionary<Type, Type> dependencyMap = new Dictionary<Type, Type>();
public T Resolve<T>()
{
return (T)Resolve(typeof(T));
private object Resolve(Type typeToResolve)
{
Type resolvedType = null;
try{
resolvedType = dependencyMap[typeToResolve];
}
catch
{
throw new Exception(string.Format("Could not resolve type {0}", typeToResolve.FullName));
}
var firstConstructor = resolvedType.GetConstructors().First();
var constructorParameters = firstConstructor.GetParameters();
if(constructorParameters.Count() == 0)
return Activator.CreateInstance(resolvedType);
IList<object> parameters = new List<object>();
foreach(var parameterToResolve in constructorParameters)
{
parameters.Add(Resolve(parameterToResolve.ParameterType);
}
return firstConstructor.Invoke(parameters.ToArray());
}
public void Register<TFrom, TTo>()
{
dependencyMap.Add(typeof(TFrom), typeof(TTo));
}
}
public class Visa : ICreditCard
{
public string Charge()
{
return "Charging with the Visa!";
}
}
public class MasterCard : ICreditCard
{
public string Charge()
{
return "Charging with the MasterCard!";
}
}
public interface ICreditCard
{
string Charge();
}
}
Reference: Pluralsight course on Inversion of Control by John Sonmez
{
static void Main(string[] args){
Resolver resolver = new Resolver();
resolver.Register<Shopper, Shopper>();
resolver.Register<ICreditCard, MasterCard>();
var shoper = resolver.Resolve<Shopper>();
shopper.Charge();
Console.Read();
}
}
public class Resolver
{
private Dictionary<Type, Type> dependencyMap = new Dictionary<Type, Type>();
public T Resolve<T>()
{
return (T)Resolve(typeof(T));
private object Resolve(Type typeToResolve)
{
Type resolvedType = null;
try{
resolvedType = dependencyMap[typeToResolve];
}
catch
{
throw new Exception(string.Format("Could not resolve type {0}", typeToResolve.FullName));
}
var firstConstructor = resolvedType.GetConstructors().First();
var constructorParameters = firstConstructor.GetParameters();
if(constructorParameters.Count() == 0)
return Activator.CreateInstance(resolvedType);
IList<object> parameters = new List<object>();
foreach(var parameterToResolve in constructorParameters)
{
parameters.Add(Resolve(parameterToResolve.ParameterType);
}
return firstConstructor.Invoke(parameters.ToArray());
}
public void Register<TFrom, TTo>()
{
dependencyMap.Add(typeof(TFrom), typeof(TTo));
}
}
public class Visa : ICreditCard
{
public string Charge()
{
return "Charging with the Visa!";
}
}
public class MasterCard : ICreditCard
{
public string Charge()
{
return "Charging with the MasterCard!";
}
}
public interface ICreditCard
{
string Charge();
}
}
Reference: Pluralsight course on Inversion of Control by John Sonmez
Saturday, March 9, 2013
Wednesday, March 6, 2013
List Cycler with jQuery
<ul id="posts">
<li><label>Title 1</label>Description</li>
<li><label>Title 2</label>Description</li>
<li><label>Title 3</label>Description</li>
</ul>
Javascript function method
var cycler = function(){
var firstPost;
removeFirst = function(){
firstPost = $("#posts li:first");
firstPost.fadeOut(appendToEnd);
};
appendToEnd = function(post){
firstPost.remove();
$("#posts").append(firstPost);
};
return{
removeFirst : removeFirst,
appendToEnd : appendToEnd
}
}();
$(function(){
$("#cycler").click(function(){
cycler.removeFirst();
});
});
Javascript class method
var ListCycler = function(parentContainer){
var listContainer = $(parentContainer);var firstPost = $(parentContainer + " li:first");
cycle = function(){
firstPost.fadeOut(appendToEnd);
};
appendToEnd = function(post){
firstPost.remove();
listContainer.append(firstPost);
firstPost.fadeIn();
};
return{
cycle : cycle
}
};
$(function(){
$("#cycle").click(function(){
var cycler = new ListCycler("#posts");
cycler.cycle();
});
});
Reference: http://vimeo.com/47483575
Tuesday, March 5, 2013
Create Bootable Disk with ImgBurn
http://www.imgburn.com/index.php?act=download
http://www.allbootdisks.com/ (Choose .img for bootable disk)
Friday, March 1, 2013
Enable NetFX3 in Windows Server 2012
C:\Users\Administrator>dism.exe /online /enable-feature /featurename:NetFX3Serve
rFeatures /Source:e:\sources\sxs /LimitAccess
Deployment Image Servicing and Management tool
Version: 6.2.9200.16384
Image Version: 6.2.9200.16384
Enabling feature(s)
[==========================100.0%==========================]
The operation completed successfully.
C:\Users\Administrator>dism.exe /online /enable-feature /featurename:NetFX3 /Sou
rce:e:\sources\sxs /LimitAccess
Deployment Image Servicing and Management tool
Version: 6.2.9200.16384
Image Version: 6.2.9200.16384
Enabling feature(s)
[==========================100.0%==========================]
The operation completed successfully.
rFeatures /Source:e:\sources\sxs /LimitAccess
Deployment Image Servicing and Management tool
Version: 6.2.9200.16384
Image Version: 6.2.9200.16384
Enabling feature(s)
[==========================100.0%==========================]
The operation completed successfully.
C:\Users\Administrator>dism.exe /online /enable-feature /featurename:NetFX3 /Sou
rce:e:\sources\sxs /LimitAccess
Deployment Image Servicing and Management tool
Version: 6.2.9200.16384
Image Version: 6.2.9200.16384
Enabling feature(s)
[==========================100.0%==========================]
The operation completed successfully.
Thursday, February 28, 2013
Issue arises after fresh install of Windows Server 2012 and SQL Server 2012
What could possibly have caused this error?
Server Error in '/' Application.
Could not load file or assembly 'AjaxControlToolkit' or one of its dependencies. Access is denied.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.IO.FileLoadException: Could not load file or assembly 'AjaxControlToolkit' or one of its dependencies. Access is denied.
Source Error:
An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.
Assembly Load Trace: The following information can be helpful to determine why the assembly 'AjaxControlToolkit' could not be loaded.
WRN: Assembly binding logging is turned OFF. To enable assembly bind failure logging, set the registry value [HKLM\Software\Microsoft\Fusion!EnableLog] (DWORD) to 1. Note: There is some performance penalty associated with assembly bind failure logging. To turn this feature off, remove the registry value [HKLM\Software\Microsoft\Fusion!EnableLog].
Stack Trace:
[FileLoadException: Could not load file or assembly 'AjaxControlToolkit' or one of its dependencies. Access is denied.] System.Reflection.RuntimeAssembly._nLoad(AssemblyName fileName, String codeBase, Evidence assemblySecurity, RuntimeAssembly locationHint, StackCrawlMark& stackMark, IntPtr pPrivHostBinder, Boolean throwOnFileNotFound, Boolean forIntrospection, Boolean suppressSecurityChecks) +0 System.Reflection.RuntimeAssembly.InternalLoadAssemblyName(AssemblyName assemblyRef, Evidence assemblySecurity, RuntimeAssembly reqAssembly, StackCrawlMark& stackMark, IntPtr pPrivHostBinder, Boolean throwOnFileNotFound, Boolean forIntrospection, Boolean suppressSecurityChecks) +210 System.Reflection.RuntimeAssembly.InternalLoad(String assemblyString, Evidence assemblySecurity, StackCrawlMark& stackMark, IntPtr pPrivHostBinder, Boolean forIntrospection) +242 System.Reflection.RuntimeAssembly.InternalLoad(String assemblyString, Evidence assemblySecurity, StackCrawlMark& stackMark, Boolean forIntrospection) +17 System.Reflection.Assembly.Load(String assemblyString) +35 System.Web.Configuration.CompilationSection.LoadAssemblyHelper(String assemblyName, Boolean starDirective) +122 [ConfigurationErrorsException: Could not load file or assembly 'AjaxControlToolkit' or one of its dependencies. Access is denied.] System.Web.Configuration.CompilationSection.LoadAssemblyHelper(String assemblyName, Boolean starDirective) +12759734 System.Web.Configuration.CompilationSection.LoadAllAssembliesFromAppDomainBinDirectory() +503 System.Web.Configuration.AssemblyInfo.get_AssemblyInternal() +142 System.Web.Compilation.BuildManager.GetReferencedAssemblies(CompilationSection compConfig) +334 System.Web.Compilation.BuildManager.CallPreStartInitMethods(String preStartInitListPath) +203 System.Web.Compilation.BuildManager.ExecutePreAppStart() +152 System.Web.Hosting.HostingEnvironment.Initialize(ApplicationManager appManager, IApplicationHost appHost, IConfigMapPathFactory configMapPathFactory, HostingEnvironmentParameters hostingParameters, PolicyLevel policyLevel, Exception appDomainCreationException) +1151 [HttpException (0x80004005): Could not load file or assembly 'AjaxControlToolkit' or one of its dependencies. Access is denied.] System.Web.HttpRuntime.FirstRequestInit(HttpContext context) +12880068 System.Web.HttpRuntime.EnsureFirstRequestInit(HttpContext context) +159 System.Web.HttpRuntime.ProcessRequestNotificationPrivate(IIS7WorkerRequest wr, HttpContext context) +12721257
Version Information: Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.0.30319.18033
Server Error in '/' Application.
Could not load file or assembly 'AjaxControlToolkit' or one of its dependencies. Access is denied.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.IO.FileLoadException: Could not load file or assembly 'AjaxControlToolkit' or one of its dependencies. Access is denied.
Source Error:
An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.
Assembly Load Trace: The following information can be helpful to determine why the assembly 'AjaxControlToolkit' could not be loaded.
WRN: Assembly binding logging is turned OFF. To enable assembly bind failure logging, set the registry value [HKLM\Software\Microsoft\Fusion!EnableLog] (DWORD) to 1. Note: There is some performance penalty associated with assembly bind failure logging. To turn this feature off, remove the registry value [HKLM\Software\Microsoft\Fusion!EnableLog].
Stack Trace:
[FileLoadException: Could not load file or assembly 'AjaxControlToolkit' or one of its dependencies. Access is denied.] System.Reflection.RuntimeAssembly._nLoad(AssemblyName fileName, String codeBase, Evidence assemblySecurity, RuntimeAssembly locationHint, StackCrawlMark& stackMark, IntPtr pPrivHostBinder, Boolean throwOnFileNotFound, Boolean forIntrospection, Boolean suppressSecurityChecks) +0 System.Reflection.RuntimeAssembly.InternalLoadAssemblyName(AssemblyName assemblyRef, Evidence assemblySecurity, RuntimeAssembly reqAssembly, StackCrawlMark& stackMark, IntPtr pPrivHostBinder, Boolean throwOnFileNotFound, Boolean forIntrospection, Boolean suppressSecurityChecks) +210 System.Reflection.RuntimeAssembly.InternalLoad(String assemblyString, Evidence assemblySecurity, StackCrawlMark& stackMark, IntPtr pPrivHostBinder, Boolean forIntrospection) +242 System.Reflection.RuntimeAssembly.InternalLoad(String assemblyString, Evidence assemblySecurity, StackCrawlMark& stackMark, Boolean forIntrospection) +17 System.Reflection.Assembly.Load(String assemblyString) +35 System.Web.Configuration.CompilationSection.LoadAssemblyHelper(String assemblyName, Boolean starDirective) +122 [ConfigurationErrorsException: Could not load file or assembly 'AjaxControlToolkit' or one of its dependencies. Access is denied.] System.Web.Configuration.CompilationSection.LoadAssemblyHelper(String assemblyName, Boolean starDirective) +12759734 System.Web.Configuration.CompilationSection.LoadAllAssembliesFromAppDomainBinDirectory() +503 System.Web.Configuration.AssemblyInfo.get_AssemblyInternal() +142 System.Web.Compilation.BuildManager.GetReferencedAssemblies(CompilationSection compConfig) +334 System.Web.Compilation.BuildManager.CallPreStartInitMethods(String preStartInitListPath) +203 System.Web.Compilation.BuildManager.ExecutePreAppStart() +152 System.Web.Hosting.HostingEnvironment.Initialize(ApplicationManager appManager, IApplicationHost appHost, IConfigMapPathFactory configMapPathFactory, HostingEnvironmentParameters hostingParameters, PolicyLevel policyLevel, Exception appDomainCreationException) +1151 [HttpException (0x80004005): Could not load file or assembly 'AjaxControlToolkit' or one of its dependencies. Access is denied.] System.Web.HttpRuntime.FirstRequestInit(HttpContext context) +12880068 System.Web.HttpRuntime.EnsureFirstRequestInit(HttpContext context) +159 System.Web.HttpRuntime.ProcessRequestNotificationPrivate(IIS7WorkerRequest wr, HttpContext context) +12721257
Version Information: Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.0.30319.18033
Wednesday, January 30, 2013
MCSD: Web Applications Solutions Developer
Exam 70-480: Programming in HTML5 with JavaScript and CSS3 (Publication Date: April 22, 2013)
Exam 70-486: Developing ASP.NET MVC 4 Web Applications (Publication Date: May 22, 2013)
Exam Ref 70-487: Developing Windows Azure and Web Services (Publication Date: June 22, 2013)
Exam 70-486: Developing ASP.NET MVC 4 Web Applications (Publication Date: May 22, 2013)
Exam Ref 70-487: Developing Windows Azure and Web Services (Publication Date: June 22, 2013)
Saturday, January 5, 2013
EF Unit of Work and Repository Pattern
GenericRepository.cs
namespace SCNData
{
public class GenericRepository<TEntity> where TEntity : class
{
internal NhacContext context;
internal DbSet<TEntity> dbSet;
public GenericRepository(NhacContext context)
{
this.context = context;
this.dbSet = context.Set<TEntity>();
}
public virtual IEnumerable<TEntity> Get(
Expression<Func<TEntity, bool>> filter = null,
Func<IQueryable<TEntity>, IOrderedQueryable<TEntity>> orderBy = null,
string includeProperties = "")
{
IQueryable<TEntity> query = dbSet;
if (filter != null)
{
query = query.Where(filter);
}
foreach (var includeProperty in includeProperties.Split
(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries))
{
query = query.Include(includeProperty);
}
if (orderBy != null)
{
return orderBy(query).ToList();
}
else
{
return query.ToList();
}
}
public virtual TEntity GetByID(object id)
{
return dbSet.Find(id);
}
public virtual void Insert(TEntity entity)
{
dbSet.Add(entity);
}
public virtual void Delete(object id)
{
TEntity entityToDelete = dbSet.Find(id);
Delete(entityToDelete);
}
public virtual void Delete(TEntity entityToDelete)
{
if (context.Entry(entityToDelete).State == EntityState.Detached)
{
dbSet.Attach(entityToDelete);
}
dbSet.Remove(entityToDelete);
}
public virtual void Update(TEntity entityToUpdate)
{
dbSet.Attach(entityToUpdate);
context.Entry(entityToUpdate).State = EntityState.Modified;
}
}
}
UnitOfWork.cs
namespace SCNData
{
public class UnitOfWork : IDisposable
{
private NhacContext context = new NhacContext();
private GenericRepository<Performer> performerRepository;
public GenericRepository<Performer> PerformerRepository
{
get
{
if (this.performerRepository == null)
{
this.performerRepository = new GenericRepository<Performer>(context);
}
return performerRepository;
}
}
public void Save()
{
context.SaveChanges();
}
private bool disposed = false;
protected virtual void Dispose(bool disposing)
{
if (!this.disposed)
{
if (disposing)
{
context.Dispose();
}
}
this.disposed = true;
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
}
}
namespace SCNData
{
public class GenericRepository<TEntity> where TEntity : class
{
internal NhacContext context;
internal DbSet<TEntity> dbSet;
public GenericRepository(NhacContext context)
{
this.context = context;
this.dbSet = context.Set<TEntity>();
}
public virtual IEnumerable<TEntity> Get(
Expression<Func<TEntity, bool>> filter = null,
Func<IQueryable<TEntity>, IOrderedQueryable<TEntity>> orderBy = null,
string includeProperties = "")
{
IQueryable<TEntity> query = dbSet;
if (filter != null)
{
query = query.Where(filter);
}
foreach (var includeProperty in includeProperties.Split
(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries))
{
query = query.Include(includeProperty);
}
if (orderBy != null)
{
return orderBy(query).ToList();
}
else
{
return query.ToList();
}
}
public virtual TEntity GetByID(object id)
{
return dbSet.Find(id);
}
public virtual void Insert(TEntity entity)
{
dbSet.Add(entity);
}
public virtual void Delete(object id)
{
TEntity entityToDelete = dbSet.Find(id);
Delete(entityToDelete);
}
public virtual void Delete(TEntity entityToDelete)
{
if (context.Entry(entityToDelete).State == EntityState.Detached)
{
dbSet.Attach(entityToDelete);
}
dbSet.Remove(entityToDelete);
}
public virtual void Update(TEntity entityToUpdate)
{
dbSet.Attach(entityToUpdate);
context.Entry(entityToUpdate).State = EntityState.Modified;
}
}
}
UnitOfWork.cs
namespace SCNData
{
public class UnitOfWork : IDisposable
{
private NhacContext context = new NhacContext();
private GenericRepository<Performer> performerRepository;
public GenericRepository<Performer> PerformerRepository
{
get
{
if (this.performerRepository == null)
{
this.performerRepository = new GenericRepository<Performer>(context);
}
return performerRepository;
}
}
public void Save()
{
context.SaveChanges();
}
private bool disposed = false;
protected virtual void Dispose(bool disposing)
{
if (!this.disposed)
{
if (disposing)
{
context.Dispose();
}
}
this.disposed = true;
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
}
}
EF Repository Pattern
IPerformerRepository.cs
namespace SCNData
{
public interface IPerformerRepository : IDisposable
{
IEnumerable<Performer> GetPerformers();
Performer GetPerformerByID(int performerId);
void InsertPerformer(Performer performer);
void DeletePerformer(int performerID);
void UpdatePerformer(Performer performer);
void Save();
}
}
PerformerRepository.cs
namespace SCNData
{
public class PerformerRepository : IPerformerRepository, IDisposable
{
private NhacContext context;
public PerformerRepository(NhacContext context)
{
this.context = context;
}
public IEnumerable<Performer> GetPerformers()
{
return context.Performers.ToList();
}
public Performer GetPerformerByID(int id)
{
return context.Performers.Find(id);
}
public void InsertPerformer(Performer performer)
{
context.Performers.Add(performer);
}
public void DeletePerformer(int performerId)
{
Performer performer = context.Performers.Find(performerId);
context.Performers.Remove(performer);
}
public void UpdatePerformer(Performer performer)
{
context.Entry(performer).State = EntityState.Modified;
}
public void Save()
{
context.SaveChanges();
}
private bool disposed = false;
protected virtual void Dispose(bool disposing)
{
if (!this.disposed)
{
if (disposing)
{
context.Dispose();
}
}
this.disposed = true;
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
}
}
namespace SCNData
{
public interface IPerformerRepository : IDisposable
{
IEnumerable<Performer> GetPerformers();
Performer GetPerformerByID(int performerId);
void InsertPerformer(Performer performer);
void DeletePerformer(int performerID);
void UpdatePerformer(Performer performer);
void Save();
}
}
PerformerRepository.cs
namespace SCNData
{
public class PerformerRepository : IPerformerRepository, IDisposable
{
private NhacContext context;
public PerformerRepository(NhacContext context)
{
this.context = context;
}
public IEnumerable<Performer> GetPerformers()
{
return context.Performers.ToList();
}
public Performer GetPerformerByID(int id)
{
return context.Performers.Find(id);
}
public void InsertPerformer(Performer performer)
{
context.Performers.Add(performer);
}
public void DeletePerformer(int performerId)
{
Performer performer = context.Performers.Find(performerId);
context.Performers.Remove(performer);
}
public void UpdatePerformer(Performer performer)
{
context.Entry(performer).State = EntityState.Modified;
}
public void Save()
{
context.SaveChanges();
}
private bool disposed = false;
protected virtual void Dispose(bool disposing)
{
if (!this.disposed)
{
if (disposing)
{
context.Dispose();
}
}
this.disposed = true;
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
}
}
Friday, December 28, 2012
Java JDBC
ILookup.java
import java.util.List;
public interface ILookup {
void SaveStudentSurveyFormData(StudentBean postData);
StudentBean GetStudentSurveyData(String studentId);
Surveys GetSurveys();
List<String> GetSurveyIds();
}
StudentDbDAO.java
package gmu.swe642.hw6;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
public class StudentDbDAO implements ILookup {
private Connection con;
public StudentDbDAO(){
try {
Class.forName ("oracle.jdbc.driver.OracleDriver");
con = DriverManager.getConnection ( "jdbc:oracle:thin:@",
dbusername, dbpassword);
} catch (SQLException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
public void SaveStudentSurveyFormData(StudentBean postData){
try {
PreparedStatement pstat = con.prepareStatement("insert into survey values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)");
pstat.setString(1, postData.getStudentId());
pstat.setString(2, postData.getFirstName());
pstat.setString(3, postData.getLastName());
pstat.setString(4, postData.getStreet());
pstat.setString(5, postData.getZip());
pstat.setString(6, postData.getCity());
pstat.setString(7, postData.getState());
pstat.setString(8, postData.getTelephone());
pstat.setString(9, postData.getEmail());
pstat.setString(10, postData.getUrl());
pstat.setString(11, postData.getDateOfSurvey());
pstat.setString(12, postData.getGraduationMonth());
pstat.setString(13, postData.getGraduationYear());
pstat.setString(14, postData.getLikes());
pstat.setString(15, postData.getInterests());
pstat.setString(16, postData.getRecommendation());
pstat.setString(17, postData.getComments());
pstat.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}
}
public StudentBean GetStudentSurveyData(String studentId){
Surveys surveys = GetSurveys();
for(StudentBean survey : surveys.data){
if(survey.getStudentId().equalsIgnoreCase(studentId)){
return survey;
}
}
return null;
}
public Surveys GetSurveys(){
Surveys surveys = new Surveys();
surveys.data = new ArrayList<StudentBean>();
Statement stmt;
try {
stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("select * from survey");
while (rs.next())
{
String studentId = rs.getString(Consts.STUDENTID);
String firstName = rs.getString(Consts.FIRSTNAME);
String lastName = rs.getString(Consts.LASTNAME);
String street = rs.getString(Consts.STREET);
String zip = rs.getString(Consts.ZIP);
String city = rs.getString(Consts.CITY);
String state = rs.getString(Consts.STATE);
String telephone = rs.getString(Consts.TELEPHONE);
String email = rs.getString(Consts.EMAIL);
String url = rs.getString(Consts.URL);
String dateOfSurvey = rs.getString(Consts.DATEOFSURVEY);
String graduationMonth = rs.getString(Consts.GRADUATIONMONTH);
String graduationYear = rs.getString(Consts.GRADUATIONYEAR);
String likes = rs.getString(Consts.LIKES);
String interests = rs.getString(Consts.INTERESTS);
String recommendation = rs.getString(Consts.RECOMMENDATION);
String comments = rs.getString(Consts.COMMENTS);
StudentBean s = new StudentBean(studentId, firstName, lastName, street, zip, city, state,
telephone, email, url, dateOfSurvey, graduationMonth,
graduationYear, likes, interests, recommendation, comments);
surveys.data.add(s);
}
} catch (SQLException e) {
e.printStackTrace();
}
return surveys;
}
public List<String> GetSurveyIds(){
List<String> surveyIds = new ArrayList<String>();
Surveys surveys = GetSurveys();
for(StudentBean survey : surveys.data){
surveyIds.add(survey.getStudentId());
}
return surveyIds;
}
}
import java.util.List;
public interface ILookup {
void SaveStudentSurveyFormData(StudentBean postData);
StudentBean GetStudentSurveyData(String studentId);
Surveys GetSurveys();
List<String> GetSurveyIds();
}
StudentDbDAO.java
package gmu.swe642.hw6;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
public class StudentDbDAO implements ILookup {
private Connection con;
public StudentDbDAO(){
try {
Class.forName ("oracle.jdbc.driver.OracleDriver");
con = DriverManager.getConnection ( "jdbc:oracle:thin:@",
dbusername, dbpassword);
} catch (SQLException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
public void SaveStudentSurveyFormData(StudentBean postData){
try {
PreparedStatement pstat = con.prepareStatement("insert into survey values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)");
pstat.setString(1, postData.getStudentId());
pstat.setString(2, postData.getFirstName());
pstat.setString(3, postData.getLastName());
pstat.setString(4, postData.getStreet());
pstat.setString(5, postData.getZip());
pstat.setString(6, postData.getCity());
pstat.setString(7, postData.getState());
pstat.setString(8, postData.getTelephone());
pstat.setString(9, postData.getEmail());
pstat.setString(10, postData.getUrl());
pstat.setString(11, postData.getDateOfSurvey());
pstat.setString(12, postData.getGraduationMonth());
pstat.setString(13, postData.getGraduationYear());
pstat.setString(14, postData.getLikes());
pstat.setString(15, postData.getInterests());
pstat.setString(16, postData.getRecommendation());
pstat.setString(17, postData.getComments());
pstat.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}
}
public StudentBean GetStudentSurveyData(String studentId){
Surveys surveys = GetSurveys();
for(StudentBean survey : surveys.data){
if(survey.getStudentId().equalsIgnoreCase(studentId)){
return survey;
}
}
return null;
}
public Surveys GetSurveys(){
Surveys surveys = new Surveys();
surveys.data = new ArrayList<StudentBean>();
Statement stmt;
try {
stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("select * from survey");
while (rs.next())
{
String studentId = rs.getString(Consts.STUDENTID);
String firstName = rs.getString(Consts.FIRSTNAME);
String lastName = rs.getString(Consts.LASTNAME);
String street = rs.getString(Consts.STREET);
String zip = rs.getString(Consts.ZIP);
String city = rs.getString(Consts.CITY);
String state = rs.getString(Consts.STATE);
String telephone = rs.getString(Consts.TELEPHONE);
String email = rs.getString(Consts.EMAIL);
String url = rs.getString(Consts.URL);
String dateOfSurvey = rs.getString(Consts.DATEOFSURVEY);
String graduationMonth = rs.getString(Consts.GRADUATIONMONTH);
String graduationYear = rs.getString(Consts.GRADUATIONYEAR);
String likes = rs.getString(Consts.LIKES);
String interests = rs.getString(Consts.INTERESTS);
String recommendation = rs.getString(Consts.RECOMMENDATION);
String comments = rs.getString(Consts.COMMENTS);
StudentBean s = new StudentBean(studentId, firstName, lastName, street, zip, city, state,
telephone, email, url, dateOfSurvey, graduationMonth,
graduationYear, likes, interests, recommendation, comments);
surveys.data.add(s);
}
} catch (SQLException e) {
e.printStackTrace();
}
return surveys;
}
public List<String> GetSurveyIds(){
List<String> surveyIds = new ArrayList<String>();
Surveys surveys = GetSurveys();
for(StudentBean survey : surveys.data){
surveyIds.add(survey.getStudentId());
}
return surveyIds;
}
}
Apache Struts with Actions and Form Beans
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
<display-name>swe642hw5khuc</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>action</servlet-name>
<servlet-class>org.apache.struts.action.ActionServlet</servlet-class>
<init-param>
<param-name>config</param-name>
<param-value>/WEB-INF/struts-config.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>action</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
</web-app>
struts-config.xml
<?xml version="1.0" encoding="ISO-8859-1" ?>
<!DOCTYPE struts-config PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 1.3//EN"
"http://struts.apache.org/dtds/struts-config_1_3.dtd">
<struts-config>
<form-beans>
<form-bean name="surveyFormBean" type="package.SurveyFormBean"/>
<form-bean name="surveyLookupFormBean" type="package.SurveyLookupFormBean"/>
</form-beans>
<action-mappings>
<action path="/submitSurvey" type="package.SubmitSurveyAction" name="surveyFormBean" scope="session">
<forward name="simple-ack" path="/jsp/SimpleAcknowledgementJSP.jsp" />
<forward name="winner-ack" path="/jsp/WinnerAcknowledgementJSP.jsp" />
</action>
<action path="/displaySurvey" type="package.DisplaySurveyAction" scope="session">
<forward name="survey-found" path="/jsp/StudentJSP.jsp" />
<forward name="survey-not-found" path="/jsp/NoSuchStudentJSP.jsp" />
</action>
</action-mappings>
</struts-config>
SubmitSurveyAction.java
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
public class SubmitSurveyAction extends Action {
public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response)
throws Exception{
SurveyFormBean formBean = (SurveyFormBean)form;
StudentBean studentBean = new StudentBean(formBean.getStudentId(),formBean.getFirstName(), formBean.getLastName(),
formBean.getStreet(), formBean.getZip(), formBean.getCity(), formBean.getState(),
formBean.getTelephone(), formBean.getEmail(), formBean.getUrl(), formBean.getDateOfSurvey(),
formBean.getGraduationMonth(), formBean.getGraduationYear(), formBean.getLikes(),
formBean.getInterests(), formBean.getRecommendation(), formBean.getComments());
StudentDAO.SaveStudentSurveyFormData(studentBean);
DataBean dataBean = DataProcessor.ComputeMeanAndStandardDeviation(formBean.getData());
List<String> surveyIdsBean = StudentDAO.GetSurveyIds();
HttpSession session = request.getSession();
session.setAttribute("student", studentBean);
session.setAttribute("data", dataBean);
session.setAttribute("surveys", surveyIdsBean);
if(dataBean.getMean() > 90){
return mapping.findForward("winner-ack");
}
return mapping.findForward("simple-ack");
}
}
DisplaySurveyAction.java
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
public class DisplaySurveyAction extends Action {
public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response)
throws Exception{
String studentId = request.getParameter("studentId");
StudentBean studentBean = null;
if(studentId != null){
studentBean = StudentDAO.GetStudentSurveyData(studentId);
}
HttpSession session = request.getSession();
if(studentBean == null){
session.setAttribute("badId", studentId);
return mapping.findForward("survey-not-found");
}
else{
session.setAttribute("student", studentBean);
return mapping.findForward("survey-found");
}
}
}
SurveyFormBean.java
import org.apache.struts.action.ActionForm;
@SuppressWarnings("serial")
public class SurveyFormBean extends ActionForm {
private String studentId;
private String firstName;
private String lastName;
private String street;
private String zip;
private String city;
private String state;
private String telephone;
private String email;
private String url;
private String dateOfSurvey;
private String graduationMonth;
private String graduationYear;
private String[] likes;
private String interests;
private String recommendation;
private String comments;
private String data;
public String getStudentId(){
return this.studentId;
}
public void setStudentId(String studentId){
this.studentId = studentId;
}
public String getFirstName(){
return this.firstName;
}
public void setFirstName(String firstName){
this.firstName = firstName;
}
public String getLastName(){
return this.lastName;
}
public void setLastName(String lastName){
this.lastName = lastName;
}
public String getStreet(){
return this.street;
}
public void setStreet(String street){
this.street = street;
}
public String getZip(){
return this.zip;
}
public void setZip(String zip){
this.zip = zip;
}
public String getCity(){
return this.city;
}
public void setCity(String city){
this.city = city;
}
public String getState(){
return this.state;
}
public void setState(String state){
this.state = state;
}
public String getTelephone(){
return this.telephone;
}
public void setTelephone(String telephone){
this.telephone = telephone;
}
public String getEmail(){
return this.email;
}
public void setEmail(String email){
this.email = email;
}
public String getUrl(){
return this.url;
}
public void setUrl(String url){
this.url = url;
}
public String getDateOfSurvey(){
return this.dateOfSurvey;
}
public void setDateOfSurvey(String dateOfSurvey){
this.dateOfSurvey = dateOfSurvey;
}
public String getGraduationMonth(){
return this.graduationMonth;
}
public void setGraduationMonth(String graduationMonth){
this.graduationMonth = graduationMonth;
}
public String getGraduationYear(){
return this.graduationYear;
}
public void setGraduationYear(String graduationYear){
this.graduationYear = graduationYear;
}
public String[] getLikes(){
return this.likes;
}
public void setLikes(String[] likes){
this.likes = likes;
}
public String getInterests(){
return this.interests;
}
public void setInterests(String interests){
this.interests = interests;
}
public String getRecommendation(){
return this.recommendation;
}
public void setRecommendation(String recommendation){
this.recommendation = recommendation;
}
public String getComments(){
return this.comments;
}
public void setComments(String comments){
this.comments = comments;
}
public String getData(){
return this.data;
}
public void setData(String data){
this.data = data;
}
}
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
<display-name>swe642hw5khuc</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>action</servlet-name>
<servlet-class>org.apache.struts.action.ActionServlet</servlet-class>
<init-param>
<param-name>config</param-name>
<param-value>/WEB-INF/struts-config.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>action</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
</web-app>
struts-config.xml
<?xml version="1.0" encoding="ISO-8859-1" ?>
<!DOCTYPE struts-config PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 1.3//EN"
"http://struts.apache.org/dtds/struts-config_1_3.dtd">
<struts-config>
<form-beans>
<form-bean name="surveyFormBean" type="package.SurveyFormBean"/>
<form-bean name="surveyLookupFormBean" type="package.SurveyLookupFormBean"/>
</form-beans>
<action-mappings>
<action path="/submitSurvey" type="package.SubmitSurveyAction" name="surveyFormBean" scope="session">
<forward name="simple-ack" path="/jsp/SimpleAcknowledgementJSP.jsp" />
<forward name="winner-ack" path="/jsp/WinnerAcknowledgementJSP.jsp" />
</action>
<action path="/displaySurvey" type="package.DisplaySurveyAction" scope="session">
<forward name="survey-found" path="/jsp/StudentJSP.jsp" />
<forward name="survey-not-found" path="/jsp/NoSuchStudentJSP.jsp" />
</action>
</action-mappings>
</struts-config>
SubmitSurveyAction.java
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
public class SubmitSurveyAction extends Action {
public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response)
throws Exception{
SurveyFormBean formBean = (SurveyFormBean)form;
StudentBean studentBean = new StudentBean(formBean.getStudentId(),formBean.getFirstName(), formBean.getLastName(),
formBean.getStreet(), formBean.getZip(), formBean.getCity(), formBean.getState(),
formBean.getTelephone(), formBean.getEmail(), formBean.getUrl(), formBean.getDateOfSurvey(),
formBean.getGraduationMonth(), formBean.getGraduationYear(), formBean.getLikes(),
formBean.getInterests(), formBean.getRecommendation(), formBean.getComments());
StudentDAO.SaveStudentSurveyFormData(studentBean);
DataBean dataBean = DataProcessor.ComputeMeanAndStandardDeviation(formBean.getData());
List<String> surveyIdsBean = StudentDAO.GetSurveyIds();
HttpSession session = request.getSession();
session.setAttribute("student", studentBean);
session.setAttribute("data", dataBean);
session.setAttribute("surveys", surveyIdsBean);
if(dataBean.getMean() > 90){
return mapping.findForward("winner-ack");
}
return mapping.findForward("simple-ack");
}
}
DisplaySurveyAction.java
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
public class DisplaySurveyAction extends Action {
public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response)
throws Exception{
String studentId = request.getParameter("studentId");
StudentBean studentBean = null;
if(studentId != null){
studentBean = StudentDAO.GetStudentSurveyData(studentId);
}
HttpSession session = request.getSession();
if(studentBean == null){
session.setAttribute("badId", studentId);
return mapping.findForward("survey-not-found");
}
else{
session.setAttribute("student", studentBean);
return mapping.findForward("survey-found");
}
}
}
SurveyFormBean.java
import org.apache.struts.action.ActionForm;
@SuppressWarnings("serial")
public class SurveyFormBean extends ActionForm {
private String studentId;
private String firstName;
private String lastName;
private String street;
private String zip;
private String city;
private String state;
private String telephone;
private String email;
private String url;
private String dateOfSurvey;
private String graduationMonth;
private String graduationYear;
private String[] likes;
private String interests;
private String recommendation;
private String comments;
private String data;
public String getStudentId(){
return this.studentId;
}
public void setStudentId(String studentId){
this.studentId = studentId;
}
public String getFirstName(){
return this.firstName;
}
public void setFirstName(String firstName){
this.firstName = firstName;
}
public String getLastName(){
return this.lastName;
}
public void setLastName(String lastName){
this.lastName = lastName;
}
public String getStreet(){
return this.street;
}
public void setStreet(String street){
this.street = street;
}
public String getZip(){
return this.zip;
}
public void setZip(String zip){
this.zip = zip;
}
public String getCity(){
return this.city;
}
public void setCity(String city){
this.city = city;
}
public String getState(){
return this.state;
}
public void setState(String state){
this.state = state;
}
public String getTelephone(){
return this.telephone;
}
public void setTelephone(String telephone){
this.telephone = telephone;
}
public String getEmail(){
return this.email;
}
public void setEmail(String email){
this.email = email;
}
public String getUrl(){
return this.url;
}
public void setUrl(String url){
this.url = url;
}
public String getDateOfSurvey(){
return this.dateOfSurvey;
}
public void setDateOfSurvey(String dateOfSurvey){
this.dateOfSurvey = dateOfSurvey;
}
public String getGraduationMonth(){
return this.graduationMonth;
}
public void setGraduationMonth(String graduationMonth){
this.graduationMonth = graduationMonth;
}
public String getGraduationYear(){
return this.graduationYear;
}
public void setGraduationYear(String graduationYear){
this.graduationYear = graduationYear;
}
public String[] getLikes(){
return this.likes;
}
public void setLikes(String[] likes){
this.likes = likes;
}
public String getInterests(){
return this.interests;
}
public void setInterests(String interests){
this.interests = interests;
}
public String getRecommendation(){
return this.recommendation;
}
public void setRecommendation(String recommendation){
this.recommendation = recommendation;
}
public String getComments(){
return this.comments;
}
public void setComments(String comments){
this.comments = comments;
}
public String getData(){
return this.data;
}
public void setData(String data){
this.data = data;
}
}
StudentDAO with FileReader and FilerWriter
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import com.google.gson.*;
public class StudentDAO {
public static String fileName = "//data//temp//SurveyData.txt";
public static void SaveStudentSurveyFormData(StudentBean postData) throws IOException{
Surveys surveys = GetSurveys();
surveys.data.add(postData);
SaveFile(new Gson().toJson(surveys));
}
public static StudentBean GetStudentSurveyData(String studentId) throws IOException{
Surveys surveys = GetSurveys();
for(StudentBean survey : surveys.data){
if(survey.getStudentId().equalsIgnoreCase(studentId)){
return survey;
}
}
return null;
}
public static Surveys GetSurveys() throws IOException{
Surveys surveys = null;
String fileText = ReadFile();
if(fileText.length() > 0){
surveys = new Gson().fromJson(fileText, Surveys.class);
}
else{
surveys = new Surveys();
surveys.data = new ArrayList<StudentBean>();
}
return surveys;
}
public static List<String> GetSurveyIds() throws IOException{
List<String> surveyIds = new ArrayList<String>();
Surveys surveys = GetSurveys();
for(StudentBean survey : surveys.data){
surveyIds.add(survey.getStudentId());
}
return surveyIds;
}
public static String ReadFile() throws IOException{
BufferedReader file = new BufferedReader(new FileReader(fileName));
String line;
StringBuffer fileText = new StringBuffer();
while((line=file.readLine()) != null){
fileText.append(line);
}
file.close();
return fileText.toString();
}
public static void SaveFile(String fileText) throws IOException{
FileWriter fWriter = new FileWriter(fileName,false);
BufferedWriter writer = new BufferedWriter(fWriter);
fWriter.append(fileText);
writer.flush();
writer.close();
}
}
import java.util.ArrayList;
public class Surveys {
public ArrayList<StudentBean> data;
}
public class StudentBean {
private String studentId;
private String firstName;
private String lastName;
private String street;
private String zip;
private String city;
private String state;
private String telephone;
private String email;
private String url;
private String dateOfSurvey;
private String graduationMonth;
private String graduationYear;
private String likes;
private String interests;
private String recommendation;
private String comments;
public StudentBean(String studentId, String firstName, String lastName, String street, String zip,
String city, String state, String telephone, String email, String url, String dateOfSurvey,
String graduationMonth, String graduationYear, String likes, String interests,
String recommendation, String comments){
this.studentId = studentId;
this.firstName = firstName;
this.lastName = lastName;
this.street = street;
this.zip = zip;
this.city = city;
this.state = state;
this.telephone = telephone;
this.email = email;
this.url = url;
this.dateOfSurvey = dateOfSurvey;
this.graduationMonth = graduationMonth;
this.graduationYear = graduationYear;
this.likes = likes;
this.interests = interests;
this.recommendation = recommendation;
this.comments = comments;
}
public String getStudentId(){
return this.studentId;
}
public String getFirstName(){
return this.firstName;
}
public String getLastName(){
return this.lastName;
}
public String getStreet(){
return this.street;
}
public String getZip(){
return this.zip;
}
public String getCity(){
return this.city;
}
public String getState(){
return this.state;
}
public String getTelephone(){
return this.telephone;
}
public String getEmail(){
return this.email;
}
public String getUrl(){
return this.url;
}
public String getDateOfSurvey(){
return this.dateOfSurvey;
}
public String getGraduationMonth(){
return this.graduationMonth;
}
public String getGraduationYear(){
return this.graduationYear;
}
public String getLikes(){
return this.likes;
}
public String getInterests(){
return this.interests;
}
public String getRecommendation(){
return this.recommendation;
}
public String getComments(){
return this.comments;
}
}
Java Servlet with RequestDispatcher
import java.io.IOException;
import java.util.List;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
@WebServlet("/Display")
public class Display extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String studentId = request.getParameter("studentid");
String address = "jsp/StudentJSP.jsp";
StudentBean studentBean = null;
if(studentId != null){
studentBean = StudentDAO.GetStudentSurveyData(studentId);
}
HttpSession session = request.getSession();
if(studentBean == null){
address = "jsp/NoSuchStudentJSP.jsp";
session.setAttribute("badId", studentId);
}
else{
session.setAttribute("student", studentBean);
}
RequestDispatcher dispatcher = request.getRequestDispatcher(address);
dispatcher.forward(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String studentId = request.getParameter("studentId");
String firstName = request.getParameter("firstName");
String lastName = request.getParameter("lastName");
String street = request.getParameter("street");
String zip = request.getParameter("zip");
String city = request.getParameter("city");
String state = request.getParameter("state");
String telephone = request.getParameter("telephone");
String email = request.getParameter("email");
String url = request.getParameter("url");
String dateOfSurvey = request.getParameter("dateOfSurvey");
String graduationMonth = request.getParameter("graduationMonth");
String graduationYear = request.getParameter("graduationYear");
String[] likes = request.getParameterValues("likes");
String interests = request.getParameter("interests");
String recommendation = request.getParameter("recommendation");
String comments = request.getParameter("comments");
String data = request.getParameter("data");
String likesString = "";
for(int i=0; i< likes.length; i++){
likesString += likes[i] + ", ";
}
likesString = likesString.substring(0, likesString.length() - 2);
StudentBean studentBean = new StudentBean(studentId, firstName, lastName, street, zip, city, state,
telephone, email, url, dateOfSurvey, graduationMonth,
graduationYear, likesString, interests, recommendation, comments);
StudentDAO.SaveStudentSurveyFormData(studentBean);
DataBean dataBean = DataProcessor.ComputeMeanAndStandardDeviation(data);
List<String> surveyIdsBean = StudentDAO.GetSurveyIds();
HttpSession session = request.getSession();
session.setAttribute("student", studentBean);
session.setAttribute("data", dataBean);
session.setAttribute("surveys", surveyIdsBean);
String address = "jsp/SimpleAcknowledgementJSP.jsp";
if(dataBean.getMean() > 90){
address = "jsp/WinnerAcknowledgementJSP.jsp";
}
RequestDispatcher dispatcher = request.getRequestDispatcher(address);
dispatcher.forward(request, response);
}
}
Subscribe to:
Posts (Atom)

