Thứ Hai, 10 tháng 4, 2017

CREATE DELETE LINK WITH MVC USING POST TO AVOID SECURITY ISSUES

CREATE DELETE LINK WITH MVC USING POST TO AVOID SECURITY ISSUES

It is fairly common to have a list of records with a hyperlink to delete a record.  The problem here is that with MVC the hyperlink will use a GET request to delete a record.  This is a fairly big security issue as anybody can browse to the URL and delete a record from your system.  In this post I’ll explain how you can use the Ajax helpers to create a hyperlink that will call your delete method without using GET.

Stephen Walther has a great post here where he explains the issue and gives a couple of different solutions; one using hand written Ajax and the other without using Ajax.  There is no point in reiterating what he has to say so it’s definately worth a read.  Here I am going to use the Ajax helpers to perform the same functionality, which minimises the code required.

I have a view that renders a table that looks like this:

Here is the Delete method in my controller:
   
[HttpDelete]
public ActionResult Delete(int id)
{
    Student student = context.Student.FirstOrDefault(s => s.ID.Equals(id));
    if (student != null)
    {
        context.DeleteObject(student);
        context.SaveChanges();
    }

    return RedirectToAction("Index");
}


In this method I am using the Entity Framework to delete a record from my database.  The problem with this method using the GET verb would be that anybody could navigate to http://www.mydomain.com/Student/Delete/1 and it would delete the record from my database. We definately don’t want this. There would also be a chance that a search engine bot could access the method, again deleting data.

You can see that I’ve decorated the method with the HttpDelete attribute. As Stephen states in his post, HTML only supports GET and POST, but as we’re using Ajax, which uses the XmlHttpRequest object we can use any of the available verbs, so delete is available.

To render my delete link on the form I am using the Ajax.ActionLink helper method:
   
<%= Ajax.ActionLink("Delete", "Delete", new { id = student.ID },
    new AjaxOptions()
    {
        HttpMethod="Delete",
        Confirm="Are you sure you want to delete this student?",
        OnComplete = "function() { $(this).parent().parent().remove() }"
    }) %>


The helper method is very similar to the Html.ActionLink method, except it will use Ajax to perform the request. The first three parameters are straight forward; the link text, the action name and the route values. The fourth parameter is an instance of AjaxOptions.

I have set three of the properties, the first being the HttpMethod which is set to delete.  This allows the request to be made to my Delete method which is decorated with the HttpDelete attribute.  I have also set the Confirm property which displays a JavaScript confirm dialog before making the request.  Lastly I’ve set the OnComplete property which is some client script that will be run once tha Ajax request has completed.  In this instance I am using jQuery to remove the row from the table.

Using this approach is a fairly simple way to use hyperlinks to delete data without using a GET request therefore improving your site’s security. Of course you may not want your site to be dependant on JavaScript in which case you can use the second approach detailed in Stephen’s post.

Thứ Sáu, 31 tháng 3, 2017

Add/Remove Class like jQuery using pure Javascript

/**/
    function hasClass(el, className) {
        if (el.classList)
            return el.classList.contains(className)
        else
            return !!el.className.match(new RegExp('(\\s|^)' + className + '(\\s|$)'))
    }
 
    function addClass(el, className) {
        if (el.classList)
            el.classList.add(className)
        else if (!hasClass(el, className)) el.className += " " + className
    }
 
    function removeClass(el, className) {
        if (el.classList)
            el.classList.remove(className)
        else if (hasClass(el, className)) {
            var reg = new RegExp('(\\s|^)' + className + '(\\s|$)')
            el.className = el.className.replace(reg, ' ')
        }
    }
    /**/

Chống Refresh Page Dropdown list ASPNET

 -------------
 Không refresh toàn bộ trang khi chọn item trên dropdown 1 để load data lên dropdown 2
--------------
The ScriptManager control and the UpdatePanel control. These controls remove the requirement to refresh the whole page with each postback, which improves the user experience. By default, a postback control (such as a button) inside an UpdatePanel control causes a partial-page update. By default, a button or other control outside an UpdatePanel control causes the whole page to be refreshed,
<asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
    <ContentTemplate>
        <fieldset>
            <div class="1">
                <asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="True" OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged">
                    <asp:ListItem Text="Select..." Value="No selection made"></asp:ListItem>
                </asp:DropDownList>
            </div>
            <div class="1">
                <asp:DropDownList ID="DropDownList2" runat="server">
                    <asp:ListItem Text="Select..." Value="No selection made"></asp:ListItem>
                </asp:DropDownList>
            </div>
        </fieldset>
    </ContentTemplate>
</asp:UpdatePanel>

Thứ Ba, 21 tháng 3, 2017

Change line height in Visual Studio

Can't change directly in Visual Studio.
--> BUT You CAN change line height of font, the font you're using.
Step 1: install Fontforge.
Step 2: Open Fontforge after install finished, go to:
Element->Font Info ->OS2 -> Unit.
Change 4 value: Down win, up win, top N, down horizontal by multiplied by the desired ratio. Sample: ratio 1.5 or 2 ..etc...
(it means: if default 800, you multiple with ratio 1.5 --> result is 1200, you change 800 -->1200)
--> click OK to save setting.
Step 3: Go to File -> Generate font --> Generate with ttf format.
Step 4: Install the font just created and change font in Visual Studio.
-------------> ENJOY------------

Visual Studio WITH C# KEY BINDINGS _ hotkey

To answer the specific question, in C# you are likely to be using the C# keyboard mapping scheme, which will use these hotkeys by default:

Ctrl+E, Ctrl+D to format the entire document.
Ctrl+E, Ctrl+F to format the selection.

You can change these in Tools > Options > Environment -> Keyboard (either by selecting a different "keyboard mapping scheme", or binding individual keys to the commands "Edit.FormatDocument" and "Edit.FormatSelection").

If you have not chosen to use the C# keyboard mapping scheme, then you may find the key shortcuts are different. For example, if you are not using the C# bindings, the keys are likely to be:

Ctrl + K + D (Entire document)
Ctrl + K + F (Selection only)

To find out which key bindings apply in YOUR copy of Visual Studio, look in the Edit > Advanced menu - the keys are displayed to the right of the menu items, so it's easy to discover what they are on your system.

ADO.NET Demo

using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
 
namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            string connectionString = @"Data Source=USERMIC-42NCNNO\SQLEXPRESS;Initial Catalog=test;User id=sa;Password=7880;";
            SqlConnection con=new SqlConnection();
            con.ConnectionString=connectionString;
            if(con.State!=ConnectionState.Open)
                con.Open();
 
            /*--------------------------------LỆNH SELECT-------------------------------------*/
 
            /*
            SqlCommand cmdSQL = new SqlCommand();
            cmdSQL.Connection = con;
            cmdSQL.CommandText = "Select * from Nhanvien where tuoi>@sTuoi";
            cmdSQL.Parameters.AddWithValue("sTuoi", 27);
            SqlDataReader dr = cmdSQL.ExecuteReader();
            while (dr.Read())
            {
                Console.WriteLine(String.Format("{0} \t | {1} \t | {2} \t | {3}",
                            dr[0], dr[1], dr[2], dr[3]));
            }
            con.Close();
             */
            SqlCommand cmd = new SqlCommand();
            cmd.Connection = con;
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.CommandText="SP_NHANVIEN_SELECT";
            /*
             Store Procedure:
             CREATE PROCEDURE SP_NHANVIEN_SELECT
                @Tuoi INT
             AS
                    SELECT * FROM   NHANVIEN WHERE  TUOI > @Tuoi
             */
            cmd.Parameters.AddWithValue("@tuoi"SqlDbType.Int).Value = 34;
 
            //SqlDataReader dr = cmd.ExecuteReader();
            //while (dr.Read())
            //{
            //    Console.WriteLine(String.Format("{0} \t | {1} \t | {2} \t | {3}",
            //               dr.GetInt32(0), dr["HoTen"], dr[2], dr[3]));
            //}
            //dr.Close();
 
            //int kq = (Int32)cmd.ExecuteScalar();
            //Console.WriteLine(kq);
 
            /*---------------------------------------------------------------------*/
 
            /*--------------------------------LỆNH INSERT-------------------------------------*/
            
            //SqlCommand insertCmd = new SqlCommand();
            //insertCmd.Connection = con;
            //insertCmd.CommandText = @"insert into NhanVien(HoTen,Tuoi,PhongBanId) values(@val1,@val2,@val3)";
            //insertCmd.Parameters.AddWithValue("val1", SqlDbType.NVarChar).Value = "Anh Anh";
            //insertCmd.Parameters.AddWithValue("val2", SqlDbType.Int).Value = 26;
            //insertCmd.Parameters.AddWithValue("val3", SqlDbType.Int).Value = 1;
 
            //int sodong = insertCmd.ExecuteNonQuery();
            //Console.WriteLine(sodong);
 
            /*---------------------------------------------------------------------*/
 
            /*--------------------------------LỆNH UPDATE-------------------------------------*/
 
            //SqlCommand updateCmd = new SqlCommand();
            //updateCmd.Connection = con;
            //updateCmd.CommandText = @"update NhanVien set HoTen=@val1,Tuoi=@val2,PhongBanId=@val3 where nhanvienid=@val4";
            //updateCmd.Parameters.AddWithValue("val1", SqlDbType.NVarChar).Value = "Anh Anh Edit";
            //updateCmd.Parameters.AddWithValue("val2", SqlDbType.Int).Value = 26;
            //updateCmd.Parameters.AddWithValue("val3", SqlDbType.Int).Value = 1;
            //updateCmd.Parameters.AddWithValue("val4", SqlDbType.Int).Value = 9;
 
            //int sodong = updateCmd.ExecuteNonQuery();
            //Console.WriteLine(sodong);
 
            /*---------------------------------------------------------------------*/
 
            /*--------------------------------LỆNH DELETE-------------------------------------*/
 
            SqlCommand delCmd = new SqlCommand();
            delCmd.Connection = con;
            delCmd.CommandText = @"delete from NhanVien where nhanvienid=@id";
            delCmd.Parameters.AddWithValue("id"SqlDbType.Int).Value = 9;
 
            int sodong = delCmd.ExecuteNonQuery();
            Console.WriteLine(sodong);
 
            con.Close();
            Console.ReadKey();
        }
    }
}