Category Archives: Post

Post

[RESOLVED]Reading CSV file for validation and after that saving it on server in MVC 4

Hi,

I have CSV file upload functionality in MVC4. Below my code is working fine on local machine, when I deploy same code on server I am getting error "Could not find file at C:WindowsSystem32InetSrv".

  [HttpPost]
        public ActionResult Upload(HttpPostedFileBase UploadedFile)
        {
            try
            {
                var fp = Path.GetFileName(UploadedFile.FileName);
                var reader = new StreamReader(UploadedFile.FileName);
                while (!reader.EndOfStream)
                {

                        string[] str = reader.ReadLine().Split(‘,’);  //Validation Logic.

                 }

                reader.Close();
                reader.Dispose();
                UploadedFile.SaveAs(@"d:FileUploadDemo" + fp);
                return View("Index");
            }
            catch (Exception)
            {
                return View("Index");
            }
        }

But If I comment below file reading code,

  var fp = Path.GetFileName(UploadedFile.FileName);
                var reader = new StreamReader(UploadedFile.FileName);
                while (!reader.EndOfStream)
                {
                    string[] str = reader.ReadLine().Split(‘,’);
                }
                reader.Close();
                reader.Dispose();

then my file is getting saved on the server perfectly fine.

But, Before saving a file, I want to validate the file data. I have implemented client side code but it is not working in IE browsers. So wanted to do server side validation.

Or any client side code, working in IE8+ browsers (without asking user to activate ActiveX object) is greatly appreciated.

The filename only contains the name of the file itself, it is for "information" purposes, the file isn’t actually saved to disc until you save it using SaveAs, so you can’t access it yet via StreamReader.  If you want to read its contents you need to access
the file data via the InputStream and convert it to a string that you can then validate

http://stackoverflow.com/questions/16030034/asp-net-mvc-read-file-from-httppostedfilebase-without-save

[RESOLVED]Authorize Attribute

Hi All, 

I am writing my custom Authorize attribute..

but I need to initialize my service with two paramteres  which in turn calls the repository

How can I initialize service or repository ?

Please help 

Thanks

Hi,

gowrifor.net

How can I initialize service or repository ?

Can you show some relevant parts of your code? Are you using dependency injection? …

Grz, Kris.

gowrifor.net

I need to initialize my service with two paramteres

Do you mean to pass parameters to you custom Authorize attribute. In that case you can pass it as a parameter. Please take a look at this stack overflow post

create the authorize filter with parameter asp.net mvc

[RESOLVED]Re-using the same model, same controller with different views

I didn’t think that this was going to cause me so much difficulty .. and I have only just started with this project Surprised

I have one model which I want to populate the model’s properties over multiple views. I was planning on using the controller to determine which View should be displayed.

The model looks like this:

public class QC_Rework
{
    public int nViewToDisplay { get; set; }
    public int nReworkNumber { get; set; }
    public string cSecondaryReferenceType { get; set; }
    public string cSecondaryReferenceNumber { get; set; }
    public int nLineQuantity { get; set; }
}

My "Create" controller looks like this:

[HttpGet]
public ActionResult Create([Bind(Prefix = "ReworkNumber")] int ReworkNumber=0)
{

    var oQC = new QC_Rework();
    oQC.nReworkNumber = ReworkNumber;
    oQC.nViewToDisplay = 1;
    return View("GetSecondaryReferenceType2", oQC);

}

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(QC_Rework oQC_Rework)
{
    // After GetSecondaryReferenceNumber2 the value of nViewToDisplay is "1"!!!
    // Even though the value in the Source Code and in the form says "2"!!!
    if (ModelState.IsValid)
    {
        switch (oQC_Rework.nViewToDisplay)
        {
            // Coming from Secondary Reference Type View
            case 1:
                if (String.IsNullOrEmpty(oQC_Rework.cSecondaryReferenceType) == true)
                {
                    ModelState.AddModelError("Model", "A secondary reference type needs to be selected!");
                    return View("GetSecondaryReferenceType2", oQC_Rework);
                }
                else
                {
                    oQC_Rework.nViewToDisplay = 2;
                    return View("GetSecondaryReferenceNumber2", oQC_Rework);

                }
            // Coming from Secondary Reference Type View
            case 2:
                {
                    oQC_Rework.nViewToDisplay = 3;
                    return View("GetQCDetails2", oQC_Rework);
                }
        }
    }
    // Should not get here at this stage!
    return View("NotFound", oQC_Rework);
}

The model’sproperty nViewToDisplay controls which Views get displayed.

When I debug the code, before the View GetSecondaryReferenceNumber2 gets called, the value in oQC_Rework.nViewToDisplay is set to 2 … but in the view itself it is "1′!!

What am I doing wrong?

Many thanks …

you don’t show the view code, but most likely its something like:

   @Html.HiddenFor(m=>m.nViewToDisplay)

with the html helpers, the lambda expression is just to get the name. ("nViewToDisplay") in your case. this name is then used to lookup the value. The postback form collection is searched before the ViewBag.Model (where you changed the data). so the postback
value is used.

just use a vanilla hidden field:

  <input type="hidden" name="nViewToDisplay" value="@Model.ViewBag.nViewToDisplay" />

or original helper that takes the value

   @Html.Hidden("nViewToDisplay",ViewBag.nViewToDisplay)

[RESOLVED]How to Post with foreign keys

public List<Job> PostNewJob(Job newJob)
        {
            Job job = new Job();

            job.JobId = newJob.JobId;
            job.JobNumber = newJob.JobNumber;
            job.JobName = newJob.JobName;
            job.JobDescription = newJob.JobDescription;
           
            db.Jobs.Add(newJob);
            db.SaveChanges();

            return db.Jobs.ToList();
        }

 public class Job
    {
        public Job()
        {
            this.Customers = new HashSet<Customer>();
            this.ChangeOrders = new HashSet<ChangeOrder>();
        }
        public int JobId { get; set; }
        public int JobNumber { get; set; }
        public string JobName { get; set; }
        public string JobDescription { get; set; }

        public virtual ICollection<Customer> Customers { get; set; }
        public virtual ICollection<ChangeOrder> ChangeOrders { get; set; }
    }


public List<Customer> PostNewCustomer(Customer newCustomer)
        {
            Customer customer = new Customer();

            customer.CustomerId = newCustomer.CustomerId;
            customer.CustomerName = newCustomer.CustomerName;
            customer.CustomerPhoneNumber = newCustomer.CustomerPhoneNumber;
            customer.CustomerFaxNumber = newCustomer.CustomerFaxNumber;
            customer.JobId = newCustomer.JobId;

            db.Customers.Add(newCustomer);
            db.SaveChanges();

            return db.Customers.ToList();
        }

 public class Customer
    {

        public int CustomerId { get; set; }
        public string CustomerName { get; set; }
        public Int64 CustomerPhoneNumber { get; set; }
        public Int64 CustomerFaxNumber { get; set; }

        public int? JobId { get; set; }
    }


 $scope.submitJob = function () {
        var id = $scope.currentItem.JobName
        var data = {
            JobId: $scope.currentItem.JobId,
            JobNumber: $scope.currentItem.JobNumber,
            JobName: $scope.currentItem.JobName,
            JobDescription: $scope.currentItem.JobDescription
            
            
        }
        $http.post('/api/apiJob/PostNewJob', data).success(function (data, status, headers) {
            console.log(data);
               $scope.PrintPreviewModal();
               window.top.location.reload();
            
        });
 };

  <form ng-submit="submitJob()" enctype="multipart/form-data">
                            <fieldset>
                                <div>
                                    <div class="inline-fields">
                                        <label>Number:</label>
                                        <input ng-model="currentItem.JobNumber" type="text">

                                        <label>Job Name:</label>
                                        <input ng-model="currentItem.JobName" type="text">
                                        <label>Customer:</label>
                                        <input type="text" ng-model="currentItem.CustomerName">
                                    </div>
                                    <div class="inline-fields">
                                        <label>Address:</label>
                                        <input ng-model="currentItem.CustomerAddress" type="text">
                                    </div>
                                    <div class="inline-fields">
                                        <label>City:</label>
                                        <input ng-model="currentItem.CustomerCity" type="text">

                                        <label>St:</label>
                                        <input ng-model="currentItem.CustomerState" type="text">

                                        <label>Zip:</label>
                                        <input ng-model="currentItem.CustomerZipcode" type="text">

                                <input type="submit" value="Save" />

                            </fieldset>
                        </form>

I am trying to change how I post and update my primary class JOB. Previously I was using the Customer Class as a List and I was storing the JOB Customer information in the Job class itself. The problem with this was If I went to go update a Customers information
in the Customer List I would have to go to every Job that has that Customer and Manually update everyone separately. So I am unsure how to do this. When I am creating a New Job how do I  Connect the appropriate Customer with that Job? I am already doing this
with another class called ChangeOrder but the difference is the Job has to be already been created before I can make that Post.. And also, the Customer can be assigned to multiple Jobs. So How does the foreign key work with this? How can you have a Customer
with multiple foreign keys "JobIds" attached to it?

What you are looking is a many to many relationship. Please take a look at this article in MSDN magazine

Handle Many-to-Many Relationships in Entity Framework and ASP.NET MVC

ok, so I created a linking table. What am I doing wrong? Here is what is coming back from the database

 {$id:1, JobCustomerId:1, JobId:1, Job:null, CustomerId:2, Customer:null}
$id: "1"
Customer: null
CustomerId: 2
Job: null
JobCustomerId: 1
JobId: 1

public class JobCustomer
    {
        public int JobCustomerId { get; set; }
        public int JobId { get; set; }
        public virtual Job Job { get; set; }
        public int CustomerId { get; set; }
        public virtual Customer Customer { get; set; }
    }
public class Job
    {
       
        public int JobId { get; set; }
        public int JobNumber { get; set; }
        public string JobName { get; set; }
        public string JobDescription { get; set; }

        public ICollection<JobCustomer> JobCustomers { get; set; }
       
    }
public class Customer
    {

        public int CustomerId { get; set; }
        public string CustomerName { get; set; }
        public Int64 CustomerPhoneNumber { get; set; }
        public Int64 CustomerFaxNumber { get; set; }

        public ICollection<JobCustomer> JobCustomers { get; set; }
      }
public List<JobCustomer> GetJobs()
        {
            List<JobCustomer> jobs = new List<JobCustomer>();
             jobs = db.JobCustomers
                .ToList();
            return jobs;
        }

Hi texas697,

You don’t need to create a link table manually, the EF will create it. For the link table, it doesn’t have the entity field, just the keys of these entities.

For your code, the fluent API would be like this:

modelBuilder.Entity<Job>() 
    .HasMany(j => j.Customers) 
    .WithMany(c => c.Jobs) 
    .Map(m => 
    { 
        m.ToTable("JobCustomer"); 
        m.MapLeftKey("JobId"); 
        m.MapRightKey("CustomerId"); 
    });
public class Job
    {
       
        public int JobId { get; set; }
        public int JobNumber { get; set; }
        public string JobName { get; set; }
        public string JobDescription { get; set; }

        public ICollection<Customer> Customers { get; set; }
       
    }
public class Customer
    {

        public int CustomerId { get; set; }
        public string CustomerName { get; set; }
        public Int64 CustomerPhoneNumber { get; set; }
        public Int64 CustomerFaxNumber { get; set; }

        public ICollection<Job> Jobs { get; set; }
      }

More information, please refer to:

# Configuring a Many-to-Many Relationship

http://msdn.microsoft.com/en-in/data/jj591620.aspx#ManyToMany

Best Regards

Starain Chen

that sure does make things easier. Now what if I have additional classes that need to be linked to Job? How would the modelBuilder look? Do i put this in my IdentityModels? If this is the correct way of doing it, I did do a migration without errors. The
tables in the sql where created. But How Do I query the information from my project? I went through the JobApi but the data for Customers, ChangeOrders, etc… came back null. 

 public class ApplicationUser : IdentityUser
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public bool? Hidden { get; set; }
        public string UserEmail { get; set; }
    }

    public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
    {
        public ApplicationDbContext()

            : base("DefaultConnection", throwIfV1Schema: false)
        {
            this.Configuration.LazyLoadingEnabled = false;
            this.Configuration.ProxyCreationEnabled = false;

        }
        public DbSet<Job> Jobs { get; set; }

        public DbSet<Employee> Employees { get; set; }
        public DbSet<Customer> Customers { get; set; }
        public DbSet<ChangeOrder> ChangeOrders { get; set; }
        public DbSet<JobType> JobTypes { get; set; }
        public DbSet<GeoArea> GeoAreas { get; set; }
        public DbSet<JobClass> JobClasses { get; set; }

        protected override void OnModelCreating
       (DbModelBuilder modelBuilder)
        {
base.OnModelCreating(modelBuilder); modelBuilder.Entity<Job>() .HasMany(j => j.Customers) .WithMany(c => c.Jobs) .Map(m => { m.ToTable("JobCustomer"); m.MapLeftKey("JobId"); m.MapRightKey("CustomerId"); }); modelBuilder.Entity<Job>() .HasMany(j => j.ChangeOrders) .WithMany(c => c.Jobs) .Map(m => { m.ToTable("JobChangeOrder"); m.MapLeftKey("JobId"); m.MapRightKey("ChangeOrderId"); }); modelBuilder.Entity<Job>() .HasMany(j => j.GeoAreas) .WithMany(c => c.Jobs) .Map(m => { m.ToTable("JobGeoArea"); m.MapLeftKey("JobId"); m.MapRightKey("GeoAreaId"); }); modelBuilder.Entity<Job>() .HasMany(j => j.JobTypes) .WithMany(c => c.Jobs) .Map(m => { m.ToTable("JobJobType"); m.MapLeftKey("JobId"); m.MapRightKey("JobTypeId"); }); modelBuilder.Entity<Job>() .HasMany(j => j.JobClasses) .WithMany(c => c.Jobs) .Map(m => { m.ToTable("JobJobClass"); m.MapLeftKey("JobId"); m.MapRightKey("JobClassId"); }); } }

 public class Job
    {
       
        public int JobId { get; set; }
        public int JobNumber { get; set; }
        public string JobName { get; set; }
        public string JobDescription { get; set; }

        
        public ICollection<Customer> Customers { get; set; }
        public ICollection<ChangeOrder> ChangeOrders { get; set; }
        public ICollection<GeoArea> GeoAreas { get; set; }
        public ICollection<JobClass> JobClasses { get; set; }
        public ICollection<JobType> JobTypes { get; set; }
    }

Hi texas697,

Your code is right.

To load the related entities, we could use Include method.

For example:

var data =db.Jobs.Include("Customers");

Best Regards

Starain Chen

[RESOLVED]How to save and display Multiple responsiblities of data into a single record

i want to manage the job posting data in website. here i am creating a page to insert the job requirement details into database and display in a webpage .

every thing is fine but when came to reponsibilities. their may be many more responsibulities for a particular job . here i  want to save it in a single column in database

but i want to display in a page in a listed format how can i save and retrieve this responsibilites columns. now every thing is in static so i am trying it to dynamic from database.

i want ot display in a format like this

<tr>
                                            <td valign="top"><p><b>Responsibilities</b></p></td>
                                            <td valign="top"><p><b>:</b></p></td>
                                            <td>
                                                <p>
                                                    <ul style="padding-left:30px;">
                                                        <li>Strong Java skills with extensive knowledge of the Android SDK.</li>
                                                        <li>Object Oriented PHP skills at all scales.  </li>
                                                        <li>Exceptional organizational & project management skills.</li>
                                                        <li>Demonstrated success in defining & launching mobile apps.</li>
                                                    </ul>
                                                </p>
                                            </td>
                                        </tr>

please give me some suggestions so how can i save it in a single column and how can rearrange it in a form look like above format

Assume that you are storing the responsibilities in a single column with comma separation

<tr>
    <td valign="top"><p><b>Responsibilities</b></p></td>
    <td valign="top"><p><b>:</b></p></td>
    <td>
        <p>
            <ul style="padding-left:30px;">

                @{
                    
                    string[] resps = Model.Responsibilities.Split(",".ToCharArray());
                    foreach(string resp in resps)
                    {
                         <li>@resp</li>
                    }
                    
                }
              
            </ul>
        </p>
    </td>
</tr>

Hi Siva,

First, please refer to cnuonline’s reply. You’d better use the special separator (E.g @#).

Secondly, to save the data, you could use
String.Join
method to combine the values.

On the other hand, in my opinion, it’s better to store the responsibilities data to another table. (One to many)

Best Regards

Starain Chen

[RESOLVED]Where to write repository Pattern in MVC+WCF project?

Hi Folks,

Wanted to learn Repository Pattern implemenation in my project whic has following structure.

Web – MVC4

Services – WCF + EF5

So in all my controller actions will make a call to WCF service to get the Models

Models are shared across WCF & MVC projects. (WCF & MVC are in diff solutions all together).

So, nmow I wanted my project to have Repository Pattern for Data Access which is in WCF.

 

Currently my Service is defined like below with methods.

 public bool SubmitManfLocationrequest(Request req)
        {
            using (LASORContext dbcontext = new LASORContext("xx"))
            {
                dbcontext.Requests.Add(req);
                dbcontext.SaveChanges();
            }
            return true;

        }


        public List<Request> GetAllMFLRequests()
        {
            List<Request> AllMFLRequests = new List<Request>();
            using (LASORContext dbcontext = new LASORContext("xx"))
            {
                AllMFLRequests  = dbcontext.Requests.ToList();
                return AllMFLRequests;
            }
        }

any suggestions on converting this to Repostiory in WCF Service side?

WCF service serving the data, so it is feasible to have a DAL in the service with Repository implementation.

MVC app acts as the client, sends request to WCF service to perform CRUD.

Refer:

http://weblogs.asp.net/sukumarraju/creating-n-tier-web-api-application

At the above blog article I walked through the repository pattern implementation.

* Note that regardless of the technology (WCF or Web API) the pattern implementation is same.

Let me know any further queries.

Hi Ram,

About repository and unit of work patterns, you also could refer to:

# Implementing the Repository and Unit of Work Patterns in an ASP.NET MVC Application

http://www.asp.net/mvc/tutorials/getting-started-with-ef-5-using-mvc-4/implementing-the-repository-and-unit-of-work-patterns-in-an-asp-net-mvc-application

Best Regards

Starain Chen

The type or namespace name 'WebGrid' could not be found (are you missing a using directive or an assembly reference?)

i am getting this kind of error message while running the programm as compilation error. previously i didn’t get this kind of error message but suddenly i am getting the error. 

previously in all modules it’s working fine but suddenly in all the modules i am getting the same error. 

what’s problem behind on this

Hi,

did you uninstall / update a nuget package related to System.Web.Helpers?

Grz, Kris.

no i didn’t uninstall any package but in references i have this System.Web.Helpers

Hi,

do you have a CVS ready so that you can go back in history of your code to a state where it worked? If so check the differences. Likely some using statement got lost.

Grz, Kris.

Hi,

You may not have "WebGrid.*.dll" with your project, or you may update your project, and "WebGrid.*.dll" is incompatible. Or accidentally deleted from your project dll libs.

You may need to add reference again to your project.

Please check carefully and Have fun

i was installed the webgridmvc from nuget also but it is not working

Hi,

Make sure that name is "WebGrid" or "WebGridMVC". It is case sensitive. Please check.

I’ll try to test it and come to you then.

WebGrid grid = new WebGrid();

i am using this thing only from the entire project upto few days back also it’s working fine. right now we are trying to add a new view with the webgrid then we are getting this

problem and we run the entire project which have this webgrid all are getting the same error. we shocked what happend and how to regetting the Webgrid we dont want to change any other things right now because i have so many forms this webgrid

Hi,

If you install webgridmvc, you must use "@using WebGridMvc;" for the nameSpace.

Please post the detail errors.

if i changed to WebgridMvc then i have to change my entire code where i have this webgrid this will again long time taken thing 

 Layout = "~/Views/Shared/_AdminLayout.cshtml";
Line 5:  
Line 6:      WebGrid grid = new WebGrid();
Line 7:      grid.Bind(Model,
Line 8:                autoSortAndPage: true

CS0246: The type or namespace name ‘WebGrid’ could not be found (are you missing a using directive or an assembly reference?)

this error i am getting when i run the page 

Are you using the appropriate @using statement?  If so, is it at the top of the page or the web.config file?  If it is in the web.config then try closing VisualStudio then re-opening it as that config setting isn’t dynamically processed as you change it. 
Also check the appropriate dll is in the bin folder.  Something else you can test to see if it is a missing assembly or missing "using" is to use the full classname, eg the namespace and classname, and see if the class is found then.

the problem is solved after remove the System.Web.Helpers from the references and add it again. But i got another problem while do it when  i tried to run the program i am getting the following error

An exception of type ‘System.TypeLoadException’ occurred in Microsoft.Owin.Security.Cookies.dll but was not handled in user code

Additional information: Could not load type ‘Microsoft.Owin.Security.AuthenticationDescription’ from assembly ‘Microsoft.Owin, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35′.

Hi Siva_540,

Thanks for your post.

Siva_540

Additional information: Could not load type ‘Microsoft.Owin.Security.AuthenticationDescription’ from assembly ‘Microsoft.Owin, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35′.

You can try install the package from Manage NuGet packages

Microsoft.Owin.Security

Hope this can be helpful.

Best Regards,

Eileen

i have already this in my project

[RESOLVED]Not able to get name of the image button on Controller side

Hello There, 

I am new to MVC and facing lot of issues :(

I have one image, acting as a button, when I clicked on it, it post back, but not able to find its name in Action. Here is my code snippet

View :-

@using (Html.BeginForm())
{

<input type="image" value="AddRoutine" name="button" src="~/Images/Add.png" id="imgAdd" title="Add" alt="Add" />

}

Controller :- 

[HttpPost]
public ActionResult Index(string button)
{
          // the parameter "button" is always comes null 

it is working fine when I use input type button instead of image 

Where I am doing mistake, what is the problem with input type image ?

Please help me out 

Thanks
Ash

An input type="image" is not an input that can carry a value to the server

try this

<button type="submit" value="AddRoutine" name="button" >
	
    <img src="~/Images/Add.png"  title="Add" alt="Add"/>
	
</button>

thats because the image posts two values containing the x & y positions. name.x and name.y. so you need an object:

public class ImageValue
{
   public int x {get; set;}
   public int y {get; set;}
}

[HttpPost]
public ActionResult Index(ImageValue button)
{

}