Filter Html Table Row in Jquery

Today trying to filter Html table and learning to create classes in javascript. It may help to someone if looking for the same:

You can find working example here:

Html Code


<div id="form">
    <input type="checkbox" value="x1" name="ch">x1</input>
    <input type="checkbox" value="x2" name="ch">x2</input>
    <input type="checkbox" value="x3" name="ch">x3</input>
<div>

<table id="table">
  <tr>
      <td col="name">x1</td>
      <td col="price">20</td>
  </tr>
 <tr>
      <td col="name">x2</td>
      <td col="price">30</td>
  </tr>
  <tr>
      <td col="name">x3</td>
      <td col="price">40</td>
  </tr>
</table>

Js code


<script>

   var cls ={
                categories:[],
                prices:[],
                filterByColName : function(colName)
                {
                     self= this;
                      $("#table td[col=" + colName + "]").filter(function(item) {
                             if(self.categories.length > 0)
                             {
                                 if(self.categories.indexOf($(this).text()) !== -1)
                                         $(this).parent().show();
                                 else
                                         $(this).parent().hide();
                              }
                              else
                                  $(this).parent().show();
                        });
                  }
           }

         $('#form :checkbox').click(function() {
                var $this = $(this);
                // $this will contain a reference to the checkbox
                if ($this.is(':checked')) {
                      cls.categories.push($(this).val());
                } else {
                     cls.categories.splice($this.val(),1);
                }
               cls.filterByColName("name");
        });

</script>
Tagged with: , ,
Posted in Javascript, JQuery

Split string in Sql Server

Today I found very good solution, to split the string in Sql Server:
//Sql Function

CREATE FUNCTION [dbo].[Split]
(
@String NVARCHAR(4000),
@Delimiter NCHAR(1)
)
RETURNS TABLE
AS
RETURN
(
WITH Split(stpos,endpos)
AS(
SELECT 0 AS stpos, CHARINDEX(@Delimiter,@String) AS endpos
UNION ALL
SELECT endpos+1, CHARINDEX(@Delimiter,@String,endpos+1)
FROM Split
WHERE endpos > 0
)
SELECT 'Id' = ROW_NUMBER() OVER (ORDER BY (SELECT 1)),
'Data' = SUBSTRING(@String,stpos,COALESCE(NULLIF(endpos,0),LEN(@String)+1)-stpos)
FROM Split
)
GO

//How to uses
DECLARE @DelimitedString NVARCHAR(128)
SET @DelimitedString = 'Duckman,Cornfed,Ajax,Charles,Mambo'
SELECT * FROM Split(@DelimitedString, ',')

http://ole.michelsen.dk/blog/split-string-to-table-using-transact-sql/

Tagged with:
Posted in SQL Server

Knockoutjs and Jquery UI Slider

How to filter an observable array based on Jquery UI slider using knockoutJs:

Html

<span id="minFare" data-bind="text : minFare"></span> &nbsp;&nbsp;-&nbsp;&nbsp;Rs&nbsp;
<span id="maxFare" data-bind="text : maxFare"></span>
<div id="slider-range"></div>

Js

//Min & Max Slider


function vm()
{
    var self = this;
    self.minFare = ko.observable();
    self.minFare.subscribe(function (newValue) {
       //TODO: Filter, min fare changed
    });

    self.maxFare = ko.observable();
    self.maxFare.subscribe(function (newValue) {
       //TODO: Filter, max fare changed
    });
 }

(function () {
 var vmm = new vm();
 ko.applyBindings(vmm);

 vm.minFare(0);
 vm.maxFare(500);

$("#slider-range").slider({
        range: true,
        min: vm.minFare(),
        max: vm.maxFare(),
        step: 1,
        values: [vm.minFare(), vm.maxFare()],
        slide: function (event, ui) {
            vm.minFare(ui.values[0]);
            vm.maxFare(ui.values[1]);
        }
    });

})();
Tagged with: , ,
Posted in Asp.Net, Jquery UI, KnockoutJS, MVC

Best way to Parse Query String value in Asp.Net

Best way to parse query string value in Asp.Net
//Use it
string cityCode = Request.QueryString.GetValue<string>("City");

//Extension method
        public static T GetValue<T>(this NameValueCollection collection, string key)
        {
            if (collection == null)
            {
                throw new ArgumentNullException("collection");
            }

            var value = collection[key];

            if (value == null)
            {
                throw new ArgumentOutOfRangeException("key");
            }

            var converter = TypeDescriptor.GetConverter(typeof(T));

            if (!converter.CanConvertFrom(typeof(string)))
            {
                throw new ArgumentException(String.Format("Cannot convert '{0}' to {1}", value, typeof(T)));
            }

            return (T)converter.ConvertFrom(value);
        }
Tagged with: ,
Posted in .Net, Asp.Net, C#

Umbraco 5 Surface Controller

In Umbraco5, Surface Controller is very interesting topic that everyone should know about this. Today I was digging with Umbraco 5.2 Beta version and successfully created my first surface controller which handle the contact form.
Surface controller is important because who one is move from Umbraco 4.7 to Umbraco 5.x then surely they looking for User Control macro stuff.

Surface Controller perform majorly 3 task:

1) Work with View-Model OR Data
2) If you want to render a partial view using View-Model
3) If you wan to submit any form

Find below steps, how to create a Contact Form using Surface Controller in Umbraco 5

Step-1 : First Create a Contact View-Model class

————————————————-
using System.ComponentModel.DataAnnotations;
namespace Site.Extensions.ViewModel
{
public class ContactViewModel
{
[Required(ErrorMessage = “Please enter your name”)]
public string Name { get; set; }

[Required(ErrorMessage = “Email address required”)]
[RegularExpression(@”[a-zA-Z0-9!#$%&’*+/=?^_`{|}~-]+(?:\.[a-zA-Z0-9!#$%&’*+/=?^_`{|}~-]+)*@(?:[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?\.)+[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?”, ErrorMessage = “Please enter a valid e-mail address”)]
public string Email { get; set; }

[Required(ErrorMessage = “Please enter your phone number”)]
public string PhoneNo { get; set; }

[Required(ErrorMessage = “Please enter a subject”)]
public string Subject { get; set; }

[Required(ErrorMessage = “Please enter a message”)]
[DataType(DataType.MultilineText)]
public string Message { get; set; }

public bool SubmitHandled { get; set; }
}
}
———————————————————

Step-2 Create Surface Controller class which handle contact form and render the contact form
//Note: First take reference of Umbraco.Cms.Web dll which is present under Umbraco Bin folder

—————————————————-
using Umbraco.Cms.Web.Context;
using Umbraco.Cms.Web.Surface;
using System.Web.Mvc;
using Site.Extensions.ViewModel;
using Umbraco.Web.Classes;

namespace Umbraco.Web.Controllers
{
//Note: All surface controller class should be inherited with “SurfaceController” class
// and should be postfix with “SurfaceController” other wise when you will create child action macro then this
// class will not able to populate under drop downlist

public class ContactFormSurfaceController : SurfaceController
{
private readonly IUmbracoApplicationContext context;
private const string FormSentKey = “ContactFormSent”;

public ContactFormSurfaceController(IUmbracoApplicationContext context)
{
//If you want to access current page data then you can use this object
//but in that can case you have to pass Hive id from partial view using “Model.Id”
context = context;
}

//ChildActionOnly annotation is required for rendering the view and return type be PartialViewResult

[ChildActionOnly]
public PartialViewResult RenderContactForm()
{
//Create your model view class as created above
var model = new ContactViewModel();

//This code block is basically used to show the confirmation message on page that email send successfully
etc.

var formSent = TempData[FormSentKey];
if (formSent != null && bool.Parse(formSent.ToString()))
model.SubmitHandled = true;

return PartialView(“contactFormRender”, model);
//PartialView takes two parameters first one is your partial view name and second one is your model class
object
}

//HttpPost annotation is required for handling your contact form submit.

[HttpPost]
public ActionResult SendContactForm(ContactViewModel model)
{
//Check if submitted form is valid
if (!ModelState.IsValid)
return CurrentUmbracoPage(); //If any error occurred then stick with current form

//Send email
EmailManager.Send(model);

//This flag value used in RenderContactForm method to show the confirmation message
TempData[FormSentKey] = true;

return RedirectToCurrentUmbracoPage(); //Redirect to current form. Note: You redirect to other page too
}
}
}
———————————————

Step-3 : Login in Umbraco back office and go to Setting section. Under Partial folder, create a partial page

————————————————

@model Site.Extensions.ViewModel.ContactViewModel
//Note: BeginUmbracoForm first two parameter is very important:
// First one: give the Surface Controller httppost handler name. In our case is "SendContactForm"
// Second one: Surface Controller name
// see controller class
:@

@using (Html.BeginUmbracoForm(“SendContactForm”, “ContactFormSurface”, null, new Dictionary { { “class”, “validate-form” } }))
{
@Html.ValidationSummary(true)

Contact Form

@Html.LabelFor(model => model.Name)
@Html.EditorFor(model => model.Name) @Html.ValidationMessageFor(model => model.Name)
@Html.LabelFor(model => model.Email)
@Html.EditorFor(model => model.Email) @Html.ValidationMessageFor(model => model.Email)
@Html.LabelFor(model => model.PhoneNo)
@Html.EditorFor(model => model.PhoneNo) @Html.ValidationMessageFor(model => model.PhoneNo)
@Html.LabelFor(model => model.Subject)
@Html.EditorFor(model => model.Subject) @Html.ValidationMessageFor(model => model.Subject)
@Html.LabelFor(model => model.Message)
@Html.TextAreaFor(model => model.Message) @Html.ValidationMessageFor(model => model.Message)

input type=”submit” value=”Send Email”
}

@if (Model.SubmitHandled)
{

Thanks, we’ll get back to you soon.

}
———————————————–

Note: after above steps, please build the project so you will get Surface Controller class under the macro.

Step-4 : Go to Developer section in umbraco back office then under macro node create a macro as

You done all steps and your form will start working.

Please let me know if found any issue.

Tagged with: , , ,
Posted in Umbraco5

Export MS Chart to PDF using Itextsharp in Asp.Net

Export MS Chart to PDF in Asp.Net

Using itextsharp, export ms chart into pdf file
I am rendering a chart using chart control in asp.Net 4.0. Now we want to export that chart image into pdf file. Interesting point is, I am not using template file here, I used Memory Mapped file feature though we can read/write file in memory.

Used tools and technology: .Net4.0, asp.net, c#, itextshartp, ms chart control

using (MemoryMappedFile mMappedFile = MemoryMappedFile.CreateNew("test.pdf", 1000000))
{
iTextSharp.text.Document doc =
new iTextSharp.text.Document(PageSize.A4, 72, 72, 172, 72);
using (MemoryMappedViewStream stream = mMappedFile.CreateViewStream())
{
// associate the document to the stream. PdfWriter.GetInstance(doc, stream);
//Save chart as image
 using (var chartimage = new MemoryStream())
 {
  //here Chart1 is chart control which rendered chart
  Chart1.SaveImage(chartimage, ChartImageFormat.Png);
  iTextSharp.text.Image img = iTextSharp.text.Image.GetInstance(chartim age.GetBuffer());
  img.ScalePercent(75f);
  doc.Open();
  doc.Add(new Paragraph(String.Format("Chart Title")));
  doc.Add(img); doc.Close();
 }
}
//read the data from the file and send it to the response stream
byte[] bytes;
using (MemoryMappedViewStream stream = mMappedFile.CreateViewStream())
{
  BinaryReader rdr = new BinaryReader(stream);
  bytes = new byte[mMappedFile.CreateViewStream().Length];
  rdr.Read(bytes, 0, (int)mMappedFile.CreateViewStream().Length);
}

Response.Clear();Response.ContentType = "Application/pdf";
Response.BinaryWrite(bytes);
Response.End();
}
Tagged with: , , , ,
Posted in .Net, Asp.Net, C#, ms Chart

Bar Chart random color in asp.Net

Display bars in random colors:

IDictionary<string, int> list= new Dictionary<string, int>();
list.Add(“Val 1”, 90);
list.Add(“Val  2”, 89);
list.Add(“Val 3”, 50);
list.Add(“Val 5”, 87);

chrtBar2.Series[“Categories”].XValueMember = “key”;
chrtBar2.Series[“Categories”].YValueMembers = “value”;
chrtBar2.ChartAreas[“MainChartArea”].AxisX.MajorGrid.Enabled = false;
chrtBar2.ChartAreas[“MainChartArea”].AxisX.MajorTickMark.Enabled = true;
chrtBar2.ChartAreas[“MainChartArea”].AxisX.MinorGrid.Enabled = false;
chrtBar2.ChartAreas[“MainChartArea”].AxisX.MinorTickMark.Enabled = false;
chrtBar2.ChartAreas[“MainChartArea”].AxisY.MajorGrid.Enabled = false;
chrtBar2.ChartAreas[“MainChartArea”].AxisY.MajorTickMark.Enabled = true;
chrtBar2.ChartAreas[“MainChartArea”].AxisY.MinorGrid.Enabled = false;
chrtBar2.ChartAreas[“MainChartArea”].AxisY.MinorTickMark.Enabled = false;
chrtBar2.Series[“Categories”][“PointWidth”] = “1.0”;
chrtBar2.Series[“Categories”].BorderWidth = 1;
chrtBar2 .Series[“Categories”].BorderColor = Color.White;
chrtBar2.DataSource = list;
chrtBar2.DataBind();

//Set random color
Random random = new Random();foreach (var item in chrtBar2.Series[“Categories”].Points)

{
Color c = Color.FromArgb(random.Next(0, 255), random.Next(0, 255), random.Next(0, 255));
item.Color = c;
}

Each time will change the bar colors  when page will refreshed.

Tagged with: , , ,
Posted in .Net, Asp.Net, C#

Active navigation menu for current url

Set the active/current menu link based or Url in Jquery:

suppose we have menu like:

<div class="nav">

 <ul>
 <li class="active"><a href="~/url1/">URL 1</a>
 <li><a href="~/url2/">URL 2</a>
 <li><a href="~/url3/">URL 3</a>
 </ul>

</div>
and user when clicked on URL 2 then item look as active :

$(function(){

    var url = window.location.pathname, 
    urlRegExp = new RegExp(url.replace(/\/$/,'') + "$"); 

     $('#nav a').each(function(){
            if(urlRegExp.test(this.href.replace(/\/$/,''))){
                $(this).addClass('active');
            }
        });

});

Edited version

$(document).ready(function() {
var str = location.href.toLowerCase();
$(".ddsmoothmenu li a").each(function() {
if (str.indexOf(this.href.toLowerCase()) > -1) {
$("li.active").removeClass("active");
$(this).parent().addClass("active");
}
});
});

Posted in Uncategorized

Wrap Label Text in asp.net

Today I found one issue with my site, that is a label text was not wrapped and display continued. Found finally working solution:

 <div style="float:left;overflow-y:auto;overflow-x:auto; word-break:break-all;">
	<asp:Label ID="lbDesc" runat="server" />
</div>
Tagged with: ,
Posted in Asp.Net

asp.net 4.0 web form routing in iis7

Today I have completed my first phase of the project on Asp.Net 4.0 and I have implemented Web Form routing feature. It was working fine on VS inbuilt IIS server but when I deployed on IIS server, it was not working. I did little bit search on Google and finally found working solution. It may help you in future.

<modules runAllManagedModulesForAllRequests="true">
      <add name="UrlRoutingModule" type="System.Web.Routing.UrlRoutingModule,
                    System.Web, Version=4.0.0.0, Culture=neutral,
                    PublicKeyToken=b03f5f7f11d50a3a" />      
    </modules>
    <handlers>
      <add
            name="UrlRoutingHandler"
            preCondition="integratedMode"
            verb="*" path="UrlRouting.axd"
            type="System.Web.HttpForbiddenHandler, System.Web,  
              Version=2.0.0.0, Culture=neutral,  
              PublicKeyToken=b03f5f7f11d50a3a"/>
    </handlers>

Tagged with: ,
Posted in Asp.Net, IIS7
Top Rated
Blog Stats
  • 32,678 hits