mardi 27 décembre 2016

Validation of Date in MVC Gridview

I have the following gridview code and I am trying to do some basic validation on my dates. As you can see I have a start date and end date and I need to validate them so that StartDate <= EndDate. Is there a simple way to add this validation to the code below?

Html.DevExpress().GridView(settings =>
{
    settings.Name = "gvActiveScheduledAnnouncements";
    settings.Width = Unit.Percentage(100);
    settings.KeyFieldName = "AnnouncementId";

    settings.CallbackRouteValues = new { Controller = "Home", Action = "ActiveScheduledAnnouncementsPartial" };

    settings.SettingsEditing.Mode = GridViewEditingMode.EditForm;

    settings.SettingsEditing.AddNewRowRouteValues = new { Controller = "Home", Action = "AddNewAnnouncement" };
    settings.SettingsEditing.UpdateRowRouteValues = new { Controller = "Home", Action = "UpdateActiveScheduledAnnouncement" };
    settings.SettingsEditing.DeleteRowRouteValues = new { Controller = "Home", Action = "DeleteActiveScheduledAnnouncement" };

    settings.Columns.Add(c =>
    {
        c.Caption = "Announcement Text";
        c.FieldName = "Text";

        c.ColumnType = MVCxGridViewColumnType.Memo;
        c.EditFormSettings.ColumnSpan = 2;

        c.ColumnType = MVCxGridViewColumnType.Memo;
        var memo = c.PropertiesEdit as MemoProperties;
        memo.Rows = 3;
    });

    settings.Columns.Add(c =>
    {
        c.Caption = "Start Date";
        c.FieldName = "StartDate";


        c.ColumnType = MVCxGridViewColumnType.DateEdit;
    });

    settings.Columns.Add(c =>
    {
        c.Caption = "End Date";
        c.FieldName = "EndDate";

        c.ColumnType = MVCxGridViewColumnType.DateEdit;
    });

    settings.Columns.Add(c =>
    {
        c.Caption = "Display Status";
        c.FieldName = "DisplayStatus";

        c.EditFormSettings.Visible = DefaultBoolean.False;
    });
})
.Bind(Model)
.Render();

How to retrieve list of data in model

I have data in model and I used to store that data in session as below in controller

 if (providerListingModel.ServiceDetails != null && providerListingModel.ServiceDetails.Count > 0)
            Session["ServiceDetails"] = providerListingModel.ServiceDetails;
 else
            Session["ServiceDetails"] = null;

and for retrieving I had used the logic as

       if (Session["ServiceDetails"] != null)
        {
            if (providerListingModel.ServiceDetails == null)
            {
                List<ServiceDetail> sam = (List<ServiceDetail>)Session["ServiceDetails"];

                foreach (var items in sam)
                {
                    var sd = new ServiceDetail();
                    sd.Id = items.Id;
                    sd.CategoryServiceId = items.CategoryServiceId;
                    sd.ServiceType = items.ServiceType;
                    sd.ServicePrice = items.ServicePrice;
                    sd.IsSelected = items.IsSelected;
                    sd.ProviderListingId = providerListingModel.ProviderListingId;
                    providerListingModel.ServiceDetails.Add(sd);
                }
            }
            Session["ServiceDetails"] = null;
        }

The session contains data but on providerListingModel.ServiceDetails.Add(sd); it throw null exception. ServiceDetails is a class and it contains list of items

namespace xyz.DAL
{
 using System;
 using System.Collections.Generic;

public partial class ServiceDetail
{
    public int Id { get; set; }
    public int ProviderListingId { get; set; }
    public Nullable<int> CategoryServiceId { get; set; }
    public string ServiceType { get; set; }
    public Nullable<int> ServicePrice { get; set; }
    public string CustomeService { get; set; }
    public Nullable<bool> IsSelected { get; set; }

    public virtual CategoryService CategoryService { get; set; }
    public virtual ProviderListing ProviderListing { get; set; }
}
}

am I missing some code? As I am new I don't know what I am doing wrong

enter image description here enter image description here

dimanche 25 décembre 2016

Retain TempData Value after creating new session

For some reason, I am creating new Session within my controller's action method. But I have TempData in my ActionMethod1 and I would like to pass the value to ActionMethod2 after creating new seesion. But after creating new session id my TempData value cleared. Below code has been used to create new sessionid.

System.Web.SessionState.SessionIDManager manager = new System.Web.SessionState.SessionIDManager(); string NewSession = manager.CreateSessionID(System.Web.HttpContext.Current);

Please let me know if any other possible solutions to retain tempdata value even after creating new session.

Difference between property with no data annotation and property with "?" asp.net MVC

I have a very basic question of ASP.Net MVC 5. What is the difference between a property defined as

1. public int a {get; set;}

and 

2. public int? a{get; set;}

and 

3. [Required]
public int a {get; set;}

I know the 3rd one; it means the value is required and cannot be NULL. Can someone please tell me the difference between 1 and 2.

i want to disable my custom validation in edit action in asp.net mvc

Model

public partial class MemberModel 
    {

        [Key]
        public int MemberID { get; set; }

        [Required]
        [Unique_Member]
        [StringLength(255)]
        [Display(Name = "First Name")]
        public string FirstName { get; set; }


        [Required]
        [Unique_Member]
        [StringLength(255)]
        [Display(Name = "Last Name")]
        public string LastName { get; set; }

        [Display(Name="Name")]
        public string FullName { get { return string.Format(FirstName + " " + LastName); } }

        [Required]
        [StringLength(355)]
        public string Address { get; set; }
        [Required(ErrorMessage="The City field is Required")]
        public int CityID { get; set; }

        [Required(ErrorMessage = "The Country field is Required")]
        public int CountryID { get; set; }


        [Required]
        [RegularExpression(@"^((0092))-{0,1}\d{3}-{0,1}\d{7}$|^\d{4}$|^\d{4}-\d{7}$", ErrorMessage = "Invalid Phone number")]
        [Unique_Member]
        public string Pin { get; set; }


        [Display(Name="Mobile No.")]
        [Required(ErrorMessage="Mobile No. Required")]
        [RegularExpression(@"^((\+92)|(0092))-{0,1}\d{3}-{0,1}\d{7}$|^\d{11}$|^\d{4}-\d{7}$",ErrorMessage="Invalid Phone number")]
        public string Phone { get; set; }


        [Required]
        [EmailAddress]
        public string Email { get; set; }


        public virtual List<Order_SummeryModel> Order_Summeries { get; set; }
        public virtual CountryModel Country { get; set; }
        public virtual CityModel City { get; set; }
    }

Custom Validation [Unique_Member]

its a custom validation for three properties "Pin","FirstName" and "LastName" which i made for create new member. It checks whether fullname and pin of new member is unique or not.

its works perfectly for create action but in edit action this restrict me to update the member model, i want to disable it for edit action, or there is another way to update the model with disable it.

  public class Unique_MemberAttribute : ValidationAttribute
    {
        private static int count;

        protected override ValidationResult IsValid(object value, ValidationContext validationContext)
        {
            Context_getway db = new Context_getway();
            string membervalue = value.ToString();
            //var count = db.Members.Where((x => x.Name == membervalue || x.Pin == membervalue || x.Email == membervalue)).Count();
            var count_fname = db.Members.Where(x => x.FirstName == membervalue).Count();
            var count_lname = db.Members.Where(x => x.LastName == membervalue).Count();
            var count_pin = db.Members.Where(x => x.Pin == membervalue).Count();

            if ((count_fname != 0)||(count_lname != 0))
            {
                count++;
                if (count == 2)
                {
                    return new ValidationResult("Member Already Exist with the same Full Name (Change First Name OR Last Name)!");

                }
            }
            if (count_pin != 0)
            {
                return new ValidationResult("Member Already Exist with the same Pin!");
            }


                return ValidationResult.Success;

        }
    }
    [MetadataType(typeof(MemberModel))]
    public partial class MemberModel
    {

    }

Member Controller (edit action)

 [HttpGet]
        public ActionResult Edit(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            else
            {
                var member = db.Members.Find(id);
                ViewBag.CountryID = new SelectList(db.CountryModels.ToList(), "CountryID", "Country",member.CountryID);
                ViewBag.CityID = new SelectList(db.CityModels.ToList(), "CityID", "City",member.CityID); 
                if (member != null)
                {
                    return View(member);
                }
                else
                    return HttpNotFound();
            }
        }
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Edit(MemberModel member)
        {

            try
            {  
                if (ModelState.IsValid)
                {
                    db.Entry(member).State = System.Data.Entity.EntityState.Modified;
                    db.SaveChanges();
                    TempData["Msg"] = "Update Successfully";
                    return RedirectToAction("Index");
                }
                else
                {
                    ViewBag.CountryID = new SelectList(db.CountryModels.ToList(), "CountryID", "Country",member.CountryID);
                    ViewBag.CityID = new SelectList(db.CityModels.ToList(), "CityID", "City",,member.CityID); 
                    return View(member);
                }
            }
            catch(Exception e)
            {
                TempData["Msg"] = "Update Unsuccessfully: "+ e.Message;
                return View();
            }
        }

samedi 24 décembre 2016

i want to run onclick event in

     <a onclick="log_out_event" href="LogIn.aspx"><i class="icon_key_alt"></i> Log Out</a>

//i want to run onclick event in

vendredi 23 décembre 2016

LINQ creates query leaving "From" clause empty

I've got an mvc3 application with the following code:

public static List<ApprovalDTO> ConvertToDTO(IQueryable<REGISTER> r2, GMIEntities db, User user)
{
    List<ApprovalDTO> rta = new List<ApprovalDTO>();

    r2= r2.Where(r => r.APPROVAL.STATE1.DESC_STATE == Constants.ON_HOLD);
    String sql = ((System.Data.Objects.ObjectQuery)r2.OrderBy(o => o.ANALYSIS.ANALYSIS_DATE)).ToTraceString();


   System.Diagnostics.Debug.WriteLine(sql);  }

Which returns the following Query to be run against an oracle database:

SELECT
"Extent1".-SOME INFO-
FROM  ( SELECT  
 -SOME INFO- FROM     ORDER BY "ANALYSIS_DATE" ASC ) "MYSCHEMA"."REGISTER"  ORDER BY "ANALYSIS_DATE" ASC ) "Extent1"

This obviously gives an "Invalid table name" error when executing the query, since LINQ isn't filling the FROM clause for extent1 What could be causing this?

mercredi 21 décembre 2016

oledb string manipulation for repeatitive strings

I have an excel sheet with column names as :

{ "test 1", "test 1","test 1","test 11","test 12"}

and is getting interpreted from oledb to C# method as

{ "test 1", "test 11","test 12","test 111","test 121"}.

How do I display the original column names in the grid of my asp .net web application?

If I use linq like :

original.Select(x => original.Where(y => x.StartsWith(y)).Min()).ToList(); 

I will get the string as :

{ "test 1", "test 1","test 1","test 1","test 1"}

So how can I get the original string array as it is?

mardi 20 décembre 2016

Rotate text using mvcrazortopdf

I needed text inside 'th' tag of table to be shown vertically i.e.,

transform: rotate(270deg); using css

while rendering into pdf using mvcrazortopdf.

vendredi 16 décembre 2016

Devexpress Gridview column styling issue

I have a devexpress gridview for managing user feedback that appears in a popup when an admin clicks a button. Currently the grid columns dynamically size based on content as you can see here:

enter image description here

The problem is this view currently doesn't scroll so if the user has too many entries the popup blows out the bottom of the page. The user specifically wants scrolling and not pagination. If I try to enable scrolling on the gridview I have 2 problems. First for some reason my command column gets truncated strangely, and second all of the columns seem to go to a fixed width which is unpleasing to read if there are longer feedback messages. Does anyone know why this happens? Full control code posted at bottom.

enter image description here

Html.DevExpress().GridView(settings =>
    {
        settings.Name = "gvManageFeedback";
        settings.Width = Unit.Percentage(100);
        settings.KeyFieldName = "FeedbackId";
        settings.Styles.Header.HorizontalAlign = HorizontalAlign.Center;
        settings.Styles.Header.Wrap = DefaultBoolean.True;
        settings.Styles.Header.VerticalAlign = VerticalAlign.Bottom;

        //Scrolling causing weird style issues for some reason
        settings.Settings.VerticalScrollBarMode = ScrollBarMode.Auto;
        settings.Settings.VerticalScrollableHeight = 400;
        settings.SettingsPager.Mode = GridViewPagerMode.ShowAllRecords;

        settings.SettingsBehavior.AllowSelectSingleRowOnly = true;
        settings.SettingsBehavior.AllowSort = true;
        settings.SettingsBehavior.AllowDragDrop = false;
        settings.SettingsBehavior.AllowGroup = false;

        settings.Settings.ShowFilterRow = false;
        settings.Settings.ShowTitlePanel = false;        
        settings.Settings.ShowFooter = false;

        settings.CallbackRouteValues = new { Controller = "Home", Action = "ManageFeedbackGrid" };

        settings.SettingsEditing.Mode = GridViewEditingMode.EditFormAndDisplayRow;

        settings.CommandColumn.Visible = true;
        settings.CommandColumn.VisibleIndex = 0;
        settings.CommandColumn.ButtonRenderMode = GridCommandButtonRenderMode.Image;
        settings.CommandColumn.Width = Unit.Pixel(20);
        settings.CommandColumn.CellStyle.HorizontalAlign = HorizontalAlign.Left;
        settings.CommandColumn.ShowEditButton = true;
        settings.SettingsCommandButton.EditButton.Image.ToolTip = "Acknowledge";
        settings.SettingsCommandButton.EditButton.Image.Url = Url.Content("~/images/20Acknowledge.png");
        settings.SettingsCommandButton.UpdateButton.Image.Url = Url.Content("~/images/20Save.png");
        settings.SettingsCommandButton.UpdateButton.Image.ToolTip = "Submit comment and acknowledge";
        settings.SettingsCommandButton.CancelButton.Image.Url = Url.Content("~/images/20Cancel.png");

        settings.SettingsEditing.UpdateRowRouteValues = new { Controller = "Home", Action = "AcknowledgeFeedback" };

        settings.CommandColumn.ShowClearFilterButton = true;
        settings.SettingsCommandButton.ClearFilterButton.Image.Url = Url.Content("~/images/20ClearFilter.png");

        settings.Settings.ShowFilterRow = true;
        settings.Settings.ShowFilterRowMenu = true;

        settings.Columns.Add(c =>
        {
            c.Caption = "User";
            c.FieldName = "UserName";

            c.ColumnType = MVCxGridViewColumnType.TextBox;
            c.EditFormSettings.Visible = DefaultBoolean.False;
        });

        settings.Columns.Add(c =>
        {
            c.Caption = "Date";
            c.FieldName = "CreatedOn";

            c.ColumnType = MVCxGridViewColumnType.DateEdit;
            c.EditFormSettings.Visible = DefaultBoolean.False;
        });

        settings.Columns.Add(c =>
        {
            c.Caption = "Category";
            c.FieldName = "Category";

            c.ColumnType = MVCxGridViewColumnType.TextBox;
            c.EditFormSettings.Visible = DefaultBoolean.False;
        });

        settings.Columns.Add(c =>
        {
            c.Caption = "Feedback";
            c.FieldName = "Text";

            c.ColumnType = MVCxGridViewColumnType.Memo;
            c.EditFormSettings.Visible = DefaultBoolean.False;
        });

        settings.Columns.Add(c =>
        {
            c.Caption = "Acknowledged By";
            c.FieldName = "AcknowledgedUserName";

            c.ColumnType = MVCxGridViewColumnType.TextBox;
            c.EditFormSettings.Visible = DefaultBoolean.False;
        });

        settings.Columns.Add(c =>
        {
            c.Caption = "Comments";
            c.FieldName = "AdministratorComments";

            c.ColumnType = MVCxGridViewColumnType.Memo;
            var memo = c.PropertiesEdit as MemoProperties;
            memo.Rows = 3;
            c.EditFormSettings.ColumnSpan = 2;
        });
    })
    .Bind(Model)
    .Render();

jeudi 15 décembre 2016

How to auto execute code / click button in JS after 1 month or by schedule?

I have a simple project in asp.net mvc3. I am trying to do in my project is to add a scheduling date or month to execute a specific button or code. I found this LINK but I can't understand enough because I just started to learn asp.net mvc. Hope someone can help me. Thanks

ASP.NET MVC post to controller action from same controller

I'm working on this project that currently has the follow method:

 [HttpPost]
 public ActionResult Service(string identifier)

This function is currently being used by a webpage form

 <form method="POST" action="/Connector/Service">
 <input type="hidden" id="identifier" name="identifier"/>

So Service is used when the user clicks on a button that submits the form on the webpage. The user is taken to this page from another action. I have to implement a feature where sometimes instead of taking the user to the webpage, the user goes directly to the Service method from the action.

I found this thread when searching: ASP.NET MVC: RedirectToAction with parameters to POST Action

But it seems like that is bad design and returning RedirectToAction with Service actually did not work for me.

return RedirectToAction("Service", new {identifier})

Upon more search it seems like I actually cannot make a post request from my controller. Asp.NET MVC : redirect to another controller with POST Action

Any ideas on what I could do here? I am fairly new to ASP.NET and have no idea what to do at this point. All help is appreciated, thanks.

mercredi 14 décembre 2016

Prevent Unauthenticated Access to Uploaded Document URLs - MVC

My application(MVC3) allows users to upload their documents on a form. Once uploaded, access to these documents is available to anonymous users by visiting the link containing the document ID and request ID in the URL.

Ex: http://ift.tt/2hI4E72

Need to secure uploaded document URLs from unauthorized access by requiring authenticated user's session cookie.

In MVC3, what are all the possible ways to implement session cookie. I really appreciate, if any other possible ways.

mardi 13 décembre 2016

Scripts are not getting rendered

Cshtml code.

@Html.EditorFor(model => model.StartDate, new { htmlAttributes = new { @class = "datefield", type = "date" } })

@section Scripts {
    @Scripts.Render("~/Content/css")
    @Scripts.Render("~/Scripts/jquery")
}

Bundle.config code

bundles.Add(new ScriptBundle("~/Scripts/jquery").Include(
   "~/Scripts/jqueryui1.12.s",
   "~/Scripts/jqueryui-12.js",   
    "~/Scripts/DateTimePicket.js"
));     

bundles.Add(new StyleBundle("~/Content/css").Include(
    "~/Content/jqueryui1.12.css"
));

code of DateTimePicker

$(function () {
    alert("hi");
    $(".datefield").datepicker();
});

where is the issue. The code of these file "~/Scripts/jqueryui1.12.s", "~/Scripts/jqueryui-12.js", are from

<script src="http://ift.tt/20g0BuL"></script>
<script src="http://ift.tt/2dsPzTA"></script>

I am just trying to add the datepicker and the code got messed up.

mercredi 7 décembre 2016

Reset ASP.NET_SessionId cookie to prevent Login Cookie Session Fixation attack - MVC3

In my application SSO(Single Sign On) has been implemented. When a user first visits the login page, they are redirected to the SSO login page.

The ASP.NET_SessionId cookie that serves as the first login cookie for application is set in the user’s browser prior to submitting a username/password.

After successful authentication, the value of the ‘ASP.NET_SessionId’ cookie is not refreshed.

Help me to Re-set the value of the ASP.NET_SessionId cookie after successful authentication in MVC3.

mardi 6 décembre 2016

Custom authentication with MVC

I want to create custom authentication with MVC3.

Scenerio:: User will have a login form, where he will input userId and password. These credentials are then verified against my business logic. I can not use default process, like validating it from User table then assign role etc..

My business logic will provide me a boolen value IsValidUser and UserRole.

PROBLEM:: I need to do two things:
1. Use these values returned by Business logic in AuthoriseAttribute filter. So that I can restrict a user from accessing any particular action of a controller.(I have tried putting these values in Session variable, but not able to use them in Authorisation filter.)
2. How to use Formsauthentication.Setauthcookie for accomplishing this task.

lundi 5 décembre 2016

Moving file from one folder to other in FTP

I have an requirement to move files from one folder to other in ftp i used the below code block but getting following error

The remote server returned an error: (501) Syntax error in parameters or arguments.

 public void MoveFile(string souce,string destination, string UserName, string Password)
    {
        FtpWebRequest ftpRequest = null;
        FtpWebResponse ftpResponse = null;
        try
        {
            ftpRequest = (FtpWebRequest)WebRequest.Create(souce);
            ftpRequest.Credentials = new NetworkCredential(UserName, Password);
            ftpRequest.UseBinary = true;
            ftpRequest.UsePassive = true;
            ftpRequest.KeepAlive = true;
            ftpRequest.Method = WebRequestMethods.Ftp.Rename;
            ftpRequest.RenameTo = destination;
            ftpResponse = (FtpWebResponse)ftpRequest.GetResponse();
            ftpResponse.Close();
            ftpRequest = null;
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }

can you please help me how to solve this issue.

Encountered end tag "li" with no matching start tag error when putting li inside if statement

i am using asp.net MVC 5 and Visual studio 2013

and working on Razor view

the view is working fine without if statement around the < li > start

if i enclosed any < li > start, with an if condition statement i get this error

Parser Error Message: Encountered end tag "li" with no matching start tag. Are your start/end tags properly balanced?

@using TheodorHR_App.Models
<div id="tree_CadreGroupLevel" class="tree-demo">
    <ul>
        @{
            TheodorHrEntities db = new TheodorHrEntities();
            var nodes = db.Cadres.ToList();
            foreach (var node in nodes)
            {
                Cadre root = new Cadre();
                root.Id = node.Id;
                if (@Model.RuleElementCadres.Select(e => e).Where(e => e.Cadre == node.Id).Count() > 0)
                {
                    <text>
                        <li id="Cnode_@node.Id" data-jstree='{ "selected" : true }'>
                    </text>
                }
                else
                {
                    <text>
                    <li id="Cnode_@node.Id">
                    </text>
                }

                        <a href="#">@node.Name</a>
                        <ul>
                            @{
                                var nodes1 = db.JobGroups.Where(jg => jg.CadreId == @node.Id).ToList();
                                foreach (var node1 in nodes1)
                                {
                                    Cadre root1 = new Cadre();
                                    root1.Id = node1.Id;
                                    <li id="Gnode_@node1.Id">
                                        <a href="#">@node1.Name</a>
                                        <ul>
                                            @{
                                                var nodes2 = db.JobGroupJobLevels.Where(jl => jl.JobGroup == @node1.Id).ToList();
                                                foreach (var node2 in nodes2)
                                                {
                                                    Cadre root2 = new Cadre();
                                                    root2.Id = node2.Id;
                                                    <li id="Lnode_@node2.Id">
                                                        <a href="#">@node2.JobLevel1.Name</a>
                                                        <ul></ul>
                                                    </li>
                                                }
                                            }
                                        </ul>
                                    </li>
                                }
                            }
                        </ul>
                </li>
            }
        }
    </ul>
</div>

samedi 3 décembre 2016

There are methods to tracking call's in MVC .NET?

I m working with a large project whith meets in mvc c# and looking for methods (plugins for visual studio, addons, frameworks) for tracking object in controller,views during the app works. Any methods exist for that ? I do not want use logging via nlog or log4net.