Answered by:
How to pass string from IWizrad run started method to razor mvc project template (.cshtml file)

Question
-
i have one razor mvc project template with wizard concept. i want to pass some string from wizard application to .cshtml file. i have passed using RunStarted method of wizard application. Please check code below.
{
try
{
dte = automationObject as DTE;.............................................................................................................
replacementsDictionary.Add("$ProductA$", "Mobile");
.................................................................
}
catch()
{
}
}
in Template .cshtml file please check the code.
<html>
<head> </head>
<body>
"$ProductA$"
</body>
</html>
but the the value of "$ProductA$" is not replaced in .cshtml page. but it was working fine in .Aspx page .CS page. how can do that in .cshtml.
urgent requirement.
Please anyone help.
Thanks..
siva
siva
Friday, April 13, 2012 8:58 AM
Answers
-
Can you post some additional details here? Its not obvious how you're getting this to be invoked. From what I've seen, the MVC3 wizard stuff is pretty closed up. It looks like they use a custom wizard that launches another template/wizard. Not sure how you were able to get this working.
If your IWizard is being invoked, what does your .vstemplate look like for this wizard? Is the CSHTML file listed as a projectitem in the vstemplate? And if so, do you set the ReplaceParameters attribute to True?
Thanks,
Ed Dore
- Proposed as answer by Ed DoreMicrosoft employee Wednesday, April 18, 2012 2:20 AM
- Marked as answer by Siva Rajini Wednesday, April 18, 2012 4:17 AM
Wednesday, April 18, 2012 2:20 AM
All replies
-
Hi Siva,
You should pass this key and value ("$ProductA$", "Mobile") with customParams parameters.
This parameters different from replacementsDictionary.
Regards,
Mehmet.
Friday, April 13, 2012 9:16 AM -
Hi Mehmetk,
Thanks for your reply.
I have tried your solution using customParams to pass the string from wizard application to template. but it is not working for me.
customParams already contains 2 items.
1. Template path
2.$targetframeworkversion$=4.0
public void RunStarted(object automationObject, Dictionary<string, string> replacementsDictionary, WizardRunKind runKind, object[] customParams)
{
try
{}
Am going to use $targetframeworkversion$ in Aspx page ,controller page (.cs) page and it was working fine.that means 4.0 string is replaced for $targetframeworkversion$ in both pages.
but if am using this same string in .cshtml page .it will not replaced. so i want to know how to replace the string .cshtml page.
passing a string from wizard is not matter. we can pass it in different way.
if the string is in ASPX page .CS page ,it will replace with specific value .but if it is .cshtml page it will not replaced. thats my only problem.
please help me.
urgent requirement.
Thanks,
siva
- Edited by Siva Rajini Friday, April 13, 2012 10:28 AM
Friday, April 13, 2012 10:27 AM -
Hi Siva,
May be this code is usefull
public void ProjectItemFinishedGenerating(EnvDTE.ProjectItem projectItem) { object[] customParams = new object[1] { "$CustomParameter$=ValueProvidedAtRuntime_Changed"}; Array customParamsAsArray = customParams; RunWizardEx(projectItem, "fileNameWithoutExtension_For_ProjItemToBeGenerated", GetVsProjectItemTemplatePath("ProjItemName_From_VSTemplateFile"), IntPtr.Zero, customParams); } public static string GetVsProjectItemTemplatePath(string itemName) { EnvDTE80.DTE2 dte = Microsoft.VisualStudio.Shell.Package.GetGlobalService(typeof(EnvDTE.DTE)) as EnvDTE80.DTE2; if (dte != null) { EnvDTE80.Solution2 solution = dte.Solution as EnvDTE80.Solution2; if (solution != null) { return solution.GetProjectItemTemplate(itemName, "ProjectTypeNode_From_ProjItemVsTemplateFile"); } } return null; } private VSADDRESULT RunWizardEx(EnvDTE.ProjectItem projectItem, string itemName, string wizardToRun, IntPtr dlgOwner, object[] customParams) { Debug.Assert(!String.IsNullOrEmpty(itemName), "The Add item dialog was passing in a null or empty item to be added to the hierrachy."); // Build up the ContextParams safearray // [0] = Wizard type guid (bstr) // [1] = Project name (bstr) // [2] = ProjectItems collection (bstr) // [3] = Local Directory (bstr) // [4] = Filename the user typed (bstr) // [5] = Product install Directory (bstr) // [6] = Run silent (bool) object[] contextParams = new object[7]; contextParams[0] = EnvDTE.Constants.vsWizardAddItem; contextParams[1] = projectItem.ContainingProject.Name; contextParams[2] = projectItem.ContainingProject.ProjectItems; contextParams[3] = Path.GetDirectoryName(projectItem.ContainingProject.FullName); contextParams[4] = itemName; object objInstallationDir = null; IVsShell shell = (IVsShell)Package.GetGlobalService(typeof(IVsShell)); ErrorHandler.ThrowOnFailure(shell.GetProperty((int)__VSSPROPID.VSSPROPID_InstallDirectory, out objInstallationDir)); string installDir = (string)objInstallationDir; // append a '\' to the install dir to mimic what the shell does (though it doesn't add one to destination dir) if (!installDir.EndsWith("\\", StringComparison.Ordinal)) { installDir += "\\"; } contextParams[5] = installDir; contextParams[6] = true; IVsExtensibility3 ivsExtensibility = Package.GetGlobalService(typeof(IVsExtensibility)) as IVsExtensibility3; Debug.Assert(ivsExtensibility != null, "Failed to get IVsExtensibility3 service"); if (ivsExtensibility == null) { return VSADDRESULT.ADDRESULT_Failure; } int wizResultAsInt; Array contextParamsAsArray = contextParams; Array customParamsAsArray = customParams; int result = ivsExtensibility.RunWizardFileEx(wizardToRun, (int)dlgOwner, ref contextParamsAsArray, ref customParamsAsArray, out wizResultAsInt); if (!ErrorHandler.Succeeded(result) && result != VSConstants.OLE_E_PROMPTSAVECANCELLED) { ErrorHandler.ThrowOnFailure(result); } EnvDTE.wizardResult wizardResult = (EnvDTE.wizardResult)wizResultAsInt; switch (wizardResult) { default: return VSADDRESULT.ADDRESULT_Cancel; case wizardResult.wizardResultSuccess: return VSADDRESULT.ADDRESULT_Success; case wizardResult.wizardResultFailure: return VSADDRESULT.ADDRESULT_Failure; } }
Mehmet.
Friday, April 13, 2012 1:31 PM -
Hi Mehmet,
Thank you very much for ur solution.
But My requirement is different. I want to pass some string from wizard to .cshtml page. i can able to pass to .Aspx page and .cs page -> it was working fine.
how can i replace the string .cshtml file.
for ex: _Index.cshtml contains "$A$"
i want to replace "$A$" by some value "Product".
how can i do this ?
i have already using this kind of coding
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
public class Wizardclass : IWizard
{
#region private members
private MainWindow wizardFrm;
private string customMessage;
private string sXmlPath = @"Products.xml";
private string[] products;
private string configPath;
private IEnumerable<string> pSelect;
private DTE dte;
private string masterPath;
private string textTransformLocation = string.Empty;
private string sAspRazor;
private string uDoc;
private string destfile;
private string srcMaster;
private string destMasterFile;
#endregion
public void BeforeOpeningFile(ProjectItem projectItem)
{
}
public void ProjectFinishedGenerating(Project project)
{
customMessage = wizardFrm.get_CustomMessage();
uDoc = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
if (customMessage != string.Empty && !customMessage.Equals("CloseApp"))
{
ProjectItem pConfigItem = project.ProjectItems.Item(9);
ProjectItem pMasterItem = dte.Solution.FindProjectItem(sAspRazor);
configPath = pConfigItem.Properties.Item("FullPath").Value;
masterPath = pMasterItem.Properties.Item("FullPath").Value;
if (pSelect.Contains("True"))
AddAssembly("Common-Mobile");
if (pSelect.Contains("False"))
AddAssembly("Common");
foreach (string product in products)
{
if (product != string.Empty)
{
switch (product)
{
case "Tools":
AddAssembly(product);
break;
case "Grid":
AddAssembly(product);
break;
case "Chart":
AddAssembly(product);
break;
case "Gauge":
AddAssembly(product);
break;
case "Schedule":
AddAssembly(product);
break;
case "Diagram":
AddAssembly(product);
break;
case "DocIO":
AddAssembly(product);
break;
case "Pdf":
AddAssembly(product);
break;
case "XlsIO":
AddAssembly(product);
break;
case "PdfViewer":
AddAssembly(product);
break;
case "OlapGrid":
AddAssembly(product);
break;
case "Mobile-Chart":
AddAssembly(product);
break;
case "Mobile-Grid":
AddAssembly(product);
break;
case "Mobile-Tools":
AddAssembly(product);
break;
case "Mobile-Gauge":
AddAssembly(product);
break;
}
}
}
if (sAspRazor.Equals("Site.tt"))
{
destfile = uDoc + @"\Site.tt";
srcMaster = uDoc + @"\Site.Master";
}
else
{
destfile = uDoc + @"\_Layout.tt";
srcMaster = uDoc + @"\_Layout.cshtml";
}
RegistryKey regKey = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion");
if ((regKey != null))
{
textTransformLocation = (string)regKey.GetValue("CommonFilesDir") + @"\Microsoft Shared\TextTemplating\10.0\TextTransform.exe";
}
File.Copy(masterPath, destfile, true);
System.Diagnostics.Process proc = new System.Diagnostics.Process();
proc.StartInfo.UseShellExecute = true;
proc.EnableRaisingEvents = false;
// Set text transform program (this could change according to the Windows version)
proc.StartInfo.FileName = textTransformLocation;
// Specify T4 template file
proc.StartInfo.Arguments = destfile;
proc.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
proc.Start();
proc.WaitForExit();
destMasterFile =sAspRazor.Equals("Site.tt") ? masterPath.Replace("Site.tt", "Site.Master") : masterPath.Replace("_Layout.tt", "_Layout.cshtml");
File.Copy(srcMaster, destMasterFile,true);
project.ProjectItems.AddFromFile(destMasterFile);
pMasterItem.Remove();
File.Delete(pMasterItem.Properties.Item("FullPath").Value);
File.Delete(destfile);
File.Delete(srcMaster);
}
}
private void AddAssembly(string prod)
{
Project project = dte.Solution.Projects.Item(1);
VSProject vsproject = project.Object;
IEnumerable<XElement> elementref;
//Assembly ass = Assembly.GetExecutingAssembly();
XElement xElement = XElement.Load(sXmlPath);
IEnumerable<XElement> address = from el in xElement.Elements("Product") where (string)el.Attribute("name") == prod select el;
XElement element = address.First();
XElement elementAssembly = element.Element("assemblies");
XElement elementNameSpace = element.Element("namespaces");
XElement elementhttpHandler = element.Element("httpHandlers");
XElement elementHandler = element.Element("handlers");
if (element.Element("References") != null)
{
elementref = element.Element("References").Elements();
foreach (XElement e1 in elementref)
vsproject.References.Add(e1.Value);
}
XElement xconfigElement = XElement.Load(configPath);
XElement xmlAssembly = xconfigElement.Element("system.web").Element("compilation").Element("assemblies");
XElement xmlNamespace = xconfigElement.Element("system.web").Element("pages").Element("namespaces");
XElement xmlHandlers = xconfigElement.Element("system.web").Element("httpHandlers");
XElement xmlserverHandlers = xconfigElement.Element("system.webServer").Element("handlers");
Addhandlers(xmlAssembly, elementAssembly, "assembly");
Addhandlers(xmlNamespace, elementNameSpace, "namespace");
Addhandlers(xmlHandlers, elementhttpHandler, "type");
Addhandlers(xmlserverHandlers, elementHandler, "type");
xconfigElement.Save(configPath);
}
private void Addhandlers(XElement destElement, XElement srcElement, string attr)
{
if (srcElement != null)
{
srcElement.Elements().ToList().ForEach(x =>
{
if (destElement != null && destElement.Elements() != null)
{
bool isExist = false;
destElement.Elements().ToList().ForEach(p =>
{
if (p != null && p.Attribute(attr) != null && x != null && x.Attribute(attr) != null && p.Attribute(attr).Value == x.Attribute(attr).Value)
{
isExist = true;
}
});
if (!isExist)
destElement.AddFirst(x);
}
});
}
}
public void ProjectItemFinishedGenerating(ProjectItem projectItem)
{
}
public void RunFinished()
{
}
public void RunStarted(object automationObject, Dictionary<string, string> replacementsDictionary, WizardRunKind runKind, object[] customParams)
{
try
{
dte = automationObject as DTE;
//Call win form created in the project to accept user input
wizardFrm = new MainWindow();
wizardFrm.ShowDialog();
customMessage = wizardFrm.get_CustomMessage();
if(customMessage != string.Empty && customMessage.Equals("CloseApp"))
{
this.wizardFrm.Close();
Application.Current.MainWindow.Close();
}
else
{
products = customMessage.Split(new char[] { '_' }, StringSplitOptions.RemoveEmptyEntries);
pSelect = products.Select(p => p.StartsWith("Mobile").ToString());
string sScriptCombine = Convert.ToString(wizardFrm.get_CompressScript()).ToLower();
string sStyleCombine = Convert.ToString(wizardFrm.get_CompressStyle()).ToLower();
string DeskTheme = wizardFrm.get_DeskTheme();
string MobTheme = wizardFrm.get_MobileTheme();
DeskTheme = string.IsNullOrEmpty(DeskTheme) ? "None" : DeskTheme;
MobTheme = string.IsNullOrEmpty(MobTheme) ? "None" : MobTheme;
MessageBox.Show("RunStart");
//customParams[customParams.Length-1] = "$Product$=Syncfusion";
MessageBox.Show(customParams.Length.ToString());
MessageBox.Show(customParams.FirstOrDefault().ToString());
MessageBox.Show(customParams.LastOrDefault().ToString());
if (pSelect.Contains("True"))
{
replacementsDictionary.Add("$ProductA$", "Mobile");
replacementsDictionary.Add("$MobTheme$", MobTheme);
replacementsDictionary.Add("$sMobStyleCombine$", sStyleCombine);
replacementsDictionary.Add("$sMobScriptCombine$", sScriptCombine);
}
else
{
replacementsDictionary.Add("$ProductA$", "");
}
if (pSelect.Contains("False"))
{
replacementsDictionary.Add("$ProductB$", "Desktop");
replacementsDictionary.Add("$DeskTheme$", DeskTheme);
replacementsDictionary.Add("$sDeskStyleCombine$", sStyleCombine);
replacementsDictionary.Add("$sDeskScriptCombine$", sScriptCombine);
}
else
{
replacementsDictionary.Add("$ProductB$", "");
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
public bool ShouldAddProjectItem(string filePath)
{
customMessage = wizardFrm.get_CustomMessage();
if ((filePath.Equals("Site.tt") || filePath.Equals("_Layout.tt")))
sAspRazor = filePath;
if (customMessage != string.Empty && !customMessage.Equals("CloseApp"))
{
return true;
}
else
{
return false;
}
}
}<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
From above coding i want to replace $ProductA$ string Index.cshtml page to "Mobile"... that's only am asking...
your solution going some where....
Please try to understood my requirement. am in hurry situation. please help me.
how to replace the string .cshtml page using wizard concept.
Thanks,
siva
Friday, April 13, 2012 2:12 PM -
Hi Anybody,
Please reply for the above question.
Please help me.
urgent requirement.
Thanks,
siva
Monday, April 16, 2012 5:19 AM -
Hi siva,
Thank you for your question.
I am trying to involve someone familiar with this topic to further look at this issue. There might be some time delay. Appreciate your patience.
Thank you for your understanding and support.Lucy Liu [MSFT]
MSDN Community Support | Feedback to us
Tuesday, April 17, 2012 6:21 AM -
Hi Siva,
same keyword in in the customParams is default. For Example, .$targetframeworkversion$ is default.
if you use custom keyword, You can use example that I wrote. This method for custom keywords.
in this example, adding key to collection what you want and value.
Regards,
Mehmet
Tuesday, April 17, 2012 1:54 PM -
Can you post some additional details here? Its not obvious how you're getting this to be invoked. From what I've seen, the MVC3 wizard stuff is pretty closed up. It looks like they use a custom wizard that launches another template/wizard. Not sure how you were able to get this working.
If your IWizard is being invoked, what does your .vstemplate look like for this wizard? Is the CSHTML file listed as a projectitem in the vstemplate? And if so, do you set the ReplaceParameters attribute to True?
Thanks,
Ed Dore
- Proposed as answer by Ed DoreMicrosoft employee Wednesday, April 18, 2012 2:20 AM
- Marked as answer by Siva Rajini Wednesday, April 18, 2012 4:17 AM
Wednesday, April 18, 2012 2:20 AM -
Hi Ed Dore,
Thanks...
You are really great.
After the long time.... (struggled more and more in .cshtml page string replacement with wizard value ) After using your solution ReplaceParameters attribute working fine..
Thanks a lot..
Thanks ,
siva
Wednesday, April 18, 2012 4:20 AM