.NET Tutorials, Forums, Interview Questions And Answers
Welcome :Guest
Sign In
Register
 
Win Surprise Gifts!!!
Congratulations!!!


Top 5 Contributors of the Month
Easy Web
Imran Ghani
Post New Web Links

Read CSV using Linq - System.IndexOutOfRangeException

Posted By:      Posted Date: October 19, 2010    Points: 0   Category :ASP.Net
 

I'm trying to get data from a CSV file and add it directly into a database using Linq.

I'm using the following code:

Dim dataImport = From line As String In File.ReadLines("c:\temp\test.csv").Skip(1)
		Let CR = line.Split(Chr(124)) _
		Select New [property] With { _
		.ADDRESS_1 = CR(0), _
		.ADDRESS_2 = CR(1), _
		.ADDRESS_3 = CR(2) _
		}

The code works if I remove all the but the first property e.g.

Dim dataImport = From line As String In File.ReadLines("c:\temp\test.csv").Skip(1)
		Let CR = line.Split(Chr(124)) _
		Select New [property] With { _
		.ADDRESS_1 = CR(0) _
		}


But then I get the old "System.IndexOutOfRangeException: Index was outside the bounds of the array." exception when adding more columns. 

I really want to get this working...

Any ideas?









View Complete Post


More Related Resource Links

The type 'System.Data.Linq.DataContext' is defined in an assembly that is not referenced. You must

  

Hi,

This is frustrating, and I don't know how to solve it.

I have a strange problem. I am adding a LinqDatasource object, and set the context:

        protected void LinqDataSource_ContextCreating(object sender, LinqDataSourceContextEventArgs e)
        {
            e.ObjectInstance = new KaruselaDataContext(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
        }


Then I get this error:
The type 'System.Data.Linq.DataContext' is defined in an assembly that is not referenced. You must add a reference to assembly 'System.Data.Linq, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'.

 

On web.config I already have this:
<add assembly="System.Data.Linq, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"/>

NOTE: The datacontext is in a different project (DLL proect) where I added a refernce to System.Data.Linq.

is there another way adding a refernce to a web project? or only though teh web.config?

Thanks.


System.Xml.Linq.XElement and XPathDocument

  

I have an XPathDocument that I want to save to a table using LINQ, but I get this error

cannot implicitly convert type 'System.Xml.XPath.XPathDocument' to 'System.Xml.Linq.XElement'


I create the XPathDocument from some (valid) xml contained in a resource file


XPathDocument xDoc = new XPathDocument(new StringReader(Resource1.TestXML));


when I try to assign it with LINQ, it flags up an error


NewDataItem.XML = xDoc  ----  error here

NewDataitem is a LINQ to SQL object created from the underlying table, 'NewDataItem.XML' is a column type of 'XML'


how do i (easily) convert xDoc so I can pass it into the LINQ object ?




How to read XML using LINQ in VB.NET

  

Can someone please tell me (sample code) how to read this XML into a SQL DB?  Should I use LINQ to XML?  Does anyone have any sample code?  I am working in VB.NET

 

<?xml version="1.0" encoding="utf-8"?>

<ReadOrderResponseType xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">

<Status xmlns="urn:mysol:apis">Success</Status>

<TimeStamp xmlns="urn:mysol:apis">2010-07-25T15:26:49.1150235Z</TimeStamp>

<StoreUrl xmlns="urn:mysol:apis">http://xyz.COM</StoreUrl>

<PageResponse xmlns="urn:mysol:apis">

<Page>1</Page>

<Size>10</Size>

<TotalSize>18033</TotalSize>

Crystal Report gives System.AccessViolationException: Attempted to read or write protected memory. T

  

when a crystal report for same id is opened again at same time or refreshed then it gives the

"System.AccessViolationException: Attempted to read or write protected memory. This is often an indication that other memory is corrupt."


Stack Trace is :-


Stack Trace:

[AccessViolationException: Attempted to read or write protected memory. This is often an indication that other memory is corrupt.]
CrystalDecisions.ReportAppServer.Controllers.DatabaseControllerClass.SetConnectionInfos(ConnectionInfos ConnectionInfos) +0
CrystalDecisions.CrystalReports.Engine.Table.ApplyLogOnInfo(TableLogOnInfo logonInfo) +362
CrystalDecisions.CrystalReports.Engine.ReportDocument.SetTableLogon(Tables tables, String user, String password, String server, String database, Boolean ignoreCase) +258
CrystalDecisions.CrystalReports.Engine.ReportDocument.SetDatabaseLogon(String user, String password, String server, String database, Boolean ignoreCase) +204
CrystalDecisions.

System.InvalidOperationException: Invalid attempt to read when no data is present.

  

Invalid attempt to read when no data is present.

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. 

Exception Details: System.InvalidOperationException: Invalid attempt to read when no data is present.

Source Error: 

Line 53:             if (reader.HasRows)
Line 54:             {
Line 55:                 Response.Write(reader.GetString(0));

Here is my code:

System.IO.IOException: Unable to read data from the transport connection

  
Hello,   I have an xml webservice calling another xml web service and occasionally i get the following error - any ideas why?Does this happen when the request is made or when reading the response? Also how i can prevent it from happening? Thanks   System.IO.IOException: Unable to read data from the transport connection: A blocking operation was interrupted by a call to WSACancelBlockingCall. ---> System.Net.Sockets.SocketException: A blocking operation was interrupted by a call to WSACancelBlockingCall   at System.Net.Sockets.Socket.Receive(Byte[] buffer, Int32 offset, Int32 size, SocketFlags socketFlags)   at System.Net.Sockets.NetworkStream.Read(Byte[] buffer, Int32 offset, Int32 size)   --- End of inner exception stack trace ---   at System.Net.ConnectStream.Read(Byte[] buffer, Int32 offset, Int32 size)   at System.IO.StreamReader.ReadBuffer(Char[] userBuffer, Int32 userOffset, Int32 desiredChars, Boolean readToUserBuffer)   at System.IO.StreamReader.Read(Char[] buffer, Int32 index, Int32 count)   at System.Xml.XmlTextReaderImpl.ReadData()   at System.Xml.XmlTextReaderImpl.InitTextReaderInput(String baseUriStr, TextReader input)   at System.Xml.XmlTextReaderImpl..ctor(String url, TextReader input, XmlNameTable nt)   at System.Xml.XmlTextReader..ctor(TextReader input)   at System.Web.Services.Protocols.SoapHttpClientProtocol.GetReaderForMessage(SoapClientMessage message, I

The type or namespace name 'Linq' does not exist in the namespace 'System'

  
Hi, I uploaded my website to the server, and I have there a working with wcf - it should be fw 3.5 I saw that fw 3.5 is installed on the server and also we have there fw 3.0 sp1. I run my website : www.qenglishcenter.com and I'm getting an error : The type or namespace name 'Linq' does not exist in the namespace 'System' (are you missing an assembly reference?) shouldn't System.linq be already existed ? Thanks for any reply.  

Read value of ID using LINQ

  
Hi,How i can ready the id value from below xml file in asp.net using VB language?<?xml version="1.0" encoding="iso-8859-1"?> <main> <callshop> <Inquiry id="inq_fun">Inquiry</Inquiry> <List id="acc_fun">Account List</List> </callshops> <Action> <Block id="blo_fun">Block</Block> <Delete id="del_fun">Delete</Delete> </Action> <Others> <Inbox id="in_fun"> Inbox</inbox> <Sent id="sn_fun">Sent</Sent> </Others> </main>Thank You

The configuration section 'system.web.extensions' cannot be read because it is missing a section d

  
My system: I have installed Windows 7, VS2010 and .NET40 and ASPAJAXExtSetup.msiI'm getting the error below. Error Summary HTTP Error 500.19 - Internal Server Error The requested page cannot be accessed because the related configuration data for the page is invalid. Detailed Error Information Module IIS Web Core Notification Unknown Handler Not yet determined Error Code 0x80070032 Config Error The configuration section 'system.web.extensions' cannot be read because it is missing a section declaration Config File \\?\C:\inetpub\tickets\web.config Requested URL http://www.tickets.com:80/ Physical Path Logon Method Not yet determined Logon User Not yet determined Config Source 45: </connectionStrings> 46: <system.web.extensions> 47: <scripting> My web.config:<?xml version="1.0"?><configuration>    <connectionStrings>            </connectionStrings>    <system.web.extensions>        <scripting>            <webServices>                <!--http://weblogs.asp.net/andrewfrederick/archive/2008/02/18/a-client-sid

Question on WCF service with Linq to SQL on 64-bit system

  
I'm trying this question one more time since I realized the work in in a 64-bit environment. I have a WCF service which runs in production in a 32-bit environment using VS2008 and .NET 2.0. We made a big change to our environment (lots at the same time) and I moved the services to VS2010, .NET 4.0, and 64-bit processes.  I wrote a new service and deployed it under IIS.  If I browse to the service I get the example screen and clicking on the link gives me the metadata.  So all of that is working. In my services I create a Linq to SQL context, perform a query, then return the result set as an Array.  I wrapped the context creation with a using.  My tests returned an exception "Attempt to access an object that has already been disposed".  I traced it down and found that the code executes, forces the query, returns the results, exits the using statement (disposing the context properly) then exits the method.  The next thing I get is the exception, inside framework code, and it is linq code attempting to fulfill the query once again. I have searched until I'm blue in the face trying to find prior incidents and fixes but all I found was one post, two years ago, same problem with less debugging, and no answer to the problem other than 'don't use the using statement' which is a bad suggestion.  So for a work around I wrote a Co

How to make linq Object Serializable... 'System.Data.EnumerableRowCollection is not marked as Seriz

  

Dear All,

Is it possible to make the linq object as serializable. I need to pass the serialized Data as parameter to the Remoting Method.

My LinQ Query is as follows

 Dim LinqQuery = From R In dsEdit.Tables(0) _

                    Where R.Field(Of Integer)("ID") < 400 _

                    Select R

ZipObject(LinqQuery)

The Definition of ZipObject is as follows.

 

 

  Public Function ZipObject(ByVal obj As Object) As Byte()

        Dim ms

System.Runtime.InteropServices.COMException (0x800A141F): Word was unable to read this document. It

  

Hi,

I am using the Interop.word.dll in my project to generate word reports. Reports are getting with out any exception if am using 2003 ms word. If i am using 2007 word iam getting the error as

 

System.Runtime.InteropServices.COMException (0x800A141F): Word was unable to read this document.  It may be corrupt

 

Please help to get reports work well in word 2007 also.

 

Regards,

Satish


WCF: Read file system image and return image thru wcf

  

Hi,

I have a service which reads an image stored in the database. I want to be able to read an image stored on the file system and return that back to the requestor, is that possible?

Thanks for your help! :)

Moneka


Linq to SQL does not implement System.Collections.IEnumerable

  

I am having a lot of the same issue as this poster did with errors on initializing type.

I am trying to learn linq and am about ready to give up - don't get how this is easier...Yell

I'm trying to do a simple update to product names in the product table based on the manufacturer ID

In order to do this I am looping through each record.  I was initally successful with changing all names in the column but when I try to query the data, I continually run into multiple problems.

 

The following poster has had the same issue I have but his solution isn't working for me. 

http://forums.asp.net/t/1467073.aspx

I keep getting the same error on the opening bracket on the select statement in the SelectByManufacturerID function...

Error 1 Cannot initialize type 'DataBaseDataManagement.ProductName' with a collection initializer because it does not implement 'System.Collections.IEnumerable'

 

Button that does the actual updating...

        protected void btnQuery_Click(object sender

No mapping exists from object type System.Xml.Linq.XDocument to a known managed provider native type

  

Hello,

I am using XML in getting client data in 3-tier architecture, using XDocument in passing XML among layers.

But when I use it in inserting this XML in XDocument, it throws the following error:

No mapping exists from object type System.Xml.Linq.XDocument to a known managed provider native type. 

I am using the following code, it throws the exception at the bold line:

 public void DALInsertXML(XDocument x)
        {
            SqlConnection connection = new SqlConnection(connection1);
            connection.Open();
            _command = ne

Read XML stored proecure result with linq 2 sql

  

I've build a query, but i like to read all values from it ,right now i only get the result of the metatags.
I also want to read the results of the tblContent.

I  access the stored procedure with linq to sql:

        public static XDocument GetPageXML(int MenuID, int LanguageID)
        {
            DbaseDataContext db = new DbaseDataContext(SelectDB());

            string raw = db.spXMLGetPage(MenuID, LanguageID).First().XML_F52E2B61_18A1_11d1_B105_00805F49916B.ToString();
            XDocument xml = XDocument.Parse(raw);

            return xml;
        }

 

Stored procedure:

 

alter PROCEDURE [dbo].[spXMLGetPage]
 @MenuID int,
 @LanguageID int
AS

print 'metatags';
SELECT    
 1 as Tag,    
 null as Parent,    
 MetaTags.ID AS [MetaTags!1!ID!element],
 MetaTags.description AS [MetaTags!1!de

system.linq.enumerable.where Issue

  

Hi,

I have a table "OSTAN" with two columns "ID" (Key index) and "NAME". I am trying to  construct a linq query to select the Name for a specific ID. I have not luck trying to construct the where clause. Here what I have so far:

 

using (XeledsEntities db = new XeledsEntities())
        {
        
            string SelectedName = db.Ostans.Name.Where( Ostan=> Ostan.Equals(Request.QueryString["Ostan"])).FirstOrDefault(); 
        }

 

Can anybody help me construct this where clause to set the Selected Name?


Categories: 
ASP.NetWindows Application  .NET Framework  C#  VB.Net  ADO.Net  
Sql Server  SharePoint  Silverlight  Others  All   

Hall of Fame    Twitter   Terms of Service    Privacy Policy    Contact Us    Archives   Tell A Friend