Fetch id from url in block file - block

What is the standard of Magento for fetch id from URL in the block file?
My URL is http://test.com/quote/savequote/view/id/7/
My XML file
<quote_savequote_view>
<label>View Quote</label>
<reference name="root">
<action method="setTemplate">
<template>page/1column.phtml</template>
</action>
</reference>
<reference name="content">
<block type="quote/savequote" name="quote.savequote" template="quote/view.phtml" />
</reference>
</quote_savequote_view>
Controller Action
public function viewAction(){
$this->loadLayout();
$this->renderLayout();
}
Block File
public function getDetails(){
// I want to get id here and I want to use the id in collection
}
Please help me what is the standard.

Finally I have solution, We can use mage register for pass data between block and controller.
public function viewAction(){
$id = Mage::app()->getRequest()->getParam('id');
$results = // your model results
Mage::register('quotedetails', $results);
$this->loadLayout();
$this->renderLayout();
}
Block File
public function getDetails(){
return Mage::registry('quotedetails');
}

Related

Sitecore Pipeline (indexing.filterIndex.inbound) not being called

I am trying to create a Lucene index in Sitecore 8.x of items that are visible to unauthenticated users (extranet\Anonymous). In order to do this I am trying to use the indexing.filterIndex.inbound pipeline.
I have tried writing a custom pipeline that returns false if the item cannot be read as extranet\Anonymous:
public class ApplyInboundIndexAccessFilter : InboundIndexFilterProcessor
{
public override void Process(InboundIndexFilterArgs args)
{
var item = args.IndexableToIndex as SitecoreIndexableItem;
var anonymousUser = Sitecore.Security.Accounts.User.FromName("extranet\\anonymous", false);
if (!item.Item.Security.CanRead(anonymousUser))
{
args.IsExcluded = true;
}
}
}
but at no time does this pipeline get invoked.
I have added my config (tried it with the default, before, after, with the default removed)
<configuration xmlns:patch="http://www.sitecore.net/xmlconfig/">
<sitecore>
<pipelines>
<indexing.filterIndex.inbound>
<processor type="MyApplication.Site.Features.ContentSearch.IndexFilters.ApplyInboundIndexAccessFilter, MyApplication.Site">
<includedIndexNames hint="list">
<indexName>siteSearchIndex_web</indexName>
</includedIndexNames>
<excludedIndexNames hint="list">
<indexName>siteSearchIndex_master</indexName>
</excludedIndexNames>
</processor>
</indexing.filterIndex.inbound>
</pipelines>
</sitecore>
</configuration>
Am I right in assuming that this should be called on indexing, if not, when?
Any suggestions would be gratefully received.

ReadAsAsync<T>,Expecting element from namespace 'http://schemas.datacontract.org/2004/07/",Encountered 'Element' with name 'workflow', namespace ''

I am trying to consume a REST API to Get data by httpclient, encountered a parsing problem ,{"Error in line 1 position 95. Expecting element 'workflow' from namespace 'http://schemas.datacontract.org/2004/07/'.. Encountered 'Element' with name 'workflow', namespace ''. "}
the client code is
string baseUri = "/rest/workflows/";
client = CreateClient(baseUri);
HttpRequestMessage request = CreateRequest(baseUri);
var task = client.SendAsync(request);
HttpResponseMessage response = task.Result;
response.EnsureSuccessStatusCode();
response.Content.ReadAsAsync<collection>().ContinueWith(wf =>
{
Console.WriteLine(wf.Result.workflow.Length);
});
the data classes
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.17929")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlRootAttribute(Namespace = "http://www.w3.org/2005/Atom", IsNullable = false)]
public partial class collection
{
private workflow[] workflowField;
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute("workflow", Form = System.Xml.Schema.XmlSchemaForm.Unqualified)]
public workflow[] workflow
{
get
{
return this.workflowField;
}
set
{
this.workflowField = value;
}
}
}
and the response xml file is in this format
<collection xmlns:ns2="http://www.w3.org/2005/Atom">
<workflow uuid="5ffbde8c-c430-4851-9c83-164c102a4d68">
<name>Remove a Volume</name>
<categories>
<category>Decommissioning</category>
</categories>
</workflow>
</collection>
I can get the string by using response.Content.ReadAsStringAsync() and save it to xml file, then ,i deserilize it to collection,can succeed ,but need and a default namespace to the serizliazer
XmlSerializer serializer = new XmlSerializer(typeof(collection), "xmlns:ns2=\"http://www.w3.org/2005/Atom\"");
c = serializer.Deserialize(stream) as collection;
anyone can help on this
You should not touch the generated file from xsd.exe tool.
Just explicitly set that you want to use the XmlSerializer instead of the DataContractSerializer used by default with XmlMediaTypeFormatter by setting UseXmlSerializer = true.
So you must create a specific type formatter like this :
var formatters = new List<MediaTypeFormatter>() {
new XmlMediaTypeFormatter(){ UseXmlSerializer = true } };
And use it as a parameter of the ReadAsAsync method :
private async Task<T> ReadAsync<T>(HttpResponseMessage response)
=> await response.Content.ReadAsAsync<T>(formatters);
Your namespaces do not match; your xml declares a namespace alias (ns2) for the atom address, but the namespace of the collection element is still empty, since it doesn't use that alias (it is not ns2:collection). Either the xml is wrong or the code is. If the xml cannot be changed, then simply set the namespace on the [XmlRoot(...)] to be the empty string. If the C# is correct and the xml is wrong, then make it the namespace instead of an alias:
<collection xmlns="http://www.w3.org/2005/Atom">
<workflow uuid="5ffbde8c-c430-4851-9c83-164c102a4d68">
<name>Remove a Volume</name>
<categories>
<category>Decommissioning</category>
</categories>
</workflow>
</collection>
or identically:
<ns2:collection xmlns:ns2="http://www.w3.org/2005/Atom">
<workflow uuid="5ffbde8c-c430-4851-9c83-164c102a4d68">
<name>Remove a Volume</name>
<categories>
<category>Decommissioning</category>
</categories>
</workflow>
</ns2:collection>
I had the exact same issue when reading data from my web api. What solved the issue for me is to decorate the class in the client with the [DataContract(Namespace="namespacefromyourwebapi")] attribute and for each property in your class decorate it with the [DataMember] attribute.

How to do Excel File upload in struts2?

I am trying to upload Excel only file in Struts2 WEB Application. So using the following Code in Jsp page:
<s:label value="File Name : *" />
<s:file name="fileUpload" label="Select a File to upload"/>
<br>
<br>
<s:submit value="Add" name="add" tabindex="8" />
</s:form>
In Response.jsp page displaying the File content and It's type as Follows:
<s:form action="saveBulkStores.action" method="get" >
<h4>
File Name : <s:property value="fileUploadFileName"/>
</h4>
<h4>
Content Type : <s:property value="fileUploadContentType"/>
</h4>
<h4>
File : <s:property value="fileUpload"/>
</h4>
<br>
</s:form>
In Struts.xml:
<action name="bulkStores" class="com.action.FilesUploadAction"
method="loadBulkStoresPage">
<result name="input">/viewfile.jsp</result>
<result name="success">/uploadfile.jsp</result>
</action>
<action name="saveBulkStores" class="com.action.FilesUploadAction"
method="saveBulkStores">
<interceptor-ref name="exception"/>
<interceptor-ref name="i18n"/>
<interceptor-ref name="fileUpload">
<param name="allowedTypes">text/plain</param>
<param name="maximumSize">10240</param>
</interceptor-ref>
<interceptor-ref name="params">
<param name="excludeParams">dojo\..*,^struts\..*</param>
</interceptor-ref>
<interceptor-ref name="validation">
<param name="excludeMethods">input,back,cancel,browse</param>
</interceptor-ref>
<interceptor-ref name="workflow">
<param name="excludeMethods">input,back,cancel,browse</param>
</interceptor-ref>
<result name="input">/uploadfile.jsp</result>
<result name="success">/success.jsp</result>
</action>
In Action Classes:
public String loadBulkStoresPage(){
System.out.println("FILES BULK UPLOADS.........");
return SUCCESS;
}
private File fileUpload;
private String fileUploadContentType;
private String fileUploadFileName;
//Getters and Setters for above Fields.
Displaying filename,content type as follows:
public String saveBulkStores(){
System.out.println("check Bulk upload file");
System.out.println("fileName:"+fileUploadFileName);
System.out.println("content type:"+fileUploadContentType);
System.out.println("fileupload:"+fileUpload);
return SUCCESS;
}
Output:
It's displaying NUll value only for my display statements. So anyone help me to fix this issue. thanks in Advance.
I am new to do this task.
FileUtils is not part of the standard JDK, it a class in the Apache Commons IO library.It contains Methods like
FileUtils.readFileToString(file);
FileUtils.copyDirectoryToDirectory(source, destination);
FileUtils.deleteDirectory(source);......................which make copying files from one directory to other directory in most easier way in word it reduces voluminous amount of code as entire code is written by Apache people
please refer this URL for reference http://www.koders.com/java/fid002DB6BD79CABA7B6AA0F2669061424E3B9776D3.aspx
<s:file id="myFile" name="myFile" disabled="true" ></s:file> is the tag that is used to upload file put the tag in jsp.
And the properties in action class as i written below
private File myFile;
private String myFileContentType;
private String myFileFileName;
/**
* #return the myFile
*/
public File getMyFile() {
return myFile;
}
/**
* #return the myFileContentType
*/
public String getMyFileContentType() {
return myFileContentType;
}
/**
* #return the myFileFileName
*/
public String getMyFileFileName() {
return myFileFileName;
}
/**
* #param myFile the myFile to set
*/
public void setMyFile(File myFile) {
this.myFile = myFile;
}
/**
* #param myFileContentType the myFileContentType to set
*/
public void setMyFileContentType(String myFileContentType) {
this.myFileContentType = myFileContentType;
}
/**
* #param myFileFileName the myFileFileName to set
*/
public void setMyFileFileName(String myFileFileName) {
this.myFileFileName = myFileFileName;
}
and In execute method insert this code
String destaddress=getText("ipaddress");
if(myFile!=null){
File destDir= new File(destaddress+myFileFileName);
destDir.createNewFile();
FileUtils.copyFile(myFile, destDir);
}
you add ip address in apllication properties file as show below
ipaddress=\\\\192.168.105.68\\Shared2\\Files\\
and the following interceptors to your struts. XML file
<interceptor-ref name="fileUpload">
<param name="maximumSize">52428800</param>
</interceptor-ref>
<interceptor-ref name="basicStack"/>
ipaddress=\\\\192.168.105.68\\Shared2\\Files\\
This will solve your problem.

How to Email an Entire Log File through Nlog

Salvete! nLog for .NET has the capability to send log entries as email. But if we want to send the entire current log file, how can it be done, short of reading the log file into a string and passing that as an nLog {$message}? I don't see that nLog has a property in its mailtarget for attachments. How can this be done?
I just did this today in C#. I followed the answer provided by arkmuetz here How to get path of current target file using NLog in runtime? to first get the filename of the Nlog target. I then read the file and copied the contents of the file to another Nlog target which emailed the log in the body of the message.
First I created an NlogHelper Class
public static class NlogHelper
{
/// <summary>
/// Gets LogFileName by TargetName
/// </summary>
/// <param name="targetName">The nLog targetname for the specified logger.</param>
/// <returns></returns>
/// <remarks>https://stackoverflow.com/questions/11452645/how-to-get-path-of-current-target-file-using-nlog-in-runtime</remarks>
public static string GetLogFileName(string targetName)
{
string fileName = null;
if (LogManager.Configuration != null && LogManager.Configuration.ConfiguredNamedTargets.Count != 0)
{
Target target = LogManager.Configuration.FindTargetByName(targetName);
if (target == null)
{
throw new Exception("Could not find target named: " + targetName);
}
FileTarget fileTarget = null;
WrapperTargetBase wrapperTarget = target as WrapperTargetBase;
// Unwrap the target if necessary.
if (wrapperTarget == null)
{
fileTarget = target as FileTarget;
}
else
{
fileTarget = wrapperTarget.WrappedTarget as FileTarget;
}
if (fileTarget == null)
{
throw new Exception("Could not get a FileTarget from " + target.GetType());
}
var logEventInfo = new LogEventInfo { TimeStamp = DateTime.Now };
fileName = fileTarget.FileName.Render(logEventInfo);
}
else
{
throw new Exception("LogManager contains no Configuration or there are no named targets");
}
//if (!File.Exists(fileName))
//{
// throw new Exception("File " + fileName + " does not exist");
//}
return fileName;
}
}
Next I retrieved the file name in the constructor and stored it for later use.
_logLileName = NlogHelper.GetLogFileName("DailyFile");
For my purposes I created property that I later used to retrieve the contents of the log file.
public string LogFileContent
{
get
{
return File.ReadAllText(_logLileName);
}
}
Finally I added the contents of the file to the log to be emailed.
_logger.Error("Excel Builder LinkShare Error encountered -- Some companies did not complete succesfully!. Please review logs. \n" + mfb.LogFileContent);
Here is my nLog.config file thought will help make things more clear.
<?xml version="1.0" encoding="utf-8" ?>
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" >
<targets>
<target name="console" xsi:type="ColoredConsole"
layout="${date:format=HH\:mm\:ss}|${level}|${stacktrace}|${message}" />
<target name="file" xsi:type="File" fileName="${basedir}/DomoExcelBuilderLog.txt"
layout="${stacktrace} ${message}" />
<target name="DailyFile" xsi:type="File" fileName="C:\Temp\Log${shortdate}.txt"
layout="${date:format=HH\:mm\:ss} --> ${message}" deleteOldFileOnStartup="true" />
<target name="file2" xsi:type="File" fileName="${basedir}/ServiceLog.txt"
layout="${stacktrace} ${message}" />
<target name="MyMailer" xsi:type="Mail"
smtpServer="some.server.com"
smtpPort="587"
smtpAuthentication="Basic"
smtpUsername="no-reply"
smtpPassword="somepassword"
enableSsl="true"
from="no-reply#some.server.com"
to="myemail#gmail.com"/>
</targets>
<rules>
<logger name="MultipleFileBuilder" minlevel="Trace" writeTo="DailyFile" />
<logger name="ExcelBuilderService" minlevel="Debug" writeto="MyMailer" />
</rules>
</nlog>
My application first logs to the logger named 'MultipleFileBuilder'. I then use the NLogHelper class to retrieve the contents of the Target 'DailiyFile'.
Hope this helps someoneout.
(NOTE: I removed the checking to see if the file exists in the 'GetLogFileName' method because in my case file didn't exist.)
I think you may use a combination of targets: default target + MethodCall and then send email manually or use Mail + Buffering to send a batch of records.

passing value object to itemRenderer

how can access/pass a value object in a custom itemrenderer? The item renderer represents a field in my datagrid and i want to be able access properties from my VO.
Thanks
You will want to override the set data method of the item renderer:
<?xml version="1.0" encoding="utf-8"?>
<mx:Canvas xmlns:fx="http://ns.adobe.com/mxml/2009" xmlns:s="library://ns.adobe.com/flex/spark" xmlns:mx="library://ns.adobe.com/flex/halo">
<fx:Script>
<![CDATA[
//Strongly typed VO for use in binding.
[Bindable]
private var myValueObject:MyValueObject;
override public function set data(value:Object) : void
{
//we don't want to update if the value is the exact same.
if(data === value)
return;
//you could simply access the data property but I think
//it is nicer to have strong typing for code hints
super.data = myValueObject = value;
validateNow();
}
]]>
</fx:Script>
<mx:Label text="{myValueObject.name}"/>
</mx:Canvas>
What about this approach?
Item renderer ItemRendererLink.mxml:
public function goTo():void {
Alert.show(goToScreen + " " + data.item_num);
}
]]>
</mx:Script>
</mx:LinkButton>
parent component:
<mx:DataGridColumn dataField="item_num"
headerText="Item #">
<mx:itemRenderer>
<mx:Component>
<e:ItemRendererLink goToScreen="item"/>
</mx:Component>
</mx:itemRenderer>
</mx:DataGridColumn>