• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 2291
  • Last Modified:

Cannot assign to XXX because it is a using variable

I get that error when compiling my app.  I'm trying to use a Using statement with a Stream object so that I can make sure it gets completely killed and disposed as soon as I'm done with it.

I've attached the source code below.  Can someone show me what i'm doing wrong and correct it.
string proxyUrl = HttpContext.Current.Server.UrlDecode(url);
        HttpWebRequest webReq;
        HttpWebResponse webResp;
        bool success = false;
        using(Stream streamHttp = null){
        //try
        //{

        webReq = (HttpWebRequest)WebRequest.Create(proxyUrl);
        webReq.Timeout = Convert.ToInt32(WebConfigurationManager.AppSettings["TimeOut"]);
        webResp = (HttpWebResponse)webReq.GetResponse();
        if (webResp.StatusCode == HttpStatusCode.OK)
        {
            streamHttp = webResp.GetResponseStream();
            //HttpContext.Current.Response.Write("OK");
            //HttpContext.Current.Response.End();
            success = true;
        }
      
        // Do not write anything if we failed the request. We may want to use old data
        // Watch for io errors. The file may be locked
        if (success)
        {
              
            HttpContext.Current.Application["OfflineCount"] = 0;    // Clear any flags when we were off line 
            String filePath = "";

            /* Begin XML validation */
            // Copy streamHttp to a memory stream to allow seeking when using in XMLTextReader
            streamHttp = copyToMemoryStream(streamHttp);
            if (!xmlIsValid(url, streamHttp, durationSeconds))
            {
                schemReader.Close();
                // Write to log when data is invalid
                cimLog.WriteLog("\tFeed provider for feed: " + url + " returned invalid data.");
                // Break out of function to ensure proxy does not cacher bad data
                return;
            }
            schemReader.Close();
            // Reset position of streamHttp;
            streamHttp.Position = 0;
            //try
            //{
            filePath = WebConfigurationManager.AppSettings["CachePath"].ToString() + cimHTTP.ConvertUrlToFileName(url);
                FileStream streamCache = new FileStream(filePath, FileMode.Create, FileAccess.Write);
                BinaryWriter binCache = new BinaryWriter(streamCache);
                int b;
                while ((b = streamHttp.ReadByte()) != -1)
                {
                    binCache.Write(Convert.ToByte(b));
                }
                binCache.Close();
                streamHttp.Close();
            //}
            //catch (IOException ioError)
            //{
                //cimLog.WriteLog("Could not write to " + filePath + ". " + ioError.Message, cimLog.LogType.Warning);
            //}
            //catch (Exception exError)
            //{
            //    cimLog.WriteLog(exError.Message);
            //}
            }
        }

Open in new window

0
davidcahan
Asked:
davidcahan
  • 3
  • 3
2 Solutions
 
käµfm³d 👽Commented:
A "using" statement should look like:
using(Stream streamHttp = new FileStream("C:\my\path\to_file.txt", FileMode.Read))
{
   // Code that uses object
   // Your initialization needs to occur within the "using"
}

Open in new window

0
 
davidcahanAuthor Commented:
thanks...perfect
0
 
davidcahanAuthor Commented:
actually...along the same vein.  i have it working now EXCEPT for when I convert it to a memoryStream in order to make it searchable.  

looks like attached code below (look for // COPY STREAM TO MEMORY STREAM comment)
 string proxyUrl = url;
        HttpWebRequest webReq;
        HttpWebResponse webResp;
        bool success = false;
            webReq = (HttpWebRequest)WebRequest.Create(proxyUrl);
            webReq.Timeout = Convert.ToInt32(WebConfigurationManager.AppSettings["TimeOut"]);
            webResp = (HttpWebResponse)webReq.GetResponse();
            using (Stream streamHttp = webResp.GetResponseStream())
            {
            if (webResp.StatusCode == HttpStatusCode.OK)
            {
                success = true;
                //HttpContext.Current.Response.Write("OK");
                //HttpContext.Current.Response.End();
            }
        // Do not write anything if we failed the request. We may want to use old data
        // Watch for io errors. The file may be locked
        if (success)
        {
            HttpContext.Current.Application["OfflineCount"] = 0;    // Clear any flags when we were off line 
            String filePath = "";
           
                /* Begin XML validation */
                // COPY STREAM TO MEMORY STREAM
                streamHttp = copyToMemoryStream(streamHttp);
                if (!xmlIsValid(url, streamHttp, durationSeconds))
                {
                    schemReader.Close();
                    // Write to log when data is invalid
                    cimLog.WriteLog("\tFeed provider for feed: " + url + " returned invalid data.");
                    // Break out of function to ensure proxy does not cacher bad data
                    return;
                }
                schemReader.Close();
                // Reset position of streamHttp;
                streamHttp.Position = 0;
                try
                {
                    filePath = WebConfigurationManager.AppSettings["CachePath"].ToString() + cimHTTP.ConvertUrlToFileName(url);
                    FileStream streamCache = new FileStream(filePath, FileMode.Create, FileAccess.Write);
                    BinaryWriter binCache = new BinaryWriter(streamCache);
                    int b;
                    while ((b = streamHttp.ReadByte()) != -1)
                    {
                        binCache.Write(Convert.ToByte(b));
                    }
                    binCache.Close();

                }
                catch (IOException ioError)
                {
                    cimLog.WriteLog("Could not write to " + filePath + ". " + ioError.Message, cimLog.LogType.Warning);
                }
                catch (Exception exError)
                {
                    cimLog.WriteLog(exError.Message);
                }
            }
        }


    private static MemoryStream copyToMemoryStream(Stream stream)
    {
        int b;
        MemoryStream memStream = new MemoryStream();
        while ((b = stream.ReadByte()) != -1)
        {
            memStream.WriteByte(Convert.ToByte(b));
        }
        memStream.Position = 0;
        return memStream;
    }

Open in new window

0
Never miss a deadline with monday.com

The revolutionary project management tool is here!   Plan visually with a single glance and make sure your projects get done.

 
käµfm³d 👽Commented:
Yes, that is because you are trying to assign to the using's variable, which can only be done within the "using" line. That is a point I didn't make clear in my last post...  my apologies  :)

You can think of a using variable as being constant/read only within that block. For your purposes, create a new, local stream variable that you can assign to and assign to it in line 25 of your last post. Something like:
    string proxyUrl = url;
    HttpWebRequest webReq;
    HttpWebResponse webResp;
    Stream tempStream;
    bool success = false;

    webReq = (HttpWebRequest)WebRequest.Create(proxyUrl);
    webReq.Timeout = Convert.ToInt32(WebConfigurationManager.AppSettings["TimeOut"]);
    webResp = (HttpWebResponse)webReq.GetResponse();

    using (Stream streamHttp = webResp.GetResponseStream())
    {
        if (webResp.StatusCode == HttpStatusCode.OK)
        {
            success = true;
            //HttpContext.Current.Response.Write("OK");
            //HttpContext.Current.Response.End();
        }

        // Do not write anything if we failed the request. We may want to use old data
        // Watch for io errors. The file may be locked
        if (success)
        {
            HttpContext.Current.Application["OfflineCount"] = 0;    // Clear any flags when we were off line 
            String filePath = "";

            /* Begin XML validation */
            // COPY STREAM TO MEMORY STREAM
            tempStream = copyToMemoryStream(streamHttp);

            if (!xmlIsValid(url, tempStream, durationSeconds))
            {
                schemReader.Close();
                // Write to log when data is invalid
                cimLog.WriteLog("\tFeed provider for feed: " + url + " returned invalid data.");
                // Break out of function to ensure proxy does not cacher bad data
                return;
            }
            schemReader.Close();
            // Reset position of streamHttp;
            streamHttp.Position = 0;

            try
            {
                filePath = WebConfigurationManager.AppSettings["CachePath"].ToString() + cimHTTP.ConvertUrlToFileName(url);
                FileStream streamCache = new FileStream(filePath, FileMode.Create, FileAccess.Write);
                BinaryWriter binCache = new BinaryWriter(streamCache);
                int b;
                while ((b = streamHttp.ReadByte()) != -1)
                {
                    binCache.Write(Convert.ToByte(b));
                }
                binCache.Close();

            }
            catch (IOException ioError)
            {
                cimLog.WriteLog("Could not write to " + filePath + ". " + ioError.Message, cimLog.LogType.Warning);
            }
            catch (Exception exError)
            {
                cimLog.WriteLog(exError.Message);
            }
        }
    }
}

private static MemoryStream copyToMemoryStream(Stream stream)
{
    int b;
    MemoryStream memStream = new MemoryStream();
    while ((b = stream.ReadByte()) != -1)
    {
        memStream.WriteByte(Convert.ToByte(b));
    }
    memStream.Position = 0;
    return memStream;
}

Open in new window

0
 
davidcahanAuthor Commented:
yes...I should have both seen and already known that.  My apologies for the thickness of my head!!!!
0
 
käµfm³d 👽Commented:
No worries :)  Always glad to help!
0

Featured Post

The new generation of project management tools

With monday.com’s project management tool, you can see what everyone on your team is working in a single glance. Its intuitive dashboards are customizable, so you can create systems that work for you.

  • 3
  • 3
Tackle projects and never again get stuck behind a technical roadblock.
Join Now