none
c# Class to byte array and vice versa sent in WCF RRS feed

  • Question

  • I am sending a class from one WCG to another which is located on renote server.

    I use next methods to convert to bytearray and back :

    public static byte[] ObjectToByteArray(Object obj)
            {
                if (obj == null)
                    return null;
    
                BinaryFormatter bf = new BinaryFormatter();
                MemoryStream ms = new MemoryStream();
                bf.Serialize(ms, obj);
    
                return ms.ToArray();
            }
    
            // Convert a byte array to an Object
            public static Object ByteArrayToObject(byte[] arrBytes)
            {
                MemoryStream memStream = new MemoryStream();
                BinaryFormatter binForm = new BinaryFormatter();
                memStream.Write(arrBytes, 0, arrBytes.Length);
                memStream.Seek(0, SeekOrigin.Begin);
                Object obj = (Object)binForm.Deserialize(memStream);
    
                return obj;
            }

    when I try do ByteArrayToObject i get error :

    System.Runtime.Serialization.SerializationException: 'Unable to find assembly 'WCF-Client

    the issue is thay the class is converted to bytes on "WCF-Client" project with namespace with that name "WCF_Client"

    and on the other side the name space is : "WCF_Server".

    how can I override this issue?

    Thursday, June 6, 2019 12:52 PM

All replies

  • i changed the namespace on both server and client to

    WCFClient

    and still same error.

    seems there is some cache create with the first name space.

    is there a wa to delete it?

    Thursday, June 6, 2019 10:10 PM
  • Hi friend,

    Welcome to the MSDN forum.

    According to the description, this issue is about the WCF development and our forum is to discuss the Unit Testing, I will help you move this thread to the appropriate forum for better support, thanks for your understanding.

    Best regards,

    Sara


    MSDN Community Support Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com

    Friday, June 7, 2019 2:16 AM
  • What is so special about this class that it can't be a data contract that is XML serialized by WCF,  the default object exchange between client and service , like a DTO?

    https://en.wikipedia.org/wiki/Data_transfer_object

    http://www.mindscapehq.com/documentation/lightspeed/Building-Distributed-Applications-/Building-WCF-Services-using-Data-Transfer-Objects

    Friday, June 7, 2019 7:54 PM
  • Hi DA924xi passed for a test very simple class with 3 fields

    and got the error.

    I tried also to pass a class with ought making a serialization but then the class on the other side was with null values.

    Friday, June 7, 2019 8:08 PM
  • Hi,
    Does your current project have project dependency?  Please try to clean the project and remove related project dependency. 
    Besides, if the class is transmitted in the WCF communication, we should make the class is decorated with DataContract for sure.
    Feel free to let me know if there is anything I can help with.
    Best Regards
    Abraham
    Monday, June 10, 2019 2:12 AM
    Moderator
  • Hi DA924xi passed for a test very simple class with 3 fields

    and got the error.

    I tried also to pass a class with ought making a serialization but then the class on the other side was with null values.

    Then make the class like the DTO example for WCF that was shown to you. The class must be known by the WCF client and service projects. You can make a classlib project call it Entities and place the DTO there and set project refernce to it from the WCF client and service projects so that they know what the DTO is about.
    Monday, June 10, 2019 5:33 AM
  • Hi DA924x

    can you provide me some article how to do it?

    Monday, June 10, 2019 7:48 AM
  • Hi DA924x

    can you provide me some article how to do it?

    Here is some WCF Web service code that's doing CRUD operations with a database with the DAL using EF sitting behind the WCF service. The  DTO pattern is being used with the ASP.NET MVC UI that you don't see calling upon an object's methods in the Service Layer, which is the WCF client to the WCF service.  

    1) Service Layer classlib project consuming the WCF Web Service.

    2) WCF Service project

    3) Repository Layer  a classlib project being referenced by the WCF service, but you really don't need the Repositroy layer, because I was playing. You can reference the DAL from the WCF service and eliminate the Repository layer.  

    3) Data Access Layer a classlib project using the Data Access Object pattern DAO that is being called by the Repository object that  has project reference to the DAL

    And you'll notice the 'using Entities'  is in all the code and  all projects have project reference to Entitles, and they know what the DTO is about.

    https://www.codeproject.com/Articles/1050468/Data-Transfer-Object-Design-Pattern-in-Csharp

    You're only seeing the Student functionality in the solution.

    You also notice how I get the exception back to the client-side using the DTO sent from the WCF service, since WCF service can't be tjrow an exception over the WCF boundary between the Wcf client and service easily, and one way to do it is send the exception back to the client by using the DTO.

    using System;
    using System.Collections.Generic;
    using System.ServiceModel;
    using Entities;
    
    namespace WcfService
    {
       
        // NOTE: You can use the "Rename" command on the "Refactor" menu to change the interface name "IService1" in both code and config file together.
        [ServiceContract]
        public interface IService1
        {
            [OperationContract]
            DTOStudent GetStudentById(Int32 id);
    
            [OperationContract]
            List<DTOStudent> GetStudents();
    
            [OperationContract]
            DTOStudent CreateStudent(DTOStudent dto);
    
            [OperationContract]
            DTOStudent UpdateStudent(DTOStudent dto);
    
            [OperationContract]
            DTOStudent DeleteStudent(Int32 id);
    
         }
    }
    

    using System;
    using System.Collections.Generic;
    using Entities;
    using Repository;
    
    namespace WcfService
    {
        public class Service1 : IService1
        {
            private IStudentRepo _studentRepo;
            private IEnrollmentRepo _enrollmentRepo;
            private DTOStudent dto;
            public Service1(IStudentRepo studentRepo, IEnrollmentRepo enrollmentRepo)
            {
                _studentRepo = studentRepo;
                _enrollmentRepo = enrollmentRepo;
    
            }
            public DTOStudent GetStudentById(Int32 id)
            {
                try
                {
                    return _studentRepo.GetStudentById(id);
                }
                catch (Exception e)
                {
                    dto = new DTOStudent();
    
                    dto.DtoResponse.Message = e.Message;
                    if (e.InnerException != null) dto.DtoResponse.InnerException = e.InnerException.Message;
                    dto.DtoResponse.StackTrace = e.StackTrace;
    
                    return dto;
                }
            }
            public List<DTOStudent> GetStudents()
            {
                try
                {
                    return _studentRepo.GetStudents();
                }
                catch (Exception e)
                {
                    var dtos = new List<DTOStudent>();
                    dto = new DTOStudent();
    
                    dto.DtoResponse.Message = e.Message;
                    if (e.InnerException != null) dto.DtoResponse.InnerException = e.InnerException.Message;
                    dto.DtoResponse.StackTrace = e.StackTrace;
         
                    dtos.Add(dto);
                    return dtos;
                } 
            }
    
            public DTOStudent CreateStudent(DTOStudent dto)
            {
                try
                {
                    _studentRepo.CreateStudent(dto);
                    return null;
                }
                catch (Exception e)
                {
                    dto = new DTOStudent();
    
                    dto.DtoResponse.Message = e.Message;
                    if (e.InnerException != null) dto.DtoResponse.InnerException = e.InnerException.Message;
                    dto.DtoResponse.StackTrace = e.StackTrace;
    
                    return dto;
                }
            }
            public DTOStudent UpdateStudent(DTOStudent dto)
            {
                try
                {
                    _studentRepo.UpdateStudent(dto);
                    return null;
                }
                catch (Exception e)
                {
                    dto = new DTOStudent();
    
                    dto.DtoResponse.Message = e.Message;
                    if (e.InnerException != null) dto.DtoResponse.InnerException = e.InnerException.Message;
                    dto.DtoResponse.StackTrace = e.StackTrace;
    
                    return dto;
                }
            }
            public DTOStudent DeleteStudent(Int32 id)
            {
                try
                {
                    _studentRepo.DeleteStudent(id);
                    return null;
                }
                catch (Exception e)
                {
                    dto.DtoResponse.Message = e.Message;
                    if (e.InnerException != null) dto.DtoResponse.InnerException = e.InnerException.Message;
                    dto.DtoResponse.StackTrace = e.StackTrace;
    
                    return dto;
                }
            }
        }
    }
    
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Data.Entity;
    using System.Data.Entity.Core.EntityClient;
    using System.Data.Entity.Core.Objects;
    using System.Data.Entity.Infrastructure;
    using System.Data.SqlClient;
    using Entities;
    using DAL.Model;
    
    namespace DAL.DAO
    {
        public class DAOStudent : IDAOStudent
        {
            public DTOStudent GetStudentById(Int32 id)
            {
                var dto = new DTOStudent();
                using (var context = new CUDataEntities())
                {
                    var student = (context.Students.Where(a => a.StudentID == id)).SingleOrDefault();
    
                    if (student != null)
                    {
                        dto.StudentID = student.StudentID;
                        dto.FirstName = student.FirstName;
                        dto.LastName = student.LastName;
                        dto.EnrollmentDate = student.EnrollmentDate;
    
                        var enrolllments =  new DAOEnrollment().GetEntrollmentsByStudentId(id).ToList();
                        var courses = new DAOCourse().GetCoursesByStudentCourseId(student.StudentID).ToList();
    
                        dto.EnrollsandCourses = (from a in enrolllments
                                      join b in courses on a.CourseID equals b.CourseID
                        select new  DTOEnrollandCourse()
                         { Title = b.Title, Credits = b.Credits, Grade = a.Grade }).ToList();
                    }
                }
    
                return dto;
            }
            public void CreateStudent(DTOStudent dto)
            {
                using (var context = new CUDataEntities())
                {
                    var student = new Student
                    {
                        FirstName = dto.FirstName,
                        LastName = dto.LastName,
                        EnrollmentDate = dto.EnrollmentDate
                    };
    
                    context.Students.Add(student);
                    context.SaveChanges();
                }
            }
    
            public void DeleteStudent(int id)
            {
                Student student;
                using (var context = new CUDataEntities())
                {
                    student = (context.Students.Where(a => a.StudentID == id)).SingleOrDefault();
                }
    
                using (var newContext = new CUDataEntities())
                {
                    newContext.Entry(student).State = System.Data.Entity.EntityState.Deleted;
                    newContext.SaveChanges();
                }
            }
    
            public List<DTOStudent> GetStudents()
            {
               
                var dtos = new List<DTOStudent>();
    
                using (var context = new CUDataEntities())
                {
                    var students = context.Students.ToList();
    
                    foreach(var stud in students)
                    {
                        var dto = new DTOStudent
                        {
                            StudentID = stud.StudentID,
                            FirstName = stud.FirstName,
                            LastName = stud.LastName,
                            EnrollmentDate = stud.EnrollmentDate
                        };
    
                        dtos.Add(dto);
                    }
                }
    
                return dtos;
            }
    
            public void UpdateStudent(DTOStudent dto)
            {
                var student = new Student();
    
                using (var context = new CUDataEntities())
                {
                    student = (context.Students.Where(a => a.StudentID == dto.StudentID)).SingleOrDefault();
                }
    
                if (student != null)
                {
                    student.FirstName = dto.FirstName;
                    student.LastName = dto.LastName;
                    student.EnrollmentDate = dto.EnrollmentDate;
                } 
    
                using (var dbcontext = new CUDataEntities())
                {
                    if (student != null)
                    {
                        dbcontext.Entry(student).State = EntityState.Modified;
                        dbcontext.SaveChanges();
                    }
                }
            }
        }
    }
    
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using Entities;
    
    namespace ServiceLayer
    {
        public class ServiceA : IServiceA
        {
            public List<DTOStudent> GetStudents()
            {
                var dtos = new List<DTOStudent>();
    
                var client = new WCFServiceReference1.Service1Client();
    
                dtos = client.GetStudents().ToList();
                 
                if (dtos[0].DtoResponse.Message != null)
                {
                    throw new Exception(dtos[0].DtoResponse.Message + " " + dtos[0].DtoResponse.InnerException
                        + " " + dtos[0].DtoResponse.StackTrace);
                }
    
                return dtos;
            }
    
            public DTOStudent GetStudentById(Int32 id)
            {
                var client = new WCFServiceReference1.Service1Client();
    
               var dto = client.GetStudentById(id);
    
                if (dto.DtoResponse.Message != null)
                {
                    throw new Exception(dto.DtoResponse.Message + " " + dto.DtoResponse.InnerException
                        + " " + dto.DtoResponse.StackTrace);
                }
    
                return dto;
            }
            public void CreateStudent(DTOStudent dto)
            {
                var client = new WCFServiceReference1.Service1Client();
    
                var dtor = client.CreateStudent(dto);
    
                if (dtor != null)
                {
                    throw new Exception(dtor.DtoResponse.Message + " " + dtor.DtoResponse.InnerException
                        + " " + dtor.DtoResponse.StackTrace);
                }
            }
            public void UpdateStudent(DTOStudent dto)
            {
                var client = new WCFServiceReference1.Service1Client();
    
                var dtor = client.UpdateStudent(dto);
    
                if (dtor != null)
                {
                    throw new Exception(dtor.DtoResponse.Message + " " + dtor.DtoResponse.InnerException
                        + " " + dtor.DtoResponse.StackTrace);
                }
            }
            public void DeleteStudent(Int32 id)
            {
                var client = new WCFServiceReference1.Service1Client();
    
                var dtor = client.DeleteStudent(id);
    
                if (dtor != null)
                {
                    throw new Exception(dtor.DtoResponse.Message + " " + dtor.DtoResponse.InnerException
                        + " " + dtor.DtoResponse.StackTrace);
                }
            }
            public DTOEnrollment GetEnrollmentById(Int32 id)
          }
    }
    

    using System;
    using System.Collections.Generic;
    using System.Runtime.Serialization;
    
    namespace Entities
    {
       [DataContract] 
        public class DTOStudent
        {
            
            private DTOResponse dtor = new DTOResponse();
    
            [DataMember]
            public Int32 StudentID { get; set; }
    
            [DataMember]
            public string LastName { get; set; }
    
            [DataMember]
            public string FirstName { get; set; }
    
            [DataMember]
            public DateTime? EnrollmentDate { get; set; }
    
            [DataMember]
            public virtual ICollection<DTOEnrollandCourse> EnrollsandCourses { get; set; }
    
            [DataMember]
            public DTOResponse DtoResponse
            {
                get { return dtor; }
                set { dtor = value; }
            } 
        }
    }
    

    using System;
    using System.Collections.Generic;
    using Entities;
    using DAL.DAO;
    
    namespace Repository
    {    public class StudentRepo : IStudentRepo
        {
            private IDAOStudent _daoStudent;
    
            public StudentRepo(IDAOStudent daoStudent)
            {
                _daoStudent = daoStudent;
            }
            public DTOStudent GetStudentById(int id)
            {
               return _daoStudent.GetStudentById(id);
            }
            public List<DTOStudent> GetStudents()
            {
                return _daoStudent.GetStudents();
            }
            public void CreateStudent(DTOStudent dto)
            {
                _daoStudent.CreateStudent(dto);
            }
            public void UpdateStudent(DTOStudent dto)
            {
                _daoStudent.UpdateStudent(dto);
            }
            public void DeleteStudent(int id)
            {
                _daoStudent.DeleteStudent(id);
            }
        }
    }
    
    
    



    Monday, June 10, 2019 11:25 AM