converting Wildcard to Regex - regex

I'm new in MVC, I want to perform Wildcard (*, ?) search on database. This is what I have done by using Regex:
Controller:
using System.Linq;
using System.Text.RegularExpressions;
using System.Web.Mvc;
using WebApplication1.Models;
namespace WebApplication1.Controllers
{
public class HomeController : Controller
{
CrossWord_dbEntities db = new CrossWord_dbEntities();
public ActionResult Index(string searching)
{
if (searching == null)
{
searching = "*";
}
string regEx = WildcardToRegex(searching);
return View(db.tbl_values.ToList().Where(x => Regex.IsMatch(x.Name, regEx, RegexOptions.Singleline)));
}
public static string WildcardToRegex(string pattern)
{
return "^" + Regex.Escape(pattern).
Replace("\\*", ".*").
Replace("\\?", ".") + "$";
}
}
}
View:
#model IEnumerable<WebApplication1.Models.tbl_values>
<br /><br />
#using (Html.BeginForm("Index", "Home", FormMethod.Get))
{
#Html.TextBox("searching") <input type="submit" value="Search" />
}
<table class="table table-striped">
<thead>
<tr>
<th>Results</th>
</tr>
</thead>
<tbody>
#if (Model.Count() == 0)
{
<tr>
<td colspan="3" style="color:red">
No Result
</td>
</tr>
}
else
{
foreach (var item in Model)
{
<tr>
<td>
#item.Name
</td>
</tr>
}
}
</tbody>
</table>
i have in my database three recordes: Hello, Hero, Shalom
when i type " H* " i get the result: Hello, Hero - this works great
but when i type " *lom " i get "No Result" instead of "Shalom"
or when i type " Hell?" i get "No Result" instead of "Hello"
what i did wrong ?

You can use the following
Expression<Func<tbl_value, bool>> query = m =>
SqlFunctions.PatIndex(searching.ToLower().Replace("*", "%"), m.Name.ToLower()) > 0;
var details = db.tbl_values.Where(query);
Hope this will help you

Related

Translate selection fields from another model - Template Website Odoo 11

I have a selection type field who is coming another model. But, my traduction file do not take it into account. I am looking to find a other solution for translate values fields this select field.
Any idea ?
EDIT :
Here my template code :
...<table class="table table-hover table_requests" id="order_tableau">
<thead>
<tr>
<th scope="col">Reference</th>
<th scope="col">Type</th>
<th scope="col">Applicant</th>
<th scope="col">Date</th>
<th scope="col">State</th>
</tr>
</thead>
<tbody>
<t t-foreach="requests_grc" t-as="request_grc">
<tr id="result_requests" t-att-onclick="'window.location=\'/web#id='+str(request_grc.id)+'&view_type=form&model=website.application&menu_id=299&action=389\''"
t-att-class="'cursor-pointer'">
<td><t t-esc="request_grc.name"/></td>
<td><t t-esc="request_grc.website_application_template_id.name"/></td>
<td><t t-esc="request_grc.applicant_id.name"/></td>
<td><t t-esc="request_grc.date" t-options="{'widget': 'date'}"/></td>
<td><t t-esc="request_grc.state"/></td>
</tr>
</t>
</tbody>
</table>...
Here my Python code :
requests_grc = http.request.env['website.application'].search([])
Result
I would translate the last element on my table : request_grc.state
EDIT :
#http.route('/web_demarches/', auth='user', website=True)
def indexDemarches(self, **kw):
user = http.request.env.user.name
active_new = False
active_in_progress = False
active_completed_request = False
active_refused_request = False
nb_new_request = 0
nb_in_progress_request = 0
nb_completed_request = 0
nb_refused_request = 0
requests_grc = http.request.env['website.application'].search([])
requests_grc_new = http.request.env['website.application'].search([('state', '=', 'new')])
requests_grc_in_progress = http.request.env['website.application'].search(['|', ('state', '=', 'in_progress'),
('state', '=', 'is_pending')])
requests_grc_completed = http.request.env['website.application'].search([('state', '=', 'completed')])
requests_grc_refused = http.request.env['website.application'].search([('state', '=', 'rejected')])
for request_new in requests_grc_new:
nb_new_request = nb_new_request + 1
for request_in_progress in requests_grc_in_progress:
nb_in_progress_request = nb_in_progress_request + 1
for request_completed in requests_grc_completed:
nb_completed_request = nb_completed_request + 1
for request_refused in requests_grc_refused:
nb_refused_request = nb_refused_request + 1
return http.request.render('grc_parthenay.demarches', {
'user': user,
'active_new': active_new,
'active_in_progress': active_in_progress,
'active_completed_request': active_completed_request,
'active_refused_request': active_refused_request,
'requests_grc': requests_grc,
'requests_grc_new': requests_grc_new,
'requests_grc_in_progress': requests_grc_in_progress,
'requests_grc_completed': requests_grc_completed,
'requests_grc_refused': requests_grc_refused,
'nb_new_request': nb_new_request,
'nb_in_progress_request': nb_in_progress_request,
'nb_completed_request': nb_completed_request,
'nb_refused_request': nb_refused_request,
})

Apache Velocity - if clause

I use Apache Velocity for create an e-mail template.
I have a mail message that contain a table with a list of elements, for create it I had used a #foreach.
In this table I'll add a column contained a conditional string, If the element is empty the string are string1 if is not empty are string2.
This is my code:
#foreach( $item in $list )
<td style="max-width: 140px; word-wrap: break-word;">
#if(${value} not null) 'String1' #else 'String2'#end</td>
#end
Error log:
org.apache.velocity.runtime.parser.ParseException: Encountered "null" at line 25, column 131. Was expecting one of:
"[" ...
"{" ...
"(" ...
<STRING_LITERAL> ...
"true" ...
"false" ...
<INTEGER_LITERAL> ...
<FLOATING_POINT_LITERAL> ...
<IDENTIFIER> ...
"{" ...
"[" ...
at org.apache.velocity.runtime.parser.Parser.generateParseException(Parser.java:3679)
I don't find any help in stack... anyone can help me?
I think this can run in your case:
#if( $value)
<td style="max-width: 140px; word-wrap: break-word;">String1</td>
#else
<td style="max-width: 140px; word-wrap: break-word;">String2</td>
#end
Try to read this question

How to select only inline style in html file using regex?

I tried to select the inline styles in p tag and div tag only. But no need to select td, inline styles
regex style=[\"\w\d\.\:\-\'\s\#\;]+
Input:
<p class="Test"><span style="font-family:Verdana">?</span><span style="font:7.0pt 'Times New Roman'">  </span><span>AAA</span></p>
<table cellspacing="0" cellpadding="0" style="border-collapse:collapse; margin-left:0pt">
<tr>
<td style="border-bottom-color:#808080; border-bottom-style:solid; border-bottom-width:0.5pt; border-top-color:#808080; border-top-style:solid; border-top-width:0.5pt; padding-bottom:2.85pt; padding-top:2.85pt; vertical-align:top; width:81pt">
<p class="Tabelle" style="margin-top:3pt; margin-bottom:3pt"><span style="font-family:Tahoma; font-size:9pt">Detail</span></p>
</td>
output:
style="margin-top:3pt; margin-bottom:3pt in p tag
Note:
I need to select only p tag, div tag tags inline styles.
You can try this:
Find by:
(<(?:p|div)[^<]*)(style="[^"]*")([^>]*>)
replace by:
$1$3
C# Code Sample:
using System;
using System.Text.RegularExpressions;
public class Test
{
public static void Main()
{
string pattern = #"(<(?:p|div)[^<]*)(style=""[^""]*"")([^>]*>)";
string substitution = #"$1$3";
string input = #"<p class=""Test""><span style=""font-family:Verdana"">?</span><span style=""font:7.0pt 'Times New Roman'"">  </span><span>AAA</span></p>
<table cellspacing=""0"" cellpadding=""0"" style=""border-collapse:collapse; margin-left:0pt"">
<tr>
<td style=""border-bottom-color:#808080; border-bottom-style:solid; border-bottom-width:0.5pt; border-top-color:#808080; border-top-style:solid; border-top-width:0.5pt; padding-bottom:2.85pt; padding-top:2.85pt; vertical-align:top; width:81pt"">
<p class=""Tabelle"" style=""margin-top:3pt; margin-bottom:3pt""><span style=""font-family:Tahoma; font-size:9pt"">Detail</span></p>
</td>
";
RegexOptions options = RegexOptions.Multiline;
Regex regex = new Regex(pattern, options);
string result = regex.Replace(input, substitution);
System.Console.WriteLine(result);
}
}
Explanation
You get yoru data in group 1

File Uploader in Edit Template in List View

I am using File uploader in edit template in list view to update the list view.
I am using on item updating to handle the update of list view. However it is throwing error at cmd.executenonquery(). Can anyone help me in this regard.
<EditItemTemplate>
<tr style="background-color:#008A8C;color: #FFFFFF;">
<td>
<asp:Button ID="UpdateButton" runat="server" Text="Update" CommandName="Update"/>
<asp:Button ID="CancelButton" runat="server" CommandName="Cancel" Text="Cancel" />
</td>
<td>
<asp:Label ID="productidLabel1" runat="server" Text='<%# Eval("productid") %>' />
</td>
<td>
<asp:TextBox ID="productnameTextBox" runat="server" Text='<%# Bind("productname") %>' />
</td>
<td>
<asp:TextBox ID="productdescTextBox" runat="server" Text='<%# Bind("productdesc") %>' />
</td>
<td>
<asp:TextBox runat="server" ID="productpriceTextBox" Text='<%# Bind("productprice") %>'> </asp:TextBox>
</td>
<td>
<asp:DropDownList SelectedValue='<%# Bind("productcateg") %>' runat="server" ID="dropdownlist" style="overflow:auto" CssClass="dropdown">
<asp:ListItem Enabled="true" Text="Select Category" Value="-1"></asp:ListItem>
<asp:ListItem Text="Watch" Value="Watch"> </asp:ListItem>
<asp:ListItem Text="Hand Bags" Value="handbag"></asp:ListItem>
<asp:ListItem Text="Television" Value="television"></asp:ListItem>
<asp:ListItem Text="Books" Value="book"></asp:ListItem>
<asp:ListItem Text="Accessories" Value="accessories"></asp:ListItem>
<asp:ListItem Text="Cars" Value="car"></asp:ListItem>
<asp:ListItem Value="bike"></asp:ListItem>
<asp:ListItem Text="Bikes" value="shoe"></asp:ListItem>
<asp:ListItem Text="Shoes" Value="garment"> </asp:ListItem>
<asp:ListItem Text="Garments" Value="cellphone"></asp:ListItem>
<asp:ListItem Text="Laptops" Value="laptop"></asp:ListItem>
<asp:ListItem Text="Home & Appliances" Value="homeappliance"></asp:ListItem>
<asp:ListItem Text="Perfumes" Value="perfume"></asp:ListItem>
<asp:ListItem Text="Sports" Value="sports"></asp:ListItem>
</asp:DropDownList>
</td>
<td>
<asp:FileUpload ID="FileUpload2" runat="server" />
<asp:Button runat="server" ID="btnupload" OnClick="btnupload_Click" Text="Upload" />
</td>
</tr>
</EditItemTemplate>
protected void ListView1_ItemUpdating(object sender, ListViewUpdateEventArgs e)
{
DropDownList dropdownlist = ListView1.Items[e.ItemIndex].FindControl("dropdownlist") as DropDownList;
string category = dropdownlist.SelectedValue;
FileUpload fileUpload1 = ListView1.Items[e.ItemIndex].FindControl("FileUpload2") as FileUpload;
System.Drawing.Bitmap bmpPostedImage = new System.Drawing.Bitmap(fileUpload1.FileContent);
System.Drawing.Image objImage = ScaleImage(bmpPostedImage, 200);
var stream = new System.IO.MemoryStream();
objImage.Save(stream, ImageFormat.Png);
stream.Position = 0;
BinaryReader br = new BinaryReader(stream);
byte[] imagebytes = br.ReadBytes((Int32)stream.Length);
string base64String = Convert.ToBase64String(imagebytes, 0, imagebytes.Length);
string url = "data:image/png;base64," + base64String;
TextBox productname = ListView1.Items[e.ItemIndex].FindControl("productnameTextBox") as TextBox;
TextBox productprice = ListView1.Items[e.ItemIndex].FindControl("productpriceTextBox") as TextBox;
TextBox productdesc = ListView1.Items[e.ItemIndex].FindControl("productdescTextBox") as TextBox;
Label productid = ListView1.Items[e.ItemIndex].FindControl("productidLabel1") as Label;
con.Open();
string query = "UPDATE products SET productname=" + productname.Text + "," + "productdesc=" + productdesc.Text + "," + "productprice=" + productprice.Text + "," + "productcateg=" + category + "," + "productimage=" + url + "WHERE productid=" + productid.Text;
cmd = new SqlCommand("UPDATE products SET productname =" + productname.Text + "," + "productdesc =" + productdesc.Text + "," + "productprice =" + productprice.Text + "," + "productcateg =" + category + "," + "productimage =" + url + "WHERE productid =" + productid.Text,con);
cmd.ExecuteNonQuery();
con.Close();
}
public static System.Drawing.Image ScaleImage(System.Drawing.Image image, int maxHeight) //Image Resize
{
var ratio = (double)maxHeight / image.Height;
var newWidth = (int)(image.Width * ratio);
var newHeight = (int)(image.Height * ratio);
var newImage = new Bitmap(newWidth, newHeight);
using (var g = Graphics.FromImage(newImage))
{
g.DrawImage(image, 0, 0, newWidth, newHeight);
}
return newImage;
}
OK I have found out the way just add e.NewValues.Add("columnname",url) and update would be reflected in list view

django-datatables-view not displaying content returned from AJAX request?

My Ajax request to update the tables is not working. Attached is the screenshot. It simply displays "processing" but nothing happens. The JSON object that is returned (if i visit the URL -{% url 'search_list_json' %} --used in AjaxSource of Js code below) seems to be correct. but still the mainpage is not displaying the JSON content in table.
Here it is:
{"result": "ok",
"iTotalRecords": 1, "aaData": [["<center><font color=\"red\">Mazda=>626:2012-1986</font>\n </center>", "04/07/2014", "10000", "1000", "<center><a href='/search/update/1/'><img src='/static/images/icons/icon_changelink.gif'></a> <a href='/search/delete/1/'><img src='/static/images/icons/icon_deletelink.gif'></a></center>"]],
"sEcho": 0,
"iTotalDisplayRecords": 1}
My views.py
class SearchListJson(BaseDatatableView):
model = Search
columns=['title','created','max_price', 'min_price','actions']
order_columns = ['created', 'max_price']
max_display_length = 500
def render_column(self, row, column):
user = self.request.user
url_edit=static('images/icons/icon_changelink.gif')
url_delete=static('images/icons/icon_deletelink.gif')
#print url_edit, url_delete
if column == 'title':
value = '{0}=>{1}:{2}-{3}'.format(row.vehicle_make,row.vehicle_model,
row.max_year,row.min_year)
edit_url = reverse('search_detail', args=(row.id,))
#print self.get_value_cell_style(edit_url, value,'red')
return self.get_value_cell_style(edit_url, value,'red')
elif column == 'max_price':
#print '%s' %row.max_price
return '%s' %row.max_price
elif column == 'min_price':
#print '%s' %row.min_price
return '%s' %row.min_price
elif column == 'created':
#print row.created.strftime('%m/%d/%Y')
return row.created.strftime('%m/%d/%Y')
elif column == 'actions':
print "in columns actions"
edit_link = """<a href='%s'><img src='%s'></a>""" %(\
reverse('search_update', args=(row.id,)),url_edit)
delete_link = """<a href='%s'><img src='%s'></a>""" %(\
reverse('search_delete', args=(row.id,)),url_delete)
print "edit_link", edit_link
print "delete_link",delete_link
return '<center>%s %s</center>' % (edit_link, delete_link)
else:
return super(SearchListJson, self).render_column(row, column)
def get_value_cell_style(self, url, value, color=None):
style = '''<center>%s</center>''' % (url, value)
if color:
style = '''<center><font color="%s">%s</font>
</center>''' % (url, color, value)
return style
def get_initial_queryset(self):
"""
Filter records to show only entries from the currently logged-in user.
"""
#print "get intial queryset called"
#print Search.objects.filter(user=self.request.user)
return Search.objects.filter(user=self.request.user)
The js-code is below:
$(document).ready(function() {
var oTable = $('#search_table').dataTable( {
"sDom": 'T<"clear">lrtip',
"bProcessing": true,
"bServerSide": true,
"sAjaxSource": "{% url 'search_list_json' %}",
"aaSorting": [ [1,'desc'], [2,'desc'] ],
// Disable sorting for the Actions column.
"aoColumnDefs": [ { "bSortable": false, "aTargets": [ 4 ] } ]
} );
} );
The HTML is:
<div class="container">
<div class="row">
<div class="col-sm-12 col-md-12">
<div class="well">
<table id="search_table">
<thead>
<tr>
<th width="10%"><center>Title</center></th>
<th width="15%">Date Created</th>
<th width="15%">Min Price</th>
<th width="15%">Max Price</th>
<th width="10%"></th>
</tr>
</thead>
</table><br>
</div>
</div>
</div>