Resharper Code Pattern for IDisposable not inside using - resharper

I'd like to know how to build a Resharper (6.1) code pattern to search and replace the following issues:
var cmd = new SqlCommand();
cmd.ExecuteNonQuery();
and turn it into this:
using (var cmd = new SqlCommand())
{
cmd.ExecuteNotQuery();
}
and:
StreamReader reader = new StreamReader("myfile.txt");
string line = reader.Read();
Console.WriteLine(line);
becomes:
using (StreamReader reader = new StreamReader("file.txt"))
{
string line = reader.ReadLine();
Console.WriteLine(line);
}
EDIT: Thanks for the answers, but I'm looking for anything that implements IDisposable

Search pattern:
var $cmd$ = $sqlcommand$;
$cmd$.ExecuteNonQuery();
Replace pattern:
using (var $cmd$ = $sqlcommand$)
{
$cmd$.ExecuteNonQuery();
}
where cmd = identifier
and sqlcommand = expression of type System.Data.SqlClient.SqlCommand

It looks like what you're really after is an inspection mechanism that goes off looking for IDisposable objects and ensures they are disposed. If that's the case, I doubt custom patterns would be the right approach - after all, what if you do call Dispose() a few lines later?
One way to implement this is by using the ReSharper SDK. In fact, one of the examples the SDK comes with is a PowerToy which implements IDisposable on a particular class, so you could take that code as a foundation for possible analysis of usage.

Use the Search with Pattern tool under the ReSharper | Find menu.
In the Search pattern make sure you have C# selected and enter the code you're searching for in the box. Click the Replace button in the top-right, and enter the code you want to replace it with in the Replace pattern box.
You can save the search and replace pattern and R# will use it for subsequent code analysis should you so desire. You can also add additional patterns in R# Options under Code Inspection | Custom Patterns.

Related

JMonkeyEngine FullScreen Script

I'm pretty new to Java scripting I was wondering if any of you could tell me what's wrong with these lines:
GraphicsDevice device = GraphicsEnviroment.
getLocalGraphicEnviroment().getDefaultScreenDevice();
settings.setResolution(modes[0].getWidth(), modes][0].getHeight());
settings.setFrequency(mdoe{[0].getFrequencyRate());
settings.setDepthBits(modes[0].getBitDepth());
settings.setFullscreen(device.isFullScreenSupported());
I'm sure we could debate the meaning of the word 'script', but that is Java, not a Java script (and certainly not javascript)...
You have several problems with extra punctuation, missing variable declarations, and misspelled method names. The code you want can be found on the jME3 website:
public void toggleToFullscreen() {
GraphicsDevice device = GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice();
DisplayMode[] modes = device.getDisplayModes();
int i=0; // note: there are usually several, let's pick the first
settings.setResolution(modes[i].getWidth(),modes[i].getHeight());
settings.setFrequency(modes[i].getRefreshRate());
settings.setBitsPerPixel(modes[i].getBitDepth());
settings.setFullscreen(device.isFullScreenSupported());
app.setSettings(settings);
app.restart(); // restart the context to apply changes
}

Resharper formatting chained method

Is there a setting in R# to format chained method to start at the same character of the class instantiated.
What I want:
var foo = new FooDataBuilder()
.WithDate(myDate)
.WithBar(myBar)
.Build();
What R# is giving me:
var foo = new FooDataBuilder()
.WithDate(myDate)
.WithBar(myBar)
.Build();
With Resharper 7.1.2, you can get the following formatting:
var foo = new FooDataBuilder().WithDate(myDate)
.WithBar(myBar)
.Build();
By setting the following Resharper options:
Code Editing->C#->Formatting Style->Line Breaks and Wrapping->Line Wrapping->Wrap chained method calls to Chop always
and
enable Code Editing->C#->Formatting Style->Other->Align Multiline Constructs->Chained method calls
I don't think you can align with FooDataBuilder() unless you do it manually. (This has been confirmed by #Dmitry Osinovskiy from Jetbrains so this may be the closest you're going to get to what you want.)

Tridion: Dreamweaver doesn't resolves the HTML code field

We have a compound CT, which outputs the code field of one of the component.
The dream-weaver part of CT is as follows:
<!-- TemplateBeginRepeat name="Component.HTMLCode" -->
##Component.HTMLCode##
<!-- TemplateEndRepeat -->
However this CT displays the code field on the page, instead of converting into HTML.
For eg: If the code field has a value as ->
<div align="center" id="loginapp"></div>
Then this same value is displayed on page instead of parsing.
In the page source, we get output as "&lt ;div align=&quot ;center" id=&quot ;loginapp&quot ;&gt ;&lt ;/div&gt ;"
I know this can be resolved if we use C#.
But is there any way using dreamweaver to stop the conversion of special characters?
You should use dwt to publish the code to server, I mean create new dwt for every code and just paste the code in the dwt. you can use this dwt with emply component or resource type component.
or if you want to use text field, try following tbb code. add this tbb at the end of the template.
public override void Transform(Engine engine, Package package)
{
Regex objExp = new Regex(#"&#\d+;", RegexOptions.IgnoreCase);
Regex objDecExp = new Regex(#"[^0-9]", RegexOptions.IgnoreCase);
this.Initialize(engine, package);
string strPackage = package.GetValue("Output");
strPackage = unescapeHTML(strPackage);
strPackage = objExp.Replace(strPackage, delegate (Match match)
{
string strInput = match.ToString();
strInput = objDecExp.Replace(strInput, "");
int intValue = Convert.ToInt32(strInput);
char strChar = (char)intValue;
return strChar.ToString();
});
strPackage = strPackage.Trim();
Item objOutput = package.CreateStringItem(ContentType.Html, strPackage);
package.PushItem("Output", objOutput);
}
private string unescapeHTML(string strInput)
{
StringBuilder strOutput = new StringBuilder(strInput);
strOutput.Replace(""", """);
strOutput.Replace(" ", " ");
strOutput.Replace("&", "&");
strOutput.Replace("&apos;", "'");
strOutput.Replace("<", "<");
strOutput.Replace(">", ">");
strOutput.Replace("¡", "&#161");
strOutput.Replace("¢", "&#162");
strOutput.Replace("£", "&#163");
strOutput.Replace("¤", "&#164");
strOutput.Replace("¥", "&#165");
strOutput.Replace("¦", "&#166");
strOutput.Replace("§", "&#167");
strOutput.Replace("¨", "&#168");
strOutput.Replace("©", "&#169");
strOutput.Replace("ª", "&#170");
strOutput.Replace("¬", "&#172");
strOutput.Replace("­", "&#173");
strOutput.Replace("®", "&#174");
strOutput.Replace("¯", "&#175");
strOutput.Replace("°", "&#176");
return strOutput.ToString();
}
}
If I recall correctly it is depending on your fieldtype, if in your Schema you use a normal text field, then HTML is escaped, if you use a rich text field, it will be resolved.
An option would perhaps be to write a Dreamweaver Custom function which allows you to unescape the field (represent it as an HTML field rather than a text field). As you mentioned you could also do it in a TBB, but the Dreamweaver Custom Functions are directly callable from the DWT Template. Either way I think you indeed need to do some coding yourself.
RenderComponentField has two parameters: bool htmlEncodeResult, and bool resolveHtmlAsRTFContent. Are you using this built in function?
Thanks for your help. After lots of trials with dreamweaver code, we decided to use C# TBB instead which solved the purpose.
Also reading the multiline field as a textfield was one of the mistake we committed. This caused the field value to be displayed on page instead of rendering as a code behind.
We finally solved the issue using "MultilineTextField".

Configuring Solr for Suggestive/Predictive Auto Complete Search

We are working on integrating Solr 3.6 to an eCommerce site. We have indexed data & search is performing really good.
We have some difficulties figuring how to use Predictive Search / Auto Complete Search Suggestion. Also interested to learn the best practices for implementing this feature.
Our goal is to offer predictive search similar to http://www.amazon.com/, but don't know how to implement it with Solr. More specifically I want to understand how to build those terms from Solr, or is it managed by something else external to solr? How the dictionary should be built for offering these kind of suggestions? Moreover, for some field, search should offer to search in category. Try typing "xper" into Amazon search box, and you will note that apart from xperia, xperia s, xperia p, it also list xperia s in Cell phones & accessories, which is a category.
Using a custom dictionary this would be difficult to manage. Or may be we don't know how to do it correctly. Looking to you to guide us on how best utilize solr to achieve this kind of suggestive search.
I would suggest you a couple of blogpost:
This one which shows you a really nice complete solution which works well but requires some additional work to be made, and uses a specific lucene index (solr core) for that specific purpose
I used the Highlight approach because the facet.prefix one is too heavy for big index, and the other ones had few or unclear documentation (i'm a stupid programmer)
So let's suppose the user has just typed "aaa bbb ccc"
Our autocomplete function (java/javascript) will call solr using the following params
q="aaa bbb"~100 ...base query, all the typed words except the last
fq=ccc* ...suggest word filter using last typed word
hl=true
hl.q=ccc* ...highlight word will be the one to suggest
fl=NONE ...return empty docs in result tag
hl.pre=### ...escape chars to locate highlight word in the response
hl.post=### ...see above
you can also control the number of suggestion with 'rows' and 'hl.fragsize' parameters
the highlight words in each document will be the right candidates for the suggestion with "aaa bbb" string
more suggestion words are the ones before/after the highlight words and, of course, you can implement more filters to extract valid words, avoid duplicates, limit suggestions
if interested i can send you some examples...
EDITED: Some further details about the approach
The portion of example i give supposes the 'autocomplete' mechanism given by jquery: we invoke a jsp (or a servlet) inside a web application passing as request param 'q' the words just typed by user.
This is the code of the jsp
ByteArrayInputStream is=null; // Used to manage Solr response
try{
StringBuffer queryUrl=new StringBuffer('putHereTheUrlOfSolrServer');
queryUrl.append("/select?wt=xml");
String typedWords=request.getParameter("q");
String base="";
if(typedWords.indexOf(" ")<=0) {
// No space typed by user: the 'easy case'
queryUrl.append("&q=text:");
queryUrl.append(URLEncoder.encode(typedWords+"*", "UTF-8"));
queryUrl.append("&hl.q=text:"+URLEncoder.encode(typedWords+"*", "UTF-8"));
} else {
// Space chars present
// we split the search in base phrase and last typed word
base=typedWords.substring(0,typedWords.lastIndexOf(" "));
queryUrl.append("&q=text:");
if(base.indexOf(" ")>0)
queryUrl.append("\""+URLEncoder.encode(base, "UTF-8")+"\"~1000");
else
queryUrl.append(URLEncoder.encode(base, "UTF-8"));
typedWords=typedWords.substring(typedWords.lastIndexOf(" ")+1);
queryUrl.append("&fq=text:"+URLEncoder.encode(typedWords+"*", "UTF-8"));
queryUrl.append("&hl.q=text:"+URLEncoder.encode(typedWords+"*", "UTF-8"));
}
// The additional parameters to control the solr response
queryUrl.append("&rows="+suggestPageSize); // Number of results returned, a parameter to control the number of suggestions
queryUrl.append("&fl=A_FIELD_NAME_THAT_DOES_NOT_EXIST"); // Interested only in highlights section, Solr return a 'light' answer
queryUrl.append("&start=0"); // Use only first page of results
queryUrl.append("&hl=true"); // Enable highlights feature
queryUrl.append("&hl.simple.pre=***"); // Use *** as 'highlight border'
queryUrl.append("&hl.simple.post=***"); // Use *** as 'highlight border'
queryUrl.append("&hl.fragsize="+suggestFragSize); // Another parameter to control the number of suggestions
queryUrl.append("&hl.fl=content,title"); // Look for result only in some fields
queryUrl.append("&facet=false"); // Disable facets
/* Omitted section: use a new URL(queryUrl.toString()) to get the solr response inside a byte array */
is=new ByteArrayInputStream(solrResponseByteArray);
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(is);
XPathFactory xPathfactory = XPathFactory.newInstance();
XPath xpath = xPathfactory.newXPath();
XPathExpression expr = xpath.compile("//response/lst[#name=\"highlighting\"]/lst/arr[#name=\"content\"]/str");
NodeList valueList = (NodeList) expr.evaluate(doc, XPathConstants.NODESET);
Vector<String> suggestions=new Vector<String>();
for (int j = 0; j < valueList.getLength(); ++j) {
Element value = (Element) valueList.item(j);
String[] result=value.getTextContent().split("\\*\\*\\*");
for(int k=0;k<result.length;k++){
String suggestedWord=result[k].toLowerCase();
if((k%2)!=0){
//Highlighted words management
if(suggestedWord.length()>=suggestedWord.length() && !suggestions.contains(suggestedWord))
suggestions.add(suggestedWord);
}else{
/* Words before/after highlighted words
we can put these words inside another vector
and use them if not enough suggestions */
}
}
}
/* Finally we build a Json Answer to be managed by our jquery function */
out.print(request.getParameter("json.wrf")+"({ \"suggestions\" : [");
boolean firstSugg=true;
for(String suggestionW:suggestions) {
out.print((firstSugg?" ":" ,"));
out.print("{ \"suggest\" : \"");
if(base.length()>0) {
out.print(base);
out.print(" ");
}
out.print(suggestionW+"\" }");
firstSugg=false;
}
out.print(" ]})");
}catch (Exception x) {
System.err.println("Exception during main process: " + x);
x.printStackTrace();
}finally{
//Gracefully close streams//
try{is.close();}catch(Exception x){;}
}
Hope to be helpfull,
Nik
This might help you out.I am trying to do the same.
http://solr.pl/en/2010/10/18/solr-and-autocomplete-part-1/

CATextlayer with AttributedString in MonoTouch

I am trying to create a "label" with different styles on different words, kind of like described here.
The problem is - as far as I can see - the MonoTouch implementation of UATextLayer does not accept assigning an NSAttributedString to the String property since the String property has the type string.
Is this an error in the implementation or is there another way of doing this?
(Yes, I am aware I can add separate labels - but I would rather not when there is a better solution).
EDIT (in response to the answer from Miguel):
After changing to GetHandler and correcting to "void_objc_msgSend_IntPtr" instead of "void_objc_msgSend_IntPrt" the code in the answer compiles and runs, but it doesn't quite work anyway (I was a bit fast in marking it as the answer).
No errors are thrown, but the text doesn't show.
Code:
string _text="Example string";
if(_textLayer==null) {
_textLayer = new CATextLayer();
_textLayer.Frame = new RectangleF(50,698,774,50);
_textLayer.Wrapped=true;
_textLayer.ForegroundColor=UIColor.White.CGColor;
_textLayer.BackgroundColor=UIColor.Clear.CGColor;
Layer.AddSublayer(_textLayer);
}
//_textLayer.String=_text;
CTFont _font=new CTFont("MarkerFelt-Thin",48);
CTStringAttributes _attrs=new CTStringAttributes();
_attrs.Font=_font;
_attrs.ForegroundColor = UIColor.White.CGColor;
var nsa = new NSAttributedString(_text);
Messaging.void_objc_msgSend_IntPtr(
_textLayer.Handle,
Selector.GetHandle("string"),
nsa.Handle);
If I uncomment the _textLayer.String=_text I see the text (but without attributes of course), so the problem is not with the layer.
For now, you can try:
using MonoTouch.ObjCRuntime;
var caTextLayer = new CATextLayer ();
var nsa = new NSAttributedString ();
[..]
Messaging.void_objc_msgSend_IntPrt (
caTextLayer.Handle,
Selector.sel_registerName ("string"),
nsa.Handle);
Alternatively, can you download this preview of the upcoming version:
http://tirania.org/tmp/monotouch.dll
It implements a property AttributedString in CATextLayer that you can set.

Resources