Could not include a project reference, kept saying it was missing even though another project in the solution used the same reference just fine. Turned out the projects had two different versions of Target Framework (in Properties > Applicaton tab). One was 4.5, the other 4.5.2.
Monday, December 19, 2016
Tuesday, December 13, 2016
IoC with Unity config vs Fortis
In our G MVC app we had one web project in the solution in addition to class library ones. In it, in the App_Start we had a UnitConfig file that registered interfaces to use concretes like this:
public static void RegisterTypes(IUnityContainer container)
{
container.RegisterType<IAccountContext, AccountContext>();
container.RegisterType<IAccountRepository, AccountRepository>();
container.RegisterType<IPreferenceService, PreferenceService>();
container.RegisterType<IFormProcessor, FormProcessor>();
}
In existing G solution they used Fortis and the following way to register container:
every project had this class
public class IoCRegistration : IIoCRegistrant
{
public void Initialize(IContainerAdapter container)
{
// Register Fortis
container.RegisterSingleton<IAccountContext, AccountContext>();
container.RegisterSingleton<IAccountRepository, AccountRepository>();
}
}
public interface IIoCRegistrant
{
void Initialize(IContainerAdapter container);
}
And then in the web project they had:
[assembly: WebActivatorEx.PreApplicationStartMethod(typeof(SimpleInjectorInitializer), "Initialize")]
And in a Core project they had
private static void InitializeContainer(IContainerAdapter container)
{
//search all onegeisinger assemblies for IIOCRegistrant implementations
List<IEnumerable<Type>> registrantsAssemblies = AppDomain.CurrentDomain.GetAssemblies()
.Where(x => x.FullName.ToLower().Contains("geisinger"))
.Select(x => x.GetTypes().Where(y => y.IsInterface == false && y.IsAssignableTo(typeof(IIoCRegistrant)))).ToList();
if (!registrantsAssemblies.Any())
{
//this most likely means the project name above might be outdated or needs changing
throw new Exception("Could not find any assemblies with IoC Registration");
}
//iterate through assemblies
foreach (IEnumerable<Type> registrantAssembly in registrantsAssemblies)
{
//register any mvc controllers for this assembly
//get the first class that implements IoCRegistrant
Type registrantClass = registrantAssembly.FirstOrDefault();
if (registrantClass != null)
{
//create an instance of IoCRegistrant
IIoCRegistrant instance = Activator.CreateInstance(registrantClass) as IIoCRegistrant;
if (instance != null)
{
try
{
//initialize IoCRegistrant
instance.Initialize(container);
}
catch (Exception e)
{
//log any errors and move to the next one
Sitecore.Diagnostics.Log.Error("IOC Initialization Error from: " + registrantClass.FullName + ", Message: " + e.Message, e);
}
}
}
}
}
public static void RegisterTypes(IUnityContainer container)
{
container.RegisterType<IAccountContext, AccountContext>();
container.RegisterType<IAccountRepository, AccountRepository>();
container.RegisterType<IPreferenceService, PreferenceService>();
container.RegisterType<IFormProcessor, FormProcessor>();
}
In existing G solution they used Fortis and the following way to register container:
every project had this class
public class IoCRegistration : IIoCRegistrant
{
public void Initialize(IContainerAdapter container)
{
// Register Fortis
container.RegisterSingleton<IAccountContext, AccountContext>();
container.RegisterSingleton<IAccountRepository, AccountRepository>();
}
}
public interface IIoCRegistrant
{
void Initialize(IContainerAdapter container);
}
And then in the web project they had:
[assembly: WebActivatorEx.PreApplicationStartMethod(typeof(SimpleInjectorInitializer), "Initialize")]
And in a Core project they had
private static void InitializeContainer(IContainerAdapter container)
{
//search all onegeisinger assemblies for IIOCRegistrant implementations
List<IEnumerable<Type>> registrantsAssemblies = AppDomain.CurrentDomain.GetAssemblies()
.Where(x => x.FullName.ToLower().Contains("geisinger"))
.Select(x => x.GetTypes().Where(y => y.IsInterface == false && y.IsAssignableTo(typeof(IIoCRegistrant)))).ToList();
if (!registrantsAssemblies.Any())
{
//this most likely means the project name above might be outdated or needs changing
throw new Exception("Could not find any assemblies with IoC Registration");
}
//iterate through assemblies
foreach (IEnumerable<Type> registrantAssembly in registrantsAssemblies)
{
//register any mvc controllers for this assembly
//get the first class that implements IoCRegistrant
Type registrantClass = registrantAssembly.FirstOrDefault();
if (registrantClass != null)
{
//create an instance of IoCRegistrant
IIoCRegistrant instance = Activator.CreateInstance(registrantClass) as IIoCRegistrant;
if (instance != null)
{
try
{
//initialize IoCRegistrant
instance.Initialize(container);
}
catch (Exception e)
{
//log any errors and move to the next one
Sitecore.Diagnostics.Log.Error("IOC Initialization Error from: " + registrantClass.FullName + ", Message: " + e.Message, e);
}
}
}
}
}
Monday, December 12, 2016
References in a project not wired up correctly.
I had to bring several projects over from a physical location into a solution. I accidentally moved nuget files with the projects and it broke things. Only bring projects themselves. I pushed to code to dev. Other devs got and it gave them errors - could not find references.
We had to fix paths in the unloaded project because the references needed to be pointed at nuget packages and not individual .dll's. But for .dll's directly referenced we needed to update the path:
had to add ..\ because the .bin folder was 1 level higher.
We had to fix paths in the unloaded project because the references needed to be pointed at nuget packages and not individual .dll's. But for .dll's directly referenced we needed to update the path:
had to add ..\ because the .bin folder was 1 level higher.
Useful commands
1. Java version:
java -version
2. Copy folders with contents (no filtering)
Copy-Item -Path C:\Users\Olga.Kogan\Source\Repos\Habitat\src\Feature -Recurse -Destination c:\Test
3. Unzip
function UnzipHabitat
{
#Get path and validate the path
$global:zipPath = Read-Host "Please specify the path to the Habitat zip file:"
if($global:zipPath -eq "")
{
Write-Host "Select a valid folder path."
exit
}
else
{
[System.IO.Compression.ZipFile]::ExtractToDirectory($global:zipPath, "C:\Habitat")
exit
}
}
Self-signed certificate in IIS
Find you site in IIS. Go to Bindings then Add and add a binding
Type in your host name. Port 443. All unassigned. Under SSL chose IIS Express Development Certificate.
==================
https://www.sslshopper.com/article-how-to-create-a-self-signed-certificate-in-Iis-7.html
SSL is an essential part of securing your IIS 7.0 site and creating a self-signed certificate in IIS 7 is much easier to do than in previous versions of IIS. SSL certificates enable the encryption of all traffic sent to and from your IIS web site, preventing others from viewing sensitive information. It uses public key cryptography to establish a secure connection. This means that anything encrypted with a public key (the SSL certificate) can only be decrypted with the private key and vice versa.
Never use a self signed certificate on an e-commerce site or any site that transfers valuable personal information like credit cards, social security numbers, etc.
Type in your host name. Port 443. All unassigned. Under SSL chose IIS Express Development Certificate.
==================
https://www.sslshopper.com/article-how-to-create-a-self-signed-certificate-in-Iis-7.html
SSL is an essential part of securing your IIS 7.0 site and creating a self-signed certificate in IIS 7 is much easier to do than in previous versions of IIS. SSL certificates enable the encryption of all traffic sent to and from your IIS web site, preventing others from viewing sensitive information. It uses public key cryptography to establish a secure connection. This means that anything encrypted with a public key (the SSL certificate) can only be decrypted with the private key and vice versa.
Never use a self signed certificate on an e-commerce site or any site that transfers valuable personal information like credit cards, social security numbers, etc.
Thursday, December 8, 2016
Nuget package restore failed
Was getting this error message.
1. Right click the project > Manage NuGet packages.
2. Upper right corner > Package Source. Pick one at a time. Those are all configured under Settings (little gear icon next to Package Source drop down).
3. Compare the version of that package to the one in the Packages.config file. Reconcile them. In my case I had to change one number in the version in the config file.
1. Right click the project > Manage NuGet packages.
2. Upper right corner > Package Source. Pick one at a time. Those are all configured under Settings (little gear icon next to Package Source drop down).
3. Compare the version of that package to the one in the Packages.config file. Reconcile them. In my case I had to change one number in the version in the config file.
Wednesday, December 7, 2016
Solr
Solr install comes with actual Solr engine and client dashboard
You can install solr directly (http://lucene.apache.org/solr/downloads.html)
or using either Bitnami (image) or Solr Canon (for sitecore)
https://bitnami.com/stack/solr/virtual-machine
https://aws.amazon.com/marketplace/pp/B00NNZTH5I
https://kamsar.net/index.php/2016/03/The-Solr-Cannon/
=============
Create cores for all the indexes
Configure replica sets
Admin console:
http://localhost:8983/solr
Solr requires Java to be installed. I had errors and turned out my version of Java was wrong. I had a 32-bit version. Had to download from here:
http://www.oracle.com/technetwork/java/javase/downloads/jre8-downloads-2133155.html
The latest 64-bit and it had to be .exe file.
After that I downloaded Solr from here: http://archive.apache.org/dist/lucene/solr/
Version I needed was 4.10.3
Tuesday, December 6, 2016
HTTP
The Hypertext Transfer Protocol (HTTP) is an application protocol for distributed, collaborative, hypermedia information systems. HTTP is the foundation of data communication for the World Wide Web. Hypertext is structured text that uses logical links (hyperlinks) between nodes containing text.
Hyper Text Transfer Protocol Secure (HTTPS) is the secure version of HTTP, the protocol over which data is sent between your browser and the website that you are connected to. The 'S' at the end of HTTPS stands for 'Secure'. It means all communications between your browser and the website are encrypted. Hypertext Transfer Protocol Secure (https) is a combination of the Hypertext Transfer Protocol (HTTP) with the Secure Socket Layer (SSL)/Transport Layer Security (TLS) protocol. TLS is an authentication and security protocol widely implemented in browsers and Web servers.
HTTP is a Stateless Protocol. HTTP is called a stateless protocol because each command is executed independently, without any knowledge of the commands that came before it. This is the main reason that it is difficult to implement Web sites that react intelligently to user input.
Short for HyperText Transfer Protocol, HTTP is the underlying protocol used by the World Wide Web. HTTP defines how messages are formatted and transmitted, and what actions Web servers and browsers should take in response to various commands.
"HTTP server" is another term for Web server. A Web server is a software program that maps URL requests from a Web client (typically a browser) to a resource that will handle the request and return a response to the client. The Web client and the Web server use HTTP to communicate over a TCP network.
When you have another protocol like HTTPS, it specifies its own default port (443) so that means when you use HTTPS to connect to a website your browser is again always going to have to just assume its going to be there on port 443. This also explains why you can't run more than one web server on port 80 and 443.
In cryptography and computer security, a self-signed certificate is an identity certificate that is signed by the same entity whose identity it certifies. This term has nothing to do with the identity of the person or organization that actually performed the signing procedure. In technical terms a self-signed certificate is one signed with its own private key. In typical public key infrastructure (PKI) arrangements, a digital signature from a certificate authority (CA) attests that a particular public key certificate is valid (i.e., contains correct information).[1]
in IIS select your site, go to bindings and add
Type: https
Host name: YourHostName
Port: 443
SSL certificate: IIS Express Development Certificate
Hyper Text Transfer Protocol Secure (HTTPS) is the secure version of HTTP, the protocol over which data is sent between your browser and the website that you are connected to. The 'S' at the end of HTTPS stands for 'Secure'. It means all communications between your browser and the website are encrypted. Hypertext Transfer Protocol Secure (https) is a combination of the Hypertext Transfer Protocol (HTTP) with the Secure Socket Layer (SSL)/Transport Layer Security (TLS) protocol. TLS is an authentication and security protocol widely implemented in browsers and Web servers.
HTTP is a Stateless Protocol. HTTP is called a stateless protocol because each command is executed independently, without any knowledge of the commands that came before it. This is the main reason that it is difficult to implement Web sites that react intelligently to user input.
Short for HyperText Transfer Protocol, HTTP is the underlying protocol used by the World Wide Web. HTTP defines how messages are formatted and transmitted, and what actions Web servers and browsers should take in response to various commands.
"HTTP server" is another term for Web server. A Web server is a software program that maps URL requests from a Web client (typically a browser) to a resource that will handle the request and return a response to the client. The Web client and the Web server use HTTP to communicate over a TCP network.
When you have another protocol like HTTPS, it specifies its own default port (443) so that means when you use HTTPS to connect to a website your browser is again always going to have to just assume its going to be there on port 443. This also explains why you can't run more than one web server on port 80 and 443.
In cryptography and computer security, a self-signed certificate is an identity certificate that is signed by the same entity whose identity it certifies. This term has nothing to do with the identity of the person or organization that actually performed the signing procedure. In technical terms a self-signed certificate is one signed with its own private key. In typical public key infrastructure (PKI) arrangements, a digital signature from a certificate authority (CA) attests that a particular public key certificate is valid (i.e., contains correct information).[1]
in IIS select your site, go to bindings and add
Type: https
Host name: YourHostName
Port: 443
SSL certificate: IIS Express Development Certificate
In cryptography, a public key certificate (also known as a digital certificate or identity certificate) is an electronic document used to prove the ownership of a public key. The certificate includes information about the key, information about its owner's identity, and the digital signature of an entity that has verified the certificate's contents are correct. If the signature is valid, and the person examining the certificate trusts the signer, then they know they can use that key to communicate with its owner.
In a typical public-key infrastructure (PKI) scheme, the signer is a certificate authority (CA), usually a company that charges customers to issue certificates for them. In a web of trust scheme, the signer is either the key's owner (a self-signed certificate) or other users ("endorsements") whom the person examining the certificate might know and trust.
Certificates are an important component of Transport Layer Security (TLS, sometimes called by its older name SSL, Secure Sockets Layer), where they prevent an attacker from impersonating a secure website or other server. They are also used in other important applications, such as email encryption and code signing.
In cryptography, a certificate authority or certification authority (CA) is an entity that issues digital certificates. A digital certificate certifies the ownership of a public key by the named subject of the certificate. This allows others (relying parties) to rely upon signatures or on assertions made about the private key that corresponds to the certified public key. In this model of trust relationships, a CA is a trusted third party—trusted both by the subject (owner) of the certificate and by the party relying upon the certificate. The most commonly encountered public-key infrastructure (PKI) schemes are those used to implement https on the world-wide web. All these are based upon the X.509 standard and feature CAs.
TDS Global Config file
In here you can setup SitecoreDeployFolder and SitecoreWebUrl and these settings will propagate to all TDS projects in your solution
Running a Power Shell script to set up a local Sitecore environment
There was this .ps1 file that I needed to run from the Power Shell console. See script below.
1. When I attempted to do that by navigating to the location of the script file in the PS console and typing in the name of the file I got an error message that running a PS script is disabled on my environment.
In PS window type in "Get-ExecutionPolicy" and hit enter. You might see 'restricted'.
set-executionpolicy unrestricted
2. After then I typed in the name of the script file agan and got a different error "not recognized comman". I was prompted to type it differently: ".\Setup.ps1"
3.
$ErrorActionPreference = "Stop"
. "$PSScriptRoot\Common.ps1"
$simUrl = "http://dl.sitecore.net/updater/sim/"
$simUrlDownload = "http://dl.sitecore.net/updater/sim/SIM.Tool.application"
$sitecoreVersion = "8.1"
$sitecoreRevision = "151207"
$sitecoreFullVersion = "Sitecore CMS $sitecoreVersion rev.$sitecoreRevision"
$localUrl = "sitecore.loc.geisinger.edu"
$frameorkVersion = "4.0"
$deploySubDirectory = "\Deploy"
$mongoUrl = "https://www.mongodb.com/download-center?jmp=homepage#community"
$mongoUrlDownload = "https://www.mongodb.com/dr/fastdl.mongodb.org/win32/mongodb-win32-x86_64-2008plus-ssl-3.2.8-signed.msi/download"
$solrUrl = "http://archive.apache.org/dist/lucene/solr/"
$solrUrlDownload = "http://archive.apache.org/dist/lucene/solr/4.10.3/solr-4.10.3.zip"
$solrVersion = "4.10.3"
$javaUrl = "http://www.oracle.com/technetwork/java/javase/downloads/jre8-downloads-2133155.html"
$javaVersion = "8u101"
$defaultMongoPath = "C:\Program Files\MongoDB\Server\3.2\bin"
$defaultMongoDataPath = "C:\data\db"
$defaultMongoLogPath = "C:\data\logs"
$mongoLogFile = "log.txt"
$mongodFile = "mongod.exe"
$mongoService = "Mongodb"
$javaVersion ="8u101"
$downloadsPath = "$($env:userprofile)\Downloads"
$defaultSolrDownloadPath = "$downloadsPath\solr-$solrVersion.zip"
$defaultSolrInstallPath = "C:\Apps\Solr\"
$solrtask = "Solr"
$repoRoot = (Get-Item (Get-Location)).parent
$gitRoot = $repoRoot.parent.FullName
$repoRoot = $repoRoot.FullName
Function Greet() {
Write-Host @"
This script will help Setup your local Dev environment for running Sitecore.
Please note that this should not be run in production under any circumstance.
All the configuration steps are required for a fresh environment so be sure to
answer Y to all questions if this is your first time.
"@ -foregroundcolor Blue
RequireAdmin
Write-Host @"
Note: Please remember that some of the configuration in this script is
generated on the fly to be environment specific. As such it is not transferable
to other environments without modification.
"@ -foregroundcolor Yellow
Pause
}
Function RequireAdmin() {
$principle = [Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()
If (!($principle.IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator"))) {
throw "This script must be run with Administrator permissions!"
}
}
Function CreateDirectory($path) {
if(!(Test-Path $path)) {
New-Item $path -type directory
}
}
Function CheckService($serviceName) {
return Get-WmiObject -Class Win32_Service -Filter "Name='$serviceName'"
}
Function DeleteService($name) {
Stop-Service $name
$command = @"
sc.exe delete "$name"
"@
iex $command
}
Function Unzip($source, $destination) {
$shell = new-object -com shell.application
$zip = $shell.NameSpace("$source")
foreach($item in $zip.items()) {
$shell.Namespace($destination).copyhere($item)
}
}
Function SetupSitecore() {
Write-Host @"
First you will want to download, install, and configure the newest version of
Sitecore Instance Manager (SIM) from $simUrl
"@ -foregroundcolor Blue
Ask "Would you like to download and install SIM? (Y/N)" $function:DownloadSIM
Write-Host @"
Now we can configure SIM.
It should have automatically opened after install. If not you should be able
to search your installed programs for SIM.
Once SIM is open, you should navigate to Home > Settings
and configure as follows:
Instance Root Folder: $gitRoot
SQL Server Connection String: Data Source=localhost;Initial Catalog=master;Integrated Security=True;Connect Timeout=1
Sitecore License File: $($env:AppData)\Sitecore\Sitecore Instance Manager\license.xml
Local Repository: $($env:AppData)\Sitecore\Sitecore Instance Manager\Repository
"@ -foregroundcolor Blue
Write-Host @"
Note: Feel free to change these as needed as these are just recommendations.
Also if you haven't already acquired a Sitecore license file, please contact
your lead for more information.
"@ -foreground Yellow
Pause
Write-Host @"
Now we can download the Sitecore installer locally.
Navigate to Home > Bundled Tools > Download Sitecore 8.x
Follow the onscreen prompts and when it asks for a version select:
$sitecoreFullVersion
"@ -foregroundcolor Blue
Write-Host @"
Warning: Other versions of Sitecore will likely not work correctly due to API
and feature changes!
"@ -foregroundcolor Red
Write-Host "When asked enter your SDN credentials." -foregroundcolor blue
Write-Host @"
For GHP employees this will likely be a @thehealthplan.com email account
If you don't know them ask your lead.
"@ -foregroundcolor Yellow
Pause
Write-Host @"
Now we can begin installing Sitecore locally.
Navigate to Home > Install Instance and configure as follows:
Product: Sitecore CMS
Version:$sitecoreVersion
Revision: $sitecoreRevision
Site Name: $localUrl
Host Name: $localUrl
SQL Prefix: $localUrl
Location: $repoRoot$deploySubDirectory
Framework: v$frameorkVersion
Pool Mode: Integrated
"@ -foregroundcolor blue
Write-Host @"
Note: Be sure to fill to double check this and fill it out in order as SIM
automatically replaces a lot of settings after you select a version.
"@ -foreground Yellow
Pause
Write-Host @"
Continue through the remaining screens accepting the default settings:
Instance Details: (all checked)
Modules list: (none)
Custom Packages: (none)
Configuration Presets: (none)
Click Install and wait for the installation to finish.
When it is complete be sure to visit http://$localUrl and verify it is
accessible.
"@ -foreground Blue
}
Function DownloadSIM() {
start $simUrlDownload
}
Function SetupMongo() {
$mongoBasePath = AskDefault "Where would you like to install Mongo?" $defaultMongoPath
if(Test-Path $mongoBasePath) {
$func = $function:InstallMongo
Ask "Mongo appears to already be installed. Would you like to reinstall? (Y/N)" {& $func $mongoBasePath}.GetNewClosure()
} else {
InstallMongo $mongoBasePath
}
if(CheckService $mongoService) {
Ask "Mongo service already exists. Would you like to reinstall? (Y/N)" $function:ReinstallMongoService
} else {
Ask "Would you like to create a Windows Service for Mongo now? (Y/N)" $function:CreateMongoService
}
}
Function InstallMongo($mongoBasePath) {
Write-Host @"
The Mongo installer can be downloaded from:
$mongoUrl
At the time of writing this is version $mongoVersion but later versions
should work.
"@ -foregroundcolor blue
Ask "Would you like to download Mongo $mongoVersion? (Y/N)" DownloadMongo
Write-Host @"
Once Mongo is downloaded, you should be able to install it using the default
installation options.
"@ -foregroundcolor blue
}
Function DownloadMongo() {
start $mongoUrlDownload
}
Function ReinstallMongoService() {
DeleteService $mongoService
CreateMongoService
}
Function CreateMongoService() {
Write-Host "Mongo requires a data directory and a logging directory to run." -foregroundcolor Blue
$mongoFullPath = "$mongoBasePath\$mongodFile"
if(!(Test-Path $mongoFullPath)) {
throw "$mongoFullPath does not exist."
}
$dataPath = AskDefault "What directory do you want to store the db in?" $defaultMongoDataPath
$logPath = AskDefault "What directory do you want to store logging in?" $defaultMongoLogPath
CreateDirectory $dataPath
CreateDirectory $logPath
$logFile = "$logPath\$mongoLogFile"
$command = @"
& "$mongoFullPath" --dbpath=$dataPath --logpath=$logFile --install
"@
Write-Host $command
iex $command
$command = "net start MongoDB"
iex $command
}
Function GetJavaVersion() {
try {
$ErrorActionPreference = "Continue"
$result = &"java.exe" -version 2>&1
$ErrorActionPreference = "Stop"
return $result[0].Exception.Message -replace "java version " -replace """"
}
catch {
return ""
}
return $result
}
Function SetupJava() {
$version = GetJavaVersion
if($version -ne '') {
Ask "Java appears to be already installed. Would like grab the latest? (Y/N)" InstallJava
} else {
InstallJava
}
}
Function InstallJava() {
Write-Host @"
The Java JRE installer can be downloaded from:
$javaUrl
At the time of writing this is version $javaVersion but later versions
should work.
"@ -foregroundcolor blue
Ask "Would you like to download Java $javaVersion? (Y/N)" $function:DownloadJava
Write-Host @"
Once Java is downloaded, you should be able to install it using the default
installation options.
"@ -foregroundcolor blue
}
Function DownloadJava() {
start $javaUrl
}
Function SetupSolr() {
$solrInstallPath = AskDefault "Where would you like to install Solr?" $defaultSolrInstallPath
if(Test-Path $solrInstallPath) {
$func = $function:CleanSolr
Ask "Solr appears to be already installed. Would you like to reinstall? (Y/N)" {& $func $solrInstallPath}.GetNewClosure()
} else {
InstallSolr $solrInstallPath
}
$func = $function:ConfigureSolr
Ask "Would you like to configure Solr? (Y/N)" {& $func $solrInstallPath}.GetNewClosure()
if(CheckTask $solrTask) {
$func = $function:ReinstallSolrTask
Ask "The Solr scheduled task appears to already be installed. Would you like to reinstall? (Y/N)" {& $func $solrInstallPath}.GetNewClosure()
} else {
CreateSolrTask $solrInstallPath
}
}
Function ConfigureSolr($solrInstallPath) {
Write-Host "Copying configuration files to Solr"
$solrConfigPath = $solrInstallPath + "example\solr"
Write-Host $solrConfigPath
Remove-Item -r $solrConfigPath
New-Item $solrConfigPath -type directory
Copy-Item "SolrConfig\solr.xml" $solrConfigPath
$cores = (Get-Item "SolrConfig\solr-cores.zip").FullName
Unzip $cores $solrConfigPath
}
Function ReinstallSolrTask($solrInstallPath) {
DeleteTask $solrTask
CreateSolrTask $solrInstallPath
}
Function CheckTask($name) {
$command = @"
schtasks /query /tn "$name"
"@
iex $command
return $false
}
Function CreateSolrTask($solrInstallPath) {
$startIn = (Get-Location).Path
$task = "powershell -file $startIn\TaskShim.ps1 -command $($solrInstallPath)bin\solr.cmd -argz start"
$command = @"
schtasks /Create /tn $solrTask /SC ONSTART /tr '$task' /ru "NT AUTHORITY\LOCALSERVICE"
"@
iex $command
RunTask $solrTask
}
Function RunTask($name) {
$command = @"
schtasks /run /tn $name
"@
iex $command
}
Function DeleteTask($name) {
$command = @"
schtasks /delete /tn "$name" /f
"@
iex $command
}
Function CleanSolr($solrInstallPath) {
Remove-Item -r $solrInstallPath
InstallSolr $solrInstallPath
}
Function InstallSolr($solrInstallPath) {
Write-Host @"
Now we can download the Solr installer locally from:
$solrUrl
"@ -foregroundcolor blue
Write-Host "At the time of writing this must be version $solrVersion" -foregroundcolor Red
Ask "Would you like to download Solr $solrVersion? (Y/N)" DownloadSolr
Write-Host @"
Once Solr is downloaded we can install it.
"@ -foregroundcolor blue
$solrDownloadPath = AskDefault "Where did you download Solr to?" $defaultSolrDownloadPath
if(!(Test-Path $solrDownloadPath)) {
throw "Unable to find $solrDownloadPath"
}
CreateDirectory $solrInstallPath
Unzip "$solrDownloadPath\solr-$solrVersion" $solrInstallPath
}
Function DownloadSolr() {
start $solrUrlDownload
}
Function SetupSQL() {
Write-Host @"
Please login to your local SQL server and navigate to:
$($env:computername) > Security > Logins
Add a new Login named: IIS AppPool\$localUrl
as Windows Authentication
Under Server Roles select all roles.
Please be aware this account will have more permissions than it needs
and should not be used in production. However at the time of writing
we have not yet identified a reduced permission set.
"@ -foregroundcolor blue
Write-Host @"
Note: IIS AppPool accounts are virtual and will not show up in a search.
This will also only work if the corresponding AppPool has already been
created.
"@ -foregroundcolor Yellow
Write-Host "You will need to restart IIS to make these changes take effect."
Ask "Would you like to restart IIS now?" $function:RestartIIS
}
Function RestartIIS() {
& iisreset.exe
}
Function SetupSSL() {
Write-Host @"
Please open MMC, run the security snap-in and request a self signed cert for
CN=*.loc.geisinger.edu
and give it a friendly name of *.loc.geisinger.edu
This cert can then be installed from
C:\Windows\System32\inetsrv
by running
appcmd set site /site.name:"$localUrl" /+bindings.[protocol='https',bindingInformation='*:443:$localUrl']
Then run
Import-Module WebAdministration
cd IIS:\SslBindings
ls cert:\LocalMachine\My\
And add the binding with
Get-Item cert:\LocalMachine\My\<thumbprint> |New-Item 0.0.0.0!443
These instruction will be automated at a later date.
"@
}
Function SetupIIS() {
Write-Host @"
You will want to make sure that your AppPool is using the
ApplicationPoolIdentity.
Next you'll want to make sure that virtual account has Modify access to
$repoRoot
You can add it by adding the user IIS AppPool\$localUrl under the security
tab and having all descendents inherit permissions. Please note that this
will be a $($env:computername) user and not a GHS_NTDOMAIN user.
"@ -foregroundcolor Yellow
}
Function SetupSitecorePackages() {
Write-Host @"
You will need to manually install the following modules into Sitecore
|Required Modules | Version |
|----------------------------|---------------------------|
| Web Forms For Marketers | 8.1 rev 151217 |
"@ -foregroundcolor Yellow
}
Greet
Ask "Do you need to setup Sitecore? (Y/N)" $function:SetupSitecore
Ask "Do you need to setup Mongo? (Y/N)" $function:SetupMongo
Ask "Do you need to setup Java? (Y/N)" $function:SetupJava
Ask "Do you need to setup Solr? (Y/N)" $function:SetupSolr
Ask "Do you need to setup SQL security (Y/N)" $function:SetupSQL
Ask "Do you need to setup IIS security (Y/N)" $function:SetupIIS
Ask "Do you need to setup SSL? (Y/N)" $function:SetupSSL
Ask "Do you need to setup Sitecore packages? (Y/N)" $function:SetupSitecorePackages
Write-Host "Warning: Fixing configuration will rewrite all content in Website\App_Config" -foregroundcolor red
$func = $function:FixConfiguration
Ask "Do you need to fix configuration settings? (Y/N)" {& $func $repoRoot $deploySubDirectory}.GetNewClosure()
Write-Host @"
You should now be able to access http://$localUrl
Once you have verified your local instance is running sync the TDS assets to the DB
and build the application.
"@ -foregroundcolor Blue
Write-Host @"
If you have any problems with an index please reconfigure solr and the fix
configuration step.
If you have any problems accessing the database or reading the license file
please rerun the Fix configuration steps.
"@ -foregroundcolor Yellow
Pause
1. When I attempted to do that by navigating to the location of the script file in the PS console and typing in the name of the file I got an error message that running a PS script is disabled on my environment.
In PS window type in "Get-ExecutionPolicy" and hit enter. You might see 'restricted'.
set-executionpolicy unrestricted
2. After then I typed in the name of the script file agan and got a different error "not recognized comman". I was prompted to type it differently: ".\Setup.ps1"
3.
$ErrorActionPreference = "Stop"
. "$PSScriptRoot\Common.ps1"
$simUrl = "http://dl.sitecore.net/updater/sim/"
$simUrlDownload = "http://dl.sitecore.net/updater/sim/SIM.Tool.application"
$sitecoreVersion = "8.1"
$sitecoreRevision = "151207"
$sitecoreFullVersion = "Sitecore CMS $sitecoreVersion rev.$sitecoreRevision"
$localUrl = "sitecore.loc.geisinger.edu"
$frameorkVersion = "4.0"
$deploySubDirectory = "\Deploy"
$mongoUrl = "https://www.mongodb.com/download-center?jmp=homepage#community"
$mongoUrlDownload = "https://www.mongodb.com/dr/fastdl.mongodb.org/win32/mongodb-win32-x86_64-2008plus-ssl-3.2.8-signed.msi/download"
$solrUrl = "http://archive.apache.org/dist/lucene/solr/"
$solrUrlDownload = "http://archive.apache.org/dist/lucene/solr/4.10.3/solr-4.10.3.zip"
$solrVersion = "4.10.3"
$javaUrl = "http://www.oracle.com/technetwork/java/javase/downloads/jre8-downloads-2133155.html"
$javaVersion = "8u101"
$defaultMongoPath = "C:\Program Files\MongoDB\Server\3.2\bin"
$defaultMongoDataPath = "C:\data\db"
$defaultMongoLogPath = "C:\data\logs"
$mongoLogFile = "log.txt"
$mongodFile = "mongod.exe"
$mongoService = "Mongodb"
$javaVersion ="8u101"
$downloadsPath = "$($env:userprofile)\Downloads"
$defaultSolrDownloadPath = "$downloadsPath\solr-$solrVersion.zip"
$defaultSolrInstallPath = "C:\Apps\Solr\"
$solrtask = "Solr"
$repoRoot = (Get-Item (Get-Location)).parent
$gitRoot = $repoRoot.parent.FullName
$repoRoot = $repoRoot.FullName
Function Greet() {
Write-Host @"
This script will help Setup your local Dev environment for running Sitecore.
Please note that this should not be run in production under any circumstance.
All the configuration steps are required for a fresh environment so be sure to
answer Y to all questions if this is your first time.
"@ -foregroundcolor Blue
RequireAdmin
Write-Host @"
Note: Please remember that some of the configuration in this script is
generated on the fly to be environment specific. As such it is not transferable
to other environments without modification.
"@ -foregroundcolor Yellow
Pause
}
Function RequireAdmin() {
$principle = [Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()
If (!($principle.IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator"))) {
throw "This script must be run with Administrator permissions!"
}
}
Function CreateDirectory($path) {
if(!(Test-Path $path)) {
New-Item $path -type directory
}
}
Function CheckService($serviceName) {
return Get-WmiObject -Class Win32_Service -Filter "Name='$serviceName'"
}
Function DeleteService($name) {
Stop-Service $name
$command = @"
sc.exe delete "$name"
"@
iex $command
}
Function Unzip($source, $destination) {
$shell = new-object -com shell.application
$zip = $shell.NameSpace("$source")
foreach($item in $zip.items()) {
$shell.Namespace($destination).copyhere($item)
}
}
Function SetupSitecore() {
Write-Host @"
First you will want to download, install, and configure the newest version of
Sitecore Instance Manager (SIM) from $simUrl
"@ -foregroundcolor Blue
Ask "Would you like to download and install SIM? (Y/N)" $function:DownloadSIM
Write-Host @"
Now we can configure SIM.
It should have automatically opened after install. If not you should be able
to search your installed programs for SIM.
Once SIM is open, you should navigate to Home > Settings
and configure as follows:
Instance Root Folder: $gitRoot
SQL Server Connection String: Data Source=localhost;Initial Catalog=master;Integrated Security=True;Connect Timeout=1
Sitecore License File: $($env:AppData)\Sitecore\Sitecore Instance Manager\license.xml
Local Repository: $($env:AppData)\Sitecore\Sitecore Instance Manager\Repository
"@ -foregroundcolor Blue
Write-Host @"
Note: Feel free to change these as needed as these are just recommendations.
Also if you haven't already acquired a Sitecore license file, please contact
your lead for more information.
"@ -foreground Yellow
Pause
Write-Host @"
Now we can download the Sitecore installer locally.
Navigate to Home > Bundled Tools > Download Sitecore 8.x
Follow the onscreen prompts and when it asks for a version select:
$sitecoreFullVersion
"@ -foregroundcolor Blue
Write-Host @"
Warning: Other versions of Sitecore will likely not work correctly due to API
and feature changes!
"@ -foregroundcolor Red
Write-Host "When asked enter your SDN credentials." -foregroundcolor blue
Write-Host @"
For GHP employees this will likely be a @thehealthplan.com email account
If you don't know them ask your lead.
"@ -foregroundcolor Yellow
Pause
Write-Host @"
Now we can begin installing Sitecore locally.
Navigate to Home > Install Instance and configure as follows:
Product: Sitecore CMS
Version:$sitecoreVersion
Revision: $sitecoreRevision
Site Name: $localUrl
Host Name: $localUrl
SQL Prefix: $localUrl
Location: $repoRoot$deploySubDirectory
Framework: v$frameorkVersion
Pool Mode: Integrated
"@ -foregroundcolor blue
Write-Host @"
Note: Be sure to fill to double check this and fill it out in order as SIM
automatically replaces a lot of settings after you select a version.
"@ -foreground Yellow
Pause
Write-Host @"
Continue through the remaining screens accepting the default settings:
Instance Details: (all checked)
Modules list: (none)
Custom Packages: (none)
Configuration Presets: (none)
Click Install and wait for the installation to finish.
When it is complete be sure to visit http://$localUrl and verify it is
accessible.
"@ -foreground Blue
}
Function DownloadSIM() {
start $simUrlDownload
}
Function SetupMongo() {
$mongoBasePath = AskDefault "Where would you like to install Mongo?" $defaultMongoPath
if(Test-Path $mongoBasePath) {
$func = $function:InstallMongo
Ask "Mongo appears to already be installed. Would you like to reinstall? (Y/N)" {& $func $mongoBasePath}.GetNewClosure()
} else {
InstallMongo $mongoBasePath
}
if(CheckService $mongoService) {
Ask "Mongo service already exists. Would you like to reinstall? (Y/N)" $function:ReinstallMongoService
} else {
Ask "Would you like to create a Windows Service for Mongo now? (Y/N)" $function:CreateMongoService
}
}
Function InstallMongo($mongoBasePath) {
Write-Host @"
The Mongo installer can be downloaded from:
$mongoUrl
At the time of writing this is version $mongoVersion but later versions
should work.
"@ -foregroundcolor blue
Ask "Would you like to download Mongo $mongoVersion? (Y/N)" DownloadMongo
Write-Host @"
Once Mongo is downloaded, you should be able to install it using the default
installation options.
"@ -foregroundcolor blue
}
Function DownloadMongo() {
start $mongoUrlDownload
}
Function ReinstallMongoService() {
DeleteService $mongoService
CreateMongoService
}
Function CreateMongoService() {
Write-Host "Mongo requires a data directory and a logging directory to run." -foregroundcolor Blue
$mongoFullPath = "$mongoBasePath\$mongodFile"
if(!(Test-Path $mongoFullPath)) {
throw "$mongoFullPath does not exist."
}
$dataPath = AskDefault "What directory do you want to store the db in?" $defaultMongoDataPath
$logPath = AskDefault "What directory do you want to store logging in?" $defaultMongoLogPath
CreateDirectory $dataPath
CreateDirectory $logPath
$logFile = "$logPath\$mongoLogFile"
$command = @"
& "$mongoFullPath" --dbpath=$dataPath --logpath=$logFile --install
"@
Write-Host $command
iex $command
$command = "net start MongoDB"
iex $command
}
Function GetJavaVersion() {
try {
$ErrorActionPreference = "Continue"
$result = &"java.exe" -version 2>&1
$ErrorActionPreference = "Stop"
return $result[0].Exception.Message -replace "java version " -replace """"
}
catch {
return ""
}
return $result
}
Function SetupJava() {
$version = GetJavaVersion
if($version -ne '') {
Ask "Java appears to be already installed. Would like grab the latest? (Y/N)" InstallJava
} else {
InstallJava
}
}
Function InstallJava() {
Write-Host @"
The Java JRE installer can be downloaded from:
$javaUrl
At the time of writing this is version $javaVersion but later versions
should work.
"@ -foregroundcolor blue
Ask "Would you like to download Java $javaVersion? (Y/N)" $function:DownloadJava
Write-Host @"
Once Java is downloaded, you should be able to install it using the default
installation options.
"@ -foregroundcolor blue
}
Function DownloadJava() {
start $javaUrl
}
Function SetupSolr() {
$solrInstallPath = AskDefault "Where would you like to install Solr?" $defaultSolrInstallPath
if(Test-Path $solrInstallPath) {
$func = $function:CleanSolr
Ask "Solr appears to be already installed. Would you like to reinstall? (Y/N)" {& $func $solrInstallPath}.GetNewClosure()
} else {
InstallSolr $solrInstallPath
}
$func = $function:ConfigureSolr
Ask "Would you like to configure Solr? (Y/N)" {& $func $solrInstallPath}.GetNewClosure()
if(CheckTask $solrTask) {
$func = $function:ReinstallSolrTask
Ask "The Solr scheduled task appears to already be installed. Would you like to reinstall? (Y/N)" {& $func $solrInstallPath}.GetNewClosure()
} else {
CreateSolrTask $solrInstallPath
}
}
Function ConfigureSolr($solrInstallPath) {
Write-Host "Copying configuration files to Solr"
$solrConfigPath = $solrInstallPath + "example\solr"
Write-Host $solrConfigPath
Remove-Item -r $solrConfigPath
New-Item $solrConfigPath -type directory
Copy-Item "SolrConfig\solr.xml" $solrConfigPath
$cores = (Get-Item "SolrConfig\solr-cores.zip").FullName
Unzip $cores $solrConfigPath
}
Function ReinstallSolrTask($solrInstallPath) {
DeleteTask $solrTask
CreateSolrTask $solrInstallPath
}
Function CheckTask($name) {
$command = @"
schtasks /query /tn "$name"
"@
iex $command
return $false
}
Function CreateSolrTask($solrInstallPath) {
$startIn = (Get-Location).Path
$task = "powershell -file $startIn\TaskShim.ps1 -command $($solrInstallPath)bin\solr.cmd -argz start"
$command = @"
schtasks /Create /tn $solrTask /SC ONSTART /tr '$task' /ru "NT AUTHORITY\LOCALSERVICE"
"@
iex $command
RunTask $solrTask
}
Function RunTask($name) {
$command = @"
schtasks /run /tn $name
"@
iex $command
}
Function DeleteTask($name) {
$command = @"
schtasks /delete /tn "$name" /f
"@
iex $command
}
Function CleanSolr($solrInstallPath) {
Remove-Item -r $solrInstallPath
InstallSolr $solrInstallPath
}
Function InstallSolr($solrInstallPath) {
Write-Host @"
Now we can download the Solr installer locally from:
$solrUrl
"@ -foregroundcolor blue
Write-Host "At the time of writing this must be version $solrVersion" -foregroundcolor Red
Ask "Would you like to download Solr $solrVersion? (Y/N)" DownloadSolr
Write-Host @"
Once Solr is downloaded we can install it.
"@ -foregroundcolor blue
$solrDownloadPath = AskDefault "Where did you download Solr to?" $defaultSolrDownloadPath
if(!(Test-Path $solrDownloadPath)) {
throw "Unable to find $solrDownloadPath"
}
CreateDirectory $solrInstallPath
Unzip "$solrDownloadPath\solr-$solrVersion" $solrInstallPath
}
Function DownloadSolr() {
start $solrUrlDownload
}
Function SetupSQL() {
Write-Host @"
Please login to your local SQL server and navigate to:
$($env:computername) > Security > Logins
Add a new Login named: IIS AppPool\$localUrl
as Windows Authentication
Under Server Roles select all roles.
Please be aware this account will have more permissions than it needs
and should not be used in production. However at the time of writing
we have not yet identified a reduced permission set.
"@ -foregroundcolor blue
Write-Host @"
Note: IIS AppPool accounts are virtual and will not show up in a search.
This will also only work if the corresponding AppPool has already been
created.
"@ -foregroundcolor Yellow
Write-Host "You will need to restart IIS to make these changes take effect."
Ask "Would you like to restart IIS now?" $function:RestartIIS
}
Function RestartIIS() {
& iisreset.exe
}
Function SetupSSL() {
Write-Host @"
Please open MMC, run the security snap-in and request a self signed cert for
CN=*.loc.geisinger.edu
and give it a friendly name of *.loc.geisinger.edu
This cert can then be installed from
C:\Windows\System32\inetsrv
by running
appcmd set site /site.name:"$localUrl" /+bindings.[protocol='https',bindingInformation='*:443:$localUrl']
Then run
Import-Module WebAdministration
cd IIS:\SslBindings
ls cert:\LocalMachine\My\
And add the binding with
Get-Item cert:\LocalMachine\My\<thumbprint> |New-Item 0.0.0.0!443
These instruction will be automated at a later date.
"@
}
Function SetupIIS() {
Write-Host @"
You will want to make sure that your AppPool is using the
ApplicationPoolIdentity.
Next you'll want to make sure that virtual account has Modify access to
$repoRoot
You can add it by adding the user IIS AppPool\$localUrl under the security
tab and having all descendents inherit permissions. Please note that this
will be a $($env:computername) user and not a GHS_NTDOMAIN user.
"@ -foregroundcolor Yellow
}
Function SetupSitecorePackages() {
Write-Host @"
You will need to manually install the following modules into Sitecore
|Required Modules | Version |
|----------------------------|---------------------------|
| Web Forms For Marketers | 8.1 rev 151217 |
"@ -foregroundcolor Yellow
}
Greet
Ask "Do you need to setup Sitecore? (Y/N)" $function:SetupSitecore
Ask "Do you need to setup Mongo? (Y/N)" $function:SetupMongo
Ask "Do you need to setup Java? (Y/N)" $function:SetupJava
Ask "Do you need to setup Solr? (Y/N)" $function:SetupSolr
Ask "Do you need to setup SQL security (Y/N)" $function:SetupSQL
Ask "Do you need to setup IIS security (Y/N)" $function:SetupIIS
Ask "Do you need to setup SSL? (Y/N)" $function:SetupSSL
Ask "Do you need to setup Sitecore packages? (Y/N)" $function:SetupSitecorePackages
Write-Host "Warning: Fixing configuration will rewrite all content in Website\App_Config" -foregroundcolor red
$func = $function:FixConfiguration
Ask "Do you need to fix configuration settings? (Y/N)" {& $func $repoRoot $deploySubDirectory}.GetNewClosure()
Write-Host @"
You should now be able to access http://$localUrl
Once you have verified your local instance is running sync the TDS assets to the DB
and build the application.
"@ -foregroundcolor Blue
Write-Host @"
If you have any problems with an index please reconfigure solr and the fix
configuration step.
If you have any problems accessing the database or reading the license file
please rerun the Fix configuration steps.
"@ -foregroundcolor Yellow
Pause
Tuesday, November 29, 2016
Async calls (JSON) with sitecore
Routes.MapRoute(“AccountUpdateEmail”, “account/updateemail”,
new {controller = “Account”, action = “UpdateEmail”});
that account/updateemail thing is an async call, not something called on page load. It appears to be working for me with a minor price to pay: registering each custom route as shown above.
In the view I have the following:
In the view I have the following:
$("#emailSave").click(function () {
//Make
an async call to an action method
var model = @Html.Raw(Json.Encode(Model));
model.Email = $("#Email").val();
var urlString = "/account/updateemail/?email=" + model.Email;
//alert(urlString);
$.getJSON(urlString, function (data) {
if (data.Message === "success") {
$("#showEmail").css('display', 'none');
$("#currentEmail").text(data.Email);
//display success message
$("#yei").css('display', 'block');
} else {
//show error message
$(".good success-bgd error").css('display', 'block');
}
});
});
REPORT #2. Components added to a page. Success. I made two partial views, both use the default sitecore MVC rendering model which implies that you can either read sitecore data from current item or datasource on your rendering. I added them to presentation details of my navigable item. Left first one without datasource and added a datasource for the other one.
@model Sitecore.Mvc.Presentation.RenderingModel
<div>
Data comes from current item: @Model.Item.Name
</div>
@using Sitecore.Mvc
@model Sitecore.Mvc.Presentation.RenderingModel
<div>
Data comes from a datasource: @Html.Sitecore().Field("Title")
</div>
Install Git developer certificates
Update Git Certificate (Developers)
Developers need to configure their local Git client to use a specially modified certificate in order to connect to the Geisinger-hosted source code repository. This step is not necessary for users who just need to access the Geisinger TFS website.
1. Install Git for Windows (aka 'Git client tools')
2. Note the folder (C:\Program Files\Git\bin)
3. Update your environment variable if neceessary
This is how you can do it:
right-click "My Computer",
select "Properties",
open "Advanced",
click "Environment Variables",
highlight the "Path" variable,
click "Edit",
add your specific path to front of "Variable value" field, separated by a semicolon from the existing entry. Do not add a space between ; and last entry
4. Run the following command in Windows Command Prompt from any location:
git config --global http.sslCAInfo "C:/Users/okogan/Downloads/ca-bundle.crt"
Path to ca-bundle.crt file or any other certificate file for that matter is unique of course.
Tuesday, November 8, 2016
Async calls in MVC with sitecore
1. Comment out code in RegisterRoutes
2. In Global.asax file in Application_Start add your custom route mappings BEFORE RegisterRoutes is called. This is important otherwise MVC routing will trigger first and custom routes would not resolve.
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
var routes = RouteTable.Routes;
routes.MapRoute(
"AccountUpdateEmail", // Route name
"account/updateemail", // URL with parameters
new { controller = "Account", action = "UpdateEmail" } // Parameter defaults
);
RouteConfig.RegisterRoutes(RouteTable.Routes);
}
Renderings:
1. Without a datasource. Make a view rendering and point to your view in the Path field like this: /views/Shared/BottomText.cshtml
2. By default MVC view renderings use
@model Sitecore.Mvc.Presentation.RenderingModel
but you don't have to specify this at the top of the view. It happens automatically.
3. Add your code:
<div>
Data comes from current item: @Model.Item.Name
</div>
<div>
Data comes from a datasource: @Html.Sitecore().Field("Title")
</div>
4. My calls are async from front end. Note the url string and an MVC route in the Application_Start.
$("#emailSave").click(function () {
//Make an async call to an action method
var model = @Html.Raw(Json.Encode(Model));
model.Email = $("#Email").val();
var urlString = "/account/updateemail/?email=" + model.Email;
//alert(urlString);
$.getJSON(urlString, function (data) {
if (data.Message === "success") {
$("#showEmail").css('display', 'none');
$("#currentEmail").text(data.Email);
//display success message
$("#yei").css('display', 'block');
} else {
//show error message
$(".good success-bgd error").css('display', 'block');
}
});
});
5. This is what UpdateEmail action method looks like:
public ActionResult UpdateEmail(SecurityModel model)
{
if (!string.IsNullOrEmpty(Request.QueryString["email"]))
{
//HHOG: Make a call to save a service to save the email(IAccountRepository Update)
CurrentUser.Account.Email = model.Email;
bool result = _accountRepository.Update(CurrentUser.Account);
if (result) //add error checking here
{
model.Message = "success";
}
else
{
model.Message = "error";
}
}
return Json(model, JsonRequestBehavior.AllowGet);
}
Thursday, November 3, 2016
Add an existing MVC app to a Sitecore 8+ site
1. Remove debug and release configs from under Web.config in solution
2. Got to webconfig's properties (in solution) set Build Action to None
3. Add a TDS project and wire it up to connect to your Sitecore site using your web project (not C# library project)
4. Right click solution => Configuration Manager and make sure the TDS project has Deploy checked in Debug coniguration.
5. Disable default route in RouteConfig
6. Make a sitecore Item you intend to be navigable
7. Make an MVC layout (.cshtml file)
@using Sitecore.Mvc
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Test1</title>
</head>
<body>
<div>
@Html.Sitecore().Placeholder("body")
</div>
</body>
</html>
8. Make a controller rendering that points to a controller and action method
9. Add the controller rendering you just created to the placeholder "body"
10. Make sure to add references to Sitecore and Sitecore.Mvc
Ways to check if you actually fully plugged in your MVC app into a sitecore site are:
1. Make your navigable item cacheable and add the DateTime.Now.Ticks to your view. Watch it not change unless you publish an item.
2. Make sure your controllers (and your views just in case) have access to Sitecore context (Sitecore.Context.Item.Name)
When you build solution insuring step 4 makes TDS project build.
Was getting an illegal routes error. Made a config file, put it in the App_Config/Include. Did not work. Had to uncomment the default route in the RouteConfig in my solution so I could see the showconfig console for the sitecore site.
That showed me two settings where should be been only one. The patch did not work.
<?xml version="1.0" encoding="utf-8" ?>
<configuration xmlns:patch="http://www.sitecore.net/xmlconfig/">
<sitecore>
<settings>
<setting name="Mvc.IllegalRoutes">
<patch:attribute name="value" value="" />
</setting>
</settings>
</sitecore>
</configuration>
Went directly to the Sitecore.Mvc.config and replaced
<setting name="Mvc.IllegalRoutes" value="|{controller}/{action}/{id}|" patch:source="Sitecore.Mvc.config"/> with
https://doc.sitecore.net/sitecore_experience_platform/developing/developing_with_sitecore/mvc/use_mvc_routing#_Define_a_custom
ToDo:
1. Set up dependencies
For a sitecore Item the layout should be either aspx or cshtml for MVC
2. Got to webconfig's properties (in solution) set Build Action to None
3. Add a TDS project and wire it up to connect to your Sitecore site using your web project (not C# library project)
4. Right click solution => Configuration Manager and make sure the TDS project has Deploy checked in Debug coniguration.
5. Disable default route in RouteConfig
6. Make a sitecore Item you intend to be navigable
7. Make an MVC layout (.cshtml file)
@using Sitecore.Mvc
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Test1</title>
</head>
<body>
<div>
@Html.Sitecore().Placeholder("body")
</div>
</body>
</html>
8. Make a controller rendering that points to a controller and action method
9. Add the controller rendering you just created to the placeholder "body"
10. Make sure to add references to Sitecore and Sitecore.Mvc
Ways to check if you actually fully plugged in your MVC app into a sitecore site are:
1. Make your navigable item cacheable and add the DateTime.Now.Ticks to your view. Watch it not change unless you publish an item.
2. Make sure your controllers (and your views just in case) have access to Sitecore context (Sitecore.Context.Item.Name)
When you build solution insuring step 4 makes TDS project build.
Was getting an illegal routes error. Made a config file, put it in the App_Config/Include. Did not work. Had to uncomment the default route in the RouteConfig in my solution so I could see the showconfig console for the sitecore site.
That showed me two settings where should be been only one. The patch did not work.
<?xml version="1.0" encoding="utf-8" ?>
<configuration xmlns:patch="http://www.sitecore.net/xmlconfig/">
<sitecore>
<settings>
<setting name="Mvc.IllegalRoutes">
<patch:attribute name="value" value="" />
</setting>
</settings>
</sitecore>
</configuration>
Went directly to the Sitecore.Mvc.config and replaced
<setting name="Mvc.IllegalRoutes" value="|{controller}/{action}/{id}|" patch:source="Sitecore.Mvc.config"/> with
https://doc.sitecore.net/sitecore_experience_platform/developing/developing_with_sitecore/mvc/use_mvc_routing#_Define_a_custom
ToDo:
1. Set up dependencies
For a sitecore Item the layout should be either aspx or cshtml for MVC
The file "/views/Shared/_Layout.cshtml" cannot be requested directly because it calls the "RenderBody" method.
Sitecore configs
When processing the web.config file, Sitecore includes configuration files specified by <sc:include> elements as well as those in the /App_Config/Include subdirectory. This allows administrators to define module-specific, feature-specific, solution-specific, instance-specific and other specific configuration in files separate from the main web.config file, which can simplify configuration, release management, and other aspects of the system.
The /App_Config/Include subdirectory contains examples that you can investigate with the .example extension. To enable the configuration in one of these example files, rename it with the .config extension.
The structure of web.config include file mimics the structure of the web.config file including the /configuration/sitecore element. Unfortunately, you can only patch elements within the /configuration/sitecore element.
Config files get included just by the virtue of being placed in the App_Config/Include folder.
Add an existing MVC app to a Sitecore 8+ site
1. Remove debug and release configs from under Web.config in solution
2. Got to webconfig's properties (in solution) set Build Action to None
3. Add a TDS project and wire it up to connect to your Sitecore site
4. Right click solution => Configuration Manager and make sure the TDS project has Deploy checked in Debug coniguration.
When you build solution insuring step 4 makes TDS project build.
Was getting an illegal routes error. Made a config file, put it in the App_Config/Include. Did not work. Had to uncomment the default route in the RouteConfig in my solution so I could see the showconfig console for the sitecore site.
That showed me two settings where should be been only one. The patch did not work.
<?xml version="1.0" encoding="utf-8" ?>
<configuration xmlns:patch="http://www.sitecore.net/xmlconfig/">
<sitecore>
<settings>
<setting name="Mvc.IllegalRoutes">
<patch:attribute name="value" value="" />
</setting>
</settings>
</sitecore>
</configuration>
Went directly to the Sitecore.Mvc.config and replaced
<setting name="Mvc.IllegalRoutes" value="|{controller}/{action}/{id}|" patch:source="Sitecore.Mvc.config"/> with
2. Got to webconfig's properties (in solution) set Build Action to None
3. Add a TDS project and wire it up to connect to your Sitecore site
4. Right click solution => Configuration Manager and make sure the TDS project has Deploy checked in Debug coniguration.
When you build solution insuring step 4 makes TDS project build.
Was getting an illegal routes error. Made a config file, put it in the App_Config/Include. Did not work. Had to uncomment the default route in the RouteConfig in my solution so I could see the showconfig console for the sitecore site.
That showed me two settings where should be been only one. The patch did not work.
<?xml version="1.0" encoding="utf-8" ?>
<configuration xmlns:patch="http://www.sitecore.net/xmlconfig/">
<sitecore>
<settings>
<setting name="Mvc.IllegalRoutes">
<patch:attribute name="value" value="" />
</setting>
</settings>
</sitecore>
</configuration>
Went directly to the Sitecore.Mvc.config and replaced
<setting name="Mvc.IllegalRoutes" value="|{controller}/{action}/{id}|" patch:source="Sitecore.Mvc.config"/> with
Delete an SQL database
Could not delete from the folder. Needed to open Management studio and delete there. Then could delete the site's folder in Inetpub. Then remove site from IIS.
Thursday, October 27, 2016
Two submit buttons on the same form in MVC
http://stackoverflow.com/questions/5706815/html-inside-label-using-html-helper
Friday, September 30, 2016
Modify object rather than properties
We had a class named Account with members like Name, Email and Alternate Email. I added a method to update Alternate Email. But Matt suggested making an abstract class (so no instantiation from there) and the updatable properties would have get; set; but the ones that are not updatable are only get; (read only).
Therefore later on you can inherit form Account and pass the entire object to an Update method and only update the updatable fields rather than have update method for each updatable field.
Therefore later on you can inherit form Account and pass the entire object to an Update method and only update the updatable fields rather than have update method for each updatable field.
Thursday, September 29, 2016
Azure
Not sure how JSON applies to Azure? Let's backup: the Azure Resource Manager is where you deploy, manage, and monitor application infrastructure
(i.e., your database, web app, and other virtual machines). Within the Azure Resource Manager you have
Azure Resource Templates which enable you to deploy multiple services and their dependencies with ease.
These Azure Resource Templates consist of JSON expressions that you can use in your deployment.
(i.e., your database, web app, and other virtual machines). Within the Azure Resource Manager you have
Azure Resource Templates which enable you to deploy multiple services and their dependencies with ease.
These Azure Resource Templates consist of JSON expressions that you can use in your deployment.
Friday, September 23, 2016
You can build multiple projects with MSBUILD
https://msdn.microsoft.com/en-us/library/bb651793.aspx
You can use MSBuild to build multiple projects faster by running them in parallel. To run builds in parallel, you use the following settings on a multi-core or multiple processor computer:
- The /maxcpucount switch at a command prompt.
- The BuildInParallel task parameter on an MSBuild task.
Tuesday, September 6, 2016
Lucene Index
in Feature.Training.config
<configuration xmlns:patch="http://www.sitecore.net/xmlconfig/" xmlns:set="http://www.sitecore.net/xmlconfig/set/">
<sitecore>
<pipelines>
<NVelocityMessage>
<processor type="Sitecore.Feature.Training.WFFM.Pipelines.ProcessTrainingMessage, Sitecore.Feature.Training" />
</NVelocityMessage>
</pipelines>
<setting name="TrainingFormIDs" value="{2C02F84E-BED7-47E5-8165-FA74916010E2}|{82084F1C-C5E3-455D-8269-A922656E90D8}|{9495AA67-9E2E-42C8-8D3A-AC9E99250150}|{62B46FD0-95D3-4362-BEAC-307B1B4B53B0}|{8A9A92B1-BA0E-49ED-AECA-C8B008DCB12C}|{A4F2DDC1-5190-4354-9DF4-65D07EB58BBB}|{F16BA235-9049-4D0E-A7E9-CAAE78319252}|{01D322D4-906A-409E-B2FB-59DE5340D4B4}|{F2B99E8B-03A1-413C-B4A9-7151B43E7B89}|{ED8C6B39-2942-43AA-9E97-53D2550ED7EC}" />
<contentSearch>
<configuration type="Sitecore.ContentSearch.ContentSearchConfiguration, Sitecore.ContentSearch">
<indexes hint="list:AddIndex">
<!-- TRAININGS INDEX configuration -->
<index id="sitecore_trainings_index" type="Sitecore.ContentSearch.LuceneProvider.LuceneIndex, Sitecore.ContentSearch.LuceneProvider">
<param desc="name">$(id)</param>
<param desc="core">trainings</param>
<param desc="propertyStore" ref="contentSearch/indexConfigurations/databasePropertyStore" param1="$(id)" />
<strategies hint="list:AddStrategy">
<strategy ref="contentSearch/indexConfigurations/indexUpdateStrategies/rebuildAfterFullPublish" />
<strategy ref="contentSearch/indexConfigurations/indexUpdateStrategies/onPublishEndAsync"/>
<strategy ref="contentSearch/indexConfigurations/indexUpdateStrategies/remoteRebuild" />
</strategies>
<locations hint="list:AddCrawler">
<crawler type="Sitecore.ContentSearch.SitecoreItemCrawler, Sitecore.ContentSearch">
<Database>web</Database>
<Root>/sitecore/content/WWW/Home/Services and Support/Training</Root>
</crawler>
</locations>
<configuration ref="contentSearch/indexConfigurations/defaultLuceneIndexConfiguration">
<indexAllFields>true</indexAllFields>
<fields hint="raw:AddComputedIndexField">
<field fieldName="areaid" storageType="no" indexType="untokenized">Sitecore.Feature.Training.Search.Provider.Solr.Fields.AreaIdField, Sitecore.Feature.Training</field>
<field fieldName="coursecategoryid" storageType="no" indexType="untokenized">Sitecore.Feature.Training.Search.Provider.Solr.Fields.CourseCategoryIdField, Sitecore.Feature.Training</field>
<field fieldName="courselanguage" storageType="no" indexType="untokenized">Sitecore.Feature.Training.Search.Provider.Solr.Fields.CourseLanguageField, Sitecore.Feature.Training</field>
<field fieldName="worldpartid" storageType="no" indexType="untokenized">Sitecore.Feature.Training.Search.Provider.Solr.Fields.WorldPartIdField, Sitecore.Feature.Training</field>
</fields>
<include hint="list:IncludeTemplate">
<template>{CEFB4D88-F881-48DD-A5B6-A5283779F99F}</template>
<template>{586E5499-E5B3-4514-9BF1-A30FFA69B40C}</template>
<template>{DB7283F4-B7BC-4C91-8BFA-C0146C1C4777}</template>
</include>
</configuration>
</index>
</indexes>
</configuration>
</contentSearch>
</sitecore>
</configuration>
And then this would be a model that is used in the search:
<configuration xmlns:patch="http://www.sitecore.net/xmlconfig/" xmlns:set="http://www.sitecore.net/xmlconfig/set/">
<sitecore>
<pipelines>
<NVelocityMessage>
<processor type="Sitecore.Feature.Training.WFFM.Pipelines.ProcessTrainingMessage, Sitecore.Feature.Training" />
</NVelocityMessage>
</pipelines>
<setting name="TrainingFormIDs" value="{2C02F84E-BED7-47E5-8165-FA74916010E2}|{82084F1C-C5E3-455D-8269-A922656E90D8}|{9495AA67-9E2E-42C8-8D3A-AC9E99250150}|{62B46FD0-95D3-4362-BEAC-307B1B4B53B0}|{8A9A92B1-BA0E-49ED-AECA-C8B008DCB12C}|{A4F2DDC1-5190-4354-9DF4-65D07EB58BBB}|{F16BA235-9049-4D0E-A7E9-CAAE78319252}|{01D322D4-906A-409E-B2FB-59DE5340D4B4}|{F2B99E8B-03A1-413C-B4A9-7151B43E7B89}|{ED8C6B39-2942-43AA-9E97-53D2550ED7EC}" />
<contentSearch>
<configuration type="Sitecore.ContentSearch.ContentSearchConfiguration, Sitecore.ContentSearch">
<indexes hint="list:AddIndex">
<!-- TRAININGS INDEX configuration -->
<index id="sitecore_trainings_index" type="Sitecore.ContentSearch.LuceneProvider.LuceneIndex, Sitecore.ContentSearch.LuceneProvider">
<param desc="name">$(id)</param>
<param desc="core">trainings</param>
<param desc="propertyStore" ref="contentSearch/indexConfigurations/databasePropertyStore" param1="$(id)" />
<strategies hint="list:AddStrategy">
<strategy ref="contentSearch/indexConfigurations/indexUpdateStrategies/rebuildAfterFullPublish" />
<strategy ref="contentSearch/indexConfigurations/indexUpdateStrategies/onPublishEndAsync"/>
<strategy ref="contentSearch/indexConfigurations/indexUpdateStrategies/remoteRebuild" />
</strategies>
<locations hint="list:AddCrawler">
<crawler type="Sitecore.ContentSearch.SitecoreItemCrawler, Sitecore.ContentSearch">
<Database>web</Database>
<Root>/sitecore/content/WWW/Home/Services and Support/Training</Root>
</crawler>
</locations>
<configuration ref="contentSearch/indexConfigurations/defaultLuceneIndexConfiguration">
<indexAllFields>true</indexAllFields>
<fields hint="raw:AddComputedIndexField">
<field fieldName="areaid" storageType="no" indexType="untokenized">Sitecore.Feature.Training.Search.Provider.Solr.Fields.AreaIdField, Sitecore.Feature.Training</field>
<field fieldName="coursecategoryid" storageType="no" indexType="untokenized">Sitecore.Feature.Training.Search.Provider.Solr.Fields.CourseCategoryIdField, Sitecore.Feature.Training</field>
<field fieldName="courselanguage" storageType="no" indexType="untokenized">Sitecore.Feature.Training.Search.Provider.Solr.Fields.CourseLanguageField, Sitecore.Feature.Training</field>
<field fieldName="worldpartid" storageType="no" indexType="untokenized">Sitecore.Feature.Training.Search.Provider.Solr.Fields.WorldPartIdField, Sitecore.Feature.Training</field>
</fields>
<include hint="list:IncludeTemplate">
<template>{CEFB4D88-F881-48DD-A5B6-A5283779F99F}</template>
<template>{586E5499-E5B3-4514-9BF1-A30FFA69B40C}</template>
<template>{DB7283F4-B7BC-4C91-8BFA-C0146C1C4777}</template>
</include>
</configuration>
</index>
</indexes>
</configuration>
</contentSearch>
</sitecore>
</configuration>
And then this would be a model that is used in the search:
namespace Sitecore.Feature.Training.Models.Search
{
using System.Collections.Generic;
using System.ComponentModel;
using Sitecore.ContentSearch;
using Sitecore.ContentSearch.Converters;
using Sitecore.ContentSearch.SearchTypes;
using Sitecore.Data;
using Foundation.Indexing.Models.Concrete;
public class TrainingAreaModel : IndexedItem
{
[IndexField("Country")]
public List<string> Countries { get; set; }
[IndexField("State")]
public List<string> States { get; set; }
}
}
Country and State are actual field names in sitecore.And this is one of the computted fields:
namespace Sitecore.Feature.Training.Search.Provider.Solr.Fields
{
using Sitecore.ContentSearch;
using Sitecore.ContentSearch.ComputedFields;
using Sitecore.Data.Items;
using Sitecore.Feature.Training.Models.Items;
using Sitecore.Foundation.SitecoreExtensions.Extensions;
public class AreaIdField : AbstractComputedIndexField
{
public override object ComputeFieldValue(IIndexable indexable)
{
var item = (Item)(indexable as SitecoreIndexableItem);
if (item == null || !item.IsItemOfType(Templates._ELearning_Course.ID))
{
return null;
}
var courseDateItem = new CourseDateItem(item);
return courseDateItem.Area.ID;
}
}
}
Luke - Lucene Index Toolbox
Lucene is an Open Source, mature and high-performance Java search engine. It is highly flexible, and scalable from hundreds to millions of documents.
Luke is a handy development and diagnostic tool, which accesses already existing Lucene indexes and allows you to display and modify their content in several ways:
- browse by document number, or by term
- view documents / copy to clipboard
- retrieve a ranked list of most frequent terms
- execute a search, and browse the results
- analyze search results
- selectively delete documents from the index
- reconstruct the original document fields, edit them and re-insert to the index
- optimize indexes
- open indexes consisting of multiple parts, and/or located on Hadoop filesystem
- and much more...
Subscribe to:
Posts (Atom)