mardi 31 janvier 2017

How to get unique identifier while executing code

I'm looking for a way to solve my problem :

I have a C# MVC web application that uses a VB6 DLL.

In this DLL, there is a class that is common for all users and I would like to change this architecture.

Is there any possibilities in Class_Initialize function to get an unique identifier to set an array with this id and the instance ?

My goal is to not add this id in all function call.

This allow me to get the correct instance anywhere in the code.

I can use Windows API function or others...

Thanks for your help

@Html.ActionLink() routing to incorrect controller

I'm using following ActionLink method:

@Html.ActionLink("Manage User Branch", "mngBranchUser", "branchUser", new { @class = "btn btn-default" })

to link to "mngBranchUser" method in "branchUser" controller but it is actually routing to "mngBranchUser" method in "Home" controller (which is the global controller of-course.) with URL as: http://localhost:57852/Home/mngBranchUser?Length=10. HTML generated by the given line of code is:

<a class="btn btn-default" href="/Home/mngBranchUser?Length=10">Manage User Branch</a>

when the desired HTML is:

<a class="btn btn-default" href="/branchUser/mngBranchUser?Length=10">Manage User Branch</a>

Also, if I change from:

@Html.ActionLink("Manage User Branch", "mngBranchUser", "branchUser", new { @class = "btn btn-default" })

to

@Html.ActionLink("Manage User Branch", "mngBranchUser", "branchUser" })

I successfully get the desired output correct. But I need new { @class = "btn btn-default" part of the code for formatting reasons. Can someone please guide. Thank you.

samedi 28 janvier 2017

Html.DisplayNameFor not show data (.net mvc)

I have a Run MODEL that I submit to View.

public class Run
{
  public List<Car> cars{get; set;}
  public Bike bike{get; set;}
}

public class Car
{
public name  {get; set;}
public Model {get; set;}
}

public class Bike
{
public name  {get; set;}
public Model {get; set;}
}

In my view I want to show List of cars names.

@Html.DisplayNameFor(model => model.cars.Name)

In tabel header Iam trying this.

This is not working. Its say somthing reference missing?!

Im my View iam able to show all MODEL data. BUT i just cant show Heading text

In my view I also have

@using //Namespace to model folder

What is wrong ?

Telerik Reporting export pdf hide metadata

is it possible to hide information about Creator/Producer/CreationDate in response when I exporting report to pdf file.

/Creator(Telerik Reporting 6.2.12.1017 \(http://ift.tt/1AOFjIR\))
/Producer(Telerik Reporting 6.2.12.1017 \(http://ift.tt/1AOFjIR\))
/CreationDate(D:20170128132024+01'00')

Version of Telerik.Reporting is 6.2. Thanks for any answers !

vendredi 27 janvier 2017

MVC controller Bulk Message Module Clone issues

private void SendMessage(string chatMsg, string Subject, int CUserId, ApplicationUser[] AllUsers, string item)
{
    if (item != "")
    {
        var Usr = AllUsers.FirstOrDefault(i => i.Username == item.Trim()).Id;

        int Groupid = 0;

        bool result = false;

        var QueryGetGroup = db.Database.SqlQuery<DtoGrouping>("select COUNT( ChatGroupId ) as GroupCount ,ChatGroupId from ChatGroupUser where ChatUserId in(" + CUserId + "," + Usr + ") group by ChatGroupId");

        if (QueryGetGroup != null)
        {
            foreach (var item1 in QueryGetGroup)
            {
                if (item1.GroupCount > 1)
                {
                    result = true;
                    Groupid = item1.ChatGroupId;
                }
            }
        }


        if (result == true)
        {
            //
        }
        else
        {
            //
            string sqlCreateGroup = "declare @GroupId int=null \n ";
            sqlCreateGroup += "insert into ChatGroup(GroupCreatorBy,IsActive,GroupName) values(" + CUserId + ",1,'" + Subject + "') set @GroupId=SCOPE_IDENTITY() \n ";
            sqlCreateGroup += "insert into ChatGroupUser (ChatUserId,ChatGroupId) values(" + CUserId + ",@GroupId) \n ";
            sqlCreateGroup += "insert into ChatGroupUser (ChatUserId,ChatGroupId) values(" + Usr + ",@GroupId) \n ";
            sqlCreateGroup += "select @GroupId \n ";

            var getgroupid = db.Database.SqlQuery<int>(sqlCreateGroup).FirstOrDefault();

            Groupid = Convert.ToInt32(getgroupid.ToString());
        }


        Guid messageId = System.Guid.NewGuid();

        ChatMessage con = new ChatMessage();
        con.Msg = chatMsg;
        con.ConnectionIDUser = messageId.ToString();
        con.SendDate = DateTime.Now;
        con.SendFrom = CUserId;
        con.ChatGroupId = Groupid;
        con.IsDeleted = false;
        //con.ImageFile=null //now not working
        con.IsSeen = false;
        db.ChatMessages.Add(con);

        db.SaveChanges();

    }
}

Message Controller.

I have a application users.

So ı have a bulkmessage send module many users, after have selected and sending message for users

panel has been dropdown user list + message body textbox

How many users were selected so sending a message.

Problem We have A,B,C,D,E users İf ı can choosen 8 user and body write sending

the same message being cloned A user has been 8 message clone or B user has been 8 message clone. Sending messages by the number of Choose users.

how to call and refresh a partial view in mvc 5 razor?

how can a partial view on the create view that has to come in empty be refreshed with new data when a user selects a value from a list a values drop down.

I have a tried a buch of stuff listed on the message board as well as others and it just drills down to more errors. I just can't believe something so easy in webforms is this hard to do in mvc.

What has been done. And I tried this both in chrome and IE and get errors so I'm lost.

I have something like this for a partial view in the shared folder:

 <table cellpadding="1" border="1">
   <tr>
       <th>
           LIST Issue 
       </th>

   </tr>

   @foreach (SYSTEMX.Models.VUE_ISSUE_LIST item in ViewBag.IssuesList)
   {
       <tr>
           <td>
               @item.Issue
           </td>

       </tr>
   }

</table>

The Create cshtml file has this:

        <div class="col-sm-6">

            <div class="form-horizontal" style="display:none"    id="PV_IssueList">

                @{ Html.RenderAction("UpdateIssuesList");}

            </div>
        </div>

In the Controller there is code similar to this

[HttpGet]
    public ActionResult UpdateIssuesList(int? VID)
    {


        ViewBag.IssuesList = GetIssuesList(VID);
        return PartialView("UpdateIssuesList");


    }

The GetIssuesList(VID) looks very similar to this and it is in the controller of the mvc application

    private List<VUE_ISSUE_LIST> GetIssuesList(int? VID)
    {

        return db.VUE_ISSUE_LIST_.Where(i => i.ID == VID).ToList();
    }

I get this error... I'm clueless to what is going on here.

The partial view 'UpdateIssuesList' was not found or no view engine supports the searched locations. The following locations were searched:
~/Views/CONTROLLERX/UpdateIssuesList.aspx
~/Views/CONTROLLERX/UpdateIssuesList.ascx
~/Views/Shared/UpdateIssuesList.aspx
~/Views/Shared/UpdateIssuesList.ascx
~/Views/CONTROLLERX/UpdateIssuesList.cshtml
~/Views/CONTROLLERX/UpdateIssuesList.vbhtml
~/Views/Shared/UpdateIssuesList.cshtml
~/Views/Shared/UpdateIssuesList.vbhtml 

A forum user posted something like this as a solution and I guess it worked for him as he put a green check mark but it does not work for me at all.

the post... the answer has green check

Updating PartialView mvc 4

also tried this: refresh a partial view in mvc

also read over this but it is so very technical that I don't follow it all that well.

http://ift.tt/2fXjqph

Thanks in advance!

Updating a Partial View In mvc 5

getting and error when trying to load a partial view that should display a list on the create view of the mvc app. the list is based on a value will come from a list of values drop control.

Well on create view there is no selection so the list is empty and will need to refreshed after the user selects a value while in the mvc create view.

So Followed this answer: The Answer is the one with the Green Check Marking. and got errors:

Updating PartialView mvc 4 But I have some questions about what is being said.

The Guys says: "There are some ways to do it. For example you may use jQuery:"

and he shows the Java Query..

But he also shows another method and says: "If you use logic in your action UpdatePoints() to update points"

[HttpPost]
public ActionResult UpdatePoints()
{    
   ViewBag.points =  _Repository.Points;
   return PartialView("UpdatePoints");
 }

I get the following error

The parameters dictionary contains a null entry for parameter 'ID' of non-nullable type 'System.Int32' for method 'System.Web.Mvc.ActionResult UpdateList(Int32)' in 'System.Controllers.RController'. An optional parameter must be a reference type, a nullable type, or be declared as an optional parameter. Parameter name: parameters

I have no clue what this error means

So in create view:

            <div class="form-horizontal" style="display:none" id="PVList">

                @{ Html.RenderAction("UpdateList");}

            </div>
        </div>

In controller under the create action as its own function

    [HttpGet]
    public ActionResult UpdateList(int ID)
    {

        if (ID != 0)
        {
            ViewBag.List = Get_List(ID);
            return PartialView("PV_List");

        }
        else
        {
            ViewBag.List = "";
            return PartialView("");
        }


    }

And the function that makes the list for the view bag function:

private List<SQL_VIEW_LIST> Get_List(int ID)
        {

            return db.SQL_VIEW_LIST.Where(i => i.ID == ID).ToList();
        }

The Java Scripts for the for the list of values drop down list of values: That also controls turning on the visibility of the list when it has data

    //Fire The List to make visible after list values select 
    $(document).ready(function () {
        $('#RES_VEH_ID').change(function ()
        {

            $("#PV_List").show(); // Shows Edit Message
            $.post('@Url.Action("PostActionTo_Partial","Create")').always(function()
                   { ('.target').load('/Create'); })

        });
    })

Also does anyone know what this string mean: ? "PostActionTo_Partial"

Also does anyone know what this means ViewBag.points = _Repository.Points; I get the view bag part but its the _Repository.Points; part that I don't understand. Any one have any ideas of what is going on there?

Thanks so very much for your time and help

jeudi 26 janvier 2017

Structure two different websites where external pages are different, internal pages are same

I have an ASP.Net MVC website, "learning Mandarin online". It's operational and it's working fine for me. Now, I want to reuse this website as a template for a new website, "learning Spanish online." Both websites will be on completely different domains and on a completely different servers.

For my "learning Mandarin online" website, 1/3 of the webpages are external pages that the user can browse without logging into the website. The other 2/3 of the webpages are internal pages that the user can only see if they login to the website. I want both websites to use different external pages (the external .aspx pages will be different for both sites) but both websites to share the same set of internal pages (the internal .aspx pages will be the same for both websites).

My question is, in ASP.Net MVC, how can I structure my project/solution for both websites? Since the only difference for both websites are the external pages, the easiest solution I can think of to handle the external pages is storing the mappings for each view in the database, fetching this mapping from the database based on some constant (ie. WebsiteType) set in web.config, and then returning the view based on the mapping. For example, in my controller:

// WebsiteType is stored in web.config.  It is set to LearnMandarin for the learn Manadarin
// online website and it is set to LearnSpanish for the learn Spanish online website
string websiteType = WebConfigurationManager.AppSettings["WebsiteType"];

// figure out which Homepage .aspx view to return, based on the websiteType
// GetView(...) will get the mapping from the database
string viewToReturn = GetView(websiteType, "HomepageView");

return View(viewToReturn);

This is the cleanest solution I can think of so far and the best structure I can think of. I would end up having two different .aspx files in the same directory - one .aspx page for the learning Mandarin online website, another.aspx file for the learning Spanish online website. Is this the best way to structure my project or is there an even cleaner way?

(I am using Visual Studio 2010 and ASP.Net MVC version 3.0.0.0)

mardi 24 janvier 2017

Get URL when calling by WebClient DownloadString in MVC

How can I get the calling url in MVC razor when it is calling by WebClient DownloadString. let me explain by example what I want to say :).

Suppose there are 2 projects. Proj-A and Proj-B.

In Proj-A below is the code written for calling Proj-B page.

using(WebClient client = new WebClient()) {
    string html = client.DownloadString("Proj-B/View1");
}

Now in View1 how can I get the calling url of Proj-A.

dimanche 22 janvier 2017

MVC DropDownListFor basic True False in View Text Change

<div class="form-group">
    @Html.LabelFor(model => model.Supervisior, new { @class = "" })
    @Html.EditorFor(model => model.Supervisior, new { @class = "", required = "required", form_id="form1" })
    @Html.ValidationMessageFor(model => model.Supervisior)
</div>

it has been dropdown list TRUE - FALSE This database is being called

So ı want True Displayed name : Confirm False Displayed name: Reject

appear on list. how can ı do ?

vendredi 20 janvier 2017

Load all data to DropDownList

I have this code below working fine.

Sample output

Computer Department

Technical Department

Product Department

Let say my department is Product Department. I am the the who log-in in the system / project. It is possible to first load my department in the DropDownList?. What I mean in first load is upon loading of the dropdown my department is set to be the first.

Controller

ViewBag.DepartmentId = new SelectList(db.Departments, "DepartmentId", "DepartmentDesc", null).OrderBy(m => m.Text);

HTML

@Html.DropDownList("DepartmentId ", ViewData["DepartmentId "] as SelectList, "", new { @style = "width:130px;" })

MVC3 on Visual Studio 2010 Build Errors

Every once in a while, almost daily, I get build errors when building MVC 3 project in Visual Studio 2010, the errors are all related to unknown MVC 3 classes.

Unknown type System.Web.Mvc.Controller

What I do then is:

  • Close Visual Studio
  • Uninstall MVC 3
  • Install MVC 3
  • Open Visual Studio
  • Build the project

Everything is fine, no build errors, build succeeded.

How can I get rid of this annoying problem?

mardi 17 janvier 2017

How to call controller method and pass the object from ajax call

I am in a learning process and working on ASP.net MVC 5 project. So, I have a model view which has other model views in it.

Parent Model View

public class FullConfigMV
{
 some properties here
 public ElementStyleMV Page { get; set; }
}

Now below is what I want to achieve.

  1. Make an ajax call

  2. once the ajax call hits the controller function set some values

  3. now from there I need to pass that object to another controller action which will return it's view.

Step 1.

<script>
    $(document).ready(function()
    {
        $("#tan").change(function()
        {
            alert(this.value);
            $.ajax({
                type: 'POST',
                url: '/Settings/GetAvailableLocationsFor',
                data: { accountId: 28462, groupId: 35},
                success: function (data) {
                    //Whatever
                },
                error: function () {
                    DisplayError('Failed to load the data.');
                }
            });


        });
    });
</script>

After step 1 my breakpoint hits at

public ActionResult GetAvailableLocationsFor(int accountId, int groupId)
        {
            FullConfigMV configData = SetLoader.GetDSettings(accountId, groupId);
            Utils.SiteCss = configData.CssStyles();
           // NOW AT THIS PLACE I WANT TO CALL ANOTHER CONTROLLER FUNCTION
           // AND PASS THE `configData Obj`
            return View();
        }

I know we have something like

return RedirectToAction("Index","Home"); 

BUT HOW TO PASS THE config Obj

The controller function that I want to call is in Home Controller and the action name is Index

public ActionResult Index(FullConfigMV data)
        {
            return View();
        }

If the requirement seems weird then kindly bear/humor me on this.

what is Easy way of calling export to excel reports in asp.net Mvc5

i need to call export to excel report in asp.net MVC5 like bellow image. My actual requirement is exporting to excel page with different dataset data . and also we has to display the report exactly like in Image. Is there any another possibilities to export excel data like bellow image. or any third party tools.or any another new technology to implement Export to excel reports.

Image Url: http://ift.tt/2j55dF9

Please please suggest me.

samedi 14 janvier 2017

Linq to SQL Group by and sum in select with entity

This is mysql query:

  select convert(date,convert(char(11),[Bill Date])) as date,SUM(Amount) as total from Bills
group by [Bill Date]
order by date asc

What will be its LINQ to SQL with entitiy.

vendredi 13 janvier 2017

MVC: Custom Validator to Check Either one of two properties has value

I need to check that user should enter one of two fields i.e either "Phone" or "Postal" field in view.

The Problem is the Validator checks for all(four) properties of model instead of just specified ones.

Heres my custom Validator

 [AttributeUsage(AttributeTargets.Class, AllowMultiple =true)]
    public class CustomValidators :ValidationAttribute
    {
        private string[] PropertyList { get; set; }
        public CustomValidators(params string[] propertyList)
        {
            this.PropertyList = propertyList;
        }
        public override bool IsValid(object value)
        {
            var typeinfo = value.GetType();
            var propertyinfo = typeinfo.GetProperties();
             foreach( var property in propertyinfo)
            {
                if(null != property.GetValue(value, null))
                {
                    return true;
                }
            }
            return false;
        }
    }  

Heres the Model

[CustomValidators("phone", "postal")]
    public class StatusViewModel
    {
        [Display(Name = "Promotion Name")]
        public string PromotionName { get; set; }
        [Required]
        public string refnumber { get; set; }  
        public string phone { get; set; }
        public string postal { get; set; }
    }
}

Why visual studio 2015 does not have ASP .NET MVC 3 Web Application template

I am trying to follow the procedures posted here, which calls for finding the ASP.NET MVC 3 Web Application template in Visual Studio. I do not see this exact name in the options I have. I did find this thread, and tried the fix but nothing has changed. I also searched via Visual Studio's on line option but the result was the same. I have Visual Studios 2015 version 14.0.25431.01 Update 3 running .Net version 4.6.01586. Is there anything else I need to do? Is there a different name for this template?

jeudi 12 janvier 2017

Set timer in ASP.net mvc website

In payment window When client clicks on payment button I want to start a timer. And if the payment processing takes more than let's say 5 second I want to redirect to a page. Below is what I could think of.

 [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult SavePayment(PaymentFormMV data)
        {
            if (Session["startTime"] == null)
            {
                Session["startTime"] = DateTime.Now;
            }

            var ticksRemaining = DateTime.Now - (DateTime)Session["startTime"];
           int x = int.Parse(ticksRemaining.ToString()); // Format Unhandled exception
            if(x == 5)
            {
                return RedirectToAction("Index", "Home");
            }
            // Payment Logic Here to 3rd Party API
             return View("PaymentConfirmation", returnData);
}

But it's not working as I expect when I calculate ticksRemaining. Do I need some theading or something here. I am new to development please guide me. I just want see the time duration between button click and current time. If it crosses 5 second I want to redirect the user to a new page.

How to display custom error messages of IIS Server in ASP.net MVC - 5

I am new to web development and I need to display custom error message that comes from IIS Server in MVC-5 application. for example "504 gateway time out error" or "500 Error". I am working on already existing code. Below is what I have till now.

BaseController

protected override void OnException(ExceptionContext filterContext)
        {
            if (!filterContext.ExceptionHandled)
            {
                filterContext.ExceptionHandled = true;
                Logger.Error("SimController", "OnException", "An exception has occurred.", filterContext.Exception);

                // this will cause the error to be displayed to the user..
                Response.StatusCode = 500;

                Response.StatusDescription = Constants.DISPLAYED_ERROR_MESSAGE_SHARED;

                if (filterContext.Exception.GetType() == typeof(ValidationException))
                { Response.StatusDescription += Constants.ADDITIONAL_DETAIL_ERROR_MESSAGE + filterContext.Exception.Message; }
                else
                { Response.StatusDescription += Constants.GENERIC_ERROR_MESSAGE; }
            }
        }

Error Controller:

 public ActionResult Index(string Message)
        {
            // We choose to use the ViewBag to communicate the error message to the view
            ViewBag.Message = Message;
            return View();
        }
        public ActionResult Oops(string Message)
        {
            // We choose to use the ViewBag to communicate the error message to the view
            ViewBag.Message = Message;
            return View();
        }

Web.Config

 <system.web>
    <compilation debug="true" targetFramework="4.5.1" />
    <httpRuntime targetFramework="4.5" />
    <customErrors mode="On" defaultRedirect="~/ErrorPage/Oops">
      <error redirect="~/Error/Oops/404" statusCode="404" />
      <error redirect="~/Error/Oops/500" statusCode="500" />
    </customErrors>
  </system.web>

Global.asax

 public class FilterConfig
    {
        public static void RegisterGlobalFilters(GlobalFilterCollection filters)
        {
            //filters.Add(new HandleErrorAttribute());
        }
    }



protected void Application_Start()
    {
        AreaRegistration.RegisterAllAreas();
        RouteConfig.RegisterRoutes(RouteTable.Routes);
        FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);

    }

I am new to coding so I have put whatever I could in this post. So, is that it? I am still not able to see the custom page for 500.

The way I am simulating the error is

Homecontroller:

 public ActionResult Index()
        {                return new HttpStatusCodeResult(500); 
            return View();
        }

Post I referrred : Custom Error

dimanche 1 janvier 2017

IIS 8.5 doesn't detect *.cshtml extension files for my index.cshtml

I have Windows Server 2012 R2, I have installed everything per microsoft website.

My program was written using ASP.NET MVC 3 Razor using c#. The published from VS2013 has bin, ctrl, view and etc.

I followed this method using from this website.

When trying to add a website it doesn't detect *.cshtml extensions. How do I add my website to IIS 8.5 on win2012R2?